Index: /issm/trunk/configure.ac
===================================================================
--- /issm/trunk/configure.ac	(revision 22757)
+++ /issm/trunk/configure.ac	(revision 22758)
@@ -2,5 +2,5 @@
 
 #AUTOCONF
-AC_INIT([Ice Sheet System Model (ISSM)],[4.12],[issm@jpl.nasa.gov],[issm],[http://issm.jpl.nasa.gov]) #Initializing configure
+AC_INIT([Ice Sheet System Model (ISSM)],[4.13],[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
@@ -20,4 +20,5 @@
 AC_PROG_CXX([icpc cl icl g++])
 AC_PROG_F77([ifort g77 gfortran])
+AC_PROG_FC([ifort gfortran])
 
 #AUTOMAKE
Index: /issm/trunk/etc/environment.csh
===================================================================
--- /issm/trunk/etc/environment.csh	(revision 22757)
+++ /issm/trunk/etc/environment.csh	(revision 22758)
@@ -18,4 +18,9 @@
 	setenv PETSC_DIR {$PETSC_DIR}
 	setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$PETSC_DIR/lib
+endif
+
+set SCOTCH_DIR="$ISSM_DIR/externalpackages/scotch/install"
+if (-d $SCOTCH_DIR) then
+	setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$SCOTCH_DIR/lib
 endif
 
Index: /issm/trunk/etc/environment.sh
===================================================================
--- /issm/trunk/etc/environment.sh	(revision 22757)
+++ /issm/trunk/etc/environment.sh	(revision 22758)
@@ -96,4 +96,7 @@
 	libpathappend "$PETSC_DIR/lib"
 fi
+
+SCOTCH_DIR="$ISSM_DIR/externalpackages/scotch/install"
+libpathappend "$SCOTCH_DIR/lib"
 
 SLEPC_DIR="$ISSM_DIR/externalpackages/slepc/install"
Index: sm/trunk/examples/Data/Download.sh
===================================================================
--- /issm/trunk/examples/Data/Download.sh	(revision 22757)
+++ 	(revision )
@@ -1,25 +1,0 @@
-#!/bin/bash
-
-echo "Downloading Square shelf dataset"
-$ISSM_DIR/scripts/DownloadExternalPackage2.py 'http://issm.jpl.nasa.gov/files/workshop2014/SquareShelf.nc' 'SquareShelf.nc'
-
-echo "Downloading SeaRISE dataset - Antarctica"
-$ISSM_DIR/scripts/DownloadExternalPackage2.py 'http://websrv.cs.umt.edu/isis/images/c/cc/Antarctica_5km_withshelves_v0.75.nc' 'Antarctica_5km_withshelves_v0.75.nc'
-
-echo "Downloading InSAR Antarctic velocities"
-$ISSM_DIR/scripts/DownloadExternalPackage2.py 'ftp://n5eil01u.ecs.nsidc.org/SAN/MEASURES/NSIDC-0484.001/1996.01.01/antarctica_ice_velocity_900m.nc' 'Antarctica_ice_velocity.nc' 
-
-echo "Downloading PIG errors"
-$ISSM_DIR/scripts/DownloadExternalPackage2.py 'http://issm.jpl.nasa.gov/files/workshop2014/CrossOvers2009.mat' 'CrossOvers2009.mat'
-
-echo "Downloading SeaRISE dataset - Greenland"
-$ISSM_DIR/scripts/DownloadExternalPackage2.py 'http://websrv.cs.umt.edu/isis/images/e/e9/Greenland_5km_dev1.2.nc' 'Greenland_5km_dev1.2.nc'
-
-echo "Downloading Jason Box's SMB"
-$ISSM_DIR/scripts/DownloadExternalPackage2.py 'http://issm.jpl.nasa.gov/files/examples/Box_Greenland_SMB_monthly_1840-2012_5km_cal_ver20141007.nc' 'Box_Greenland_SMB_monthly_1840-2012_5km_cal_ver20141007.nc'
-
-echo "Downloading IceBridge Jakobshavn bedrock"
-$ISSM_DIR/scripts/DownloadExternalPackage2.py 'https://data.cresis.ku.edu/data/grids/old_versions/Jakobshavn_2008_2011_Composite.zip' 'Jakobshavn_2008_2011_Composite.zip'
-unzip Jakobshavn_2008_2011_Composite.zip
-mv Jakobshavn_2008_2011_Composite/grids/Jakobshavn_2008_2011_Composite_XYZGrid.txt .
-rm -rf Jakobshavn_2008_2011_Composite Jakobshavn_2008_2011_Composite.zip
Index: /issm/trunk/examples/UncertaintyQuantification/runme.m
===================================================================
--- /issm/trunk/examples/UncertaintyQuantification/runme.m	(revision 22757)
+++ /issm/trunk/examples/UncertaintyQuantification/runme.m	(revision 22758)
@@ -14,6 +14,6 @@
 		textpositions{i}=[contour.x(end) contour.y(end)];
 	end
-
-	plotmodel(md,'data',md.results.StressbalanceSolution.Vel,'log',10,'expdisp',...
+	vel=md.results.StressbalanceSolution.Vel; vel(vel==0)=nan;
+	plotmodel(md,'data',vel,'log',10,'expdisp',...
 		{'MassFluxes/MassFlux1.exp','MassFluxes/MassFlux2.exp',...
 		'MassFluxes/MassFlux3.exp','MassFluxes/MassFlux4.exp',...
Index: /issm/trunk/examples/shakti/moulin.par
===================================================================
--- /issm/trunk/examples/shakti/moulin.par	(revision 22758)
+++ /issm/trunk/examples/shakti/moulin.par	(revision 22758)
@@ -0,0 +1,58 @@
+%Start defining model parameters here
+
+% Set up bed topography and ice geometry for a tilted 500m thick slab
+    md.geometry.base = .02*md.mesh.x;
+    md.geometry.bed = md.geometry.base;
+    md.geometry.surface = .02*md.mesh.x + 500;
+    md.geometry.thickness = md.geometry.surface - md.geometry.bed;
+
+% Define ice sliding velocity (m/yr) 
+    md.initialization.vx = 10^-6*md.constants.yts*ones(md.mesh.numberofvertices,1);
+    md.initialization.vy = zeros(md.mesh.numberofvertices,1);
+    md.initialization.pressure=zeros(md.mesh.numberofvertices,1);
+
+md.initialization.pressure=zeros(md.mesh.numberofvertices,1);
+
+% Materials
+    % Ice flow law parameter (note that the standard parameter A=B^(-3))
+    md.materials.rheology_B= (5e-25)^(-1/3)*ones(md.mesh.numberofvertices,1);
+    md.initialization.temperature=(273)*ones(md.mesh.numberofvertices,1);
+    md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
+
+%Calving
+md.calving.calvingrate=zeros(md.mesh.numberofvertices,1);
+%md.calving.spclevelset=NaN(md.mesh.numberofvertices,1);
+
+% Friction law and coefficient
+    md.friction=frictionsommers(md.friction);
+    md.friction.coefficient=20.*ones(md.mesh.numberofvertices,1);
+
+
+%Numerical parameters
+md.stressbalance.viscosity_overshoot=0.0;
+md.masstransport.stabilization=1.;
+md.thermal.stabilization=1.;
+md.verbose=verbose(0);
+md.settings.waitonlock=30;
+md.stressbalance.restol=0.05;
+md.steadystate.reltol=0.05;
+md.stressbalance.reltol=0.05;
+md.stressbalance.abstol=NaN;
+md.timestepping.time_step=1.;
+md.timestepping.final_time=3.;
+
+%GIA: 
+md.gia.lithosphere_thickness=100.*ones(md.mesh.numberofvertices,1); % in km
+md.gia.mantle_viscosity=1.0*10^21*ones(md.mesh.numberofvertices,1); % in Pa.s
+md.materials.lithosphere_shear_modulus=6.7*10^10;                   % in Pa
+md.materials.lithosphere_density=3.32;                              % in g/cm^-3
+md.materials.mantle_shear_modulus=1.45*10^11;                       % in Pa
+md.materials.mantle_density=3.34;                                   % in g/cm^-3
+
+%Boundary conditions:
+md=SetIceSheetBC(md);
+
+%Change name so that no test have the same name
+A=dbstack;
+if (length(A)>2), md.miscellaneous.name=A(3).file(1:end-2); end
+
Index: /issm/trunk/examples/shakti/outline.exp
===================================================================
--- /issm/trunk/examples/shakti/outline.exp	(revision 22758)
+++ /issm/trunk/examples/shakti/outline.exp	(revision 22758)
@@ -0,0 +1,10 @@
+## Name:DomainOutline
+## Icon:0
+# Points Count  Value
+5 1.000000
+# X pos Y pos
+0 0
+1000 0
+1000 1000
+0 1000
+0 0
Index: /issm/trunk/examples/shakti/runme.m
===================================================================
--- /issm/trunk/examples/shakti/runme.m	(revision 22758)
+++ /issm/trunk/examples/shakti/runme.m	(revision 22758)
@@ -0,0 +1,82 @@
+steps=[1:3];
+
+if any(steps==1)
+	disp('	Step 1: Mesh');
+
+	%Generate unstructured mesh on 1,000 m square with typical element edge length of 20 m
+	md=triangle(model,'./outline.exp',20);
+
+	save MoulinMesh md
+end
+if any(steps==2)
+	disp('	Step 2: Parameterization');
+	md=loadmodel('MoulinMesh');
+
+	md=setmask(md,'','');
+
+	% Run parameterization script to set up geometry, velocity, material properties, etc.
+	md=parameterize(md,'moulin.par');
+
+	% HYDROLOGY SPECIFIC PARAMETERIZATION:
+	% Change hydrology class to Sommers' SHaKTI model
+	md.hydrology=hydrologysommers();
+
+	% Define initial water head such that water pressure is 50% of ice overburden pressure
+	md.hydrology.head = 0.5*md.materials.rho_ice/md.materials.rho_freshwater*md.geometry.thickness + md.geometry.base;
+
+	% Initial subglacial gap height of 0.01m everywhere
+	md.hydrology.gap_height = 0.01*ones(md.mesh.numberofelements,1);
+
+	% Typical bed bump bump spacing (2m)
+	md.hydrology.bump_spacing = 2*ones(md.mesh.numberofelements,1);
+
+	% Typical bed bump height (0.1m)
+	md.hydrology.bump_height = 0.1*ones(md.mesh.numberofelements,1);
+
+	% Define distributed englacial input to the subglacial system (m/yr)
+	% Change the value 0.0 to add distributed input
+	md.hydrology.englacial_input = 0.0*ones(md.mesh.numberofvertices,1);
+
+	% Initial Reynolds number (start at Re=1000 everywhere)
+	md.hydrology.reynolds= 1000*ones(md.mesh.numberofelements,1);
+
+	% Set up atmospheric pressure Type I boundary condition at left edge of
+	% domain (outflow, i.e. h=zb at x=xmin)
+	md.hydrology.spchead = NaN(md.mesh.numberofvertices,1);
+	pos=find(md.mesh.vertexonboundary & md.mesh.x==min(md.mesh.x));
+	md.hydrology.spchead(pos)=md.geometry.base(pos);
+
+	save MoulinParam md;
+end
+if any(steps==3);
+	disp('	Step 3: Solve!');
+	md=loadmodel('MoulinParam');
+
+	md.transient=deactivateall(md.transient);
+	md.transient.ishydrology=1;
+
+	% Specify that you want to run the model on your current computer
+	% Change the number of processors according to your machine (here np=4)
+	md.cluster=generic('np',2);
+
+	% Define the time stepping scheme: run for 90 days with a time step of 1 hr
+	md.timestepping.time_step=3600/md.constants.yts; % Time step (in years)
+	md.timestepping.final_time=30/365;
+
+	%Add one moulin with steady input at x=500, y=500
+	[a,pos] = min(sqrt((md.mesh.x-500).^2+(md.mesh.y-500).^2));
+	time=0:md.timestepping.time_step:md.timestepping.final_time;
+	md.hydrology.moulin_input = zeros(md.mesh.numberofvertices+1,numel(time));
+	md.hydrology.moulin_input(end,:)=time;
+	md.hydrology.moulin_input(pos,:)=4;
+
+	% Specify no-flux Type 2 boundary conditions on all edges (except
+	% the Type 1 condition set at the outflow above)
+	md.hydrology.neumannflux=zeros(md.mesh.numberofelements+1,numel(time));
+	md.hydrology.neumannflux(end,:)=time;
+
+	md.verbose.solution=1;
+	md=solve(md,'Transient');
+
+	save MoulinTransient md
+end
Index: /issm/trunk/externalpackages/adolc/install-withampi.sh
===================================================================
--- /issm/trunk/externalpackages/adolc/install-withampi.sh	(revision 22757)
+++ /issm/trunk/externalpackages/adolc/install-withampi.sh	(revision 22758)
@@ -15,4 +15,6 @@
 
 #Compile ADOL-C
+export CFLAGS="-O2 -L$ISSM_DIR/externalpackages/mpich/install/lib -lmpi"
+export CXXFLAGS="-O2 -std=c++11 -L$ISSM_DIR/externalpackages/mpich/install/lib -lmpi"
 cd src
 ./configure --prefix=$ISSM_DIR/externalpackages/adolc/install  \
Index: /issm/trunk/externalpackages/boost/install-1.55-linux.sh
===================================================================
--- /issm/trunk/externalpackages/boost/install-1.55-linux.sh	(revision 22757)
+++ /issm/trunk/externalpackages/boost/install-1.55-linux.sh	(revision 22758)
@@ -1,4 +1,5 @@
 #!/bin/bash
-set -eu
+#set -eu
+#unhook set -eu because some target do fail and it is not a big deal
 
 #Note of caution:  stop after boostrap phase, and run 
Index: sm/trunk/externalpackages/boost/install.sh
===================================================================
--- /issm/trunk/externalpackages/boost/install.sh	(revision 22757)
+++ 	(revision )
@@ -1,35 +1,0 @@
-#!/bin/bash
-set -eu
-
-#Note of caution:  stop after boostrap phase, and run 
-#bjam --debug-configuration, to figure out which paths boost is using to include 
-#python. make sure everyone of these paths is covered by python. If not, just make 
-#symlinks in externalpackages/python to what boost is expecting. Ther is NO WAY 
-#to get the boost library to include python support without doing that. 
-
-#Some cleanup
-rm -rf install boost_1_49_0 src
-mkdir install src
-
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/boost_1_49_0.tar.gz' 'boost_1_49_0.tar.gz'
-
-#Untar 
-tar -zxvf  boost_1_49_0.tar.gz
-
-#Move boost into install directory
-mv boost_1_49_0/* src
-rm -rf boost_1_49_0
-#Configure and compile
-cd src 
-./bootstrap.sh \
-	--prefix="$ISSM_DIR/externalpackages/boost/install" \
-	--with-python=python3.2 \
-	--with-python-root="$ISSM_DIR/externalpackages/python/install" 
-
-#Compile boost
-./bjam install
-
-#put bjam into install also: 
-mkdir ../install/bin
-cp bjam ../install/bin
Index: /issm/trunk/externalpackages/cython/install-26.sh
===================================================================
--- /issm/trunk/externalpackages/cython/install-26.sh	(revision 22758)
+++ /issm/trunk/externalpackages/cython/install-26.sh	(revision 22758)
@@ -0,0 +1,13 @@
+#!/bin/bash
+set -eu
+
+#clean up
+rm -rf Cython-0.26
+
+#download numpy first
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/Cython-0.26.tar.gz' 'cython.tar.gz'
+
+#install numpy
+tar -zxvf cython.tar.gz
+cd Cython-0.26
+python setup.py install
Index: /issm/trunk/externalpackages/dakota/configs/6.2/BuildDakotaCustom.cmake.patch
===================================================================
--- /issm/trunk/externalpackages/dakota/configs/6.2/BuildDakotaCustom.cmake.patch	(revision 22757)
+++ /issm/trunk/externalpackages/dakota/configs/6.2/BuildDakotaCustom.cmake.patch	(revision 22758)
@@ -1,3 +1,3 @@
-67a68,75
+67a68,78
 > set( DAKOTA_HAVE_MPI ON
 >  CACHE BOOL "Always build with MPI enabled" FORCE)
@@ -8,4 +8,7 @@
 >  "$ENV{ISSM_DIR}/externalpackages/mpich/install/lib/libmpich.so"
 >  CACHE FILEPATH "Use installed MPI library" FORCE)
+> set( MPI_EXTRA_LIBRARY
+>  "$ENV{ISSM_DIR}/externalpackages/mpich/install/lib/libmpich.so"
+>	CACHE FILEPATH "Use MPI extra libraries" FORCE)
 73,77c73,77
 < #set(BOOST_ROOT
Index: /issm/trunk/externalpackages/dakota/configs/6.2/CMakeLists.txt.discover16.patch
===================================================================
--- /issm/trunk/externalpackages/dakota/configs/6.2/CMakeLists.txt.discover16.patch	(revision 22758)
+++ /issm/trunk/externalpackages/dakota/configs/6.2/CMakeLists.txt.discover16.patch	(revision 22758)
@@ -0,0 +1,6 @@
+156c153,155
+< # TODO: Can't this be integrated into the following logic?
+---
+> # TODO: Can't this be integrated into the following logic?
+> set(BLAS_LIBS "-L/usr/local/intel/2016/compilers_and_libraries_2016.2.181/linux/mkl/lib/intel64/ -lmkl_intel_lp64 -lmkl_sequential -lmkl_core -L/usr/lib64/ -lpthread -lm")
+> set(LAPACK_LIBS "-L/usr/local/intel/2016/compilers_and_libraries_2016.2.181/linux/mkl/lib/intel64/ -lmkl_intel_lp64 -lmkl_sequential -lmkl_core -L/usr/lib64/ -lpthread -lm")
Index: /issm/trunk/externalpackages/dakota/configs/6.2/CMakeLists.txt.petsclibs.patch
===================================================================
--- /issm/trunk/externalpackages/dakota/configs/6.2/CMakeLists.txt.petsclibs.patch	(revision 22758)
+++ /issm/trunk/externalpackages/dakota/configs/6.2/CMakeLists.txt.petsclibs.patch	(revision 22758)
@@ -0,0 +1,6 @@
+156c153,155
+< # TODO: Can't this be integrated into the following logic?
+---
+> # TODO: Can't this be integrated into the following logic?
+> set(BLAS_LIBS "-L$ENV{ISSM_DIR}/externalpackages/petsc/install/lib -lfblas -L/usr/lib/gcc/x86_64-linux-gnu/4.9 -lgfortran")
+> set(LAPACK_LIBS "-L$ENV{ISSM_DIR}/externalpackages/petsc/install/lib -lflapack -L/usr/lib/gcc/x86_64-linux-gnu/4.9 -lgfortran")
Index: /issm/trunk/externalpackages/dakota/configs/6.2/sandia_rules.cpp.patch
===================================================================
--- /issm/trunk/externalpackages/dakota/configs/6.2/sandia_rules.cpp.patch	(revision 22758)
+++ /issm/trunk/externalpackages/dakota/configs/6.2/sandia_rules.cpp.patch	(revision 22758)
@@ -0,0 +1,4 @@
+24145c24145
+<     if ( i_hi < 0 )
+---
+>     if ( *i_hi < 0 )
Index: /issm/trunk/externalpackages/dakota/install-6.2-intel16-discover.sh
===================================================================
--- /issm/trunk/externalpackages/dakota/install-6.2-intel16-discover.sh	(revision 22758)
+++ /issm/trunk/externalpackages/dakota/install-6.2-intel16-discover.sh	(revision 22758)
@@ -0,0 +1,58 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf Dakota
+rm -rf src 
+rm -rf build 
+rm -rf install 
+mkdir src build install 
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/dakota-6.2-public.src.tar.gz' 'dakota-6.2-public-src.tar.gz'
+
+#Untar 
+tar -zxvf dakota-6.2-public-src.tar.gz
+
+#Move Dakota to src directory
+mv dakota-6.2.0.src/* src
+rm -rf dakota-6.2.0.src
+
+#Set up Dakota cmake variables and config
+export DAK_SRC=$ISSM_DIR/externalpackages/dakota/src
+export DAK_BUILD=$ISSM_DIR/externalpackages/dakota/build
+export MPIHOME=$ISSM_DIR/externalpackages/mpich/install
+cp $DAK_SRC/cmake/BuildDakotaTemplate.cmake $DAK_SRC/cmake/BuildDakotaCustom.cmake
+patch $DAK_SRC/cmake/BuildDakotaCustom.cmake configs/6.2/BuildDakotaCustom.cmake.discover.patch
+patch $DAK_SRC/cmake/DakotaDev.cmake configs/6.2/DakotaDev.cmake.patch
+patch $DAK_SRC/CMakeLists.txt configs/6.2/CMakeLists.txt.discover16.patch
+
+#Apply patches
+patch src/src/NonDSampling.cpp configs/6.2/NonDSampling.cpp.patch
+patch src/src/NonDLocalReliability.cpp configs/6.2/NonDLocalReliability.cpp.patch
+patch src/packages/pecos/src/pecos_global_defs.hpp configs/6.2/pecos_global_defs.hpp.patch
+
+#Configure dakota
+cd $DAK_BUILD
+
+cmake -D CMAKE_C_COMPILER=mpicc \
+	   -D CMAKE_CXX_COMPILER=mpicxx \
+	   -D CMAKE_Fortran_COMPILER=/usr/bin/gfortran \
+		-DHAVE_ACRO=off \
+		-DHAVE_JEGA=off \
+		-C $DAK_SRC/cmake/BuildDakotaCustom.cmake \
+		-C $DAK_SRC/cmake/DakotaDev.cmake \
+		$DAK_SRC
+cd ..
+
+#Compile and install dakota
+cd $DAK_BUILD
+if [ $# -eq 0 ];
+then
+	make
+	make install
+else
+	make -j $1
+	make -j $1 install
+fi
+cd ..
Index: /issm/trunk/externalpackages/dakota/install-6.2-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/dakota/install-6.2-linux64.sh	(revision 22757)
+++ /issm/trunk/externalpackages/dakota/install-6.2-linux64.sh	(revision 22758)
@@ -26,4 +26,5 @@
 patch $DAK_SRC/cmake/BuildDakotaCustom.cmake configs/6.2/BuildDakotaCustom.cmake.patch
 patch $DAK_SRC/cmake/DakotaDev.cmake configs/6.2/DakotaDev.cmake.patch
+patch $DAK_SRC/CMakeLists.txt configs/6.2/CMakeLists.txt.petsclibs.patch
 
 #Apply patches
Index: /issm/trunk/externalpackages/dakota/install-6.2-macosx64-highsierra.sh
===================================================================
--- /issm/trunk/externalpackages/dakota/install-6.2-macosx64-highsierra.sh	(revision 22758)
+++ /issm/trunk/externalpackages/dakota/install-6.2-macosx64-highsierra.sh	(revision 22758)
@@ -0,0 +1,70 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf Dakota
+rm -rf src 
+rm -rf build 
+rm -rf install 
+mkdir src build install 
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/dakota-6.2-public.src.tar.gz' 'dakota-6.2-public-src.tar.gz'
+
+#Untar 
+tar -zxvf dakota-6.2-public-src.tar.gz
+
+#Move Dakota to src directory
+mv dakota-6.2.0.src/* src
+rm -rf dakota-6.2.0.src
+
+#Set up Dakota cmake variables and config
+export DAK_SRC=$ISSM_DIR/externalpackages/dakota/src
+export DAK_BUILD=$ISSM_DIR/externalpackages/dakota/build
+export MPIHOME=$ISSM_DIR/externalpackages/mpich/install
+cp $DAK_SRC/cmake/BuildDakotaTemplate.cmake $DAK_SRC/cmake/BuildDakotaCustom.cmake
+patch $DAK_SRC/cmake/BuildDakotaCustom.cmake configs/6.2/BuildDakotaCustom.cmake.mac.patch
+patch $DAK_SRC/cmake/DakotaDev.cmake configs/6.2/DakotaDev.cmake.patch
+patch $DAK_SRC/CMakeLists.txt configs/6.2/CMakeLists.txt.patch
+
+#Apply patches
+patch src/src/NonDSampling.cpp configs/6.2/NonDSampling.cpp.patch
+patch src/src/NonDLocalReliability.cpp configs/6.2/NonDLocalReliability.cpp.patch
+patch src/packages/pecos/src/pecos_global_defs.hpp configs/6.2/pecos_global_defs.hpp.patch
+patch src/packages/VPISparseGrid/src/sandia_rules.cpp configs/6.2/sandia_rules.cpp.patch
+
+export BOOST_ROOT=$ISSM_DIR/externalpackages/boost/install
+
+#Configure dakota
+# Set your local gcc compiler here
+cd $DAK_BUILD
+cmake -DBoost_NO_BOOST_CMAKE=TRUE \
+	-DBoost_NO_SYSTEM_PATHS=TRUE \
+	-DBOOST_ROOT:PATHNAME=$BOOST_ROOT \
+	-DBoost_LIBRARY_DIRS:FILEPATH=${BOOST_ROOT}/lib \
+	-D CMAKE_C_COMPILER=$ISSM_DIR/externalpackages/mpich/install/bin/mpicc \
+	-D CMAKE_CXX_COMPILER=$ISSM_DIR/externalpackages/mpich/install/bin/mpicxx \
+	-D CMAKE_Fortran_COMPILER=$ISSM_DIR/externalpackages/mpich/install/bin/mpif77 \
+	-D CMAKE_CXX_FLAGS=-fdelayed-template-parsing \
+	-DHAVE_ACRO=off \
+	-DHAVE_JEGA=off \
+	-C $DAK_SRC/cmake/BuildDakotaCustom.cmake \
+	-C $DAK_SRC/cmake/DakotaDev.cmake \
+	$DAK_SRC
+cd ..
+
+# Snowleopard: Mpi should be made with these compilers
+#-DCMAKE_CXX_COMPILER=/usr/bin/g++ -DCMAKE_CC_COMPILER=/usr/bin/gcc \
+#-DCMAKE_Fortran_COMPILER=/usr/local/gfortran/bin/x86_64-apple-darwin10-gfortran \
+
+#Compile and install dakota
+cd $DAK_BUILD
+if [ $# -eq 0 ];
+then
+	make
+	make install
+else
+	make -j $1
+	make -j $1 install
+fi
+cd ..
Index: /issm/trunk/externalpackages/emscripten/install.sh
===================================================================
--- /issm/trunk/externalpackages/emscripten/install.sh	(revision 22757)
+++ /issm/trunk/externalpackages/emscripten/install.sh	(revision 22758)
@@ -2,6 +2,9 @@
 set -eu
 
+export CC=gcc
+export CXX=g++
+
 #Some cleanup
-rm -rf src
+rm -rf install
 
 #Download from ISSM server
@@ -10,12 +13,13 @@
 #Untar and move petsc to install directory
 tar -zxvf  emsdk-portable.tar.gz
-mv emsdk_portable src
+mv emsdk_portable install
 
-cd src
-
-export CXX=g++
-export CC=gcc
+cd install
 
 ./emsdk update
-./emsdk install latest
-./emsdk activate latest
+./emsdk install sdk-tag-1.34.12-64bit
+./emsdk activate sdk-tag-1.34.12-64bit
+
+#Related to moving the install path after installation - However, not safe to install in dir named "install" since a failure would not be noticed by jenkins when triggering
+#Not reliable - when executed in subshell without sourcing the install file, this has no effect. Safer to explicitly source for each dependent externalpackage.
+source emsdk_env.sh
Index: /issm/trunk/externalpackages/gmsh/install.sh
===================================================================
--- /issm/trunk/externalpackages/gmsh/install.sh	(revision 22757)
+++ /issm/trunk/externalpackages/gmsh/install.sh	(revision 22758)
@@ -7,9 +7,25 @@
 
 #Download latest version
-svn co --username gmsh --password gmsh https://geuz.org/svn/gmsh/trunk src
+#svn co --username gmsh --password gmsh https://geuz.org/svn/gmsh/trunk src
+#git clone http://gitlab.onelab.info/gmsh/gmsh.git src
+
+#Set gmsh version
+GMSH_VER="3.0.5"
+
+#Remove tarball if it exists
+rm -f gmsh-$GMSH_VER-source.tgz
+
+#Download last stable version that we know works
+wget http://gmsh.info/src/gmsh-$GMSH_VER-source.tgz
+
+#Untar gmsh
+tar -xvzf gmsh-$GMSH_VER-source.tgz
+
+#Rename gmsh source directory
+mv gmsh-$GMSH_VER-source src
 
 #Configure
 cd install
-cmake ../src -DCMAKE_INSTALL_PREFIX="$ISSM_DIR/externalpackages/gmsh/install"
+cmake ../src -DCMAKE_INSTALL_PREFIX="$ISSM_DIR/externalpackages/gmsh/install" -DENABLE_MPI=1
 
 #Compile and install
Index: /issm/trunk/externalpackages/gsl/install-javascript.sh
===================================================================
--- /issm/trunk/externalpackages/gsl/install-javascript.sh	(revision 22757)
+++ /issm/trunk/externalpackages/gsl/install-javascript.sh	(revision 22758)
@@ -1,4 +1,12 @@
 #!/bin/bash
 set -eu
+
+#Source emscripten to ensure emcc/em++ compiler are in env
+source $ISSM_DIR/externalpackages/emscripten/install/emsdk_env.sh
+export CC=emcc
+export CXX=em++
+
+# Issue with variadic function signatures.
+export CFLAGS=-DSTDC_HEADERS
 
 #Some cleanup
@@ -19,11 +27,6 @@
 cd src-javascript
 
-export CC=emcc
-export CXX=em++
-
-# Issue with variadic function signatures.
-export CFLAGS=-DSTDC_HEADERS
-
-./configure --prefix="$ISSM_DIR/externalpackages/gsl/install-javascript" 
+./configure --prefix="$ISSM_DIR/externalpackages/gsl/install-javascript" \
+	--disable-shared
 
 #Compile gsl
Index: /issm/trunk/externalpackages/gslib/install.sh
===================================================================
--- /issm/trunk/externalpackages/gslib/install.sh	(revision 22757)
+++ /issm/trunk/externalpackages/gslib/install.sh	(revision 22758)
@@ -18,7 +18,7 @@
 #Change compiler to gfortran
 cd install
-cat Makefile | sed -e "s/FC=g95/FC=ifort/g" > Makefile.bak
+cat Makefile | sed -e "s/FC=g95/FC=gfortran/g" > Makefile.bak
 mv Makefile.bak Makefile
-cat gslib/Makefile | sed -e "s/FC=g95/FC=ifort/g" > Makefile.bak
+cat gslib/Makefile | sed -e "s/FC=g95/FC=gfortran/g" > Makefile.bak
 mv Makefile.bak gslib/Makefile
 make 
Index: /issm/trunk/externalpackages/neopz/install.sh
===================================================================
--- /issm/trunk/externalpackages/neopz/install.sh	(revision 22757)
+++ /issm/trunk/externalpackages/neopz/install.sh	(revision 22758)
@@ -23,12 +23,7 @@
 
 cd $PROJECT_SOURCE_DIR
-#Compile and install 
-if [ $# -eq 0 ]; then
-	make
-	make install
-else
-	make -j $1
-	make -j $1 install
-fi
+make
+make install
+
 cd $PROJECT_BINARY_DIR/pzlib
 mv lib ../
Index: /issm/trunk/externalpackages/petsc/install-3.6-discover.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.6-discover.sh	(revision 22757)
+++ /issm/trunk/externalpackages/petsc/install-3.6-discover.sh	(revision 22758)
@@ -21,7 +21,7 @@
 	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
 	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
-	--with-blas-lapack-dir="/usr/local/intel/Composer/composer_xe_2015.0.090/mkl/" \
-	--with-mpi-lib="/usr/local/intel/mpi/4.0.3.008/lib64/libmpi.so" \
-	--with-mpi-include="/usr/local/intel/mpi/4.0.3.008/intel64/include/" \
+	--with-blas-lapack-dir="/usr/local/intel/2016/compilers_and_libraries_2016.2.181/linux/mkl/" \
+	--with-mpi-lib="/usr/local/intel/2016/impi/5.1.3.181/lib64/libmpi.so" \
+	--with-mpi-include="/usr/local/intel/2016/impi/5.1.3.181/include64/" \
 	--known-mpi-shared-libraries=1 \
 	--with-debugging=0 \
@@ -42,5 +42,5 @@
 #SBATCH -N 1
 #SBATCH -n 1
-#SBATCH -A s1010
+#SBATCH -A s1690
 #SBATCH -t 00:01:00 # Run time (hh:mm:ss) - 1.5 hours
 #SBATCH --qos=debug
@@ -49,6 +49,7 @@
 
 . /usr/share/modules/init/bash
-module load comp/intel-15.0.0.090
-module load mpi/impi-4.0.3.008
+module load comp/intel-16.0.2.181
+module load mpi/impi-5.1.3.181
+module load other/cmake-3.8.2
 
 export PATH="$PATH:."
Index: /issm/trunk/externalpackages/petsc/install-3.7-aci.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.7-aci.sh	(revision 22758)
+++ /issm/trunk/externalpackages/petsc/install-3.7-aci.sh	(revision 22758)
@@ -0,0 +1,53 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.7.6 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.7.6.tar.gz' 'petsc-3.7.6.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.7.6.tar.gz
+mv petsc-3.7.6/* src/
+rm -rf petsc-3.7.6
+
+#configure
+cd src
+./config/configure.py \
+	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
+	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	--with-blas-lapack-dir="/opt/intel/compilers_and_libraries_2016.3.210/linux/mkl/lib/" \
+	--with-mpi-dir="/opt/intel/compilers_and_libraries_2016.3.210/linux/mpi/intel64/" \
+	--known-mpi-shared-libraries=1 \
+	--with-debugging=0 \
+	--with-valgrind=0 \
+	--with-x=0 \
+	--with-ssl=0 \
+	--with-batch=1  \
+	--with-shared-libraries=1 \
+	--download-metis=1 \
+	--download-parmetis=1 \
+	--download-mumps=1 \
+	--download-scalapack=1 
+
+#prepare script to reconfigure petsc
+cat > script.queue << EOF
+#PBS -A open
+#PBS -l nodes=1:ppn=1:stmem
+#PBS -l walltime=200 
+
+module load intel/16.0.3
+module load impi/5.1.3
+module load mkl/11.3.3
+
+export PATH="$PATH:." 
+cd $ISSM_DIR/externalpackages/petsc/src
+mpirun -np 1 ./conftest-arch-linux2-c-opt
+EOF
+
+#print instructions
+echo "== Now: cd src/ "
+echo "== qsub script.queue "
+echo "== Then run reconfigure script generated by PETSc and follow instructions"
Index: /issm/trunk/externalpackages/petsc/install-3.8-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.8-linux64.sh	(revision 22758)
+++ /issm/trunk/externalpackages/petsc/install-3.8-linux64.sh	(revision 22758)
@@ -0,0 +1,36 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.8.3 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.8.3.tar.gz' 'petsc-3.8.3.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.8.3.tar.gz
+mv petsc-3.8.3/* src/
+rm -rf petsc-3.8.3
+
+#configure
+cd src
+./config/configure.py \
+	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-mpi-dir="$ISSM_DIR/externalpackages/mpich/install" \
+	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	--with-debugging=1 \
+	--with-valgrind=0 \
+	--with-x=0 \
+	--with-ssl=0 \
+	--with-shared-libraries=1 \
+	--download-metis=1 \
+	--download-parmetis=1 \
+	--download-mumps=1 \
+	--download-scalapack=1 \
+	--download-fblaslapack=1 \
+	--with-pic=1
+
+#Compile and intall
+make
+make install
Index: /issm/trunk/externalpackages/petsc/install-3.8-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.8-macosx64.sh	(revision 22758)
+++ /issm/trunk/externalpackages/petsc/install-3.8-macosx64.sh	(revision 22758)
@@ -0,0 +1,34 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.8.3 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.8.3.tar.gz' 'petsc-3.8.3.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.8.3.tar.gz
+mv petsc-3.8.3/* src/
+rm -rf petsc-3.8.3
+
+#configure
+cd src
+./config/configure.py \
+	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-mpi-dir="$ISSM_DIR/externalpackages/mpich/install" \
+	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	--with-debugging=1 \
+	--with-valgrind=0 \
+	--with-x=0 \
+	--with-ssl=0 \
+	--with-shared-libraries=1 \
+	--download-metis=1 \
+	--download-parmetis=1 \
+	--download-mumps=1 \
+	--download-scalapack=1
+
+#Compile and intall
+make
+make install
Index: /issm/trunk/externalpackages/petsc/install-dev-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-dev-linux64.sh	(revision 22757)
+++ /issm/trunk/externalpackages/petsc/install-dev-linux64.sh	(revision 22758)
@@ -1,26 +1,17 @@
 #!/bin/bash
 
-STEP=1
+STEP=2
 
 if [ $STEP -eq 1 ]; then
-	# Used Mercurial to get code
 	rm -rf src
-	hg clone http://petsc.cs.iit.edu/petsc/petsc-dev src
-	cd src
-	hg clone http://petsc.cs.iit.edu/petsc/BuildSystem config/BuildSystem
+	git clone https://bitbucket.org/petsc/petsc src
 fi
 
-# To update (via Mercurial):
-#      cd petsc-dev
-#      hg pull -u
-#      cd config/BuildSystem
-#      hg pull -u
+# To update 
+#      cd src
+#      git pull
 
 # configure script
 # Note: 
-#  Metis: -using metis from externalpackages did not work...
-#         -for now download new metis
-#         -rename metis in externalpackages to metis2
-#
 # SuperLU: -If download-..-=yes does not work try downloading from
 #    --download-superlu=http://crd.lbl.gov/~xiaoye/SuperLU/superlu_4.3.tar.gz \
@@ -30,27 +21,26 @@
 	rm -rf install
 	cd src
-	./config/configure.py \
-	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
-	--with-mpi-dir="$ISSM_DIR/externalpackages/mpich/install" \
-	--with-clanguage=C++ \
-	--PETSC_ARCH=linux-gnu-amd64 \
-	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
-	--with-debugging=0 \
-	--with-shared-libraries=1 \
-	--download-mumps=yes \
-	--download-scalapack=yes \
-	--download-blacs=yes  \
-	--download-blas=yes \
-	--download-f-blas-lapack=yes \
-	--download-parmetis=yes \
-	--download-metis=yes \
-	--download-trilinos=yes \
-	--download-euclid=yes \
-	--download-spooles=yes \
-	--download-spai=yes \
-	--download-superlu=http://crd.lbl.gov/~xiaoye/SuperLU/superlu_4.3.tar.gz \
-	--download-hypre=yes \
-	--download-c2html=yes
-#	--with-pic=1
+	./configure \
+		--prefix="$ISSM_DIR/externalpackages/petsc/install" \
+		--with-mpi-dir="$ISSM_DIR/externalpackages/mpich/install" \
+		--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+		--with-debugging=1 \
+		--with-valgrind=0 \
+		--with-x=0 \
+		--with-ssl=0 \
+		--with-shared-libraries=1 \
+		--download-metis=1 \
+		--download-parmetis=1 \
+		--download-mumps=1 \
+		--download-scalapack=1 \
+		--download-fblaslapack=1 \
+		--with-pic=1
+
+#	--download-trilinos=yes \
+#	--download-euclid=yes \
+#	--download-spooles=yes \
+#	--download-spai=yes \
+#	--download-superlu=http://crd.lbl.gov/~xiaoye/SuperLU/superlu_4.3.tar.gz \
+#	--download-hypre=yes \
 
 	#Compile petsc and install it
Index: sm/trunk/externalpackages/python/install-2.7.3-macosx-lion.sh
===================================================================
--- /issm/trunk/externalpackages/python/install-2.7.3-macosx-lion.sh	(revision 22757)
+++ 	(revision )
@@ -1,40 +1,0 @@
-#!/bin/bash
-set -eu
-
-#Some cleanup
-rm -rf install src
-rm -rf Python-2.7.3
-mkdir install src
-
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py http://issm.jpl.nasa.gov/files/externalpackages/Python-2.7.3.tgz Python-2.7.3.tgz
-
-#Untar and move python into install directory
-tar -zxvf  Python-2.7.3.tgz
-mv Python-2.7.3/* src
-rm -rf Python-2.7.3
-
-#Configure and compile
-cd src 
-./configure \
- --enable-framework="$ISSM_DIR/externalpackages/python/install/Library/Frameworks" 
-if [ $# -eq 0 ]; then
-	make
-else
-	make -j $1
-fi
-make install
-
-cd ../install
-
-#get rid of bin, because it's just a copy of
-#Library/Frameworks/Python.framework/Versions/2.7/bin, and will not reflect
-#new changes being made
-rm -rf bin
-ln -s Library/Frameworks/Python.framework/Headers include
-ln -s Library/Frameworks/Python.framework/Versions/2.7/lib lib
-ln -s Library/Frameworks/Python.framework/Versions/2.7/bin bin
-
-#Patch pyport.h:
-cd include
-patch pyport.h $ISSM_DIR/externalpackages/python/patches/pyport.h.patch
Index: sm/trunk/externalpackages/python/install-2.7.3-macosx-mlion.sh
===================================================================
--- /issm/trunk/externalpackages/python/install-2.7.3-macosx-mlion.sh	(revision 22757)
+++ 	(revision )
@@ -1,40 +1,0 @@
-#!/bin/bash
-set -eu
-
-#Some cleanup
-rm -rf install src
-rm -rf Python-2.7.3
-mkdir install src
-
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py http://issm.jpl.nasa.gov/files/externalpackages/Python-2.7.3.tgz Python-2.7.3.tgz
-
-#Untar and move python into install directory
-tar -zxvf  Python-2.7.3.tgz
-mv Python-2.7.3/* src
-rm -rf Python-2.7.3
-
-#Configure and compile
-cd src 
-./configure \
- --enable-framework="$ISSM_DIR/externalpackages/python/install/Library/Frameworks" 
-if [ $# -eq 0 ]; then
-	make
-else
-	make -j $1
-fi
-make install
-
-cd ../install
-
-#get rid of bin, because it's just a copy of
-#Library/Frameworks/Python.framework/Versions/2.7/bin, and will not reflect
-#new changes being made
-rm -rf bin
-ln -s Library/Frameworks/Python.framework/Headers include
-ln -s Library/Frameworks/Python.framework/Versions/2.7/lib lib
-ln -s Library/Frameworks/Python.framework/Versions/2.7/bin bin
-
-#Patch pyport.h:
-cd include
-patch pyport.h $ISSM_DIR/externalpackages/python/patches/pyport.h.patch
Index: /issm/trunk/externalpackages/python/install-2.7.3-macosx.sh
===================================================================
--- /issm/trunk/externalpackages/python/install-2.7.3-macosx.sh	(revision 22758)
+++ /issm/trunk/externalpackages/python/install-2.7.3-macosx.sh	(revision 22758)
@@ -0,0 +1,40 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install src
+rm -rf Python-2.7.3
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py http://issm.jpl.nasa.gov/files/externalpackages/Python-2.7.3.tgz Python-2.7.3.tgz
+
+#Untar and move python into install directory
+tar -zxvf  Python-2.7.3.tgz
+mv Python-2.7.3/* src
+rm -rf Python-2.7.3
+
+#Configure and compile
+cd src 
+./configure \
+ --enable-framework="$ISSM_DIR/externalpackages/python/install/Library/Frameworks" 
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
+
+cd ../install
+
+#get rid of bin, because it's just a copy of
+#Library/Frameworks/Python.framework/Versions/2.7/bin, and will not reflect
+#new changes being made
+rm -rf bin
+ln -s Library/Frameworks/Python.framework/Headers include
+ln -s Library/Frameworks/Python.framework/Versions/2.7/lib lib
+ln -s Library/Frameworks/Python.framework/Versions/2.7/bin bin
+
+#Patch pyport.h:
+cd include
+patch pyport.h $ISSM_DIR/externalpackages/python/patches/pyport.h.patch
Index: sm/trunk/externalpackages/python/install-3.2.2-macosx-lion.sh
===================================================================
--- /issm/trunk/externalpackages/python/install-3.2.2-macosx-lion.sh	(revision 22757)
+++ 	(revision )
@@ -1,40 +1,0 @@
-#!/bin/bash
-set -eu
-
-#Some cleanup
-rm -rf install src
-rm -rf Python-3.2.2
-mkdir install src
-
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py http://issm.jpl.nasa.gov/files/externalpackages/Python-3.2.2.tgz Python-3.2.2.tgz
-
-#exports
-export CC
-
-#Untar and move python into install directory
-tar -zxvf  Python-3.2.2.tgz
-mv Python-3.2.2/* src
-rm -rf Python-3.2.2
-
-#Configure doxygen
-cd src 
-./configure \
- --enable-framework="$ISSM_DIR/externalpackages/python/install/Library/Frameworks" 
-
-#obsolete? 
-#./configure --prefix="$ISSM_DIR/externalpackages/python/install" --enable-framework="$ISSM_DIR/externalpackages/python/install"
-
-#make
-if [ $# -eq 0 ]; then
-	make
-else
-	make -j $1
-fi
-make install
-
-cd install/bin
-ln -s python3.2 python 
-cd ../
-ln -s Python.framework/Versions/3.2/include/python3.2m include
-ln -s Python.framework/Versions/3.2/lib/ lib
Index: /issm/trunk/externalpackages/python/install-3.2.2-macosx.sh
===================================================================
--- /issm/trunk/externalpackages/python/install-3.2.2-macosx.sh	(revision 22758)
+++ /issm/trunk/externalpackages/python/install-3.2.2-macosx.sh	(revision 22758)
@@ -0,0 +1,40 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install src
+rm -rf Python-3.2.2
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py http://issm.jpl.nasa.gov/files/externalpackages/Python-3.2.2.tgz Python-3.2.2.tgz
+
+#exports
+export CC
+
+#Untar and move python into install directory
+tar -zxvf  Python-3.2.2.tgz
+mv Python-3.2.2/* src
+rm -rf Python-3.2.2
+
+#Configure doxygen
+cd src 
+./configure \
+ --enable-framework="$ISSM_DIR/externalpackages/python/install/Library/Frameworks" 
+
+#obsolete? 
+#./configure --prefix="$ISSM_DIR/externalpackages/python/install" --enable-framework="$ISSM_DIR/externalpackages/python/install"
+
+#make
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
+
+cd install/bin
+ln -s python3.2 python 
+cd ../
+ln -s Python.framework/Versions/3.2/include/python3.2m include
+ln -s Python.framework/Versions/3.2/lib/ lib
Index: /issm/trunk/externalpackages/scotch/Makefile.inc.mac
===================================================================
--- /issm/trunk/externalpackages/scotch/Makefile.inc.mac	(revision 22758)
+++ /issm/trunk/externalpackages/scotch/Makefile.inc.mac	(revision 22758)
@@ -0,0 +1,26 @@
+EXE	=
+LIB	= .a
+OBJ	= .o
+MEX	= .mexa64
+
+MAKE	= make
+AR	= ar
+ARFLAGS	= -ruv
+CAT	= cat
+CCS	= gcc
+CCP     = mpicc
+CCD     = mpicc
+CCM	= ${MATLAB_DIR}/bin/mex
+#CFLAGS	= -m64 -O3 -std=c99 -DCOMMON_RANDOM_FIXED_SEED -DSCOTCH_RENAME -Du_int32_t=uint32_t -Du_int64_t=uint64_t -DCOMMON_TIMING_OLD -DMATLAB -fPIC -I${MATLAB_DIR}/extern/include
+CFLAGS	= -m64 -O3 -std=c99 -DCOMMON_RANDOM_FIXED_SEED -DSCOTCH_RENAME -Du_int32_t=uint32_t -Du_int64_t=uint64_t -DCOMMON_TIMING_OLD -fPIC
+#LDFLAGS	= -lz -lm -L${MATLAB_DIR}/bin/glnxa64 -lmex -lmat
+#LDFLAGS	= -lz -lm -Wl,-rpath-link,${MATLAB_DIR}/bin/glnxa64 -L${MATLAB_DIR}/bin/glnxa64 -lmex -lmat
+LDFLAGS	= -lz -lm 
+MFLAGS	= -DCOMMON_RANDOM_FIXED_SEED -DSCOTCH_RENAME -Du_int32_t=uint32_t -Du_int64_t=uint64_t -DCOMMON_TIMING_OLD -DNOFILEIO -DMATLAB -I${MATLAB_DIR}/extern/include -largeArrayDims
+CP	= cp
+LEX	= flex
+LN	= ln
+MKDIR	= mkdir
+MV	= mv
+RANLIB	= ranlib
+YACC	= yacc
Index: /issm/trunk/externalpackages/scotch/install_macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/scotch/install_macosx64.sh	(revision 22758)
+++ /issm/trunk/externalpackages/scotch/install_macosx64.sh	(revision 22758)
@@ -0,0 +1,57 @@
+#!/bin/bash
+set -eu
+
+# Some cleanup
+rm -rf scotch_5.1
+rm -rf src 
+rm -rf install 
+
+# Create src and install directories
+mkdir src install 
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/scotch_5.1.6.tar.gz' 'scotch_5.1.6.tar.gz'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/docs/ptscotch_user5.1.pdf' 'ptscotch_user5.1.pdf'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/docs/scotch_user5.1.pdf' 'scotch_user5.1.pdf'
+
+# Untar 
+tar -xvzf scotch_5.1.6.tar.gz
+
+# Apply patches (all at once, since many)
+# (written by diff -rc old_src new_src > scotch.patch)
+patch -p0 < scotch.patch
+
+# Move scotch to src directory
+mv scotch_5.1/* src
+rm -rf scotch_5.1
+
+# Build scotch
+cp -p Makefile.inc.mac src/src/Makefile.inc
+cp -p gmap_mex.c src/src/scotch
+cp -p gmapx.c src/src/scotch
+cd src/src
+# For stand-alone scotch modules:
+make scotch
+make clean
+# For no-file-io scotch modules:
+make nfioscotch
+# Clean up
+make clean
+cd ../..
+
+# Populate install directory
+cp -pr src/grf install
+cp -pr src/tgt install
+cp -pr src/doc install
+cp -pr src/man install
+mkdir install/include
+cp -p src/src/libscotch/module.h install/include/scotch_module.h
+cp -p src/src/libscotch/common.h install/include/scotch_common.h
+cp -p src/include/scotch.h install/include/
+cp -p src/src/scotch/gmap.h install/include/scotch_gmap.h
+mkdir install/lib
+mv src/lib/* install/lib
+mkdir install/bin
+mv src/bin/* install/bin
+#cp -p gmap.m install/bin
+#cp -p gpart.m install/bin
Index: /issm/trunk/externalpackages/scotch/scotch.patch
===================================================================
--- /issm/trunk/externalpackages/scotch/scotch.patch	(revision 22757)
+++ /issm/trunk/externalpackages/scotch/scotch.patch	(revision 22758)
@@ -2227,10 +2227,9 @@
 ***************
 *** 192,197 ****
---- 192,214 ----
+--- 192,213 ----
   stratParserInit (
   const char * const          string)               /*+ Strategy string to parse +*/
   {
 + /*  reset static variables from previous runs (jes, 4/29/10)  */
-+   yy_current_buffer = 0;
 +   yy_hold_char = (char) 0;
 +   yy_n_chars=0;          /* number of characters read into yy_ch_buf */
Index: /issm/trunk/externalpackages/triangle/install-javascript.sh
===================================================================
--- /issm/trunk/externalpackages/triangle/install-javascript.sh	(revision 22757)
+++ /issm/trunk/externalpackages/triangle/install-javascript.sh	(revision 22758)
@@ -1,4 +1,9 @@
 #!/bin/bash
 set -eu
+
+#Source emscripten to ensure emcc/em++ compiler are in env
+source $ISSM_DIR/externalpackages/emscripten/install/emsdk_env.sh
+export CC=emcc
+export CXX=em++
 
 #Some cleanup 
Index: /issm/trunk/externalpackages/valgrind/install-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/valgrind/install-linux64.sh	(revision 22757)
+++ /issm/trunk/externalpackages/valgrind/install-linux64.sh	(revision 22758)
@@ -3,26 +3,19 @@
 
 #Some cleanup
-rm -rf install valgrind-3.10.0
-mkdir install
+rm -rf install 
 
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.10.0.tar.bz2' 'valgrind-3.10.0.tar.bz2'
-
-#Untar 
-tar -jxvf  valgrind-3.10.0.tar.bz2
-
-#Move valgrind into install directory
-mv valgrind-3.10.0/* install
-rm -rf valgrind-3.10.0
+#Download development version
+git clone git://sourceware.org/git/valgrind.git install
 
 #configure
 cd install
-./configure  --prefix="$ISSM_DIR/externalpackages/valgrind/install"
+./autogen.sh
+./configure  --prefix="$ISSM_DIR/externalpackages/valgrind/install" --enable-only64bit
 
 #Compile valgrind
-make  -j 4
-make install
-
-#final thing: if mpi is compiled in, soft link its target to a simpler name
-cd lib
-ln -s valgrind/libmpiwrap-*  ./libmpidebug.so
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: sm/trunk/externalpackages/valgrind/install-macosx32.sh
===================================================================
--- /issm/trunk/externalpackages/valgrind/install-macosx32.sh	(revision 22757)
+++ 	(revision )
@@ -1,24 +1,0 @@
-#!/bin/bash
-set -eu
-
-#Some cleanup
-rm -rf install valgrind-3.10.0
-mkdir install
-
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.10.0.tar.bz2' 'valgrind-3.10.0.tar.bz2'
-
-#Untar 
-tar -jxvf  valgrind-3.10.0.tar.bz2
-
-#Move valgrind into install directory
-mv valgrind-3.10.0/* install
-rm -rf valgrind-3.10.0
-
-#configure
-cd install
-./configure  --prefix="$ISSM_DIR/externalpackages/valgrind/install" --enable-only32bit
-
-#Compile valgrind
-make  -j 4
-make install
Index: /issm/trunk/externalpackages/valgrind/install-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/valgrind/install-macosx64.sh	(revision 22757)
+++ /issm/trunk/externalpackages/valgrind/install-macosx64.sh	(revision 22758)
@@ -6,5 +6,5 @@
 
 #Download development version, the current release never supports the latest OS X releases
-svn co svn://svn.valgrind.org/valgrind/trunk install
+git clone git://sourceware.org/git/valgrind.git install
 
 #configure
@@ -14,5 +14,8 @@
 
 #Compile valgrind
-
-make  -j 8
-make install
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: /issm/trunk/externalpackages/valgrind/issm.supp
===================================================================
--- /issm/trunk/externalpackages/valgrind/issm.supp	(revision 22757)
+++ /issm/trunk/externalpackages/valgrind/issm.supp	(revision 22758)
@@ -51,4 +51,39 @@
 	  obj:/lib/x86_64-linux-gnu/ld-2.15.so
 	  obj:*
+	  obj:*
+	  obj:*
+	  obj:*
+	  obj:*
+}
+{
+	<OS3>
+	  Memcheck:Cond
+	  fun:index
+	  fun:expand_dynamic_string_token
+	  fun:_dl_map_object
+	  fun:map_doit
+	  fun:_dl_catch_error
+	  fun:do_preload
+	  fun:handle_ld_preload
+	  fun:dl_main
+	  fun:_dl_sysdep_start
+	  fun:_dl_start_final
+	  fun:_dl_start
+	  obj:/lib/x86_64-linux-gnu/ld-2.19.so
+	  obj:*
+	  obj:*
+}
+{
+	<OS4>
+	  Memcheck:Cond
+	  fun:index
+	  fun:expand_dynamic_string_token
+	  fun:fillin_rpath
+	  fun:_dl_init_paths
+	  fun:dl_main
+	  fun:_dl_sysdep_start
+	  fun:_dl_start_final
+	  fun:_dl_start
+	  obj:/lib/x86_64-linux-gnu/ld-2.19.so
 	  obj:*
 	  obj:*
@@ -259,3 +294,35 @@
 	  fun:dmumps_f77_
 }
+{
+	<mumps16>
+	  Memcheck:Cond
+	  fun:MPIC_Waitall
+	  fun:MPIR_Alltoall_intra
+	  fun:MPIR_Alltoall
+	  fun:MPIR_Alltoall_impl
+	  fun:PMPI_Alltoall
+	  fun:PMPI_ALLTOALL
+	  fun:__dmumps_parallel_analysis_MOD_dmumps_build_dist_graph
+	  fun:__dmumps_parallel_analysis_MOD_dmumps_parmetis_ord
+	  fun:__dmumps_parallel_analysis_MOD_dmumps_do_par_ord
+	  fun:__dmumps_parallel_analysis_MOD_dmumps_ana_f_par
+	  fun:dmumps_ana_driver_
+	  fun:dmumps_
+}
+{
+	<iparmetis1>
+	  Memcheck:Cond
+	  fun:MPIC_Waitall
+	  fun:MPIR_Scatterv
+	  fun:MPIR_Scatterv_impl
+	  fun:PMPI_Scatterv
+	  fun:libparmetis__gkMPI_Scatterv
+	  fun:libparmetis__InitMultisection
+	  fun:libparmetis__Order_Partition
+	  fun:libparmetis__Order_Partition_Multiple
+	  fun:libparmetis__MultilevelOrder
+	  fun:ParMETIS_V32_NodeND
+	  fun:ParMETIS_V3_NodeND
+	  fun:mumps_parmetis_
+}
 #}}}
Index: /issm/trunk/externalpackages/vim/addons/vim/syntax/c.vim
===================================================================
--- /issm/trunk/externalpackages/vim/addons/vim/syntax/c.vim	(revision 22757)
+++ /issm/trunk/externalpackages/vim/addons/vim/syntax/c.vim	(revision 22758)
@@ -410,4 +410,6 @@
 
 "ISSM's objects begin
+syn keyword cType AdaptiveMeshRefinement
+syn keyword cType AmrBamg
 syn keyword cType BoolInput
 syn keyword cType BoolParam
@@ -472,4 +474,5 @@
 syn keyword cType Matestar
 syn keyword cType Matice
+syn keyword cType Matlitho
 syn keyword cType Matpar
 syn keyword cType matrixobjects
@@ -481,4 +484,5 @@
 syn keyword cType Node
 syn keyword cType Nodes
+syn keyword cType Numberedcostfunction
 syn keyword cType Numericalflux
 syn keyword cType Observation
@@ -497,4 +501,5 @@
 syn keyword cType Profiler
 syn keyword cType Quadtree
+syn keyword cType Regionaloutput
 syn keyword cType Results
 syn keyword cType Riftfront
@@ -513,4 +518,5 @@
 syn keyword cType TetraInput
 syn keyword cType TetraRef
+syn keyword cType TransientArrayParam
 syn keyword cType TransientInput
 syn keyword cType TransientParam
@@ -535,4 +541,5 @@
 syn keyword cType EnthalpyAnalysis
 syn keyword cType EnumToAnalysis
+syn keyword cType EsaAnalysis
 syn keyword cType ExtrapolationAnalysis
 syn keyword cType ExtrudeFromBaseAnalysis
@@ -540,5 +547,5 @@
 syn keyword cType FreeSurfaceBaseAnalysis
 syn keyword cType FreeSurfaceTopAnalysis
-syn keyword cType GiaAnalysis
+syn keyword cType GiaIvinsAnalysis
 syn keyword cType HydrologyDCEfficientAnalysis
 syn keyword cType HydrologyDCInefficientAnalysis
@@ -548,8 +555,7 @@
 syn keyword cType L2ProjectionEPLAnalysis
 syn keyword cType LevelsetAnalysis
-syn keyword cType LsfReinitializationAnalysis
+syn keyword cType LoveAnalysis
 syn keyword cType MasstransportAnalysis
 syn keyword cType MeltingAnalysis
-syn keyword cType MeshdeformationAnalysis
 syn keyword cType SealevelriseAnalysis
 syn keyword cType SmbAnalysis
@@ -562,24 +568,35 @@
 "ISSM's objects end
 "ISSM's Enums begin
+syn keyword cConstant FemModelEnum
 syn keyword cConstant ParametersSTARTEnum
-syn keyword cConstant FemModelEnum
+syn keyword cConstant AdolcParamEnum
+syn keyword cConstant FSSolverEnum
 syn keyword cConstant FemModelCommEnum
 syn keyword cConstant WorldCommEnum
 syn keyword cConstant IcecapToEarthCommEnum
+syn keyword cConstant ToMITgcmCommEnum
 syn keyword cConstant NumModelsEnum
 syn keyword cConstant ModelIdEnum
 syn keyword cConstant EarthIdEnum
+syn keyword cConstant SolutionTypeEnum
+syn keyword cConstant AnalysisTypeEnum
+syn keyword cConstant AnalysisCounterEnum
+syn keyword cConstant ConfigurationTypeEnum
+syn keyword cConstant InputToExtrudeEnum
+syn keyword cConstant InputToL2ProjectEnum
+syn keyword cConstant InputToDepthaverageInEnum
+syn keyword cConstant InputToDepthaverageOutEnum
+syn keyword cConstant InputToSmoothEnum
+syn keyword cConstant SmoothThicknessMultiplierEnum
+syn keyword cConstant LevelsetStabilizationEnum
+syn keyword cConstant TimesteppingTypeEnum
+syn keyword cConstant FixedTimesteppingEnum
+syn keyword cConstant AdaptiveTimesteppingEnum
+syn keyword cConstant TimesteppingTimeStepMinEnum
+syn keyword cConstant TimesteppingTimeStepMaxEnum
 syn keyword cConstant AutodiffIsautodiffEnum
 syn keyword cConstant AutodiffNumDependentsEnum
-syn keyword cConstant AutodiffNumDependentObjectsEnum
-syn keyword cConstant AutodiffDependentObjectNamesEnum
-syn keyword cConstant AutodiffDependentObjectTypesEnum
-syn keyword cConstant AutodiffDependentObjectIndicesEnum
 syn keyword cConstant AutodiffDependentObjectsEnum
 syn keyword cConstant AutodiffNumIndependentsEnum
-syn keyword cConstant AutodiffNumIndependentObjectsEnum
-syn keyword cConstant AutodiffIndependentObjectNamesEnum
-syn keyword cConstant AutodiffIndependentObjectTypesEnum
-syn keyword cConstant AutodiffIndependentObjectsEnum
 syn keyword cConstant AutodiffJacobianEnum
 syn keyword cConstant AutodiffXpEnum
@@ -588,5 +605,4 @@
 syn keyword cConstant AutodiffFovForwardIndicesEnum
 syn keyword cConstant AutodiffFosReverseIndexEnum
-syn keyword cConstant AutodiffMassFluxSegmentsPresentEnum
 syn keyword cConstant AutodiffKeepEnum
 syn keyword cConstant AutodiffObufsizeEnum
@@ -596,5 +612,4 @@
 syn keyword cConstant AutodiffGcTriggerRatioEnum
 syn keyword cConstant AutodiffGcTriggerMaxSizeEnum
-syn keyword cConstant BalancethicknessSpcthicknessEnum
 syn keyword cConstant BalancethicknessStabilizationEnum
 syn keyword cConstant BalancethicknessThickeningRateEnum
@@ -625,4 +640,15 @@
 syn keyword cConstant MismipFloatingMeltRateEnum
 syn keyword cConstant MantlePlumeGeothermalFluxEnum
+syn keyword cConstant BasalforcingsPicoEnum
+syn keyword cConstant BasalforcingsPicoNumBasinsEnum
+syn keyword cConstant BasalforcingsPicoBasinIdEnum
+syn keyword cConstant BasalforcingsPicoMaxboxcountEnum
+syn keyword cConstant BasalforcingsPicoBoxIdEnum
+syn keyword cConstant BasalforcingsPicoOverturningCoeffEnum
+syn keyword cConstant BasalforcingsPicoGammaTEnum
+syn keyword cConstant BasalforcingsPicoFarOceantemperatureEnum
+syn keyword cConstant BasalforcingsPicoFarOceansalinityEnum
+syn keyword cConstant DistanceToGroundinglineEnum
+syn keyword cConstant DistanceToCalvingfrontEnum
 syn keyword cConstant BedEnum
 syn keyword cConstant BaseEnum
@@ -636,25 +662,15 @@
 syn keyword cConstant StressbalanceMaxiterEnum
 syn keyword cConstant StressbalancePenaltyFactorEnum
-syn keyword cConstant StressbalanceReferentialEnum
 syn keyword cConstant StressbalanceReltolEnum
 syn keyword cConstant StressbalanceNumRequestedOutputsEnum
 syn keyword cConstant StressbalanceRequestedOutputsEnum
 syn keyword cConstant StressbalanceRestolEnum
-syn keyword cConstant StressbalanceRiftPenaltyLockEnum
 syn keyword cConstant StressbalanceRiftPenaltyThresholdEnum
 syn keyword cConstant StressbalanceShelfDampeningEnum
-syn keyword cConstant StressbalanceSpcvxEnum
-syn keyword cConstant StressbalanceSpcvyEnum
-syn keyword cConstant StressbalanceSpcvzEnum
 syn keyword cConstant StressbalanceFSreconditioningEnum
-syn keyword cConstant StressbalanceVertexPairingEnum
 syn keyword cConstant StressbalanceViscosityOvershootEnum
 syn keyword cConstant LoadingforceXEnum
 syn keyword cConstant LoadingforceYEnum
 syn keyword cConstant LoadingforceZEnum
-syn keyword cConstant FlowequationBorderSSAEnum
-syn keyword cConstant FlowequationBorderHOEnum
-syn keyword cConstant FlowequationBorderFSEnum
-syn keyword cConstant FlowequationElementEquationEnum
 syn keyword cConstant FlowequationIsSIAEnum
 syn keyword cConstant FlowequationIsSSAEnum
@@ -662,11 +678,10 @@
 syn keyword cConstant FlowequationIsHOEnum
 syn keyword cConstant FlowequationIsFSEnum
-syn keyword cConstant FlowequationFeSSAEnum
-syn keyword cConstant FlowequationFeHOEnum
 syn keyword cConstant FlowequationFeFSEnum
-syn keyword cConstant FlowequationVertexEquationEnum
+syn keyword cConstant FlowequationBorderFSEnum
 syn keyword cConstant FrictionAsEnum
 syn keyword cConstant FrictionCoefficientEnum
 syn keyword cConstant FrictionCoefficientcoulombEnum
+syn keyword cConstant FrictionPressureAdjustedTemperatureEnum
 syn keyword cConstant FrictionPEnum
 syn keyword cConstant FrictionQEnum
@@ -681,14 +696,23 @@
 syn keyword cConstant GeometryHydrostaticRatioEnum
 syn keyword cConstant HydrologyModelEnum
+syn keyword cConstant HydrologyNumRequestedOutputsEnum
+syn keyword cConstant HydrologyRequestedOutputsEnum
 syn keyword cConstant HydrologyshreveEnum
-syn keyword cConstant HydrologyshreveSpcwatercolumnEnum
 syn keyword cConstant HydrologyshreveStabilizationEnum
 syn keyword cConstant HydrologydcEnum
+syn keyword cConstant HydrologydtEnum
+syn keyword cConstant HydrologyStepsPerStepEnum
 syn keyword cConstant SedimentHeadEnum
 syn keyword cConstant SedimentHeadOldEnum
+syn keyword cConstant SedimentHeadStackedEnum
+syn keyword cConstant SedimentHeadTimeAverageEnum
 syn keyword cConstant SedimentHeadResidualEnum
 syn keyword cConstant EffectivePressureEnum
+syn keyword cConstant EffectivePressureStackedEnum
+syn keyword cConstant EffectivePressureTimeAverageEnum
 syn keyword cConstant EplHeadEnum
 syn keyword cConstant EplHeadOldEnum
+syn keyword cConstant EplHeadStackedEnum
+syn keyword cConstant EplHeadTimeAverageEnum
 syn keyword cConstant EplHeadSlopeXEnum
 syn keyword cConstant EplHeadSlopeYEnum
@@ -696,5 +720,4 @@
 syn keyword cConstant HydrologydcMaxIterEnum
 syn keyword cConstant HydrologydcRelTolEnum
-syn keyword cConstant HydrologydcSpcsedimentHeadEnum
 syn keyword cConstant HydrologydcSedimentCompressibilityEnum
 syn keyword cConstant HydrologydcSedimentPorosityEnum
@@ -702,5 +725,4 @@
 syn keyword cConstant HydrologydcSedimentTransmitivityEnum
 syn keyword cConstant HydrologydcWaterCompressibilityEnum
-syn keyword cConstant HydrologydcSpceplHeadEnum
 syn keyword cConstant HydrologydcMaskEplactiveNodeEnum
 syn keyword cConstant HydrologydcMaskEplactiveEltEnum
@@ -712,4 +734,6 @@
 syn keyword cConstant HydrologydcEplThicknessEnum
 syn keyword cConstant HydrologydcEplThicknessOldEnum
+syn keyword cConstant HydrologydcEplThicknessStackedEnum
+syn keyword cConstant HydrologydcEplThicknessTimeAverageEnum
 syn keyword cConstant HydrologydcEplThickCompEnum
 syn keyword cConstant HydrologydcEplConductivityEnum
@@ -718,4 +742,5 @@
 syn keyword cConstant HydrologydcSedimentlimitEnum
 syn keyword cConstant HydrologydcTransferFlagEnum
+syn keyword cConstant HydrologydcUnconfinedFlagEnum
 syn keyword cConstant HydrologydcLeakageFactorEnum
 syn keyword cConstant HydrologydcPenaltyFactorEnum
@@ -723,10 +748,8 @@
 syn keyword cConstant HydrologydcEplflipLockEnum
 syn keyword cConstant HydrologydcBasalMoulinInputEnum
-syn keyword cConstant HydrologyLayerEnum
-syn keyword cConstant HydrologySedimentEnum
-syn keyword cConstant HydrologyEfficientEnum
 syn keyword cConstant HydrologySedimentKmaxEnum
 syn keyword cConstant HydrologysommersEnum
 syn keyword cConstant HydrologyHeadEnum
+syn keyword cConstant HydrologyHeadOldEnum
 syn keyword cConstant HydrologyGapHeightEnum
 syn keyword cConstant HydrologyBumpSpacingEnum
@@ -736,6 +759,8 @@
 syn keyword cConstant HydrologyReynoldsEnum
 syn keyword cConstant HydrologyNeumannfluxEnum
-syn keyword cConstant HydrologySpcheadEnum
-syn keyword cConstant HydrologyConductivityEnum
+syn keyword cConstant HydrologyRelaxationEnum
+syn keyword cConstant HydrologyBasalFluxEnum
+syn keyword cConstant HydrologyStorageEnum
+syn keyword cConstant DegreeOfChannelizationEnum
 syn keyword cConstant InversionControlParametersEnum
 syn keyword cConstant InversionControlScalingFactorsEnum
@@ -747,5 +772,4 @@
 syn keyword cConstant InversionTypeEnum
 syn keyword cConstant InversionIncompleteAdjointEnum
-syn keyword cConstant InversionMaxParametersEnum
 syn keyword cConstant InversionMaxiterPerStepEnum
 syn keyword cConstant InversionMaxiterEnum
@@ -757,5 +781,4 @@
 syn keyword cConstant InversionGttolEnum
 syn keyword cConstant InversionAlgorithmEnum
-syn keyword cConstant InversionMinParametersEnum
 syn keyword cConstant InversionNstepsEnum
 syn keyword cConstant InversionDxminEnum
@@ -768,4 +791,5 @@
 syn keyword cConstant InversionVyObsEnum
 syn keyword cConstant InversionVzObsEnum
+syn keyword cConstant InversionVelObsEnum
 syn keyword cConstant MaskIceLevelsetEnum
 syn keyword cConstant MaskOceanLevelsetEnum
@@ -780,11 +804,10 @@
 syn keyword cConstant MaterialsRheologyLawEnum
 syn keyword cConstant MaterialsRheologyNEnum
-syn keyword cConstant MaterialsRheologyKoEnum
-syn keyword cConstant MaterialsRheologyKobarEnum
+syn keyword cConstant MaterialsRheologyEEnum
+syn keyword cConstant MaterialsRheologyEbarEnum
 syn keyword cConstant MaterialsRheologyEcEnum
 syn keyword cConstant MaterialsRheologyEcbarEnum
 syn keyword cConstant MaterialsRheologyEsEnum
 syn keyword cConstant MaterialsRheologyEsbarEnum
-syn keyword cConstant DamageIsdamageEnum
 syn keyword cConstant DamageDEnum
 syn keyword cConstant DamageFEnum
@@ -801,5 +824,4 @@
 syn keyword cConstant DamageStabilizationEnum
 syn keyword cConstant DamageMaxiterEnum
-syn keyword cConstant DamageSpcdamageEnum
 syn keyword cConstant DamageMaxDamageEnum
 syn keyword cConstant DamageEquivStressEnum
@@ -812,9 +834,16 @@
 syn keyword cConstant CalvingCalvingrateEnum
 syn keyword cConstant CalvingMeltingrateEnum
+syn keyword cConstant CalvingHeightAboveFloatationEnum
 syn keyword cConstant CalvingLevermannEnum
-syn keyword cConstant CalvingDevEnum
+syn keyword cConstant CalvingVonmisesEnum
 syn keyword cConstant CalvingMinthicknessEnum
+syn keyword cConstant CalvingHabEnum
+syn keyword cConstant CalvingCrevasseDepthEnum
+syn keyword cConstant CalvingDev2Enum
+syn keyword cConstant SurfaceCrevasseEnum
+syn keyword cConstant BasalCrevasseEnum
+syn keyword cConstant CrevasseDepthEnum
+syn keyword cConstant WaterheightEnum
 syn keyword cConstant DefaultCalvingEnum
-syn keyword cConstant CalvingRequestedOutputsEnum
 syn keyword cConstant CalvinglevermannCoeffEnum
 syn keyword cConstant CalvinglevermannMeltingrateEnum
@@ -824,4 +853,8 @@
 syn keyword cConstant CalvingratexAverageEnum
 syn keyword cConstant CalvingrateyAverageEnum
+syn keyword cConstant CalvingStressThresholdGroundediceEnum
+syn keyword cConstant CalvingStressThresholdFloatingiceEnum
+syn keyword cConstant CalvingMaxEnum
+syn keyword cConstant SigmaVMEnum
 syn keyword cConstant StrainRateparallelEnum
 syn keyword cConstant StrainRateperpendicularEnum
@@ -840,24 +873,18 @@
 syn keyword cConstant MaterialsEarthDensityEnum
 syn keyword cConstant MeshAverageVertexConnectivityEnum
-syn keyword cConstant MeshElements2dEnum
+syn keyword cConstant MeshLatEnum
+syn keyword cConstant MeshLongEnum
+syn keyword cConstant MeshXEnum
+syn keyword cConstant MeshYEnum
+syn keyword cConstant MeshZEnum
+syn keyword cConstant MeshScaleFactorEnum
 syn keyword cConstant MeshElementsEnum
-syn keyword cConstant MeshLowerelementsEnum
-syn keyword cConstant MeshNumberofelements2dEnum
 syn keyword cConstant MeshNumberofelementsEnum
 syn keyword cConstant MeshNumberoflayersEnum
-syn keyword cConstant MeshNumberofvertices2dEnum
 syn keyword cConstant MeshNumberofverticesEnum
-syn keyword cConstant MeshUpperelementsEnum
 syn keyword cConstant MeshVertexonbaseEnum
 syn keyword cConstant MeshVertexonsurfaceEnum
 syn keyword cConstant MeshVertexonboundaryEnum
-syn keyword cConstant MeshXEnum
-syn keyword cConstant MeshYEnum
-syn keyword cConstant MeshZEnum
-syn keyword cConstant MeshLatEnum
-syn keyword cConstant MeshLongEnum
-syn keyword cConstant MeshREnum
 syn keyword cConstant MeshElementtypeEnum
-syn keyword cConstant MeshSegmentsEnum
 syn keyword cConstant DomainTypeEnum
 syn keyword cConstant DomainDimensionEnum
@@ -866,5 +893,4 @@
 syn keyword cConstant Domain3DEnum
 syn keyword cConstant Domain3DsurfaceEnum
-syn keyword cConstant MiscellaneousNameEnum
 syn keyword cConstant MasstransportHydrostaticAdjustmentEnum
 syn keyword cConstant MasstransportIsfreesurfaceEnum
@@ -873,5 +899,4 @@
 syn keyword cConstant MasstransportSpcthicknessEnum
 syn keyword cConstant MasstransportStabilizationEnum
-syn keyword cConstant MasstransportVertexPairingEnum
 syn keyword cConstant MasstransportNumRequestedOutputsEnum
 syn keyword cConstant MasstransportRequestedOutputsEnum
@@ -879,5 +904,4 @@
 syn keyword cConstant MassFluxSegmentsEnum
 syn keyword cConstant MassFluxSegmentsPresentEnum
-syn keyword cConstant QmuMassFluxSegmentsPresentEnum
 syn keyword cConstant QmuNumberofpartitionsEnum
 syn keyword cConstant QmuNumberofresponsesEnum
@@ -885,6 +909,4 @@
 syn keyword cConstant QmuResponsedescriptorsEnum
 syn keyword cConstant QmuVariabledescriptorsEnum
-syn keyword cConstant RiftsNumriftsEnum
-syn keyword cConstant RiftsRiftstructEnum
 syn keyword cConstant SettingsResultsOnNodesEnum
 syn keyword cConstant SettingsIoGatherEnum
@@ -893,4 +915,5 @@
 syn keyword cConstant SettingsRecordingFrequencyEnum
 syn keyword cConstant SettingsWaitonlockEnum
+syn keyword cConstant SettingsSolverResidueThresholdEnum
 syn keyword cConstant DebugProfilingEnum
 syn keyword cConstant ProfilingCurrentMemEnum
@@ -922,6 +945,8 @@
 syn keyword cConstant TimesteppingTimeStepEnum
 syn keyword cConstant TimesteppingInterpForcingsEnum
+syn keyword cConstant TimesteppingCouplingTimeEnum
 syn keyword cConstant TransientIssmbEnum
 syn keyword cConstant TransientIscouplerEnum
+syn keyword cConstant TransientIsoceancouplingEnum
 syn keyword cConstant TransientIsstressbalanceEnum
 syn keyword cConstant TransientIsgroundinglineEnum
@@ -929,4 +954,5 @@
 syn keyword cConstant TransientIsthermalEnum
 syn keyword cConstant TransientIsgiaEnum
+syn keyword cConstant TransientIsesaEnum
 syn keyword cConstant TransientIsdamageevolutionEnum
 syn keyword cConstant TransientIshydrologyEnum
@@ -935,11 +961,9 @@
 syn keyword cConstant TransientNumRequestedOutputsEnum
 syn keyword cConstant TransientRequestedOutputsEnum
-syn keyword cConstant PotentialEnum
-syn keyword cConstant BalancethicknessSpcpotentialEnum
+syn keyword cConstant BalancethicknessSpcthicknessEnum
 syn keyword cConstant BalancethicknessApparentMassbalanceEnum
-syn keyword cConstant Balancethickness2MisfitEnum
 syn keyword cConstant BalancethicknessDiffusionCoefficientEnum
-syn keyword cConstant BalancethicknessCmuEnum
 syn keyword cConstant BalancethicknessOmegaEnum
+syn keyword cConstant BalancethicknessOmega0Enum
 syn keyword cConstant BalancethicknessD0Enum
 syn keyword cConstant SmbEnum
@@ -949,4 +973,14 @@
 syn keyword cConstant SmbRequestedOutputsEnum
 syn keyword cConstant SmbIsInitializedEnum
+syn keyword cConstant SmbDziniEnum
+syn keyword cConstant SmbDiniEnum
+syn keyword cConstant SmbReiniEnum
+syn keyword cConstant SmbGdniniEnum
+syn keyword cConstant SmbGspiniEnum
+syn keyword cConstant SmbECiniEnum
+syn keyword cConstant SmbWiniEnum
+syn keyword cConstant SmbAiniEnum
+syn keyword cConstant SmbTiniEnum
+syn keyword cConstant SmbSizeiniEnum
 syn keyword cConstant SMBforcingEnum
 syn keyword cConstant SmbMassBalanceEnum
@@ -958,5 +992,4 @@
 syn keyword cConstant SmbDlwrfEnum
 syn keyword cConstant SmbPEnum
-syn keyword cConstant SmbSwfEnum
 syn keyword cConstant SmbEAirEnum
 syn keyword cConstant SmbPAirEnum
@@ -988,8 +1021,9 @@
 syn keyword cConstant SmbGspEnum
 syn keyword cConstant SmbECEnum
-syn keyword cConstant SmbCondensationEnum
 syn keyword cConstant SmbWEnum
 syn keyword cConstant SmbAEnum
 syn keyword cConstant SmbTEnum
+syn keyword cConstant SmbAValueEnum
+syn keyword cConstant SmbTeValueEnum
 syn keyword cConstant SmbIsgraingrowthEnum
 syn keyword cConstant SmbIsalbedoEnum
@@ -1000,8 +1034,11 @@
 syn keyword cConstant SmbIsdensificationEnum
 syn keyword cConstant SmbIsturbulentfluxEnum
+syn keyword cConstant SmbDz_addEnum
+syn keyword cConstant SmbM_addEnum
 syn keyword cConstant SMBpddEnum
 syn keyword cConstant SmbDelta18oEnum
 syn keyword cConstant SmbDelta18oSurfaceEnum
 syn keyword cConstant SmbIsdelta18oEnum
+syn keyword cConstant SmbIssetpddfacEnum
 syn keyword cConstant SmbIsmungsmEnum
 syn keyword cConstant SmbIsd18opdEnum
@@ -1011,4 +1048,6 @@
 syn keyword cConstant SmbTemperaturesLgmEnum
 syn keyword cConstant SmbPrecipitationEnum
+syn keyword cConstant SmbPddfacSnowEnum
+syn keyword cConstant SmbPddfacIceEnum
 syn keyword cConstant SmbDesfacEnum
 syn keyword cConstant SmbS0pEnum
@@ -1021,4 +1060,5 @@
 syn keyword cConstant SMBd18opddEnum
 syn keyword cConstant SmbDpermilEnum
+syn keyword cConstant SmbFEnum
 syn keyword cConstant SMBgradientsEnum
 syn keyword cConstant SmbMonthlytemperaturesEnum
@@ -1036,167 +1076,8 @@
 syn keyword cConstant SmbRefreezeEnum
 syn keyword cConstant SMBgcmEnum
-syn keyword cConstant SmbIspddEnum
-syn keyword cConstant SmbIssmbgradientsEnum
-syn keyword cConstant SolutionTypeEnum
-syn keyword cConstant AnalysisTypeEnum
-syn keyword cConstant ConfigurationTypeEnum
-syn keyword cConstant AdjointBalancethicknessAnalysisEnum
-syn keyword cConstant AdjointBalancethickness2AnalysisEnum
-syn keyword cConstant AdjointHorizAnalysisEnum
-syn keyword cConstant AnalysisCounterEnum
-syn keyword cConstant DefaultAnalysisEnum
-syn keyword cConstant BalancethicknessAnalysisEnum
-syn keyword cConstant BalancethicknessSolutionEnum
-syn keyword cConstant Balancethickness2AnalysisEnum
-syn keyword cConstant Balancethickness2SolutionEnum
-syn keyword cConstant BalancethicknessSoftAnalysisEnum
-syn keyword cConstant BalancethicknessSoftSolutionEnum
-syn keyword cConstant BalancevelocityAnalysisEnum
-syn keyword cConstant BalancevelocitySolutionEnum
-syn keyword cConstant L2ProjectionEPLAnalysisEnum
-syn keyword cConstant L2ProjectionBaseAnalysisEnum
-syn keyword cConstant BedSlopeSolutionEnum
-syn keyword cConstant DamageEvolutionSolutionEnum
-syn keyword cConstant DamageEvolutionAnalysisEnum
-syn keyword cConstant StressbalanceAnalysisEnum
-syn keyword cConstant StressbalanceSIAAnalysisEnum
-syn keyword cConstant StressbalanceSolutionEnum
-syn keyword cConstant StressbalanceVerticalAnalysisEnum
-syn keyword cConstant EnthalpyAnalysisEnum
-syn keyword cConstant FlaimAnalysisEnum
-syn keyword cConstant FlaimSolutionEnum
-syn keyword cConstant HydrologyShreveAnalysisEnum
-syn keyword cConstant HydrologyDCInefficientAnalysisEnum
-syn keyword cConstant HydrologyDCEfficientAnalysisEnum
-syn keyword cConstant HydrologySommersAnalysisEnum
-syn keyword cConstant HydrologySolutionEnum
-syn keyword cConstant MeltingAnalysisEnum
-syn keyword cConstant MasstransportAnalysisEnum
-syn keyword cConstant MasstransportSolutionEnum
-syn keyword cConstant FreeSurfaceBaseAnalysisEnum
-syn keyword cConstant FreeSurfaceTopAnalysisEnum
-syn keyword cConstant SurfaceNormalVelocityEnum
-syn keyword cConstant ExtrudeFromBaseAnalysisEnum
-syn keyword cConstant ExtrudeFromTopAnalysisEnum
-syn keyword cConstant DepthAverageAnalysisEnum
-syn keyword cConstant SteadystateSolutionEnum
-syn keyword cConstant SurfaceSlopeSolutionEnum
-syn keyword cConstant SmoothAnalysisEnum
-syn keyword cConstant ThermalAnalysisEnum
-syn keyword cConstant ThermalSolutionEnum
-syn keyword cConstant TransientSolutionEnum
-syn keyword cConstant UzawaPressureAnalysisEnum
-syn keyword cConstant GiaSolutionEnum
-syn keyword cConstant GiaAnalysisEnum
-syn keyword cConstant MeshdeformationSolutionEnum
-syn keyword cConstant MeshdeformationAnalysisEnum
-syn keyword cConstant LevelsetAnalysisEnum
-syn keyword cConstant LevelsetStabilizationEnum
-syn keyword cConstant ExtrapolationAnalysisEnum
-syn keyword cConstant LsfReinitializationAnalysisEnum
-syn keyword cConstant ApproximationEnum
-syn keyword cConstant NoneApproximationEnum
-syn keyword cConstant SIAApproximationEnum
-syn keyword cConstant SSAApproximationEnum
-syn keyword cConstant SSAHOApproximationEnum
-syn keyword cConstant SSAFSApproximationEnum
-syn keyword cConstant L1L2ApproximationEnum
-syn keyword cConstant HOApproximationEnum
-syn keyword cConstant HOFSApproximationEnum
-syn keyword cConstant FSApproximationEnum
-syn keyword cConstant FSvelocityEnum
-syn keyword cConstant FSpressureEnum
-syn keyword cConstant DataSetEnum
-syn keyword cConstant ConstraintsEnum
-syn keyword cConstant LoadsEnum
-syn keyword cConstant MaterialsEnum
-syn keyword cConstant NodesEnum
-syn keyword cConstant ContoursEnum
-syn keyword cConstant ParametersEnum
-syn keyword cConstant VerticesEnum
-syn keyword cConstant ResultsEnum
-syn keyword cConstant GenericParamEnum
-syn keyword cConstant AdolcParamEnum
-syn keyword cConstant BoolInputEnum
-syn keyword cConstant BoolParamEnum
-syn keyword cConstant ContourEnum
-syn keyword cConstant ControlInputEnum
-syn keyword cConstant DatasetInputEnum
-syn keyword cConstant DoubleInputEnum
-syn keyword cConstant DoubleArrayInputEnum
-syn keyword cConstant DataSetParamEnum
-syn keyword cConstant DoubleMatArrayParamEnum
-syn keyword cConstant DoubleMatParamEnum
-syn keyword cConstant DoubleParamEnum
-syn keyword cConstant DoubleVecParamEnum
-syn keyword cConstant ElementEnum
-syn keyword cConstant ElementHookEnum
-syn keyword cConstant HookEnum
-syn keyword cConstant ExternalResultEnum
-syn keyword cConstant FileParamEnum
-syn keyword cConstant InputEnum
-syn keyword cConstant IntInputEnum
-syn keyword cConstant InputToExtrudeEnum
-syn keyword cConstant InputToL2ProjectEnum
-syn keyword cConstant InputToDepthaverageEnum
-syn keyword cConstant InputToSmoothEnum
-syn keyword cConstant SmoothThicknessMultiplierEnum
-syn keyword cConstant IntParamEnum
-syn keyword cConstant IntVecParamEnum
-syn keyword cConstant TransientParamEnum
-syn keyword cConstant MaticeEnum
-syn keyword cConstant MatdamageiceEnum
-syn keyword cConstant MatestarEnum
-syn keyword cConstant MatparEnum
-syn keyword cConstant NodeEnum
-syn keyword cConstant NumericalfluxEnum
-syn keyword cConstant NumericalfluxTypeEnum
-syn keyword cConstant NeumannfluxEnum
-syn keyword cConstant ParamEnum
-syn keyword cConstant MoulinEnum
-syn keyword cConstant PengridEnum
-syn keyword cConstant PenpairEnum
-syn keyword cConstant ProfilerEnum
-syn keyword cConstant MatrixParamEnum
-syn keyword cConstant MassconEnum
-syn keyword cConstant MassconNameEnum
-syn keyword cConstant MassconDefinitionenumEnum
-syn keyword cConstant MassconLevelsetEnum
-syn keyword cConstant MassconaxpbyEnum
-syn keyword cConstant MassconaxpbyNameEnum
-syn keyword cConstant MassconaxpbyDefinitionenumEnum
-syn keyword cConstant MassconaxpbyNamexEnum
-syn keyword cConstant MassconaxpbyNameyEnum
-syn keyword cConstant MassconaxpbyAlphaEnum
-syn keyword cConstant MassconaxpbyBetaEnum
-syn keyword cConstant NodeSIdEnum
-syn keyword cConstant VectorParamEnum
-syn keyword cConstant RiftfrontEnum
-syn keyword cConstant RiftfrontTypeEnum
-syn keyword cConstant SegmentEnum
-syn keyword cConstant SegmentRiftfrontEnum
-syn keyword cConstant SpcDynamicEnum
-syn keyword cConstant SpcStaticEnum
-syn keyword cConstant SpcTransientEnum
-syn keyword cConstant StringArrayParamEnum
-syn keyword cConstant StringParamEnum
-syn keyword cConstant SegEnum
-syn keyword cConstant SegInputEnum
-syn keyword cConstant TriaEnum
-syn keyword cConstant TriaInputEnum
-syn keyword cConstant TetraEnum
-syn keyword cConstant TetraInputEnum
-syn keyword cConstant PentaEnum
-syn keyword cConstant PentaInputEnum
-syn keyword cConstant VertexEnum
-syn keyword cConstant VertexPIdEnum
-syn keyword cConstant VertexSIdEnum
-syn keyword cConstant AirEnum
-syn keyword cConstant IceEnum
-syn keyword cConstant MelangeEnum
-syn keyword cConstant WaterEnum
-syn keyword cConstant ClosedEnum
-syn keyword cConstant FreeEnum
-syn keyword cConstant OpenEnum
+syn keyword cConstant SMBgradientselaEnum
+syn keyword cConstant SmbElaEnum
+syn keyword cConstant SmbBMaxEnum
+syn keyword cConstant SmbBMinEnum
 syn keyword cConstant AdjointpEnum
 syn keyword cConstant AdjointxEnum
@@ -1208,7 +1089,4 @@
 syn keyword cConstant BoundaryEnum
 syn keyword cConstant ConvergedEnum
-syn keyword cConstant FillEnum
-syn keyword cConstant FractionIncrementEnum
-syn keyword cConstant FrictionEnum
 syn keyword cConstant InternalEnum
 syn keyword cConstant MassFluxEnum
@@ -1219,5 +1097,4 @@
 syn keyword cConstant AndroidFrictionCoefficientEnum
 syn keyword cConstant ResetPenaltiesEnum
-syn keyword cConstant SegmentOnIceShelfEnum
 syn keyword cConstant SurfaceAbsVelMisfitEnum
 syn keyword cConstant SurfaceAreaEnum
@@ -1233,4 +1110,7 @@
 syn keyword cConstant ThicknessAbsMisfitEnum
 syn keyword cConstant SurfaceAbsMisfitEnum
+syn keyword cConstant OmegaAbsGradientEnum
+syn keyword cConstant EtaDiffEnum
+syn keyword cConstant EtaAbsGradientEnum
 syn keyword cConstant VelEnum
 syn keyword cConstant VelocityEnum
@@ -1261,6 +1141,7 @@
 syn keyword cConstant TransientInputEnum
 syn keyword cConstant WaterfractionEnum
+syn keyword cConstant WaterfractionDrainageEnum
+syn keyword cConstant WaterfractionDrainageIntegratedEnum
 syn keyword cConstant WatercolumnEnum
-syn keyword cConstant BasalFrictionEnum
 syn keyword cConstant ViscousHeatingEnum
 syn keyword cConstant HydrologyWaterVxEnum
@@ -1298,27 +1179,4 @@
 syn keyword cConstant GiadWdtEnum
 syn keyword cConstant GiaWEnum
-syn keyword cConstant P0Enum
-syn keyword cConstant P0ArrayEnum
-syn keyword cConstant P1Enum
-syn keyword cConstant P1DGEnum
-syn keyword cConstant P1bubbleEnum
-syn keyword cConstant P1bubblecondensedEnum
-syn keyword cConstant P2Enum
-syn keyword cConstant P2bubbleEnum
-syn keyword cConstant P2bubblecondensedEnum
-syn keyword cConstant P2xP1Enum
-syn keyword cConstant P1xP2Enum
-syn keyword cConstant P1xP3Enum
-syn keyword cConstant P2xP4Enum
-syn keyword cConstant P1P1Enum
-syn keyword cConstant P1P1GLSEnum
-syn keyword cConstant MINIEnum
-syn keyword cConstant MINIcondensedEnum
-syn keyword cConstant TaylorHoodEnum
-syn keyword cConstant LATaylorHoodEnum
-syn keyword cConstant XTaylorHoodEnum
-syn keyword cConstant OneLayerP4zEnum
-syn keyword cConstant CrouzeixRaviartEnum
-syn keyword cConstant LACrouzeixRaviartEnum
 syn keyword cConstant SaveResultsEnum
 syn keyword cConstant BoolExternalResultEnum
@@ -1326,4 +1184,5 @@
 syn keyword cConstant DoubleMatExternalResultEnum
 syn keyword cConstant IntExternalResultEnum
+syn keyword cConstant IntMatExternalResultEnum
 syn keyword cConstant JEnum
 syn keyword cConstant StringExternalResultEnum
@@ -1331,4 +1190,6 @@
 syn keyword cConstant TimeEnum
 syn keyword cConstant WaterColumnOldEnum
+syn keyword cConstant SurfaceObservationEnum
+syn keyword cConstant WeightsSurfaceObservationEnum
 syn keyword cConstant OutputdefinitionEnum
 syn keyword cConstant Outputdefinition1Enum
@@ -1434,46 +1295,9 @@
 syn keyword cConstant OutputdefinitionListEnum
 syn keyword cConstant MassfluxatgateEnum
-syn keyword cConstant MassfluxatgateNameEnum
-syn keyword cConstant MassfluxatgateDefinitionenumEnum
-syn keyword cConstant MassfluxatgateSegmentsEnum
 syn keyword cConstant NodalvalueEnum
-syn keyword cConstant NodalvalueNameEnum
-syn keyword cConstant NodalvalueDefinitionenumEnum
-syn keyword cConstant NodalvalueModelEnumEnum
-syn keyword cConstant NodalvalueNodeEnum
-syn keyword cConstant MisfitNameEnum
-syn keyword cConstant MisfitDefinitionenumEnum
-syn keyword cConstant MisfitModelEnumEnum
-syn keyword cConstant MisfitObservationEnum
-syn keyword cConstant MisfitObservationEnumEnum
-syn keyword cConstant MisfitLocalEnum
-syn keyword cConstant MisfitTimeinterpolationEnum
-syn keyword cConstant MisfitWeightsEnum
-syn keyword cConstant MisfitWeightsEnumEnum
-syn keyword cConstant SurfaceObservationEnum
-syn keyword cConstant WeightsSurfaceObservationEnum
+syn keyword cConstant RegionaloutputEnum
 syn keyword cConstant VxObsEnum
-syn keyword cConstant WeightsVxObsEnum
 syn keyword cConstant VyObsEnum
-syn keyword cConstant WeightsVyObsEnum
-syn keyword cConstant MinVelEnum
-syn keyword cConstant MaxVelEnum
-syn keyword cConstant MinVxEnum
-syn keyword cConstant MaxVxEnum
-syn keyword cConstant MaxAbsVxEnum
-syn keyword cConstant MinVyEnum
-syn keyword cConstant MaxVyEnum
-syn keyword cConstant MaxAbsVyEnum
-syn keyword cConstant MinVzEnum
-syn keyword cConstant MaxVzEnum
-syn keyword cConstant MaxAbsVzEnum
-syn keyword cConstant FloatingAreaEnum
-syn keyword cConstant GroundedAreaEnum
-syn keyword cConstant IceMassEnum
-syn keyword cConstant IceVolumeEnum
-syn keyword cConstant IceVolumeAboveFloatationEnum
-syn keyword cConstant TotalFloatingBmbEnum
-syn keyword cConstant TotalGroundedBmbEnum
-syn keyword cConstant TotalSmbEnum
+syn keyword cConstant NumberedcostfunctionEnum
 syn keyword cConstant AbsoluteEnum
 syn keyword cConstant IncrementalEnum
@@ -1488,12 +1312,9 @@
 syn keyword cConstant SubelementMigrationEnum
 syn keyword cConstant SubelementMigration2Enum
+syn keyword cConstant SubelementMigration3Enum
+syn keyword cConstant SubelementMigration4Enum
 syn keyword cConstant ContactEnum
 syn keyword cConstant GroundingOnlyEnum
 syn keyword cConstant MaskGroundediceLevelsetEnum
-syn keyword cConstant GaussSegEnum
-syn keyword cConstant GaussTriaEnum
-syn keyword cConstant GaussTetraEnum
-syn keyword cConstant GaussPentaEnum
-syn keyword cConstant FSSolverEnum
 syn keyword cConstant AdjointEnum
 syn keyword cConstant ColinearEnum
@@ -1529,10 +1350,4 @@
 syn keyword cConstant SeparateEnum
 syn keyword cConstant SsetEnum
-syn keyword cConstant VerboseEnum
-syn keyword cConstant TriangleInterpEnum
-syn keyword cConstant BilinearInterpEnum
-syn keyword cConstant NearestInterpEnum
-syn keyword cConstant XYEnum
-syn keyword cConstant XYZEnum
 syn keyword cConstant DenseEnum
 syn keyword cConstant MpiDenseEnum
@@ -1542,8 +1357,4 @@
 syn keyword cConstant MumpsEnum
 syn keyword cConstant GslEnum
-syn keyword cConstant OptionEnum
-syn keyword cConstant GenericOptionEnum
-syn keyword cConstant OptionCellEnum
-syn keyword cConstant OptionStructEnum
 syn keyword cConstant CuffeyEnum
 syn keyword cConstant BuddJackaEnum
@@ -1552,5 +1363,4 @@
 syn keyword cConstant ArrheniusEnum
 syn keyword cConstant LliboutryDuvalEnum
-syn keyword cConstant SpclevelsetEnum
 syn keyword cConstant ExtrapolationVariableEnum
 syn keyword cConstant IceMaskNodeActivationEnum
@@ -1559,25 +1369,303 @@
 syn keyword cConstant LevelsetfunctionPicardEnum
 syn keyword cConstant LevelsetReinitFrequencyEnum
-syn keyword cConstant SealevelriseSolutionEnum
-syn keyword cConstant SealevelriseAnalysisEnum
 syn keyword cConstant SealevelEnum
+syn keyword cConstant SealevelUmotionEnum
+syn keyword cConstant SealevelNmotionEnum
+syn keyword cConstant SealevelEmotionEnum
+syn keyword cConstant SealevelAbsoluteEnum
 syn keyword cConstant SealevelEustaticEnum
+syn keyword cConstant SealevelInertiaTensorXZEnum
+syn keyword cConstant SealevelInertiaTensorYZEnum
+syn keyword cConstant SealevelInertiaTensorZZEnum
+syn keyword cConstant SealevelObsEnum
+syn keyword cConstant SealevelWeightsEnum
 syn keyword cConstant SealevelriseDeltathicknessEnum
 syn keyword cConstant SealevelriseMaxiterEnum
 syn keyword cConstant SealevelriseReltolEnum
 syn keyword cConstant SealevelriseAbstolEnum
-syn keyword cConstant SealevelriseLoveHEnum
-syn keyword cConstant SealevelriseLoveKEnum
-syn keyword cConstant SealevelriseTideLoveHEnum
-syn keyword cConstant SealevelriseTideLoveKEnum
 syn keyword cConstant SealevelriseRigidEnum
 syn keyword cConstant SealevelriseElasticEnum
 syn keyword cConstant SealevelriseRotationEnum
+syn keyword cConstant SealevelriseTidalLoveHEnum
+syn keyword cConstant SealevelriseTidalLoveKEnum
+syn keyword cConstant SealevelriseFluidLoveEnum
+syn keyword cConstant SealevelriseEquatorialMoiEnum
+syn keyword cConstant SealevelrisePolarMoiEnum
+syn keyword cConstant SealevelriseAngularVelocityEnum
+syn keyword cConstant SealevelriseOceanAreaScalingEnum
+syn keyword cConstant SealevelriseStericRateEnum
 syn keyword cConstant SealevelriseGElasticEnum
-syn keyword cConstant SealevelriseDegaccEnum
+syn keyword cConstant SealevelriseUElasticEnum
+syn keyword cConstant SealevelriseHElasticEnum
 syn keyword cConstant SealevelriseTransitionsEnum
 syn keyword cConstant SealevelriseRequestedOutputsEnum
 syn keyword cConstant SealevelriseNumRequestedOutputsEnum
+syn keyword cConstant LoveNfreqEnum
+syn keyword cConstant LoveFrequenciesEnum
+syn keyword cConstant LoveShNmaxEnum
+syn keyword cConstant LoveShNminEnum
+syn keyword cConstant LoveG0Enum
+syn keyword cConstant LoveR0Enum
+syn keyword cConstant LoveMu0Enum
+syn keyword cConstant LoveAllowLayerDeletionEnum
+syn keyword cConstant LoveForcingTypeEnum
+syn keyword cConstant LoveHrEnum
+syn keyword cConstant LoveKrEnum
+syn keyword cConstant LoveLrEnum
+syn keyword cConstant LoveHiEnum
+syn keyword cConstant LoveKiEnum
+syn keyword cConstant LoveLiEnum
+syn keyword cConstant LoveKernelsEnum
+syn keyword cConstant LoveKernelsRealEnum
+syn keyword cConstant LoveKernelsImagEnum
+syn keyword cConstant EsaUmotionEnum
+syn keyword cConstant EsaNmotionEnum
+syn keyword cConstant EsaEmotionEnum
+syn keyword cConstant EsaXmotionEnum
+syn keyword cConstant EsaYmotionEnum
+syn keyword cConstant EsaHemisphereEnum
+syn keyword cConstant EsaStrainratexxEnum
+syn keyword cConstant EsaStrainratexyEnum
+syn keyword cConstant EsaStrainrateyyEnum
+syn keyword cConstant EsaRotationrateEnum
+syn keyword cConstant EsaDeltathicknessEnum
+syn keyword cConstant EsaUElasticEnum
+syn keyword cConstant EsaHElasticEnum
+syn keyword cConstant EsaTransitionsEnum
+syn keyword cConstant EsaRequestedOutputsEnum
+syn keyword cConstant EsaNumRequestedOutputsEnum
+syn keyword cConstant TransientAmrFrequencyEnum
+syn keyword cConstant AmrTypeEnum
+syn keyword cConstant AmrRestartEnum
+syn keyword cConstant AmrNeopzEnum
+syn keyword cConstant AmrLevelMaxEnum
+syn keyword cConstant AmrLagEnum
+syn keyword cConstant AmrBamgEnum
+syn keyword cConstant AmrHminEnum
+syn keyword cConstant AmrHmaxEnum
+syn keyword cConstant AmrFieldEnum
+syn keyword cConstant AmrErrEnum
+syn keyword cConstant AmrKeepMetricEnum
+syn keyword cConstant AmrGradationEnum
+syn keyword cConstant AmrGroundingLineResolutionEnum
+syn keyword cConstant AmrGroundingLineDistanceEnum
+syn keyword cConstant AmrIceFrontResolutionEnum
+syn keyword cConstant AmrIceFrontDistanceEnum
+syn keyword cConstant AmrThicknessErrorResolutionEnum
+syn keyword cConstant AmrThicknessErrorThresholdEnum
+syn keyword cConstant AmrThicknessErrorGroupThresholdEnum
+syn keyword cConstant AmrThicknessErrorMaximumEnum
+syn keyword cConstant AmrDeviatoricErrorResolutionEnum
+syn keyword cConstant AmrDeviatoricErrorThresholdEnum
+syn keyword cConstant AmrDeviatoricErrorGroupThresholdEnum
+syn keyword cConstant AmrDeviatoricErrorMaximumEnum
+syn keyword cConstant DeviatoricStressErrorEstimatorEnum
+syn keyword cConstant ThicknessErrorEstimatorEnum
 syn keyword cConstant ParametersENDEnum
+syn keyword cConstant XYEnum
+syn keyword cConstant XYZEnum
+syn keyword cConstant GenericParamEnum
+syn keyword cConstant BoolInputEnum
+syn keyword cConstant BoolParamEnum
+syn keyword cConstant ContourEnum
+syn keyword cConstant ControlInputEnum
+syn keyword cConstant DatasetInputEnum
+syn keyword cConstant DoubleInputEnum
+syn keyword cConstant DoubleArrayInputEnum
+syn keyword cConstant DataSetParamEnum
+syn keyword cConstant DoubleMatArrayParamEnum
+syn keyword cConstant DoubleMatParamEnum
+syn keyword cConstant DoubleParamEnum
+syn keyword cConstant DoubleVecParamEnum
+syn keyword cConstant ElementEnum
+syn keyword cConstant ElementHookEnum
+syn keyword cConstant HookEnum
+syn keyword cConstant ExternalResultEnum
+syn keyword cConstant FileParamEnum
+syn keyword cConstant InputEnum
+syn keyword cConstant IntInputEnum
+syn keyword cConstant IntParamEnum
+syn keyword cConstant IntVecParamEnum
+syn keyword cConstant TransientParamEnum
+syn keyword cConstant TransientArrayParamEnum
+syn keyword cConstant MaticeEnum
+syn keyword cConstant MatlithoEnum
+syn keyword cConstant MatdamageiceEnum
+syn keyword cConstant MatenhancediceEnum
+syn keyword cConstant MatestarEnum
+syn keyword cConstant MatparEnum
+syn keyword cConstant NodeEnum
+syn keyword cConstant NumericalfluxEnum
+syn keyword cConstant NeumannfluxEnum
+syn keyword cConstant ParamEnum
+syn keyword cConstant MoulinEnum
+syn keyword cConstant PengridEnum
+syn keyword cConstant PenpairEnum
+syn keyword cConstant ProfilerEnum
+syn keyword cConstant MatrixParamEnum
+syn keyword cConstant MassconEnum
+syn keyword cConstant MassconaxpbyEnum
+syn keyword cConstant NodeSIdEnum
+syn keyword cConstant ElementSIdEnum
+syn keyword cConstant VectorParamEnum
+syn keyword cConstant RiftfrontEnum
+syn keyword cConstant SegmentEnum
+syn keyword cConstant SegmentRiftfrontEnum
+syn keyword cConstant SpcDynamicEnum
+syn keyword cConstant SpcStaticEnum
+syn keyword cConstant SpcTransientEnum
+syn keyword cConstant StringArrayParamEnum
+syn keyword cConstant StringParamEnum
+syn keyword cConstant SegEnum
+syn keyword cConstant SegInputEnum
+syn keyword cConstant TriaEnum
+syn keyword cConstant TriaInputEnum
+syn keyword cConstant TetraEnum
+syn keyword cConstant TetraInputEnum
+syn keyword cConstant PentaEnum
+syn keyword cConstant PentaInputEnum
+syn keyword cConstant VertexEnum
+syn keyword cConstant VertexPIdEnum
+syn keyword cConstant VertexSIdEnum
+syn keyword cConstant OptionEnum
+syn keyword cConstant GenericOptionEnum
+syn keyword cConstant AdjointBalancethicknessAnalysisEnum
+syn keyword cConstant AdjointBalancethickness2AnalysisEnum
+syn keyword cConstant AdjointHorizAnalysisEnum
+syn keyword cConstant DefaultAnalysisEnum
+syn keyword cConstant BalancethicknessAnalysisEnum
+syn keyword cConstant BalancethicknessSolutionEnum
+syn keyword cConstant Balancethickness2AnalysisEnum
+syn keyword cConstant Balancethickness2SolutionEnum
+syn keyword cConstant BalancethicknessSoftAnalysisEnum
+syn keyword cConstant BalancethicknessSoftSolutionEnum
+syn keyword cConstant BalancevelocityAnalysisEnum
+syn keyword cConstant BalancevelocitySolutionEnum
+syn keyword cConstant L2ProjectionEPLAnalysisEnum
+syn keyword cConstant L2ProjectionBaseAnalysisEnum
+syn keyword cConstant BedSlopeSolutionEnum
+syn keyword cConstant DamageEvolutionSolutionEnum
+syn keyword cConstant DamageEvolutionAnalysisEnum
+syn keyword cConstant StressbalanceAnalysisEnum
+syn keyword cConstant StressbalanceSIAAnalysisEnum
+syn keyword cConstant StressbalanceSolutionEnum
+syn keyword cConstant StressbalanceVerticalAnalysisEnum
+syn keyword cConstant EnthalpyAnalysisEnum
+syn keyword cConstant HydrologyShreveAnalysisEnum
+syn keyword cConstant HydrologyDCInefficientAnalysisEnum
+syn keyword cConstant HydrologyDCEfficientAnalysisEnum
+syn keyword cConstant HydrologySommersAnalysisEnum
+syn keyword cConstant HydrologySolutionEnum
+syn keyword cConstant MeltingAnalysisEnum
+syn keyword cConstant MasstransportAnalysisEnum
+syn keyword cConstant MasstransportSolutionEnum
+syn keyword cConstant FreeSurfaceBaseAnalysisEnum
+syn keyword cConstant FreeSurfaceTopAnalysisEnum
+syn keyword cConstant ExtrudeFromBaseAnalysisEnum
+syn keyword cConstant ExtrudeFromTopAnalysisEnum
+syn keyword cConstant DepthAverageAnalysisEnum
+syn keyword cConstant SealevelriseSolutionEnum
+syn keyword cConstant SealevelriseAnalysisEnum
+syn keyword cConstant SteadystateSolutionEnum
+syn keyword cConstant SurfaceSlopeSolutionEnum
+syn keyword cConstant SmoothAnalysisEnum
+syn keyword cConstant ThermalAnalysisEnum
+syn keyword cConstant ThermalSolutionEnum
+syn keyword cConstant TransientSolutionEnum
+syn keyword cConstant UzawaPressureAnalysisEnum
+syn keyword cConstant GiaSolutionEnum
+syn keyword cConstant GiaIvinsAnalysisEnum
+syn keyword cConstant EsaSolutionEnum
+syn keyword cConstant EsaAnalysisEnum
+syn keyword cConstant LoveSolutionEnum
+syn keyword cConstant LoveAnalysisEnum
+syn keyword cConstant LevelsetAnalysisEnum
+syn keyword cConstant ExtrapolationAnalysisEnum
+syn keyword cConstant ApproximationEnum
+syn keyword cConstant NoneApproximationEnum
+syn keyword cConstant SIAApproximationEnum
+syn keyword cConstant SSAApproximationEnum
+syn keyword cConstant SSAHOApproximationEnum
+syn keyword cConstant SSAFSApproximationEnum
+syn keyword cConstant L1L2ApproximationEnum
+syn keyword cConstant HOApproximationEnum
+syn keyword cConstant HOFSApproximationEnum
+syn keyword cConstant FSApproximationEnum
+syn keyword cConstant FSvelocityEnum
+syn keyword cConstant FSpressureEnum
+syn keyword cConstant GaussSegEnum
+syn keyword cConstant GaussTriaEnum
+syn keyword cConstant GaussTetraEnum
+syn keyword cConstant GaussPentaEnum
+syn keyword cConstant TriangleInterpEnum
+syn keyword cConstant BilinearInterpEnum
+syn keyword cConstant NearestInterpEnum
+syn keyword cConstant MinVelEnum
+syn keyword cConstant MaxVelEnum
+syn keyword cConstant MinVxEnum
+syn keyword cConstant MaxVxEnum
+syn keyword cConstant MaxAbsVxEnum
+syn keyword cConstant MinVyEnum
+syn keyword cConstant MaxVyEnum
+syn keyword cConstant MaxAbsVyEnum
+syn keyword cConstant MinVzEnum
+syn keyword cConstant MaxVzEnum
+syn keyword cConstant MaxAbsVzEnum
+syn keyword cConstant FloatingAreaEnum
+syn keyword cConstant FloatingAreaScaledEnum
+syn keyword cConstant GroundedAreaEnum
+syn keyword cConstant GroundedAreaScaledEnum
+syn keyword cConstant IceMassEnum
+syn keyword cConstant IceMassScaledEnum
+syn keyword cConstant IceVolumeEnum
+syn keyword cConstant IceVolumeScaledEnum
+syn keyword cConstant IceVolumeAboveFloatationEnum
+syn keyword cConstant IceVolumeAboveFloatationScaledEnum
+syn keyword cConstant TotalFloatingBmbEnum
+syn keyword cConstant TotalFloatingBmbScaledEnum
+syn keyword cConstant TotalGroundedBmbEnum
+syn keyword cConstant TotalGroundedBmbScaledEnum
+syn keyword cConstant TotalSmbEnum
+syn keyword cConstant TotalSmbScaledEnum
+syn keyword cConstant P0Enum
+syn keyword cConstant P0ArrayEnum
+syn keyword cConstant P1Enum
+syn keyword cConstant P1DGEnum
+syn keyword cConstant P1bubbleEnum
+syn keyword cConstant P1bubblecondensedEnum
+syn keyword cConstant P2Enum
+syn keyword cConstant P2bubbleEnum
+syn keyword cConstant P2bubblecondensedEnum
+syn keyword cConstant P2xP1Enum
+syn keyword cConstant P1xP2Enum
+syn keyword cConstant P1xP3Enum
+syn keyword cConstant P1xP4Enum
+syn keyword cConstant P2xP4Enum
+syn keyword cConstant P1P1Enum
+syn keyword cConstant P1P1GLSEnum
+syn keyword cConstant MINIEnum
+syn keyword cConstant MINIcondensedEnum
+syn keyword cConstant TaylorHoodEnum
+syn keyword cConstant LATaylorHoodEnum
+syn keyword cConstant XTaylorHoodEnum
+syn keyword cConstant OneLayerP4zEnum
+syn keyword cConstant CrouzeixRaviartEnum
+syn keyword cConstant LACrouzeixRaviartEnum
+syn keyword cConstant ClosedEnum
+syn keyword cConstant FreeEnum
+syn keyword cConstant OpenEnum
+syn keyword cConstant AirEnum
+syn keyword cConstant IceEnum
+syn keyword cConstant MelangeEnum
+syn keyword cConstant WaterEnum
+syn keyword cConstant DataSetEnum
+syn keyword cConstant ConstraintsEnum
+syn keyword cConstant LoadsEnum
+syn keyword cConstant MaterialsEnum
+syn keyword cConstant NodesEnum
+syn keyword cConstant ContoursEnum
+syn keyword cConstant ParametersEnum
+syn keyword cConstant VerticesEnum
+syn keyword cConstant ResultsEnum
 "ISSM's Enums end
 """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
Index: /issm/trunk/externalpackages/vim/addons/vimrc
===================================================================
--- /issm/trunk/externalpackages/vim/addons/vimrc	(revision 22757)
+++ /issm/trunk/externalpackages/vim/addons/vimrc	(revision 22758)
@@ -208,5 +208,5 @@
 au BufRead,BufNewFile *.html   iabbr <silent> CO <code></code><Left><Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
 au BufRead,BufNewFile *.html   iabbr <silent> PP <p></p><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
-"au BufRead,BufNewFile *.m      iabbr <silent> p1  disp('');<Left><Left><Left><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.m      iabbr <silent> p1  disp('');<Left><Left><Left><C-R>=Eatchar('\s')<CR>
 au BufRead,BufNewFile *.m      iab <expr> p0  "disp('-------------- file: ".expand('%')." line: ".line(".")."');"
 au BufRead,BufNewFile *.c*,*.h iabbr <silent> p1  printf("\n");<Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
Index: /issm/trunk/jenkins/javascript/karma/index.html
===================================================================
--- /issm/trunk/jenkins/javascript/karma/index.html	(revision 22757)
+++ /issm/trunk/jenkins/javascript/karma/index.html	(revision 22758)
@@ -7,14 +7,11 @@
         <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
         <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"></link>
-        <script type="text/javascript" src="lib/bin/issm-binaries.js"> </script>
-        <script type="text/javascript" src="lib/bin/issm-extlibraries.js"> </script>
-        <script type="text/javascript" src="lib/Exp/Square.js"></script>
-        <script type="text/javascript" src="lib/Par/SquareShelfConstrained.js"></script>
-        <script type="text/javascript" src="lib/Data/SquareShelfConstrained.data.js"></script>
-        <script type="text/javascript" src="lib/mesh2d.js"></script>
-        <script type="text/javascript" src="lib/mesh3dprisms.js"></script>
-        <script type="text/javascript" src="lib/bin/model.js"></script>
-        <!--<script src="scripts/runscript.js"></script>-->
-        <script src="scripts/runscript.js"></script>
+        <script type="text/javascript" src="../../../bin/issm-bin.js"> </script>
+        <script type="text/javascript" src="../../../bin/IssmModule.js"> </script>
+        <script type="text/javascript" src="../../../bin/issm-prebin.js"> </script>
+        <script type="text/javascript" src="../../../test/Exp/Square.js"></script>
+        <script type="text/javascript" src="../../../test/Par/SquareShelfConstrained.js"></script>
+        <script type="text/javascript" src="../../../test/Data/SquareShelfConstrained.data.js"></script>
+        <script src="./scripts/runscript.js"></script>
 
         <style>
Index: /issm/trunk/jenkins/javascript/karma/karma.conf.js
===================================================================
--- /issm/trunk/jenkins/javascript/karma/karma.conf.js	(revision 22757)
+++ /issm/trunk/jenkins/javascript/karma/karma.conf.js	(revision 22758)
@@ -12,6 +12,6 @@
     // list of files / patterns to load in the browser
     files: [
-      'node_modules/jquery/dist/jquery.min.js',
-      'node_modules/mathjs/dist/math.min.js',
+      './../../../externalpackages/emscripten/src/node/4.1.1_64bit/lib/node_modules/jquery/dist/jquery.min.js',
+      './../../../externalpackages/emscripten/src/node/4.1.1_64bit/lib/node_modules/mathjs/dist/math.min.js',
       'lib/Exp/Square.js',
       'lib/Par/SquareShelfConstrained.js',
Index: /issm/trunk/jenkins/javascript/karma/scripts/runscript.js
===================================================================
--- /issm/trunk/jenkins/javascript/karma/scripts/runscript.js	(revision 22757)
+++ /issm/trunk/jenkins/javascript/karma/scripts/runscript.js	(revision 22758)
@@ -4,5 +4,5 @@
     });
 
-    var PORT=8081;
+    var PORT=80;
     var tests = []; //last test to check
 
@@ -30,5 +30,5 @@
             $('#debug').empty();
             var id = this.id.replace(/[^\d]/g, ''); 
-            $.getScript('http://localhost:'+PORT+'/test'+id+'.js', function(src, status) {
+            $.getScript('../../../test/NightlyRun/test'+id+'.js', function(src, status) {
                 console.log('='.repeat(30));
                 console.log('Status: ' + status);
Index: /issm/trunk/jenkins/jenkins.sh
===================================================================
--- /issm/trunk/jenkins/jenkins.sh	(revision 22757)
+++ /issm/trunk/jenkins/jenkins.sh	(revision 22758)
@@ -157,4 +157,5 @@
 			echo "    ERROR: installation of $PACKAGENAME failed        ";
 			echo "======================================================";
+			cat compil.log
 			echo "<testcase classname=\"externalpackages\" name=\"$PACKAGENAME\">" >> $EXTERNAL_TEST_FILE
 			echo '<failure message="failure">External packages did not install right. Check it.' >> $EXTERNAL_TEST_FILE
@@ -240,4 +241,10 @@
 		make
 	fi
+	if [ $? -ne 0 ] && [ $NUMCPUS_INSTALL -gt 1 ]; then 
+		echo " "
+		echo "Compilation failed, trying to compile with only one threatd"
+		echo " "
+		make
+	fi
 	if [ $? -ne 0 ]; then 
 		echo "ISSM_COMPILATION failed!"
@@ -320,5 +327,7 @@
 echo '-----------------------------'
 
-rm matlab_log.log
+if [ -f matlab_log.log ]; then
+	rm matlab_log.log
+fi
 
 for job in `jobs -p`
@@ -342,5 +351,4 @@
 if [ $PYTHON_TEST -eq 1 ]; then
 #Launch all tests on different cpus
-PYTHON_START_TIME=$(timer);
 export PYTHONSTARTUP=$ISSM_DIR/src/m/dev/devpath.py
 export PYTHONUNBUFFERED=1 #we don't want python to buffer otherwise issm.exe output is not captured
@@ -355,5 +363,7 @@
 # concatenate reports
 cd $ISSM_DIR/nightlylog/
-rm python_log.log
+if [ -f python_log.log ]; then
+	rm python_log.log
+fi
 
 for job in `jobs -p`
Index: /issm/trunk/jenkins/linux64_caladan
===================================================================
--- /issm/trunk/jenkins/linux64_caladan	(revision 22757)
+++ /issm/trunk/jenkins/linux64_caladan	(revision 22758)
@@ -39,9 +39,10 @@
 
 #List of external pakages to be installed and their installation scripts
-EXTERNALPACKAGES="autotools     install.sh                
+EXTERNALPACKAGES="autotools     install.sh
+						cmake        install.sh                
 						mpich         install-3.2-linux64.sh    
 						petsc         install-3.7-linux64.sh    
 						triangle      install-linux64.sh        
-						boost         install.sh                
+						boost         install-1.55-linux.sh
 						dakota        install-6.2-linux64.sh  
 						chaco         install.sh 
@@ -64,4 +65,4 @@
 #by Matlab and runme.m
 #ex: "'id',[101 102 103]"
-PYTHON_NROPTIONS="--exclude 119 514 701 702 435"
-MATLAB_NROPTIONS="'exclude',[119,514,701,702,435]"
+PYTHON_NROPTIONS="--exclude 701 702 435 703"
+MATLAB_NROPTIONS="'exclude',[701,702,435]"
Index: /issm/trunk/jenkins/linux64_caladan_ad
===================================================================
--- /issm/trunk/jenkins/linux64_caladan_ad	(revision 22757)
+++ /issm/trunk/jenkins/linux64_caladan_ad	(revision 22758)
@@ -28,5 +28,6 @@
 
 #List of external pakages to be installed and their installation scripts
-EXTERNALPACKAGES="autotools install.sh                
+EXTERNALPACKAGES="autotools install.sh
+					cmake install.sh                
 					 mpich install-3.2-linux64.sh
 					 petsc install-3.7-linux64.sh
Index: /issm/trunk/jenkins/linux64_caladan_ampi
===================================================================
--- /issm/trunk/jenkins/linux64_caladan_ampi	(revision 22757)
+++ /issm/trunk/jenkins/linux64_caladan_ampi	(revision 22758)
@@ -37,5 +37,6 @@
 
 #List of external pakages to be installed and their installation scripts
-EXTERNALPACKAGES="autotools install.sh 
+EXTERNALPACKAGES="autotools install.sh
+					 cmake install.sh 
 					 mpich install-3.2-linux64.sh
 					 petsc install-3.7-linux64.sh
Index: /issm/trunk/jenkins/linux64_ross
===================================================================
--- /issm/trunk/jenkins/linux64_ross	(revision 22757)
+++ /issm/trunk/jenkins/linux64_ross	(revision 22758)
@@ -37,5 +37,6 @@
 
 #List of external pakages to be installed and their installation scripts
-EXTERNALPACKAGES="autotools     install.sh                
+EXTERNALPACKAGES="autotools     install.sh
+						cmake        install.sh                
 						mpich         install-3.2-linux64.sh    
 						petsc         install-3.7-linux64.sh    
@@ -67,4 +68,4 @@
 #by Matlab and runme.m
 #ex: "'id',[101 102 103]"
-PYTHON_NROPTIONS="--exclude 119 243 514 701 702 435"
+PYTHON_NROPTIONS="--exclude 243 701 702 703"
 MATLAB_NROPTIONS="'exclude',[IdFromString('Dakota')]"
Index: /issm/trunk/jenkins/linux64_ross_ad
===================================================================
--- /issm/trunk/jenkins/linux64_ross_ad	(revision 22757)
+++ /issm/trunk/jenkins/linux64_ross_ad	(revision 22758)
@@ -14,4 +14,5 @@
 				--without-kml \
 				--without-GiaIvins \
+				--without-Love \
 				--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install \
 				--with-adolc-dir=$ISSM_DIR/externalpackages/adolc/install \
@@ -20,4 +21,5 @@
 				--with-python-numpy-dir=/usr/lib/python2.7/dist-packages/numpy\
 				--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
+				--with-fortran-lib="-L/usr/lib/gcc/x86_64-linux-gnu/4.9/ -lgfortran" \
 				--enable-development \
 				--enable-debugging '
@@ -32,5 +34,6 @@
 
 #List of external pakages to be installed and their installation scripts
-EXTERNALPACKAGES="autotools install.sh                
+EXTERNALPACKAGES="autotools install.sh
+					 cmake install.sh                
 					 mpich install-3.2-linux64.sh
 					 petsc install-3.7-linux64.sh
Index: /issm/trunk/jenkins/linux64_ross_ampi
===================================================================
--- /issm/trunk/jenkins/linux64_ross_ampi	(revision 22757)
+++ /issm/trunk/jenkins/linux64_ross_ampi	(revision 22758)
@@ -21,5 +21,5 @@
 				--with-metis-dir=$ISSM_DIR/externalpackages/petsc/install \
 				--with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
-				--with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib -lmpi" \
+				--with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib -lmpifort -lmpi" \
 				--with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
 				--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
@@ -40,5 +40,6 @@
 
 #List of external pakages to be installed and their installation scripts
-EXTERNALPACKAGES="autotools install.sh 
+EXTERNALPACKAGES="autotools install.sh
+					 cmake install.sh 
 					 mpich install-3.2-linux64.sh
 					 petsc install-3.7-linux64.sh
Index: /issm/trunk/jenkins/linux64_ross_dakota
===================================================================
--- /issm/trunk/jenkins/linux64_ross_dakota	(revision 22757)
+++ /issm/trunk/jenkins/linux64_ross_dakota	(revision 22758)
@@ -13,18 +13,18 @@
 	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
 	--with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
-	--with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib -lmpi" \
+	--with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib -lmpi -lmpicxx -lmpifort" \
 	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
 	--with-metis-dir=$ISSM_DIR/externalpackages/petsc/install \
 	--with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install \
-	--with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+	--with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install \
 	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
-	--with-chaco-dir="$ISSM_DIR/externalpackages/chaco/install" \
+	--with-chaco-dir=$ISSM_DIR/externalpackages/chaco/install \
 	--with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
-	--with-boost-dir=$ISSM_DIR/externalpackages/boost/install/ \
-	--with-fortran-lib="-L/usr/lib/gcc/x86_64-linux-gnu/4.9/ -lgfortran" \
+	--with-boost-dir=$ISSM_DIR/externalpackages/boost/install \
+	--with-fortran-lib="-L/usr/lib/gcc/x86_64-linux-gnu/4.9 -lgfortran" \
 	--with-m1qn3-dir=$ISSM_DIR/externalpackages/m1qn3/install \
 	--with-numthreads=4 \
 	--enable-development \
-	--enable-debugging '
+	--enable-debugging'
 
 #PYTHON and MATLAB testing
@@ -37,5 +37,6 @@
 
 #List of external pakages to be installed and their installation scripts
-EXTERNALPACKAGES="autotools     install.sh                
+EXTERNALPACKAGES="autotools     install.sh
+						cmake        install.sh                
 						mpich         install-3.2-linux64.sh    
 						petsc         install-3.7-linux64.sh    
@@ -62,4 +63,4 @@
 #by Matlab and runme.m
 #ex: "'id',[101 102 103]"
-PYTHON_NROPTIONS=""
-MATLAB_NROPTIONS="'exclude',[119,243,514,701,702,435]"
+PYTHON_NROPTIONS="--exclude 243 701 702 703"
+MATLAB_NROPTIONS="'exclude',[243,701,702,435]"
Index: /issm/trunk/jenkins/linux64_ross_gia
===================================================================
--- /issm/trunk/jenkins/linux64_ross_gia	(revision 22757)
+++ /issm/trunk/jenkins/linux64_ross_gia	(revision 22758)
@@ -38,4 +38,5 @@
 #List of external pakages to be installed and their installation scripts
 EXTERNALPACKAGES="autotools     install.sh
+					 	cmake 		  install.sh
 						mpich         install-3.2-linux64.sh    
 						petsc         install-3.7-linux64.sh    
Index: /issm/trunk/jenkins/linux64_ross_iceocean
===================================================================
--- /issm/trunk/jenkins/linux64_ross_iceocean	(revision 22757)
+++ /issm/trunk/jenkins/linux64_ross_iceocean	(revision 22758)
@@ -20,4 +20,5 @@
 	--with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
 	--with-fortran-lib="-L/usr/lib/gcc/x86_64-linux-gnu/4.9/ -lgfortran" \
+	--with-ocean=yes \
 	--with-numthreads=4 \
 	--enable-development \
@@ -33,7 +34,7 @@
 
 #List of external pakages to be installed and their installation scripts
-EXTERNALPACKAGES="autotools     install.sh                
-						mpich         install-3.2-linux64.sh    
+EXTERNALPACKAGES="autotools     install.sh    
 						cmake         install.sh                
+						mpich      	  install-3.2-linux64.sh                
 						petsc         install-3.7-linux64.sh    
 						triangle      install-linux64.sh        
@@ -55,4 +56,4 @@
 #by Matlab and runme.m
 #ex: "'id',[101 102 103]"
-MATLAB_NROPTIONS="'benchmark','all','id',4001"
+MATLAB_NROPTIONS="'benchmark','all','id',[4001 4002]"
 PYTHON_NROPTIONS=""
Index: /issm/trunk/jenkins/linux64_ross_javascript
===================================================================
--- /issm/trunk/jenkins/linux64_ross_javascript	(revision 22757)
+++ /issm/trunk/jenkins/linux64_ross_javascript	(revision 22758)
@@ -10,7 +10,10 @@
     --with-triangle-dir="$ISSM_DIR/externalpackages/triangle/install-javascript" \
     --with-gsl-dir="$ISSM_DIR/externalpackages/gsl/install-javascript" \
-    --without-kml\
-    --without-kriging\
-    --with-cxxoptflags="-O2"'
+	--without-Love \
+    --without-kml \
+    --without-kriging \
+    --with-cxxoptflags="-O2" \
+    CXXFLAGS="-O2" \
+    CFLAGS="-O2"'
 
 #PYTHON and MATLAB testing
@@ -24,6 +27,8 @@
 
 #List of external pakages to be installed and their installation scripts
-EXTERNALPACKAGES="emscripten	  install.sh        
-						gsl			  install-javascript.sh    
+EXTERNALPACKAGES="autotools     install.sh
+						cmake         install.sh
+						emscripten    install.sh        
+						gsl           install-javascript.sh    
 						triangle      install-javascript.sh        
 						shell2junit   install.sh"
@@ -44,4 +49,4 @@
 #by Matlab and runme.m
 #ex: "'id',[101 102 103]"
-#PYTHON_NROPTIONS="--exclude 119 243 514 701 702 435"
+#PYTHON_NROPTIONS="--exclude 119 243 514 701 702 703 435"
 #MATLAB_NROPTIONS="'exclude',[119,243,514,701,702,435,IdFromString('Dakota')]"
Index: /issm/trunk/jenkins/linux64_ross_python
===================================================================
--- /issm/trunk/jenkins/linux64_ross_python	(revision 22757)
+++ /issm/trunk/jenkins/linux64_ross_python	(revision 22758)
@@ -37,4 +37,5 @@
 #List of external pakages to be installed and their installation scripts
 EXTERNALPACKAGES="mpich         install-3.2-linux64.sh    
+						cmake         install.sh    
 						petsc         install-3.7-linux64.sh    
 						triangle      install-linux64.sh        
@@ -58,4 +59,4 @@
 #by Matlab and runme.m
 #ex: "'id',[101 102 103]"
-PYTHON_NROPTIONS="--exclude 119 243 514 701 702 435"
+PYTHON_NROPTIONS="--exclude 243 701 702 703"
 MATLAB_NROPTIONS="'exclude',[IdFromString('Dakota')]"
Index: /issm/trunk/jenkins/linux64_ross_se
===================================================================
--- /issm/trunk/jenkins/linux64_ross_se	(revision 22757)
+++ /issm/trunk/jenkins/linux64_ross_se	(revision 22758)
@@ -15,5 +15,5 @@
 	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
 	--with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
-	--with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib -lmpi" \
+	--with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib -lmpi -lmpicxx -lmpifort" \
 	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
 	--with-metis-dir=$ISSM_DIR/externalpackages/petsc/install \
@@ -36,10 +36,10 @@
 
 #List of external pakages to be installed and their installation scripts
-EXTERNALPACKAGES="autotools     install.sh                
-						mpich         install-3.2-linux64.sh    
-						cmake         install.sh
+EXTERNALPACKAGES="autotools     install.sh    
+						cmake         install.sh                
+						mpich         install-3.2-linux64.sh
 						petsc         install-3.7-linux64.sh    
 						triangle      install-linux64.sh        
-						boost         install.sh                
+						boost         install-1.55-linux.sh
 						python        install-2.7.3-linux64.sh
                   nose          install-linux64-python2.sh
@@ -63,6 +63,6 @@
 NUMCPUS_INSTALL=5
 
-#number of cpus used in the nightly runs.
-NUMCPUS_RUN=4
+#number of cpus used in the nightly runs. (pb of access to all_vertices.txt if more than 1)
+NUMCPUS_RUN=1
 
 #Nightly run options. The matlab routine runme.m will be called
Index: /issm/trunk/jenkins/linux64_ross_static
===================================================================
--- /issm/trunk/jenkins/linux64_ross_static	(revision 22757)
+++ /issm/trunk/jenkins/linux64_ross_static	(revision 22758)
@@ -12,17 +12,17 @@
 	--enable-standalone-executables \
 	--enable-standalone-libraries \
+	--enable-standalone-modules \
 	--with-matlab-dir=$MATLAB_PATH \
 	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
 	--with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
-	--with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib -lmpich" \
+	--with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib -lmpi -lmpifort" \
 	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install  \
-	--with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install \
-	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
 	--with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install \
 	--with-metis-dir=$ISSM_DIR/externalpackages/petsc/install \
 	--with-m1qn3-dir=$ISSM_DIR/externalpackages/m1qn3/install \
-	--with-fortran-lib="-L/usr/lib/gcc/x86_64-linux-gnu/4.9 -lgfortran" \
-	--with-numthreads=4 \
-	--with-cxxoptflags="-fPIC"'
+	--with-fortran-lib="-L/usr/lib/gcc/x86_64-linux-gnu/4.9/ -lgfortran" \
+	--with-numthreads=4'
 
 #PYTHON and MATLAB testing
@@ -37,7 +37,7 @@
 EXTERNALPACKAGES="autotools    install.sh
 						cmake        install.sh
-						mpich        install-3.0-linux64-static.sh
+						mpich        install-3.2-linux64-static.sh
 						m1qn3        install.sh
-						petsc        install-3.6-linux64-static.sh
+						petsc        install-3.7-linux64-static.sh
 						triangle     install-linux64.sh
 						shell2junit  install.sh"
Index: /issm/trunk/jenkins/linux64_ross_test
===================================================================
--- /issm/trunk/jenkins/linux64_ross_test	(revision 22757)
+++ /issm/trunk/jenkins/linux64_ross_test	(revision 22758)
@@ -43,5 +43,5 @@
 						petsc         install-3.7-linux64.sh    
 						triangle      install-linux64.sh        
-						boost         install.sh                
+						boost         install-1.55-linux.sh
 						dakota        install-6.2-linux64.sh  
 						chaco         install.sh 
@@ -64,4 +64,4 @@
 #by Matlab and runme.m
 #ex: "'id',[101 102 103]"
-PYTHON_NROPTIONS="--exclude 119 243 514 701 702 435"
-MATLAB_NROPTIONS="'exclude',[119,243,514,701,702,435]"
+PYTHON_NROPTIONS="--exclude 243 701 702 703 435"
+MATLAB_NROPTIONS="'exclude',[243,701,702,435]"
Index: /issm/trunk/jenkins/macosx_pine-island
===================================================================
--- /issm/trunk/jenkins/macosx_pine-island	(revision 22757)
+++ /issm/trunk/jenkins/macosx_pine-island	(revision 22758)
@@ -54,5 +54,5 @@
 #by Matlab and runme.m
 #ex: "'id',[101 102 103]"
-##                           bamg mesh   FS                     
+##                           FS                     
 PYTHON_NROPTIONS=""
-MATLAB_NROPTIONS="'exclude',[119,514,701,702,703,435,IdFromString('Dakota')]"
+MATLAB_NROPTIONS="'exclude',[701,702,703,435,IdFromString('Dakota')]"
Index: /issm/trunk/jenkins/macosx_pine-island_dakota_static
===================================================================
--- /issm/trunk/jenkins/macosx_pine-island_dakota_static	(revision 22757)
+++ /issm/trunk/jenkins/macosx_pine-island_dakota_static	(revision 22758)
@@ -64,3 +64,3 @@
 ##                           bamg mesh   FS                     
 #PYTHON_NROPTIONS=""
-#MATLAB_NROPTIONS="'exclude',[119,243,514,701,702,703,435,IdFromString('Dakota')]"
+#MATLAB_NROPTIONS="'exclude',[243,701,702,703,435,IdFromString('Dakota')]"
Index: /issm/trunk/jenkins/windows
===================================================================
--- /issm/trunk/jenkins/windows	(revision 22757)
+++ /issm/trunk/jenkins/windows	(revision 22758)
@@ -11,8 +11,9 @@
 	--with-vendor=MSVC-Win64  \
 	--with-cxxoptflags='-fp:strict' \
-   --disable-static \
+	--disable-static \
 	--enable-standalone-libraries \
 	--with-fortran=no  \
 	--without-GiaIvins \
+	--without-Love \
 	--without-kriging \
 	--without-kml \
@@ -60,4 +61,4 @@
 
 #In Windows, we don't yet have MUMPS, can't do full stokes, so exclude all FS runs. Also exclude all runs with Dakota. And exclude higher order runs that have penalties. And 800+ tests because we don't want to have --with-development since we do the binaries with this version
-MATLAB_NROPTIONS="'exclude',[104, 124,125,126, 204, 211, 215, 220, 221, 285, 290, 308, 322, 404, 421, 422, 503, 507, 510, 511, 513, 701, 702, 703, 218, 234, 235, 250, 251, 412, 413, 414, 417, 418, 420, 440, 205, 274, 331, 405, 409, 455, 612, 514, 435, 280,801,802,803,804,805,291,340,341,460,243]"
+MATLAB_NROPTIONS="'exclude',[104,119, 124,125,126, 204, 211, 215, 220, 221, 285, 290, 308, 322, 404, 421, 422, 503, 507, 510, 511, 513, 701, 702, 703, 218, 234, 235, 250, 251, 412, 413, 414, 417, 418, 420, 440,444, 205, 274, 331, 405, 409, 455, 612, 514, 435, 280, 801, 802, 803, 804, 805, 291, 340, 341, 460, 243, 430, 441, 442, 463, 464, 465, 244]"
 PYTHON_NROPTIONS=""
Index: /issm/trunk/jenkins/windows_test
===================================================================
--- /issm/trunk/jenkins/windows_test	(revision 22757)
+++ /issm/trunk/jenkins/windows_test	(revision 22758)
@@ -31,4 +31,4 @@
 
 #In Windows, we don't yet have MUMPS, can't do full stokes, so exclude all FS runs. Also exclude all runs with Dakota. And exclude higher order runs that have penalties. And 800+ tests because we don't want to have --with-development since we do the binaries with this version
-MATLAB_NROPTIONS="'exclude',[104, 124, 204, 211, 215, 220, 221, 285, 290, 308, 322, 404, 421, 422, 503, 507, 510, 511, 513, 701, 702, 703, 218, 234, 235, 412, 413, 414, 417, 418, 420, 205, 274, 331, 405, 409, 455, 612, 514, 435, 280,801,802,803,804,805,291,340,341]"
+MATLAB_NROPTIONS="'exclude',[104, 124, 204, 211, 215, 220, 221, 285, 290, 308, 322, 404, 421, 422, 503, 507, 510, 511, 513, 701, 702, 703, 218, 234, 235, 412, 413, 414, 417, 418, 420, 205, 274, 331, 405, 409, 455, 612, 514, 435, 280, 801, 802, 803, 804, 805, 291, 340, 341]"
 PYTHON_NROPTIONS=""
Index: /issm/trunk/m4/analyses.m4
===================================================================
--- /issm/trunk/m4/analyses.m4	(revision 22757)
+++ /issm/trunk/m4/analyses.m4	(revision 22758)
@@ -842,28 +842,28 @@
 
 dnl }}}
-dnl with-Meshdeformation{{{
-
-AC_ARG_WITH([Meshdeformation],
-
-	AS_HELP_STRING([--with-Meshdeformation = YES], [compile with Meshdeformation capabilities (default is yes)]),
-
-	[MESHDEFORMATION=$withval],[MESHDEFORMATION=yes])
-
-AC_MSG_CHECKING(for Meshdeformation capability compilation)
-
-
-HAVE_MESHDEFORMATION=no 
-
-if test "x$MESHDEFORMATION" = "xyes"; then
-
-	HAVE_MESHDEFORMATION=yes
-
-	AC_DEFINE([_HAVE_MESHDEFORMATION_],[1],[with Meshdeformation capability])
-
-fi
-
-AM_CONDITIONAL([MESHDEFORMATION], [test x$HAVE_MESHDEFORMATION = xyes])
-
-AC_MSG_RESULT($HAVE_MESHDEFORMATION)
+dnl with-Love{{{
+
+AC_ARG_WITH([Love],
+
+	AS_HELP_STRING([--with-Love = YES], [compile with Love capabilities (default is yes)]),
+
+	[LOVE=$withval],[LOVE=yes])
+
+AC_MSG_CHECKING(for Love capability compilation)
+
+
+HAVE_LOVE=no 
+
+if test "x$LOVE" = "xyes"; then
+
+	HAVE_LOVE=yes
+
+	AC_DEFINE([_HAVE_LOVE_],[1],[with Love capability])
+
+fi
+
+AM_CONDITIONAL([LOVE], [test x$HAVE_LOVE = xyes])
+
+AC_MSG_RESULT($HAVE_LOVE)
 
 dnl }}}
Index: /issm/trunk/m4/issm_options.m4
===================================================================
--- /issm/trunk/m4/issm_options.m4	(revision 22757)
+++ /issm/trunk/m4/issm_options.m4	(revision 22758)
@@ -714,5 +714,5 @@
 	if test "x$HAVE_SCOTCH" = "xyes"; then
 		SCOTCHINCL="-DNOFILEIO -I$SCOTCH_ROOT/include -DSCOTCH_VERSION=\\\"UNKNOWN\\\""
-		SCOTCHLIB="-L$SCOTCH_ROOT/lib -lnfioscotch -lnfioscotcherr -lnfioscotcherrexit -lscotchmetis"
+		SCOTCHLIB="-L$SCOTCH_ROOT/lib -lnfioscotch -lnfioscotcherr -lnfioscotcherrexit "
 		AC_DEFINE([_HAVE_SCOTCH_],[1],[with Scotch in ISSM src])
 		AC_SUBST([SCOTCHINCL])
@@ -1302,27 +1302,36 @@
 	dnl }}}
 	dnl scalapack{{{
+
+	dnl Here, either just the directory is provided, or the library, we handle both cases
 	AC_ARG_WITH([scalapack-dir],
 	  AS_HELP_STRING([--with-scalapack-dir=DIR],[scalapack root directory]),
 	  [SCALAPACK_ROOT=$withval],[SCALAPACK_ROOT="no"])
+
+	AC_ARG_WITH([scalapack-lib],
+	  AS_HELP_STRING([--with-scalapack-lib=LIBS],[scalapack libraries to include]),
+	  [SCALAPACKLIB=$withval],[SCALAPACKLIB="no"])
 			  
 	dnl Check whether scalapack is enabled
 	AC_MSG_CHECKING([for scalapack])
-	if test "x$SCALAPACK_ROOT" = "xno" ; then
-		HAVE_SCALAPACK=no
-	else
+	if test "x$SCALAPACK_ROOT" = "xno" && test "x$SCALAPACKLIB" = "xno"; then
+			HAVE_SCALAPACK=no
+			SCALAPACKLIB=
+	else if test "x$SCALAPACK_ROOT" != "xno"; then
+		if ! test -d "$SCALAPACK_ROOT"; then
+		 AC_MSG_ERROR([scalapack directory provided ($SCALAPACK_ROOT) does not exist]);
+		fi
 		HAVE_SCALAPACK=yes
-		if ! test -d "$SCALAPACK_ROOT"; then
-			AC_MSG_ERROR([scalapack directory provided ($SCALAPACK_ROOT) does not exist]);
-		fi
+		SCALAPACKLIB=-L"$SCALAPACK_ROOT/ -lscalapack"
+	else if test "x$SCALAPACKLIB" != "xno"; then
+		HAVE_SCALAPACK=yes
+	else
+	   AC_MSG_ERROR([cannot provide both scalapack dir and scalapack-lib])
+	fi
+	fi
 	fi
 	AC_MSG_RESULT($HAVE_SCALAPACK)
 	
 	dnl scalapack headers and libraries
-	if test "x$HAVE_SCALAPACK" == "xyes"; then
-		if test x$VENDOR = xintel-discover; then
-		 SCALAPACKLIB=-L"$SCALAPACK_ROOT/ -lmkl_scalapack_lp64"
-		else
-		 SCALAPACKLIB=-L"$SCALAPACK_ROOT/ -lscalapack"
-		fi
+	if test "x$HAVE_SCALAPACK" = "xyes"; then
 		AC_DEFINE([_HAVE_SCALAPACK_],[1],[with Scalapack in ISSM src])
 		AC_SUBST([SCALAPACKLIB])
@@ -1349,23 +1358,16 @@
 	if test "x$HAVE_BLASLAPACK" == "xyes"; then
 		BLASLAPACKINCL=""
-		if test x$VENDOR = xintel-discover; then
-		   dnl works for intel 11
-			dnl BLASLAPACKLIB=-L"$BLASLAPACK_ROOT -lmkl_lapack -lmkl -lguide -lpthread "
-			dnl dnl works for intel 13
-			BLASLAPACKLIB=-L"$BLASLAPACK_ROOT -lmkl_lapack95_lp64 -lmkl_rt " 
-		else
-			dnl: branch on whether we are running on windows or linux.
-			case "${host_os}" in
-				*cygwin*)
-				BLASLAPACKLIB="-L`cygpath -m $BLASLAPACK_ROOT` -Wl,libf2cblas.lib  -Wl,libf2clapack.lib"
-				;;
-				*linux*)
-				BLASLAPACKLIB=-L"$BLASLAPACK_ROOT/lib -lflapack -lfblas " 
-				;;
-				*darwin*)
-				BLASLAPACKLIB=-L"$BLASLAPACK_ROOT/lib -lflapack -lfblas " 
-				;;
-			esac
-		fi
+		dnl: branch on whether we are running on windows or linux.
+		case "${host_os}" in
+		*cygwin*)
+		  BLASLAPACKLIB="-L`cygpath -m $BLASLAPACK_ROOT` -Wl,libf2cblas.lib  -Wl,libf2clapack.lib"
+		  ;;
+		*linux*)
+		  BLASLAPACKLIB=-L"$BLASLAPACK_ROOT/lib -lflapack -lfblas " 
+		  ;;
+		*darwin*)
+		  BLASLAPACKLIB=-L"$BLASLAPACK_ROOT/lib -lflapack -lfblas " 
+		  ;;
+		esac
 		AC_DEFINE([_HAVE_BLASLAPACK_],[1],[with blas lapack in ISSM src])
 		AC_SUBST([BLASLAPACKLIB])
@@ -1472,9 +1474,5 @@
 	if test "x$HAVE_BLACS" == "xyes"; then
 		BLACSINCL=""
-		if test x$VENDOR = xintel-discover; then
-		 BLACSLIB=-L"$BLACS_ROOT/ -lmkl_blacs_intelmpi_lp64"
-		else
-		 BLACSLIB=-L"$BLACS_ROOT/ -lblacs"
-		fi
+		BLACSLIB=-L"$BLACS_ROOT/ -lblacs"
 		AC_DEFINE([_HAVE_BLACS_],[1],[with Blacs in ISSM src])
 		AC_SUBST([BLACSINCL])
@@ -1873,5 +1871,28 @@
 	if test "x$HAVE_NEOPZ" == "xyes"; then
 	  NEOPZLIB="$NEOPZ_ROOT/lib/libpz.a"
-     NEOPZINCL=-I"$NEOPZ_ROOT/include"
+     NEOPZINCL=" -I$NEOPZ_ROOT/include"
+	  NEOPZINCL+=" -I$NEOPZ_ROOT/include/Analysis"
+	  NEOPZINCL+=" -I$NEOPZ_ROOT/include/Common"
+	  NEOPZINCL+=" -I$NEOPZ_ROOT/include/External"
+	  NEOPZINCL+=" -I$NEOPZ_ROOT/include/Frontal"
+	  NEOPZINCL+=" -I$NEOPZ_ROOT/include/Geom"
+	  NEOPZINCL+=" -I$NEOPZ_ROOT/include/Integral"
+	  NEOPZINCL+=" -I$NEOPZ_ROOT/include/LinearSolvers"
+	  NEOPZINCL+=" -I$NEOPZ_ROOT/include/Material"
+	  NEOPZINCL+=" -I$NEOPZ_ROOT/include/Matrix"
+	  NEOPZINCL+=" -I$NEOPZ_ROOT/include/Mesh"
+	  NEOPZINCL+=" -I$NEOPZ_ROOT/include/Multigrid"
+	  NEOPZINCL+=" -I$NEOPZ_ROOT/include/PerfUtil"
+	  NEOPZINCL+=" -I$NEOPZ_ROOT/include/Post"
+	  NEOPZINCL+=" -I$NEOPZ_ROOT/include/Pre"
+	  NEOPZINCL+=" -I$NEOPZ_ROOT/include/Refine"
+	  NEOPZINCL+=" -I$NEOPZ_ROOT/include/Save"
+	  NEOPZINCL+=" -I$NEOPZ_ROOT/include/Shape"
+	  NEOPZINCL+=" -I$NEOPZ_ROOT/include/SpecialMaps"
+	  NEOPZINCL+=" -I$NEOPZ_ROOT/include/StrMatrix"
+	  NEOPZINCL+=" -I$NEOPZ_ROOT/include/SubStruct"
+	  NEOPZINCL+=" -I$NEOPZ_ROOT/include/Topology"
+	  NEOPZINCL+=" -I$NEOPZ_ROOT/include/Util"
+	  CXXFLAGS+=" -std=c++11"
 	  AC_DEFINE([_HAVE_NEOPZ_],[1],[with NEOPZ in ISSM src])
 	  AC_SUBST([NEOPZINCL])
@@ -1912,6 +1933,6 @@
 	dnl with-kml{{{
 	AC_ARG_WITH([kml],
-		AS_HELP_STRING([--with-kml = YES],[compile with kml capabilities (default is yes)]),
-		[KML=$withval],[KML=yes]) 
+		AS_HELP_STRING([--with-kml = YES],[compile with kml capabilities (default is no)]),
+		[KML=$withval],[KML=no]) 
 	AC_MSG_CHECKING(for kml capability compilation)
 
@@ -2075,4 +2096,14 @@
 		  fi
 
+       dnl check that fortran is provided if GiaIvins is on
+		 if test "$HAVE_GIAIVINS" = "yes" &&  test "$HAVE_FORTRAN" = "no" ; then
+			  AC_MSG_ERROR([need fortran compiler to compile GiaIvins (or use --without-GiaIvins )]);
+		 fi
+			
+       dnl check that fortran is provided if Love is on
+		 if test "$HAVE_LOVE" = "yes" &&  test "$HAVE_FORTRAN" = "no" ; then
+			  AC_MSG_ERROR([need fortran compiler to compile Love (or use --without-Love)]);
+		 fi
+
 		  dnl check that if we have MPI, we have metis
 		  if test "$HAVE_METIS" = "yes"  && test "$HAVE_MPI" = "no" ; then
Index: /issm/trunk/src/c/Makefile.am
===================================================================
--- /issm/trunk/src/c/Makefile.am	(revision 22757)
+++ /issm/trunk/src/c/Makefile.am	(revision 22758)
@@ -50,4 +50,10 @@
 					 ./modules/BamgConvertMeshx/BamgConvertMeshx.cpp\
 					 ./modules/BamgTriangulatex/BamgTriangulatex.cpp
+
+#do not include AmrBamg with ADOLC
+if ADOLC
+else
+issm_sources += ./classes/AmrBamg.cpp
+endif
 endif
 #}}}
@@ -66,6 +72,13 @@
 					./classes/DofIndexing.cpp\
 					./classes/Contours.cpp\
+					./classes/Vertices.cpp\
 					./classes/Nodes.cpp\
-					./classes/Vertices.cpp\
+					./classes/Numberedcostfunction.cpp\
+					./classes/Misfit.cpp\
+					./classes/Cfsurfacesquare.cpp\
+					./classes/Cfdragcoeffabsgrad.cpp\
+					./classes/Cfsurfacelogvel.cpp\
+					./classes/Regionaloutput.cpp\
+					./classes/Nodalvalue.cpp\
 					./classes/Node.cpp\
 					./classes/Vertex.cpp\
@@ -93,4 +106,5 @@
 					./classes/Materials/Materials.cpp\
 					./classes/Materials/Matice.cpp\
+					./classes/Materials/Matlitho.cpp\
 					./classes/Materials/Matestar.cpp\
 					./classes/Materials/Matpar.cpp\
@@ -122,4 +136,5 @@
 					./classes/Params/VectorParam.cpp\
 					./classes/Params/TransientParam.cpp\
+					./classes/Params/TransientArrayParam.cpp\
 					./classes/Params/DataSetParam.cpp\
 					./classes/Profiler.cpp\
@@ -208,4 +223,5 @@
 					./modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp\
 					./modules/FloatingiceMeltingRatex/FloatingiceMeltingRatex.cpp\
+					./modules/FloatingiceMeltingRatePicox/FloatingiceMeltingRatePicox.cpp\
 					./modules/ConfigureObjectsx/ConfigureObjectsx.cpp\
 					./modules/SpcNodesx/SpcNodesx.cpp\
@@ -272,4 +288,5 @@
 					./cores/controlad_core.cpp\
 					./cores/controlm1qn3_core.cpp\
+					./cores/controladm1qn3_core.cpp\
 					./cores/controlvalidation_core.cpp\
 					./cores/adjointstressbalance_core.cpp\
@@ -280,4 +297,5 @@
 					./cores/hydrology_core.cpp\
 					./solutionsequences/solutionsequence_hydro_nonlinear.cpp\
+					./solutionsequences/solutionsequence_shakti_nonlinear.cpp\
 					./cores/stressbalance_core.cpp\
 					./solutionsequences/solutionsequence_stokescoupling_nonlinear.cpp\
@@ -288,5 +306,4 @@
 					./cores/surfaceslope_core.cpp\
 					./cores/bedslope_core.cpp\
-					./cores/meshdeformation_core.cpp\
 					./cores/damage_core.cpp\
 					./cores/levelsetfunctionslope_core.cpp\
@@ -323,5 +340,4 @@
 					./toolkits/petsc/patches/NewVec.cpp\
 					./toolkits/petsc/patches/PetscOptionsDetermineSolverType.cpp\
-					./toolkits/petsc/patches/PetscOptionsInsertMultipleString.cpp\
 					./toolkits/petsc/patches/NewMat.cpp\
 					./toolkits/petsc/patches/VecFree.cpp\
@@ -442,7 +458,4 @@
 issm_sources += ./analyses/SmoothAnalysis.cpp
 endif
-if MESHDEFORMATION
-issm_sources += ./analyses/MeshdeformationAnalysis.cpp
-endif
 if LEVELSET
 issm_sources += ./analyses/LevelsetAnalysis.cpp
@@ -453,6 +466,7 @@
 endif
 #}}}
-#Gia sources  {{{
+#Gia sources  (only if have fortran){{{
 if GIAIVINS
+if FORTRAN
 issm_sources +=  ./cores/gia_core.cpp\
 					./analyses/GiaIvinsAnalysis.cpp\
@@ -466,4 +480,19 @@
 					./modules/GiaDeflectionCorex/what0.f
 endif
+endif
+#}}}
+#Love sources  (only if have fortran){{{
+if LOVE
+if FORTRAN
+issm_sources +=  ./cores/love_core.cpp\
+				 ./analyses/LoveAnalysis.cpp\
+				./modules/FourierLoveCorex/FourierLoveCorex.cpp\
+				./modules/FourierLoveCorex/lnb_param.f90\
+				./modules/FourierLoveCorex/model.f90\
+				./modules/FourierLoveCorex/util.f90\
+				./modules/FourierLoveCorex/lovenb_sub.f90\
+				./modules/FourierLoveCorex/love_numbers.f90
+endif
+endif
 #}}}
 #Esa sources  {{{
@@ -493,7 +522,4 @@
 
 #Wrapper sources
-#Bamg sources  {{{
-
-#}}}
 #Kml sources  {{{
 kml_sources = ./modules/Exp2Kmlx/Exp2Kmlx.cpp\
@@ -538,11 +564,11 @@
 			./shared/Threads/PartitionRange.cpp\
 			./shared/Exp/exp.cpp\
-			./shared/TriMesh/AssociateSegmentToElement.cpp\
-			./shared/TriMesh/GridInsideHole.cpp\
-			./shared/TriMesh/OrderSegments.cpp\
-			./shared/TriMesh/SplitMeshForRifts.cpp\
-			./shared/TriMesh/TriMeshUtils.cpp\
-			./modules/TriMeshx/TriMeshx.cpp\
-			./modules/TriMeshProcessRiftsx/TriMeshProcessRiftsx.cpp\
+			./shared/Triangle/AssociateSegmentToElement.cpp\
+			./shared/Triangle/GridInsideHole.cpp\
+			./shared/Triangle/OrderSegments.cpp\
+			./shared/Triangle/SplitMeshForRifts.cpp\
+			./shared/Triangle/TriangleUtils.cpp\
+			./modules/Trianglex/Trianglex.cpp\
+			./modules/ProcessRiftsx/ProcessRiftsx.cpp\
 			./modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.cpp\
 			./modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp\
Index: /issm/trunk/src/c/analyses/AdjointBalancethickness2Analysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/AdjointBalancethickness2Analysis.cpp	(revision 22757)
+++ /issm/trunk/src/c/analyses/AdjointBalancethickness2Analysis.cpp	(revision 22758)
@@ -90,4 +90,10 @@
 				case SurfaceAbsMisfitEnum:
 					for(i=0;i<numnodes;i++) pe->values[i]+=(surfaceobs-surface)*weight*Jdet*gauss->weight*basis[i];
+					break;
+				case OmegaAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case EtaDiffEnum:
+					/*Nothing in P vector*/
 					break;
 				default:
@@ -132,4 +138,6 @@
 			/*Nothing, \partial J/\partial k = 0*/
 			break;
+		case OmegaAbsGradientEnum: GradientJOmegaGradient(element,gradient,control_index); break;
+		case EtaDiffEnum: GradientJEtaDiff(element,gradient,control_index); break;
 		default: _error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
 	}
@@ -192,5 +200,6 @@
 
 	/*Intermediaries*/
-	IssmDouble dlambda[2],ds[2],D0,omega,Jdet; 
+	int         n=3;
+	IssmDouble  dlambda[2],ds[2],slopex,slopey,slope,omega,Jdet,velobs;
 	IssmDouble *xyz_list= NULL;
 
@@ -207,7 +216,9 @@
 	element->GradientIndexing(&vertexpidlist[0],control_index);
 	Input* adjoint_input = element->GetInput(AdjointEnum);            _assert_(adjoint_input);
-	Input* s_input       = element->GetInput(SurfaceEnum);            _assert_(s_input);
-	Input* D0_input      = element->GetInput(BalancethicknessD0Enum); _assert_(D0_input);
 	Input* omega_input   = element->GetInput(BalancethicknessOmegaEnum); _assert_(omega_input);
+	Input* surface_input = element->GetInput(SurfaceEnum); _assert_(surface_input); 
+	Input* surfaceslopex_input = element->GetInput(SurfaceSlopeXEnum); _assert_(surfaceslopex_input); 
+	Input* surfaceslopey_input = element->GetInput(SurfaceSlopeYEnum); _assert_(surfaceslopey_input); 
+	Input* velobs_input        = element->GetInput(InversionVelObsEnum); _assert_(velobs_input); 
 
 	Gauss* gauss=element->NewGauss(2);
@@ -218,12 +229,17 @@
 		element->NodalFunctionsP1(basis,gauss);
 
-		D0_input->GetInputValue(&D0,gauss);
 		omega_input->GetInputValue(&omega,gauss);
 		adjoint_input->GetInputDerivativeValue(&dlambda[0],xyz_list,gauss);
-		s_input->GetInputDerivativeValue(&ds[0],xyz_list,gauss);
+		surface_input->GetInputDerivativeValue(&ds[0],xyz_list,gauss);
+		surfaceslopex_input->GetInputValue(&slopex,gauss);
+		surfaceslopey_input->GetInputValue(&slopey,gauss);
+		velobs_input->GetInputValue(&velobs,gauss);
+
+		slope = sqrt(slopex*slopex + slopey*slopey);
+		//if(slope<1.e-5) slope = 1.e-5;
 
 		/*Build gradient vector (actually -dJ/da): */
 		for(int i=0;i<numvertices;i++){
-			ge[i]+= -Jdet*gauss->weight*basis[i]*exp(omega)*D0*(ds[0]*dlambda[0] + ds[1]*dlambda[1]);
+			ge[i]+= - Jdet*gauss->weight*basis[i]*velobs/slope*(ds[0]*dlambda[0] + ds[1]*dlambda[1]);
 			_assert_(!xIsNan<IssmDouble>(ge[i]));
 		}
@@ -237,4 +253,104 @@
 	xDelete<int>(vertexpidlist);
 	delete gauss;
+}/*}}}*/
+void           AdjointBalancethickness2Analysis::GradientJOmegaGradient(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble Jdet,weight;
+	IssmDouble dk[3]; 
+	IssmDouble *xyz_list= NULL;
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* dbasis        = xNew<IssmDouble>(2*numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Retrieve all inputs we will be needing: */
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* omega_input = element->GetInput(BalancethicknessOmegaEnum); _assert_(omega_input);
+	Input* weights_input         = element->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctionsP1Derivatives(dbasis,xyz_list,gauss);
+		weights_input->GetInputValue(&weight,gauss,OmegaAbsGradientEnum);
+
+		/*Build alpha_complement_list: */
+		omega_input->GetInputDerivativeValue(&dk[0],xyz_list,gauss);
+
+		/*Build gradient vector (actually -dJ/ddrag): */
+		for(int i=0;i<numvertices;i++){
+			ge[i]+=-weight*Jdet*gauss->weight*2*(dk[0]*dk[0] + dk[1]*dk[1])*(dbasis[0*numvertices+i]*dk[0]+dbasis[1*numvertices+i]*dk[1]);
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(dbasis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+
+}/*}}}*/
+void           AdjointBalancethickness2Analysis::GradientJEtaDiff(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble Jdet,weight;
+	IssmDouble omega,omega0; 
+	IssmDouble *xyz_list= NULL;
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Retrieve all inputs we will be needing: */
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* omega_input = element->GetInput(BalancethicknessOmegaEnum);   _assert_(omega_input);
+	Input* omega0_input = element->GetInput(BalancethicknessOmega0Enum); _assert_(omega0_input);
+	Input* weights_input = element->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctionsP1(basis,gauss);
+		weights_input->GetInputValue(&weight,gauss,EtaDiffEnum);
+
+		/*Build alpha_complement_list: */
+		omega_input->GetInputValue(&omega,gauss);
+		omega0_input->GetInputValue(&omega0,gauss);
+
+		/*Build gradient vector (actually -dJ/ddrag): */
+		for(int i=0;i<numvertices;i++){
+			ge[i]+=-weight*Jdet*gauss->weight*(omega - omega0)*basis[i];
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+
 }/*}}}*/
 void           AdjointBalancethickness2Analysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
Index: /issm/trunk/src/c/analyses/AdjointBalancethickness2Analysis.h
===================================================================
--- /issm/trunk/src/c/analyses/AdjointBalancethickness2Analysis.h	(revision 22757)
+++ /issm/trunk/src/c/analyses/AdjointBalancethickness2Analysis.h	(revision 22758)
@@ -30,4 +30,6 @@
 		void           GradientJdHdt(Element* element,Vector<IssmDouble>* gradient,int control_index);
 		void           GradientJOmega(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void           GradientJOmegaGradient(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void           GradientJEtaDiff(Element* element,Vector<IssmDouble>* gradient,int control_index);
 		void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
 		void           UpdateConstraints(FemModel* femmodel);
Index: /issm/trunk/src/c/analyses/AdjointBalancethicknessAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/AdjointBalancethicknessAnalysis.cpp	(revision 22757)
+++ /issm/trunk/src/c/analyses/AdjointBalancethicknessAnalysis.cpp	(revision 22758)
@@ -176,4 +176,5 @@
 	if(control_type!=VxEnum && 
 		control_type!=VyEnum && 
+		control_type!=BalancethicknessSpcthicknessEnum && 
 		control_type!=BalancethicknessThickeningRateEnum){
 		_error_("Control "<<EnumToStringx(control_type)<<" not supported");
@@ -192,4 +193,5 @@
 	/*Deal with second term*/
 	switch(control_type){
+		case BalancethicknessSpcthicknessEnum:   GradientJDirichlet(element,gradient,control_index); break;
 		case BalancethicknessThickeningRateEnum: GradientJDhDt(element,gradient,control_index); break;
 		case VxEnum:                             GradientJVx(  element,gradient,control_index); break;
@@ -201,4 +203,41 @@
 	xDelete<int>(responses);
 
+}/*}}}*/
+void           AdjointBalancethicknessAnalysis::GradientJDirichlet(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	IssmDouble* lambda        = xNew<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Retrieve all inputs we will be needing: */
+	element->GradientIndexing(&vertexpidlist[0],control_index);
+	element->GetInputListOnVertices(lambda,AdjointEnum);
+
+	BalancethicknessAnalysis* analysis = new BalancethicknessAnalysis();
+	ElementMatrix* Ke = analysis->CreateKMatrix(element);
+	delete analysis;
+
+	/*Transpose and return Ke*/
+	Ke->Transpose();
+	_assert_(Ke->nrows == numvertices && Ke->ncols == numvertices);
+
+	for(int i=0;i<numvertices;i++){
+		for(int j=0;j<numvertices;j++){
+			ge[i] += Ke->values[i*Ke->ncols + j] * lambda[j];
+		}
+		//ge[i]=-lambda[i];
+		_assert_(!xIsNan<IssmDouble>(ge[i]));
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,INS_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(ge);
+	xDelete<IssmDouble>(lambda);
+	xDelete<int>(vertexpidlist);
+	delete Ke;
 }/*}}}*/
 void           AdjointBalancethicknessAnalysis::GradientJDhDt(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
Index: /issm/trunk/src/c/analyses/AdjointBalancethicknessAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/AdjointBalancethicknessAnalysis.h	(revision 22757)
+++ /issm/trunk/src/c/analyses/AdjointBalancethicknessAnalysis.h	(revision 22758)
@@ -28,4 +28,5 @@
 		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
 		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void           GradientJDirichlet(Element* element,Vector<IssmDouble>* gradient,int control_index);
 		void           GradientJDhDt(Element* element,Vector<IssmDouble>* gradient,int control_index);
 		void           GradientJVx(Element* element,Vector<IssmDouble>* gradient,int control_index);
Index: /issm/trunk/src/c/analyses/AdjointHorizAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/AdjointHorizAnalysis.cpp	(revision 22757)
+++ /issm/trunk/src/c/analyses/AdjointHorizAnalysis.cpp	(revision 22758)
@@ -105,5 +105,5 @@
 
 		element->StrainRateHO(&epsilon[0],xyz_list,gauss,vx_input,vy_input);
-		element->material->ViscosityFSDerivativeEpsSquare(&mu_prime,&epsilon[0]);
+		element->material->ViscosityFSDerivativeEpsSquare(&mu_prime,&epsilon[0],gauss);
 		eps1[0]=epsilon[0];   eps2[0]=epsilon[2];   eps3[0]=epsilon[3];
 		eps1[1]=epsilon[2];   eps2[1]=epsilon[1];   eps3[1]=epsilon[4];
@@ -179,5 +179,5 @@
 
 		element->StrainRateHO(&epsilon[0],xyz_list,gauss,vx_input,vy_input);
-		element->material->ViscosityHODerivativeEpsSquare(&mu_prime,&epsilon[0]);
+		element->material->ViscosityHODerivativeEpsSquare(&mu_prime,&epsilon[0],gauss);
 		eps1[0]=2.*epsilon[0]+epsilon[1];   eps2[0]=epsilon[2];
 		eps1[1]=epsilon[2];                 eps2[1]=epsilon[0]+2.*epsilon[1];
@@ -226,4 +226,7 @@
 }/*}}}*/
 ElementMatrix* AdjointHorizAnalysis::CreateKMatrixSSA(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
 
 	/*Intermediaries*/
@@ -283,5 +286,5 @@
 		thickness_input->GetInputValue(&thickness, gauss);
 		basalelement->StrainRateSSA(&epsilon[0],xyz_list,gauss,vx_input,vy_input);
-		basalelement->material->ViscositySSADerivativeEpsSquare(&mu_prime,&epsilon[0]);
+		basalelement->material->ViscositySSADerivativeEpsSquare(&mu_prime,&epsilon[0],gauss);
 		eps1[0]=2.*epsilon[0]+epsilon[1]; eps2[0]=epsilon[2];
 		eps1[1]=epsilon[2];               eps2[1]=epsilon[0]+2*epsilon[1];
@@ -808,4 +811,7 @@
 	Element* basalelement;
 
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
 	/*Get basal element*/
 	element->FindParam(&domaintype,DomainTypeEnum);
@@ -2172,4 +2178,6 @@
 			alpha=(pow(q_exp-1,q_exp-1))/pow(q_exp,q_exp);
 		}
+
+		vmag  = sqrt(vx*vx + vy*vy);
 		Chi   = vmag/(pow(C_param,n)*pow(Neff,n)*As);
 		Gamma = (Chi/(1.+alpha*pow(Chi,q_exp)));
Index: /issm/trunk/src/c/analyses/Balancethickness2Analysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/Balancethickness2Analysis.cpp	(revision 22757)
+++ /issm/trunk/src/c/analyses/Balancethickness2Analysis.cpp	(revision 22758)
@@ -35,8 +35,9 @@
 	iomodel->FetchDataToInput(elements,"md.slr.sealevel",SealevelEnum,0);
 	iomodel->FetchDataToInput(elements,"md.mask.ice_levelset",MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,"md.initialization.vx",VxEnum);
+	iomodel->FetchDataToInput(elements,"md.initialization.vy",VyEnum);
 	iomodel->FetchDataToInput(elements,"md.basalforcings.groundedice_melting_rate",BasalforcingsGroundediceMeltingRateEnum);
 	iomodel->FetchDataToInput(elements,"md.smb.mass_balance",SmbMassBalanceEnum);
 	iomodel->FetchDataToInput(elements,"md.balancethickness.thickening_rate",BalancethicknessThickeningRateEnum);
-	iomodel->FetchDataToInput(elements,"md.balancethickness.omega",BalancethicknessOmegaEnum);
 
 	/*Update elements: */
@@ -63,68 +64,4 @@
 	return NULL;
 }/*}}}*/
-void           Balancethickness2Analysis::CreateD0(Element* element){/*{{{*/
-
-	/*Intermediaries */
-	IssmDouble       Gamma,h,mu0,ds[2],Cmu,B,k,s,b,normds;
-	const int        n = 3;
-	const IssmDouble Hstar = 500.;
-	const IssmDouble Lstar = 500.e+3;
-	IssmDouble *xyz_list  = NULL;
-
-	/*Fetch number of vertices and allocate output*/
-	int  numnodes = element->GetNumberOfNodes();
-	IssmDouble* D0     = xNew<IssmDouble>(numnodes);
-
-	/*retrieve what we need: */
-	element->GetVerticesCoordinates(&xyz_list);
-	Input* surfaceslopex_input = element->GetInput(SurfaceSlopeXEnum);
-	Input* surfaceslopey_input = element->GetInput(SurfaceSlopeYEnum);
-	Input* surface_input       = element->GetInput(SurfaceEnum);            _assert_(surface_input);
-	Input* B_input             = element->GetInput(MaterialsRheologyBEnum); _assert_(B_input);
-	IssmDouble rhog            = element->GetMaterialParameter(MaterialsRhoIceEnum)*element->GetMaterialParameter(ConstantsGEnum);
-
-	/*Calculate damage evolution source term: */
-	Gauss* gauss=element->NewGauss();
-	for (int i=0;i<numnodes;i++){
-		gauss->GaussNode(element->GetElementType(),i);
-		
-		B_input->GetInputValue(&B,gauss);
-		if(surfaceslopex_input && surfaceslopey_input){
-			surfaceslopex_input->GetInputValue(&ds[0],gauss);
-			surfaceslopey_input->GetInputValue(&ds[1],gauss);
-		}
-		else{
-			surface_input->GetInputDerivativeValue(&ds[0],xyz_list,gauss);
-		}
-
-		/*check slopes*/
-		normds = sqrt(ds[0]*ds[0]+ds[1]*ds[1]);
-		if (normds==0.){
-			_error_("surface slope is zero");
-		}
-		if(normds<1.e-5){
-			ds[0] = ds[0]/normds*1.e+5;
-			ds[1] = ds[1]/normds*1.e+5;
-			normds = 1.e-5;
-		}
-
-		mu0   = pow(2.,(1-3*n)/(2.*n)) * B;
-		Gamma = pow(rhog,n) * pow(Hstar,2*(n+1)) * pow(Hstar/Lstar,2*(n+1)) * 1./pow(mu0,n);
-
-		D0[i] = Gamma*pow(ds[0]*ds[0]+ds[1]*ds[1],(n-1)/2)/(n+2);
-	}
-
-	/*Add input*/
-	element->AddInput(BalancethicknessD0Enum,D0,element->GetElementType());
-	//if(surfaceslopex_input && surfaceslopey_input){
-	//	element->DeleteInput(SurfaceSlopeXEnum);
-	//	element->DeleteInput(SurfaceSlopeYEnum);
-	//}
-	
-	/*Clean up and return*/
-	xDelete<IssmDouble>(D0);
-	xDelete<IssmDouble>(xyz_list);
-	delete gauss;
-}/*}}}*/
 ElementMatrix* Balancethickness2Analysis::CreateJacobianMatrix(Element* element){/*{{{*/
 _error_("Not implemented");
@@ -133,5 +70,6 @@
 
 	/*Intermediaries */
-	IssmDouble  Jdet,D0,omega;
+	IssmDouble  yts = 365*24*3600.;
+	IssmDouble  Jdet,vx,vy,vel;
 	IssmDouble* xyz_list = NULL;
 
@@ -145,10 +83,9 @@
 	/*Retrieve all inputs and parameters*/
 	element->GetVerticesCoordinates(&xyz_list);
-	Input* omega_input = element->GetInput(BalancethicknessOmegaEnum); _assert_(omega_input);
-	Input* D0_input    = element->GetInput(BalancethicknessD0Enum);
-	if(!D0_input){
-		this->CreateD0(element);
-		D0_input = element->GetInput(BalancethicknessD0Enum); _assert_(D0_input);
-	}
+	Input* vx_input = element->GetInput(VxEnum); _assert_(vx_input); 
+	Input* vy_input = element->GetInput(VyEnum); _assert_(vy_input);
+
+	/*Get element characteristic length*/
+	IssmDouble h = element->CharacteristicLength();
 
 	/* Start  looping on the number of gaussian points: */
@@ -158,10 +95,26 @@
 		element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
 		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
-		D0_input->GetInputValue(&D0,gauss);
-		omega_input->GetInputValue(&omega,gauss);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+
+		/*make sure are diffusivisty is large enough*/
+		vel = sqrt(vx*vx+vy*vy);
+		if(sqrt(vx*vx+vy*vy)==0.){
+			vx = 0.1/yts;
+			vy = 0.1/yts;
+			vel = sqrt(vx*vx+vy*vy);
+		}
+		else if(vel<30./yts){
+			vx = 0.;//vx/vel*0.01;
+			vy = 0.;//vy/vel*0.01;
+			vel = sqrt(vx*vx+vy*vy);
+			vel = 30./yts*500000.;
+		}
 
 		for(int i=0;i<numnodes;i++){
 			for(int j=0;j<numnodes;j++){
-				Ke->values[i*numnodes+j] += D0*exp(omega)*gauss->weight*Jdet*(dbasis[0*numnodes+i]*dbasis[0*numnodes+j] + dbasis[1*numnodes+i]*dbasis[1*numnodes+j]);
+				Ke->values[i*numnodes+j] += gauss->weight*Jdet*(
+							(vx*dbasis[0*numnodes+i] + vy*dbasis[1*numnodes+i])*(vx*dbasis[0*numnodes+j] + vy*dbasis[1*numnodes+j])
+				+ vel/500000.*(dbasis[0*numnodes+i]*dbasis[0*numnodes+j] + dbasis[1*numnodes+i]*dbasis[1*numnodes+j]));
 			}
 		}
@@ -176,6 +129,7 @@
 ElementVector* Balancethickness2Analysis::CreatePVector(Element* element){/*{{{*/
 
+	return NULL;
 	/*Intermediaries */
-	IssmDouble  dhdt,mb,ms,Jdet;
+	IssmDouble  dhdt[2],mb[2],ms[2],Jdet;
 	IssmDouble* xyz_list = NULL;
 
@@ -201,10 +155,12 @@
 		element->NodalFunctions(basis,gauss);
 
-		ms_input->GetInputValue(&ms,gauss);
-		mb_input->GetInputValue(&mb,gauss);
-		dhdt_input->GetInputValue(&dhdt,gauss);
+		ms_input->GetInputDerivativeValue(&ms[0],xyz_list,gauss);
 
-		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(
-					(ms-mb-dhdt)*basis[i]
+		ms_input->GetInputDerivativeValue(&ms[0],xyz_list,gauss);
+		mb_input->GetInputDerivativeValue(&mb[0],xyz_list,gauss);
+		dhdt_input->GetInputDerivativeValue(&dhdt[0],xyz_list,gauss);
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=0*Jdet*gauss->weight*(
+					(ms[0]+ms[1]-mb[0]-mb[1]-dhdt[0]-dhdt[1])*basis[i]
 					);
 	}
@@ -217,5 +173,5 @@
 }/*}}}*/
 void           Balancethickness2Analysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
-		element->GetSolutionFromInputsOneDof(solution,SurfaceEnum);
+		element->GetSolutionFromInputsOneDof(solution,ThicknessEnum);
 }/*}}}*/
 void           Balancethickness2Analysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
@@ -224,55 +180,6 @@
 void           Balancethickness2Analysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
-	/*Intermediaries*/
-	IssmDouble  ds[2],s,b,D;
-	IssmDouble* xyz_list = NULL;
+			element->InputUpdateFromSolutionOneDof(solution,ThicknessEnum);
 
-	//element->InputUpdateFromSolutionOneDof(solution,ThicknessEnum);
-	element->InputUpdateFromSolutionOneDof(solution,SurfaceEnum);
-
-	/*Fetch number of vertices and allocate velocity vectors*/
-	int numvertices = element->GetNumberOfVertices();
-	IssmDouble* vel_list = xNew<IssmDouble>(numvertices);
-	IssmDouble* vx_list  = xNew<IssmDouble>(numvertices);
-	IssmDouble* vy_list  = xNew<IssmDouble>(numvertices);
-
-	/*Retrieve all inputs and parameters*/
-	element->GetVerticesCoordinates(&xyz_list);
-	Input* D_input   = element->GetInput(BalancethicknessDiffusionCoefficientEnum);
-	Input* H_input   = element->GetInput(ThicknessEnum);                            _assert_(H_input);
-	Input* s_input   = element->GetInput(SurfaceEnum);                              _assert_(s_input);
-	Input* b_input   = element->GetInput(BaseEnum);                                 _assert_(b_input);
-
-	/*Calculate velocities*/
-	Gauss* gauss=element->NewGauss();
-	for(int iv=0;iv<numvertices;iv++){
-		gauss->GaussVertex(iv);
-
-		if(D_input){
-			D_input->GetInputValue(&D,gauss);
-		}
-		else{
-			D = 0.;
-		}
-		b_input->GetInputValue(&b,gauss);
-		s_input->GetInputValue(&s,gauss);
-		s_input->GetInputDerivativeValue(&ds[0],xyz_list,gauss);
-
-		vx_list[iv] = -1./(s-b)*D*ds[0];
-		vy_list[iv] = -1./(s-b)*D*ds[1];
-		vel_list[iv] = sqrt(pow(vx_list[iv],2) + pow(vy_list[iv],2));
-	}
-
-	/*Add vx and vy as inputs to the tria element: */
-	element->AddInput(VxEnum,vx_list,P1Enum);
-	element->AddInput(VyEnum,vy_list,P1Enum);
-	element->AddInput(VelEnum,vel_list,P1Enum);
-
-	/*Free ressources:*/
-	delete gauss;
-	xDelete<IssmDouble>(vy_list);
-	xDelete<IssmDouble>(vx_list);
-	xDelete<IssmDouble>(vel_list);
-	xDelete<IssmDouble>(xyz_list);
 }/*}}}*/
 void           Balancethickness2Analysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
Index: /issm/trunk/src/c/analyses/Balancethickness2Analysis.h
===================================================================
--- /issm/trunk/src/c/analyses/Balancethickness2Analysis.h	(revision 22757)
+++ /issm/trunk/src/c/analyses/Balancethickness2Analysis.h	(revision 22758)
@@ -23,5 +23,4 @@
 		void           Core(FemModel* femmodel);
 		ElementVector* CreateDVector(Element* element);
-		void           CreateD0(Element* element);
 		ElementMatrix* CreateJacobianMatrix(Element* element);
 		ElementMatrix* CreateKMatrix(Element* element);
Index: /issm/trunk/src/c/analyses/DamageEvolutionAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/DamageEvolutionAnalysis.cpp	(revision 22757)
+++ /issm/trunk/src/c/analyses/DamageEvolutionAnalysis.cpp	(revision 22758)
@@ -78,7 +78,5 @@
 	parameters->AddObject(iomodel->CopyConstantObject("md.damage.law",DamageLawEnum));
 	parameters->AddObject(iomodel->CopyConstantObject("md.damage.stabilization",DamageStabilizationEnum));
-	parameters->AddObject(iomodel->CopyConstantObject("md.damage.maxiter",DamageMaxiterEnum));
 	parameters->AddObject(iomodel->CopyConstantObject("md.damage.max_damage",DamageMaxDamageEnum));
-	parameters->AddObject(iomodel->CopyConstantObject("md.damage.elementinterp",DamageElementinterpEnum));
 
 	/*Requested outputs*/
@@ -99,5 +97,4 @@
 		parameters->AddObject(iomodel->CopyConstantObject("md.damage.c2",DamageC2Enum));
 		parameters->AddObject(iomodel->CopyConstantObject("md.damage.c3",DamageC3Enum));
-		parameters->AddObject(iomodel->CopyConstantObject("md.damage.c4",DamageC4Enum));
 		parameters->AddObject(iomodel->CopyConstantObject("md.damage.stress_threshold",DamageStressThresholdEnum));
 		parameters->AddObject(iomodel->CopyConstantObject("md.damage.kappa",DamageKappaEnum));
Index: /issm/trunk/src/c/analyses/EnthalpyAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/EnthalpyAnalysis.cpp	(revision 22757)
+++ /issm/trunk/src/c/analyses/EnthalpyAnalysis.cpp	(revision 22758)
@@ -20,6 +20,8 @@
 	/*Output*/
 	IssmDouble *spcvector  = NULL;
+	IssmDouble *spcvectorstatic  = NULL;
 	IssmDouble* times=NULL;
 	IssmDouble* values=NULL;
+	IssmDouble* issurface = NULL;
 
 	/*Fetch parameters: */
@@ -32,13 +34,7 @@
 
 	/*Fetch data: */
+	iomodel->FetchData(&issurface,&M,&N,"md.mesh.vertexonsurface"); _assert_(N>0); _assert_(M==iomodel->numberofvertices);
 	iomodel->FetchData(&spcvector,&M,&N,"md.thermal.spctemperature");
-
-	/*Convert spcs from temperatures to enthalpy*/
-	_assert_(N>0); _assert_(M>=iomodel->numberofvertices);
-	for(int i=0;i<iomodel->numberofvertices;i++){
-		for(int j=0;j<N;j++){
-			spcvector[i*N+j] = heatcapacity*(spcvector[i*N+j]-referencetemperature);
-		}
-	}
+	iomodel->FetchData(&spcvectorstatic,&M,&N,"md.thermal.spctemperature");
 
 	/*Specific case for PDD, we want the constaints to be updated by the PDD scheme itself*/
@@ -51,6 +47,27 @@
 	}
 
+	/*Convert spcs from temperatures to enthalpy*/
+	_assert_(N>0); _assert_(M>=iomodel->numberofvertices);
+	for(int i=0;i<iomodel->numberofvertices;i++){
+		for(int j=0;j<N;j++){
+			if (isdynamic){
+				if (issurface[i]==1){
+					spcvector[i*N+j] = heatcapacity*(spcvector[i*N+j]-referencetemperature);
+					spcvectorstatic[i*N+j] = NAN;
+				}
+				else{
+					spcvector[i*N+j] = NAN;
+					spcvectorstatic[i*N+j] = heatcapacity*(spcvectorstatic[i*N+j]-referencetemperature);
+				}
+			}
+			else{
+				spcvector[i*N+j] = heatcapacity*(spcvector[i*N+j]-referencetemperature);
+			}
+		}
+	}
+
 	if(isdynamic){
-		IoModelToDynamicConstraintsx(constraints,iomodel,spcvector,M,N,EnthalpyAnalysisEnum,finiteelement);
+		IoModelToDynamicConstraintsx(constraints,iomodel,spcvector,iomodel->numberofvertices,1,EnthalpyAnalysisEnum,finiteelement);
+		IoModelToConstraintsx(constraints,iomodel,spcvectorstatic,M,N,EnthalpyAnalysisEnum,finiteelement);
 	}
 	else{
@@ -60,4 +77,6 @@
 	/*Free ressources:*/
 	iomodel->DeleteData(spcvector,"md.thermal.spctemperature");
+	iomodel->DeleteData(spcvectorstatic,"md.thermal.spctemperature");
+	iomodel->DeleteData(issurface,"md.mesh.vertexonsurface");
 	xDelete<IssmDouble>(times);
 	xDelete<IssmDouble>(values);
@@ -174,7 +193,11 @@
 	switch(frictionlaw){
 		case 1:
+			iomodel->FindConstant(&FrictionCoupling,"md.friction.coupling");
 			iomodel->FetchDataToInput(elements,"md.friction.coefficient",FrictionCoefficientEnum);
 			iomodel->FetchDataToInput(elements,"md.friction.p",FrictionPEnum);
 			iomodel->FetchDataToInput(elements,"md.friction.q",FrictionQEnum);
+			if (FrictionCoupling==1){
+				iomodel->FetchDataToInput(elements,"md.friction.effective_pressure",FrictionEffectivePressureEnum);
+			}
 			break;
 		case 2:
@@ -187,5 +210,5 @@
 			iomodel->FetchDataToInput(elements,"md.friction.As",FrictionAsEnum);
 			iomodel->FetchDataToInput(elements,"md.friction.q",FrictionQEnum);
-			if (FrictionCoupling==0){
+			if (FrictionCoupling==1){
 				iomodel->FetchDataToInput(elements,"md.friction.effective_pressure",FrictionEffectivePressureEnum);
 			}
@@ -210,4 +233,14 @@
 			iomodel->FetchDataToInput(elements,"md.initialization.temperature",TemperatureEnum);
 			break;
+		case 7:
+			iomodel->FindConstant(&FrictionCoupling,"md.friction.coupling");
+			iomodel->FetchDataToInput(elements,"md.friction.coefficient",FrictionCoefficientEnum);
+			iomodel->FetchDataToInput(elements,"md.friction.coefficientcoulomb",FrictionCoefficientcoulombEnum);
+			iomodel->FetchDataToInput(elements,"md.friction.p",FrictionPEnum);
+			iomodel->FetchDataToInput(elements,"md.friction.q",FrictionQEnum);
+			if (FrictionCoupling==1){
+				iomodel->FetchDataToInput(elements,"md.friction.effective_pressure",FrictionEffectivePressureEnum);
+			}
+			break;
 		case 9:
 			iomodel->FetchDataToInput(elements,"md.friction.coefficient",FrictionCoefficientEnum);
@@ -217,5 +250,5 @@
 			break;
 		default:
-			_error_("not supported");
+			_error_("friction law not supported");
 	}
 
@@ -244,7 +277,14 @@
 	int frictionlaw;
 	iomodel->FindConstant(&frictionlaw,"md.friction.law");
-	if(frictionlaw==4 || frictionlaw==6) parameters->AddObject(iomodel->CopyConstantObject("md.friction.gamma",FrictionGammaEnum));
-	if(frictionlaw==3) parameters->AddObject(iomodel->CopyConstantObject("md.friction.coupling",FrictionCouplingEnum));
-	if(frictionlaw==9) parameters->AddObject(iomodel->CopyConstantObject("md.friction.gamma",FrictionGammaEnum));
+	if(frictionlaw==4 || frictionlaw==6){
+		parameters->AddObject(iomodel->CopyConstantObject("md.friction.gamma",FrictionGammaEnum));
+	}
+	if(frictionlaw==3 || frictionlaw==1 || frictionlaw==7){
+		parameters->AddObject(iomodel->CopyConstantObject("md.friction.coupling",FrictionCouplingEnum));
+	}
+	if(frictionlaw==9){
+		parameters->AddObject(iomodel->CopyConstantObject("md.friction.gamma",FrictionGammaEnum));
+		parameters->AddObject(new IntParam(FrictionCouplingEnum,0));
+	}
 }/*}}}*/
 
@@ -302,4 +342,8 @@
 		ComputeBasalMeltingrate(element);
 	}
+
+	/*extrude inputs*/
+	femmodel->parameters->SetParam(BasalforcingsGroundediceMeltingRateEnum,InputToExtrudeEnum);
+	extrudefrombase_core(femmodel);
 }/*}}}*/
 void           EnthalpyAnalysis::ComputeBasalMeltingrate(Element* element){/*{{{*/
@@ -525,7 +569,5 @@
 	IssmDouble*    basis    = xNew<IssmDouble>(numnodes);
 	IssmDouble*    dbasis   = xNew<IssmDouble>(3*numnodes);
-	IssmDouble*    B        = xNew<IssmDouble>(3*numnodes);
 	IssmDouble*    Bprime   = xNew<IssmDouble>(3*numnodes);
-	IssmDouble     D[3][3]  = {0.};
 	IssmDouble     K[3][3];
 
@@ -556,39 +598,39 @@
 
 		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis,gauss);
+		element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
 		D_scalar=gauss->weight*Jdet;
 		if(dt!=0.) D_scalar=D_scalar*dt;
 
 		/*Conduction: */
-		GetBConduct(B,element,xyz_list,gauss); 
-		D[0][0]=D_scalar*kappa/rho_ice;
-		D[1][1]=D_scalar*kappa/rho_ice;
-		D[2][2]=D_scalar*kappa/rho_ice;
-		TripleMultiply(B,3,numnodes,1,
-					&D[0][0],3,3,0,
-					B,3,numnodes,0,
-					&Ke->values[0],1);
+		for(int i=0;i<numnodes;i++){
+			for(int j=0;j<numnodes;j++){
+				Ke->values[i*numnodes+j] += D_scalar*kappa/rho_ice*(
+							dbasis[0*numnodes+j]*dbasis[0*numnodes+i] + dbasis[1*numnodes+j]*dbasis[1*numnodes+i] + dbasis[2*numnodes+j]*dbasis[2*numnodes+i]
+							);
+			}
+		}
 
 		/*Advection: */
-		GetBAdvec(B,element,xyz_list,gauss); 
-		GetBAdvecprime(Bprime,element,xyz_list,gauss); 
 		vx_input->GetInputValue(&u,gauss); vxm_input->GetInputValue(&um,gauss); vx=u-um;
 		vy_input->GetInputValue(&v,gauss); vym_input->GetInputValue(&vm,gauss); vy=v-vm;
 		vz_input->GetInputValue(&w,gauss); vzm_input->GetInputValue(&wm,gauss); vz=w-wm;
-		D[0][0]=D_scalar*vx;
-		D[1][1]=D_scalar*vy;
-		D[2][2]=D_scalar*vz;
-		TripleMultiply(B,3,numnodes,1,
-					&D[0][0],3,3,0,
-					Bprime,3,numnodes,0,
-					&Ke->values[0],1);
+		for(int i=0;i<numnodes;i++){
+			for(int j=0;j<numnodes;j++){
+				Ke->values[i*numnodes+j] += D_scalar*(
+							vx*dbasis[0*numnodes+j]*basis[i] + vy*dbasis[1*numnodes+j]*basis[i] +vz*dbasis[2*numnodes+j]*basis[i]
+							);
+			}
+		}
 
 		/*Transient: */
 		if(dt!=0.){
 			D_scalar=gauss->weight*Jdet;
-			element->NodalFunctions(basis,gauss);
-			TripleMultiply(basis,numnodes,1,0,
-						&D_scalar,1,1,0,
-						basis,1,numnodes,0,
-						&Ke->values[0],1);
+			for(int i=0;i<numnodes;i++){
+				for(int j=0;j<numnodes;j++){
+					Ke->values[i*numnodes+j] += D_scalar*basis[j]*basis[i];
+				}
+			}
 			D_scalar=D_scalar*dt;
 		}
@@ -634,5 +676,4 @@
 	xDelete<IssmDouble>(basis);
 	xDelete<IssmDouble>(dbasis);
-	xDelete<IssmDouble>(B);
 	xDelete<IssmDouble>(Bprime);
 	delete gauss;
@@ -1063,6 +1104,6 @@
 		xDelete<IssmDouble>(watercolumn);
 		xDelete<IssmDouble>(drainage_int);
-	}
-	xDelete<int>(basalnodeindices);
+		xDelete<int>(basalnodeindices);
+	}
 }/*}}}*/
 void				EnthalpyAnalysis::DrainageUpdateEnthalpy(FemModel* femmodel){/*{{{*/
@@ -1510,5 +1551,5 @@
 		/*Update Rheology only if converged (we must make sure that the temperature is below melting point
 		 * otherwise the rheology could be negative*/
-		element->FindParam(&rheology_law,MaterialsRheologyLawEnum);
+		rheology_law=element->GetIntegerMaterialParameter(MaterialsRheologyLawEnum);
 		element->GetInputListOnNodes(&surface[0],SurfaceEnum);
 		switch(rheology_law){
Index: /issm/trunk/src/c/analyses/EnumToAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/EnumToAnalysis.cpp	(revision 22757)
+++ /issm/trunk/src/c/analyses/EnumToAnalysis.cpp	(revision 22758)
@@ -14,21 +14,18 @@
 
 	switch(analysis_enum){
-		#ifdef _HAVE_SMB_
-		case SmbAnalysisEnum : return new SmbAnalysis();
+		#ifdef _HAVE_ADJOINTBALANCETHICKNESS2_
+		case AdjointBalancethickness2AnalysisEnum : return new AdjointBalancethickness2Analysis();
 		#endif
 		#ifdef _HAVE_ADJOINTBALANCETHICKNESS_
 		case AdjointBalancethicknessAnalysisEnum : return new AdjointBalancethicknessAnalysis();
 		#endif
-		#ifdef _HAVE_ADJOINTBALANCETHICKNESS2_
-		case AdjointBalancethickness2AnalysisEnum : return new AdjointBalancethickness2Analysis();
-		#endif
 		#ifdef _HAVE_ADJOINTHORIZ_
 		case AdjointHorizAnalysisEnum : return new AdjointHorizAnalysis();
 		#endif
+		#ifdef _HAVE_BALANCETHICKNESS2_
+		case Balancethickness2AnalysisEnum : return new Balancethickness2Analysis();
+		#endif
 		#ifdef _HAVE_BALANCETHICKNESS_
 		case BalancethicknessAnalysisEnum : return new BalancethicknessAnalysis();
-		#endif
-		#ifdef _HAVE_BALANCETHICKNESS2_
-		case Balancethickness2AnalysisEnum : return new Balancethickness2Analysis();
 		#endif
 		#ifdef _HAVE_BALANCETHICKNESSSOFT_
@@ -38,12 +35,72 @@
 		case BalancevelocityAnalysisEnum : return new BalancevelocityAnalysis();
 		#endif
-		#ifdef _HAVE_L2PROJECTIONEPL_
-		case L2ProjectionEPLAnalysisEnum : return new L2ProjectionEPLAnalysis();
+		#ifdef _HAVE_DAMAGEEVOLUTION_
+		case DamageEvolutionAnalysisEnum : return new DamageEvolutionAnalysis();
+		#endif
+		#ifdef _HAVE_DEPTHAVERAGE_
+		case DepthAverageAnalysisEnum : return new DepthAverageAnalysis();
+		#endif
+		#ifdef _HAVE_ENTHALPY_
+		case EnthalpyAnalysisEnum : return new EnthalpyAnalysis();
+		#endif
+		#ifdef _HAVE_ESA_
+		case EsaAnalysisEnum : return new EsaAnalysis();
+		#endif
+		#ifdef _HAVE_EXTRAPOLATION_
+		case ExtrapolationAnalysisEnum : return new ExtrapolationAnalysis();
+		#endif
+		#ifdef _HAVE_EXTRUDEFROMBASE_
+		case ExtrudeFromBaseAnalysisEnum : return new ExtrudeFromBaseAnalysis();
+		#endif
+		#ifdef _HAVE_EXTRUDEFROMTOP_
+		case ExtrudeFromTopAnalysisEnum : return new ExtrudeFromTopAnalysis();
+		#endif
+		#ifdef _HAVE_FREESURFACEBASE_
+		case FreeSurfaceBaseAnalysisEnum : return new FreeSurfaceBaseAnalysis();
+		#endif
+		#ifdef _HAVE_FREESURFACETOP_
+		case FreeSurfaceTopAnalysisEnum : return new FreeSurfaceTopAnalysis();
+		#endif
+		#ifdef _HAVE_GIAIVINS_
+		case GiaIvinsAnalysisEnum : return new GiaIvinsAnalysis();
+		#endif
+		#ifdef _HAVE_HYDROLOGYDCEFFICIENT_
+		case HydrologyDCEfficientAnalysisEnum : return new HydrologyDCEfficientAnalysis();
+		#endif
+		#ifdef _HAVE_HYDROLOGYDCINEFFICIENT_
+		case HydrologyDCInefficientAnalysisEnum : return new HydrologyDCInefficientAnalysis();
+		#endif
+		#ifdef _HAVE_HYDROLOGYSHREVE_
+		case HydrologyShreveAnalysisEnum : return new HydrologyShreveAnalysis();
+		#endif
+		#ifdef _HAVE_HYDROLOGYSOMMERS_
+		case HydrologySommersAnalysisEnum : return new HydrologySommersAnalysis();
 		#endif
 		#ifdef _HAVE_L2PROJECTIONBASE_
 		case L2ProjectionBaseAnalysisEnum : return new L2ProjectionBaseAnalysis();
 		#endif
-		#ifdef _HAVE_DAMAGEEVOLUTION_
-		case DamageEvolutionAnalysisEnum : return new DamageEvolutionAnalysis();
+		#ifdef _HAVE_L2PROJECTIONEPL_
+		case L2ProjectionEPLAnalysisEnum : return new L2ProjectionEPLAnalysis();
+		#endif
+		#ifdef _HAVE_LEVELSET_
+		case LevelsetAnalysisEnum : return new LevelsetAnalysis();
+		#endif
+		#ifdef _HAVE_LOVE_
+		case LoveAnalysisEnum : return new LoveAnalysis();
+		#endif
+		#ifdef _HAVE_MASSTRANSPORT_
+		case MasstransportAnalysisEnum : return new MasstransportAnalysis();
+		#endif
+		#ifdef _HAVE_MELTING_
+		case MeltingAnalysisEnum : return new MeltingAnalysis();
+		#endif
+		#ifdef _HAVE_SEALEVELRISE_
+		case SealevelriseAnalysisEnum : return new SealevelriseAnalysis();
+		#endif
+		#ifdef _HAVE_SMB_
+		case SmbAnalysisEnum : return new SmbAnalysis();
+		#endif
+		#ifdef _HAVE_SMOOTH_
+		case SmoothAnalysisEnum : return new SmoothAnalysis();
 		#endif
 		#ifdef _HAVE_STRESSBALANCE_
@@ -56,46 +113,4 @@
 		case StressbalanceVerticalAnalysisEnum : return new StressbalanceVerticalAnalysis();
 		#endif
-		#ifdef _HAVE_ENTHALPY_
-		case EnthalpyAnalysisEnum : return new EnthalpyAnalysis();
-		#endif
-		#ifdef _HAVE_HYDROLOGYSHREVE_
-		case HydrologyShreveAnalysisEnum : return new HydrologyShreveAnalysis();
-		#endif
-		#ifdef _HAVE_HYDROLOGYDCINEFFICIENT_
-		case HydrologyDCInefficientAnalysisEnum : return new HydrologyDCInefficientAnalysis();
-		#endif
-		#ifdef _HAVE_HYDROLOGYDCEFFICIENT_
-		case HydrologyDCEfficientAnalysisEnum : return new HydrologyDCEfficientAnalysis();
-		#endif
-		#ifdef _HAVE_HYDROLOGYSOMMERS_
-		case HydrologySommersAnalysisEnum : return new HydrologySommersAnalysis();
-		#endif
-		#ifdef _HAVE_MELTING_
-		case MeltingAnalysisEnum : return new MeltingAnalysis();
-		#endif
-		#ifdef _HAVE_MASSTRANSPORT_
-		case MasstransportAnalysisEnum : return new MasstransportAnalysis();
-		#endif
-		#ifdef _HAVE_FREESURFACEBASE_
-		case FreeSurfaceBaseAnalysisEnum : return new FreeSurfaceBaseAnalysis();
-		#endif
-		#ifdef _HAVE_FREESURFACETOP_
-		case FreeSurfaceTopAnalysisEnum : return new FreeSurfaceTopAnalysis();
-		#endif
-		#ifdef _HAVE_EXTRUDEFROMBASE_
-		case ExtrudeFromBaseAnalysisEnum : return new ExtrudeFromBaseAnalysis();
-		#endif
-		#ifdef _HAVE_EXTRUDEFROMTOP_
-		case ExtrudeFromTopAnalysisEnum : return new ExtrudeFromTopAnalysis();
-		#endif
-		#ifdef _HAVE_DEPTHAVERAGE_
-		case DepthAverageAnalysisEnum : return new DepthAverageAnalysis();
-		#endif
-		#ifdef _HAVE_SEALEVELRISE_
-		case SealevelriseAnalysisEnum : return new SealevelriseAnalysis();
-		#endif
-		#ifdef _HAVE_SMOOTH_
-		case SmoothAnalysisEnum : return new SmoothAnalysis();
-		#endif
 		#ifdef _HAVE_THERMAL_
 		case ThermalAnalysisEnum : return new ThermalAnalysis();
@@ -104,19 +119,4 @@
 		case UzawaPressureAnalysisEnum : return new UzawaPressureAnalysis();
 		#endif
-		#ifdef _HAVE_GIAIVINS_
-		case GiaIvinsAnalysisEnum : return new GiaIvinsAnalysis();
-		#endif
-		#ifdef _HAVE_ESA_
-		case EsaAnalysisEnum : return new EsaAnalysis();
-		#endif
-		#ifdef _HAVE_MESHDEFORMATION_
-		case MeshdeformationAnalysisEnum : return new MeshdeformationAnalysis();
-		#endif
-		#ifdef _HAVE_LEVELSET_
-		case LevelsetAnalysisEnum : return new LevelsetAnalysis();
-		#endif
-		#ifdef _HAVE_EXTRAPOLATION_
-		case ExtrapolationAnalysisEnum : return new ExtrapolationAnalysis();
-		#endif
 		default : _error_("enum provided not supported ("<<EnumToStringx(analysis_enum)<<")");
 	}
Index: /issm/trunk/src/c/analyses/EsaAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/EsaAnalysis.cpp	(revision 22757)
+++ /issm/trunk/src/c/analyses/EsaAnalysis.cpp	(revision 22758)
@@ -57,4 +57,7 @@
 	int          ntransitions;
 
+	/*some constant parameters: */
+	parameters->AddObject(iomodel->CopyConstantObject("md.esa.hemisphere",EsaHemisphereEnum));
+
 	/*love numbers: */
 	iomodel->FetchData(&love_h,&nl,NULL,"md.esa.love_h");
@@ -80,6 +83,13 @@
 		U_elastic_local[i-lower_row]= (love_h[nl-1])/2.0/sin(alpha/2.0);
 		H_elastic_local[i-lower_row]= 0; 
-		IssmDouble Pn,Pn1,Pn2;
-		IssmDouble Pn_p,Pn_p1,Pn_p2;
+		//IssmDouble Pn,Pn1,Pn2;
+		//IssmDouble Pn_p,Pn_p1,Pn_p2;
+		IssmDouble Pn = 0.; 
+		IssmDouble Pn1 = 0.; 
+		IssmDouble Pn2 = 0.; 
+		IssmDouble Pn_p = 0.; 
+		IssmDouble Pn_p1 = 0.; 
+		IssmDouble Pn_p2 = 0.; 
+
 		for (int n=0;n<nl;n++) {
 			IssmDouble deltalove_U;
@@ -158,5 +168,4 @@
 	/*Requested outputs*/
 	iomodel->FindConstant(&requestedoutputs,&numoutputs,"md.esa.requested_outputs");
-	parameters->AddObject(new IntParam(EsaNumRequestedOutputsEnum,numoutputs));
 	if(numoutputs)parameters->AddObject(new StringArrayParam(EsaRequestedOutputsEnum,requestedoutputs,numoutputs));
 	iomodel->DeleteData(&requestedoutputs,numoutputs,"md.esa.requested_outputs");
Index: /issm/trunk/src/c/analyses/ExtrapolationAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/ExtrapolationAnalysis.cpp	(revision 22757)
+++ /issm/trunk/src/c/analyses/ExtrapolationAnalysis.cpp	(revision 22758)
@@ -332,5 +332,5 @@
 	/* Intermediaries */
 	int extvar_enum;
-	IssmDouble phi,value;
+	IssmDouble active,value;
 	Node* node = NULL;
 
@@ -338,5 +338,5 @@
 	element->FindParam(&extvar_enum, ExtrapolationVariableEnum);
 	
-	Input* levelset_input=element->GetInput(MaskIceLevelsetEnum); _assert_(levelset_input);
+	Input* active_input=element->GetInput(IceMaskNodeActivationEnum); _assert_(active_input);
 	Input* extvar_input=element->GetInput(extvar_enum); _assert_(extvar_input);
 
@@ -345,7 +345,7 @@
 		gauss->GaussNode(element->GetElementType(),in);
 		node=element->GetNode(in);
-		levelset_input->GetInputValue(&phi,gauss);
+		active_input->GetInputValue(&active,gauss);
 		if(node->IsActive()){
-			if(phi<=0.){
+			if(active>0.5){
 				/* if ice, set dirichlet BC */
 				extvar_input->GetInputValue(&value,gauss);
Index: /issm/trunk/src/c/analyses/FreeSurfaceBaseAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/FreeSurfaceBaseAnalysis.cpp	(revision 22757)
+++ /issm/trunk/src/c/analyses/FreeSurfaceBaseAnalysis.cpp	(revision 22758)
@@ -79,5 +79,5 @@
 	iomodel->FetchDataToInput(elements,"md.slr.sealevel",SealevelEnum,0);
 	iomodel->FetchDataToInput(elements,"md.mask.ice_levelset",MaskIceLevelsetEnum);
-	iomodel->FetchDataToInput(elements,"md.basalforcings.groundedice_melting_rate",BasalforcingsGroundediceMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,"md.basalforcings.groundedice_melting_rate",BasalforcingsGroundediceMeltingRateEnum,0.);
 	iomodel->FetchDataToInput(elements,"md.basalforcings.floatingice_melting_rate",BasalforcingsFloatingiceMeltingRateEnum);
 	iomodel->FetchDataToInput(elements,"md.initialization.vx",VxEnum);
Index: /issm/trunk/src/c/analyses/HydrologyDCEfficientAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/HydrologyDCEfficientAnalysis.cpp	(revision 22757)
+++ /issm/trunk/src/c/analyses/HydrologyDCEfficientAnalysis.cpp	(revision 22758)
@@ -223,5 +223,6 @@
 	/*Retrieve all inputs and parameters*/
 	basalelement->GetVerticesCoordinates(&xyz_list);
-	basalelement->FindParam(&dt,TimesteppingTimeStepEnum);
+	//basalelement->FindParam(&dt,TimesteppingTimeStepEnum);
+	basalelement ->FindParam(&dt,HydrologydtEnum);
 
 	Input* epl_thick_input = basalelement->GetInput(HydrologydcEplThicknessEnum); _assert_(epl_thick_input);
@@ -240,4 +241,5 @@
 		/*Diffusivity*/
 		D_scalar=epl_transmitivity*gauss->weight*Jdet;
+		//D_scalar=gauss->weight*Jdet;
 		if(dt!=0.) D_scalar=D_scalar*dt;
 		D[0][0]=D_scalar;
@@ -253,4 +255,5 @@
 			basalelement->NodalFunctions(&basis[0],gauss);
 			D_scalar=epl_storing*gauss->weight*Jdet;
+			//D_scalar=(epl_storing/epl_transmitivity)*gauss->weight*Jdet;
 			TripleMultiply(basis,numnodes,1,0,
 						&D_scalar,1,1,0,
@@ -262,4 +265,5 @@
 			transfer=GetHydrologyKMatrixTransfer(basalelement);
 			D_scalar=dt*transfer*gauss->weight*Jdet;
+			//D_scalar=dt*(transfer/epl_transmitivity)*gauss->weight*Jdet;
 			TripleMultiply(basis,numnodes,1,0,
 										 &D_scalar,1,1,0,
@@ -312,5 +316,5 @@
 	IssmDouble dt,scalar,water_head;
 	IssmDouble water_load,transfer;
-	IssmDouble epl_storing;
+	IssmDouble epl_storing,epl_transmitivity;
 	IssmDouble Jdet;
 	IssmDouble residual,connectivity;
@@ -329,5 +333,6 @@
 	/*Retrieve all inputs and parameters*/
 	basalelement->GetVerticesCoordinates(&xyz_list);
-	basalelement->FindParam(&dt,TimesteppingTimeStepEnum);	
+	//basalelement->FindParam(&dt,TimesteppingTimeStepEnum);	
+	basalelement ->FindParam(&dt,HydrologydtEnum);
 
 	Input* epl_thick_input = basalelement->GetInput(HydrologydcEplThicknessEnum); _assert_(epl_thick_input);
@@ -348,7 +353,10 @@
 		basalelement ->NodalFunctions(basis,gauss);
 		epl_storing	= EplStoring(basalelement,gauss,epl_thick_input,epl_head_input,base_input);
+		epl_transmitivity = EplTransmitivity(basalelement,gauss,epl_thick_input,epl_head_input,base_input);
+
 		/*Loading term*/
 		water_input->GetInputValue(&water_load,gauss);
 		scalar = Jdet*gauss->weight*(water_load);
+		//scalar = Jdet*gauss->weight*(water_load)/epl_transmitivity;
 		if(dt!=0.) scalar = scalar*dt;
 		for(int i=0;i<numnodes;i++)pe->values[i]+=scalar*basis[i];
@@ -360,4 +368,5 @@
 			transfer=GetHydrologyPVectorTransfer(basalelement,gauss,sed_head_input);
 			scalar = Jdet*gauss->weight*((water_head*epl_storing)+(dt*transfer));
+			//scalar = Jdet*gauss->weight*((water_head*epl_storing)+(dt*transfer))/epl_transmitivity;
 			for(int i=0;i<numnodes;i++)pe->values[i]+=scalar*basis[i];
 		}
@@ -369,7 +378,9 @@
 	for(int iv=0;iv<numvertices;iv++){
 		gauss->GaussVertex(iv);
+		epl_transmitivity = EplTransmitivity(basalelement,gauss,epl_thick_input,epl_head_input,base_input);
 		connectivity = IssmDouble(basalelement->VertexConnectivity(iv));
 		residual_input->GetInputValue(&residual,gauss);
 		pe->values[iv]+=residual/connectivity;
+		//pe->values[iv]+=residual/(epl_transmitivity*connectivity);
 	}
 	/*Clean up and return*/
@@ -415,4 +426,6 @@
 	/*Fetch dof list and allocate solution vector*/
 	IssmDouble* eplHeads    = xNew<IssmDouble>(numnodes);
+	IssmDouble* basevalue    = xNew<IssmDouble>(numnodes);
+	IssmDouble* initvalue    = xNew<IssmDouble>(numnodes);
 	basalelement->GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
 
@@ -422,4 +435,5 @@
 	/*Use the dof list to index into the solution vector: */
 	/*If the EPL is not active we revert to the bedrock elevation*/
+
 	if(active_element){
 		for(int i=0;i<numnodes;i++){
@@ -430,6 +444,9 @@
 	}
 	else{
-		basalelement->GetInputListOnVertices(&eplHeads[0],BaseEnum);
+		//tradeof between keeping initial condition and not getting to far from head at deactivation
+		basalelement->GetInputListOnVertices(&basevalue[0],BaseEnum);
+		basalelement->GetInputListOnVertices(&initvalue[0],EplHeadEnum);
 		for(int i=0;i<numnodes;i++){
+			eplHeads[i]=max(basevalue[i],initvalue[i]);
 			if(xIsNan<IssmDouble>(eplHeads[i])) _error_("NaN found in solution vector");
 			if(xIsInf<IssmDouble>(eplHeads[i])) _error_("Inf found in solution vector");
@@ -440,4 +457,6 @@
 	/*Free ressources:*/
 	xDelete<IssmDouble>(eplHeads);
+	xDelete<IssmDouble>(basevalue);
+	xDelete<IssmDouble>(initvalue);
 	xDelete<int>(doflist);
 	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
@@ -464,5 +483,5 @@
 	case 1:
 		element->FindParam(&leakage,HydrologydcLeakageFactorEnum);
-		transfer=leakage;
+		transfer=+leakage;
 		break;
 	default:
@@ -489,5 +508,5 @@
 		sed_head_input->GetInputValue(&sediment_head,gauss);
 		element->FindParam(&leakage,HydrologydcLeakageFactorEnum);
-		transfer=sediment_head*leakage;
+		transfer=+sediment_head*leakage;
 		break;
 	default:
@@ -503,5 +522,5 @@
 	int         iseplthickcomp;
 	int         domaintype;
-	IssmDouble  dt,A,B;
+	IssmDouble  dt,A;
 	IssmDouble  EPLgrad2;
 	IssmDouble  EPL_N;
@@ -515,18 +534,10 @@
 		Element* element=(Element*)femmodel->elements->GetObjectByOffset(j);
 		
-		switch(domaintype){
-		case Domain2DhorizontalEnum:
-			if(!element->IsOnBase()) return;	
-			B = element->GetMaterialParameter(MaterialsRheologyBbarEnum);
-			break;
-		case Domain3DEnum:
-			B = element->GetMaterialParameter(MaterialsRheologyBEnum);
-			break;
-		default:
-		_error_("not Implemented Yet");
-		}
+		/*skip element if 3d and not on base*/
+		if(domaintype==Domain3DEnum && !element->IsOnBase()) continue;
 		
 		int         numnodes      = element->GetNumberOfNodes();
 		IssmDouble* thickness     = xNew<IssmDouble>(numnodes);
+		IssmDouble* B             = xNew<IssmDouble>(numnodes);
 		IssmDouble* eplhead       = xNew<IssmDouble>(numnodes);
 		IssmDouble* epl_slopeX    = xNew<IssmDouble>(numnodes);
@@ -538,5 +549,6 @@
 		Input* 	active_element_input=element->GetInput(HydrologydcMaskEplactiveEltEnum); _assert_(active_element_input);		
 		active_element_input->GetInputValue(&active_element);
-		element->FindParam(&dt,TimesteppingTimeStepEnum);
+		//element->FindParam(&dt,TimesteppingTimeStepEnum);
+		element ->FindParam(&dt,HydrologydtEnum);
 	
 		/*For now, assuming just one way to compute EPL thickness*/
@@ -549,6 +561,10 @@
 		IssmDouble init_thick       =	element->GetMaterialParameter(HydrologydcEplInitialThicknessEnum);
 		IssmDouble max_thick        =	element->GetMaterialParameter(HydrologydcEplMaxThicknessEnum);
-		
-		A=pow(B,-n);
+
+		switch(domaintype){
+			case Domain2DhorizontalEnum: element->GetInputListOnVertices(&B[0],MaterialsRheologyBbarEnum); break;
+			case Domain3DEnum:           element->GetInputListOnVertices(&B[0],MaterialsRheologyBEnum); break;
+			default: _error_("not Implemented Yet");
+		}
 		
 		element->GetInputListOnVertices(&eplhead[0],EplHeadEnum);
@@ -558,5 +574,5 @@
 		element->GetInputListOnVertices(&ice_thickness[0],ThicknessEnum);
 		element->GetInputListOnVertices(&bed[0],BaseEnum);
-		
+
 		if(!active_element){
 			/*Keeping thickness to initial value if EPL is not active*/
@@ -567,4 +583,5 @@
 		else{
 			for(int i=0;i<numnodes;i++){
+				A=pow(B[i],-n);
 				/*Compute first the effective pressure in the EPL*/
 				EPL_N=gravity*((rho_ice*ice_thickness[i])-(rho_water*(eplhead[i]-bed[i])));
@@ -590,4 +607,5 @@
 		xDelete<IssmDouble>(ice_thickness);
 		xDelete<IssmDouble>(bed);
+		xDelete<IssmDouble>(B);
 	}
 }/*}}}*/
@@ -708,5 +726,8 @@
 	basalelement->AddInput(HydrologydcEplThicknessEnum,epl_thickness,basalelement->GetElementType());
 
-	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	if(domaintype!=Domain2DhorizontalEnum){
+		basalelement->DeleteMaterials(); 
+		delete basalelement;
+	}
 	xDelete<IssmDouble>(epl_thickness);
 	xDelete<IssmDouble>(old_active);
@@ -731,5 +752,4 @@
 	base_input->GetInputValue(&base_elev,gauss);
 	water_sheet=max(0.0,(prestep_head-base_elev));
-
 	storing=rho_freshwater*g*epl_porosity*epl_thickness*(water_compressibility+(epl_compressibility/epl_porosity));
 
@@ -760,5 +780,4 @@
 
 	water_sheet=max(0.0,(prestep_head-base_elev));
-	
 	epl_transmitivity=epl_conductivity*epl_thickness;
 	//epl_transmitivity=max(1.0e-6,(epl_conductivity*min(water_sheet,epl_thickness)));
Index: /issm/trunk/src/c/analyses/HydrologyDCInefficientAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/HydrologyDCInefficientAnalysis.cpp	(revision 22757)
+++ /issm/trunk/src/c/analyses/HydrologyDCInefficientAnalysis.cpp	(revision 22758)
@@ -16,6 +16,9 @@
 	int         sedimentlimit_flag;
 	int         transfer_flag;
+	int         unconfined_flag;
 	int         penalty_lock;
 	int         hydro_maxiter;
+	int         hydroslices;
+	int         numoutputs;
 	bool        isefficientlayer;
 	IssmDouble  penalty_factor;
@@ -23,4 +26,5 @@
 	IssmDouble  leakagefactor;
 	IssmDouble  sedimentlimit;
+	char**      requestedoutputs = NULL;
 
 	/*retrieve some parameters: */
@@ -32,8 +36,10 @@
 	iomodel->FetchData(&sedimentlimit_flag, "md.hydrology.sedimentlimit_flag" );
 	iomodel->FetchData(&transfer_flag,      "md.hydrology.transfer_flag" );
+	iomodel->FetchData(&unconfined_flag,    "md.hydrology.unconfined_flag" );
+	iomodel->FetchData(&penalty_lock,       "md.hydrology.penalty_lock" );
+	iomodel->FetchData(&hydro_maxiter,      "md.hydrology.max_iter" );
+	iomodel->FetchData(&hydroslices,        "md.hydrology.steps_per_step");
+	iomodel->FetchData(&isefficientlayer,   "md.hydrology.isefficientlayer");
 	iomodel->FetchData(&penalty_factor,     "md.hydrology.penalty_factor" );
-	iomodel->FetchData(&isefficientlayer,   "md.hydrology.isefficientlayer");
-	iomodel->FetchData(&hydro_maxiter,      "md.hydrology.max_iter" );
-	iomodel->FetchData(&penalty_lock,       "md.hydrology.penalty_lock" );
 	iomodel->FetchData(&rel_tol,            "md.hydrology.rel_tol" );
 
@@ -41,6 +47,9 @@
 	parameters->AddObject(new IntParam(HydrologydcSedimentlimitFlagEnum,sedimentlimit_flag));
 	parameters->AddObject(new IntParam(HydrologydcTransferFlagEnum,transfer_flag));
+	parameters->AddObject(new IntParam(HydrologydcUnconfinedFlagEnum,unconfined_flag));
 	parameters->AddObject(new IntParam(HydrologydcPenaltyLockEnum,penalty_lock));
 	parameters->AddObject(new IntParam(HydrologydcMaxIterEnum,hydro_maxiter));
+	parameters->AddObject(new IntParam(HydrologyStepsPerStepEnum,hydroslices));
+
 	parameters->AddObject(new BoolParam(HydrologydcIsefficientlayerEnum,isefficientlayer));
 	parameters->AddObject(new DoubleParam(HydrologydcPenaltyFactorEnum,penalty_factor));
@@ -54,4 +63,9 @@
 		parameters->AddObject(new DoubleParam(HydrologydcSedimentlimitEnum,sedimentlimit));
 	}
+  /*Requested outputs*/
+  iomodel->FindConstant(&requestedoutputs,&numoutputs,"md.hydrology.requested_outputs");
+  parameters->AddObject(new IntParam(HydrologyNumRequestedOutputsEnum,numoutputs));
+  if(numoutputs)parameters->AddObject(new StringArrayParam(HydrologyRequestedOutputsEnum,requestedoutputs,numoutputs));
+  iomodel->DeleteData(&requestedoutputs,numoutputs,"md.hydrology.requested_outputs");
 }/*}}}*/
 
@@ -59,5 +73,4 @@
 
 	bool   isefficientlayer;
-	bool   element_active;
 	int    hydrology_model;
 	
@@ -80,5 +93,4 @@
 		}
 	}
-
 	iomodel->FetchDataToInput(elements,"md.geometry.thickness",ThicknessEnum);
 	iomodel->FetchDataToInput(elements,"md.geometry.base",BaseEnum);
@@ -95,4 +107,5 @@
 	if(isefficientlayer){
 		iomodel->FetchDataToInput(elements,"md.hydrology.mask_eplactive_node",HydrologydcMaskEplactiveNodeEnum);
+		iomodel->FetchDataToInput(elements,"md.initialization.epl_head",EplHeadEnum);
 	}
 }/*}}}*/
@@ -208,9 +221,11 @@
 	/*Retrieve all inputs and parameters*/
 	basalelement ->GetVerticesCoordinates(&xyz_list);
-	basalelement ->FindParam(&dt,TimesteppingTimeStepEnum);
+	//basalelement ->FindParam(&dt,TimesteppingTimeStepEnum);
+	basalelement ->FindParam(&dt,HydrologydtEnum);
 	basalelement ->FindParam(&isefficientlayer,HydrologydcIsefficientlayerEnum);
 	Input* SedTrans_input = basalelement->GetInput(HydrologydcSedimentTransmitivityEnum); _assert_(SedTrans_input);
 	Input* sed_head_input = basalelement->GetInput(SedimentHeadEnum);
 	Input* base_input     = basalelement->GetInput(BaseEnum);
+	Input* old_wh_input = basalelement->GetInput(SedimentHeadOldEnum);                  _assert_(old_wh_input);
 
 	/*Transfer related Inputs*/
@@ -221,4 +236,5 @@
 	/* Start  looping on the number of gaussian points: */
 	Gauss* gauss=basalelement->NewGauss(2);
+
 	for(int ig=gauss -> begin();ig<gauss->end();ig++){
 		gauss          -> GaussPoint(ig);
@@ -230,4 +246,5 @@
 		/*Diffusivity*/
 		D_scalar=sediment_transmitivity*gauss->weight*Jdet;
+		//D_scalar=gauss->weight*Jdet;
 		if(dt!=0.) D_scalar=D_scalar*dt;
 		D[0][0]=D_scalar;
@@ -243,4 +260,5 @@
 			basalelement->NodalFunctions(&basis[0],gauss);
 			D_scalar=sediment_storing*gauss->weight*Jdet;
+			//D_scalar=(sediment_storing/sediment_transmitivity)*gauss->weight*Jdet;
 			TripleMultiply(basis,numnodes,1,0,
 										 &D_scalar,1,1,0,
@@ -255,4 +273,5 @@
 					basalelement->NodalFunctions(&basis[0],gauss);
 					D_scalar=dt*transfer*gauss->weight*Jdet;
+					//D_scalar=dt*(transfer/sediment_transmitivity)*gauss->weight*Jdet;
 					TripleMultiply(basis,numnodes,1,0,
 												 &D_scalar,1,1,0,
@@ -268,5 +287,8 @@
 	xDelete<IssmDouble>(basis);
 	delete gauss;
-	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	if(domaintype!=Domain2DhorizontalEnum){
+		basalelement->DeleteMaterials(); 
+		delete basalelement;
+	}
 	return Ke;
 }/*}}}*/
@@ -294,5 +316,5 @@
 	bool       active_element,isefficientlayer;
 	IssmDouble dt,scalar,sediment_storing;
-	IssmDouble water_head;
+	IssmDouble water_head,sediment_transmitivity;
 	IssmDouble water_load,transfer;
 	IssmDouble Jdet;
@@ -311,5 +333,6 @@
 	/*Retrieve all inputs and parameters*/
 	basalelement->GetVerticesCoordinates(&xyz_list);
-	basalelement->FindParam(&dt,TimesteppingTimeStepEnum);
+	//basalelement->FindParam(&dt,TimesteppingTimeStepEnum);
+	basalelement ->FindParam(&dt,HydrologydtEnum);
 	basalelement->FindParam(&isefficientlayer,HydrologydcIsefficientlayerEnum);
 
@@ -318,4 +341,6 @@
 	Input* base_input		  = basalelement->GetInput(BaseEnum);
 	Input* water_input	  = basalelement->GetInput(BasalforcingsGroundediceMeltingRateEnum); _assert_(water_input);
+	Input* SedTrans_input = basalelement->GetInput(HydrologydcSedimentTransmitivityEnum); _assert_(SedTrans_input);
+
 	if(dt!= 0.){
 		old_wh_input = basalelement->GetInput(SedimentHeadOldEnum);                  _assert_(old_wh_input);
@@ -332,4 +357,5 @@
 		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
 		basalelement->NodalFunctions(basis,gauss);
+		sediment_transmitivity = SedimentTransmitivity(basalelement,gauss,sed_head_input,base_input,SedTrans_input);
 
 		/*Loading term*/
@@ -337,4 +363,5 @@
 			water_input->GetInputValue(&water_load,gauss);
 			scalar = Jdet*gauss->weight*(water_load);
+			//scalar = Jdet*gauss->weight*(water_load)/sediment_transmitivity;
 			if(dt!=0.) scalar = scalar*dt;
 			for(int i=0;i<numnodes;i++){
@@ -348,4 +375,5 @@
 				water_input->GetInputValue(&water_load,gauss);
 				scalar = Jdet*gauss->weight*(water_load);
+				//scalar = Jdet*gauss->weight*(water_load)/sediment_transmitivity;
 				if(dt!=0.) scalar = scalar*dt;
 				for(int i=0;i<numnodes;i++){
@@ -369,8 +397,10 @@
 				}
 				scalar = Jdet*gauss->weight*((water_head*sediment_storing)+(dt*transfer));
+				//scalar = Jdet*gauss->weight*((water_head*sediment_storing)+(dt*transfer))/sediment_transmitivity;
 				for(int i=0;i<numnodes;i++)pe->values[i]+=scalar*basis[i];
 			}
 			else{
 				scalar = Jdet*gauss->weight*(water_head*sediment_storing);
+				//scalar = Jdet*gauss->weight*(water_head*sediment_storing)/sediment_transmitivity;
 				for(int i=0;i<numnodes;i++)pe->values[i]+=scalar*basis[i];
 			}
@@ -381,5 +411,8 @@
 	xDelete<IssmDouble>(basis);
 	delete gauss;
-	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	if(domaintype!=Domain2DhorizontalEnum){
+		basalelement->DeleteMaterials(); 
+		delete basalelement;
+	}
 	return pe;
 }/*}}}*/
@@ -467,4 +500,5 @@
 		IssmDouble* thickness = xNew<IssmDouble>(numnodes);
 		IssmDouble* base      = xNew<IssmDouble>(numnodes);
+		IssmDouble* transmitivity = xNew<IssmDouble>(numnodes);
 
 		basalelement->FindParam(&kmax,HydrologySedimentKmaxEnum);
@@ -476,5 +510,5 @@
 		basalelement->GetInputListOnVertices(thickness,ThicknessEnum);
 		basalelement->GetInputListOnVertices(base,BaseEnum);
-
+		basalelement->GetInputListOnVertices(transmitivity,HydrologydcSedimentTransmitivityEnum);
 		kappa=kmax*pow(10.,penalty_factor);
 
@@ -483,4 +517,5 @@
 			if(values[i]>h_max) {
 				residual[i] = kappa*(values[i]-h_max);
+				//residual[i] = kappa*(values[i]-h_max)*transmitivity[i];
 			}
 			else{
@@ -492,4 +527,5 @@
 		}
 		xDelete<IssmDouble>(thickness);
+		xDelete<IssmDouble>(transmitivity);
 		xDelete<IssmDouble>(base);
 	}
@@ -497,6 +533,6 @@
 	/*Add input to the element: */
 	element->AddBasalInput(SedimentHeadEnum,values,P1Enum);
+	element->AddBasalInput(EffectivePressureEnum,pressure,P1Enum);
 	element->AddBasalInput(SedimentHeadResidualEnum,residual,P1Enum);
-	element->AddBasalInput(EffectivePressureEnum,pressure,P1Enum);
 
 	/*Free ressources:*/
@@ -505,5 +541,8 @@
 	xDelete<IssmDouble>(pressure);
 	xDelete<int>(doflist);
-	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	if(domaintype!=Domain2DhorizontalEnum){
+		basalelement->DeleteMaterials(); 
+		delete basalelement;
+	}
 }/*}}}*/
 
@@ -514,6 +553,8 @@
 
 IssmDouble HydrologyDCInefficientAnalysis::SedimentStoring(Element* element,Gauss* gauss,Input* sed_head_input, Input* base_input){/*{{{*/
+	int unconf_scheme;
+	IssmDouble expfac; 
 	IssmDouble sediment_storing;
-	IssmDouble storing;
+	IssmDouble storing,yield;
 	IssmDouble base_elev,prestep_head,water_sheet;
 	IssmDouble rho_freshwater           = element->GetMaterialParameter(MaterialsRhoFreshwaterEnum);
@@ -523,31 +564,60 @@
 	IssmDouble sediment_compressibility = element->GetMaterialParameter(HydrologydcSedimentCompressibilityEnum);
 	IssmDouble water_compressibility    = element->GetMaterialParameter(HydrologydcWaterCompressibilityEnum);
-	base_input->GetInputValue(&base_elev,gauss);
-	sed_head_input->GetInputValue(&prestep_head,gauss);
-	water_sheet=max(0.0,(prestep_head-(base_elev-sediment_thickness)));
-
-	storing=rho_freshwater*g*sediment_porosity*sediment_thickness*(water_compressibility+(sediment_compressibility/sediment_porosity));
-	
-	//Heavyside approximation (1/(1+exp(-2kx))) with k=25 centering at thickness minus 1%
-	sediment_storing=(sediment_porosity*exp(-20.*(water_sheet-0.99*sediment_thickness))+storing)/(1+exp(-20.*(water_sheet-0.99*sediment_thickness)));
-
+	element->FindParam(&unconf_scheme,HydrologydcUnconfinedFlagEnum);
+	switch(unconf_scheme){
+	case 0:
+		sediment_storing=rho_freshwater*g*sediment_porosity*sediment_thickness*(water_compressibility+(sediment_compressibility/sediment_porosity));
+		break;
+	case 1:
+		base_input->GetInputValue(&base_elev,gauss);
+		sed_head_input->GetInputValue(&prestep_head,gauss);
+		water_sheet=max(0.0,(prestep_head-(base_elev-sediment_thickness)));
+
+		/* if (water_sheet<sediment_thickness){ */
+		/* 	sediment_storing=rho_freshwater*g*sediment_porosity*sediment_thickness*(water_compressibility+(sediment_compressibility/sediment_porosity)); */
+		/* } */
+		/* else{ */
+		/* 	sediment_storing=sediment_porosity; */
+		/* } */
+		storing=rho_freshwater*g*sediment_porosity*sediment_thickness*(water_compressibility+(sediment_compressibility/sediment_porosity));
+		//using logistic function for heavyside approximation
+		expfac=10.;
+		yield=sediment_porosity;
+		sediment_storing=yield+(storing-yield)/(1+exp(-2*expfac*(water_sheet-0.99*sediment_thickness)));
+		break;
+	default:
+		_error_("UnconfinedFlag is 0 or 1");
+	}
 	return sediment_storing;
 }/*}}}*/
 
 IssmDouble HydrologyDCInefficientAnalysis::SedimentTransmitivity(Element* element,Gauss* gauss,Input* sed_head_input, Input* base_input,Input* SedTrans_input){/*{{{*/
+	int unconf_scheme;
+	IssmDouble ratio,expfac;
 	IssmDouble sediment_transmitivity;
 	IssmDouble FullLayer_transmitivity;
 	IssmDouble base_elev,prestep_head,water_sheet;
 	IssmDouble sediment_thickness       = element->GetMaterialParameter(HydrologydcSedimentThicknessEnum);
-	base_input->GetInputValue(&base_elev,gauss);
-	sed_head_input->GetInputValue(&prestep_head,gauss);
+
+	element->FindParam(&unconf_scheme,HydrologydcUnconfinedFlagEnum);
 	SedTrans_input->GetInputValue(&FullLayer_transmitivity,gauss);
-	water_sheet=max(0.0,(prestep_head-(base_elev-sediment_thickness)));
-
-	if (water_sheet<=sediment_thickness){
-		sediment_transmitivity=FullLayer_transmitivity*water_sheet/sediment_thickness;
-	}
-	else{
+	switch(unconf_scheme){
+	case 0:
 		sediment_transmitivity=FullLayer_transmitivity;
+		break;
+	case 1:
+		base_input->GetInputValue(&base_elev,gauss);
+		sed_head_input->GetInputValue(&prestep_head,gauss);
+		water_sheet=max(0.0,(prestep_head-(base_elev-sediment_thickness)));
+		
+		//min definition of the if test
+		sediment_transmitivity=FullLayer_transmitivity*min(water_sheet/sediment_thickness,1.);
+		if (sediment_transmitivity==0){
+			sediment_transmitivity=1.0e-20;
+		}
+
+		break;
+	default:
+		_error_("UnconfinedFlag is 0 or 1");
 	}
 	return sediment_transmitivity;
@@ -604,5 +674,5 @@
 	case 1:
 		element->FindParam(&leakage,HydrologydcLeakageFactorEnum);
-		transfer=leakage; 
+		transfer=+leakage; 
 		break;
 	default:
@@ -628,6 +698,9 @@
 		_assert_(epl_head_input);
 		epl_head_input->GetInputValue(&epl_head,gauss);
+		if (element->Id()==42){
+			_printf_("epl head in sed Pvec transfer is "<<  epl_head <<"\n");
+		}
 		element->FindParam(&leakage,HydrologydcLeakageFactorEnum);
-		transfer=epl_head*leakage;
+		transfer=+epl_head*leakage;
 		break;
 	default:
Index: /issm/trunk/src/c/analyses/HydrologyShreveAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/HydrologyShreveAnalysis.cpp	(revision 22757)
+++ /issm/trunk/src/c/analyses/HydrologyShreveAnalysis.cpp	(revision 22758)
@@ -73,5 +73,7 @@
 
 	/*retrieve some parameters: */
-	int  hydrology_model;
+	int    hydrology_model;
+	int    numoutputs;
+	char** requestedoutputs = NULL;
 	iomodel->FindConstant(&hydrology_model,"md.hydrology.model");
 
@@ -81,4 +83,9 @@
 	parameters->AddObject(new IntParam(HydrologyModelEnum,hydrology_model));
 	parameters->AddObject(iomodel->CopyConstantObject("md.hydrology.stabilization",HydrologyshreveStabilizationEnum));
+  /*Requested outputs*/
+  iomodel->FindConstant(&requestedoutputs,&numoutputs,"md.hydrology.requested_outputs");
+  parameters->AddObject(new IntParam(HydrologyNumRequestedOutputsEnum,numoutputs));
+  if(numoutputs)parameters->AddObject(new StringArrayParam(HydrologyRequestedOutputsEnum,requestedoutputs,numoutputs));
+  iomodel->DeleteData(&requestedoutputs,numoutputs,"md.hydrology.requested_outputs");
 
 }/*}}}*/
Index: /issm/trunk/src/c/analyses/HydrologySommersAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/HydrologySommersAnalysis.cpp	(revision 22757)
+++ /issm/trunk/src/c/analyses/HydrologySommersAnalysis.cpp	(revision 22758)
@@ -139,5 +139,7 @@
 
 	/*retrieve some parameters: */
-	int  hydrology_model;
+	int    hydrology_model;
+	int    numoutputs;
+	char** requestedoutputs = NULL;
 	iomodel->FindConstant(&hydrology_model,"md.hydrology.model");
 
@@ -149,4 +151,10 @@
    parameters->AddObject(iomodel->CopyConstantObject("md.hydrology.relaxation",HydrologyRelaxationEnum));
 	parameters->AddObject(iomodel->CopyConstantObject("md.hydrology.storage",HydrologyStorageEnum));
+
+  /*Requested outputs*/
+  iomodel->FindConstant(&requestedoutputs,&numoutputs,"md.hydrology.requested_outputs");
+  parameters->AddObject(new IntParam(HydrologyNumRequestedOutputsEnum,numoutputs));
+  if(numoutputs)parameters->AddObject(new StringArrayParam(HydrologyRequestedOutputsEnum,requestedoutputs,numoutputs));
+  iomodel->DeleteData(&requestedoutputs,numoutputs,"md.hydrology.requested_outputs");
 }/*}}}*/
 
@@ -206,4 +214,5 @@
 	/*Clean up and return*/
 	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
 	xDelete<IssmDouble>(dbasis);
 	delete gauss;
@@ -313,5 +322,5 @@
 		PMPheat=-CT*CW*conductivity*(dh[0]*dpressure_water[0]+dh[1]*dpressure_water[1]);
 
-		meltrate = 1/latentheat*(G+frictionheat+rho_water*g*conductivity*(dh[0]*dh[0]+dh[1]*dh[1])-PMPheat);
+   	meltrate = 1/latentheat*(G+frictionheat+rho_water*g*conductivity*(dh[0]*dh[0]+dh[1]*dh[1])-PMPheat);
 		_assert_(meltrate>0.);
 	
@@ -380,7 +389,7 @@
 
 		/*Make sure that negative pressure is not allowed*/
-      if(values[i]<bed[i]){
-			values[i] = bed[i];
-		}
+  //    if(values[i]<bed[i]){
+	//		values[i] = bed[i];
+	//	}
 
 		/*Under-relaxation*/
@@ -466,4 +475,5 @@
    IssmDouble  dpressure_water[2],dbed[2],PMPheat;
 	IssmDouble q = 0.;
+   IssmDouble channelization = 0.;
 
 	/*Retrieve all inputs and parameters*/
@@ -542,5 +552,5 @@
 		dpressure_water[1] = rho_water*g*(dh[1] - dbed[1]);
 		PMPheat=-CT*CW*conductivity*(dh[0]*dpressure_water[0]+dh[1]*dpressure_water[1]);
-	
+
 		meltrate = 1/latentheat*(G+frictionheat+rho_water*g*conductivity*(dh[0]*dh[0]+dh[1]*dh[1])-PMPheat);
 		_assert_(meltrate>0.);
@@ -555,4 +565,7 @@
 		/* Compute basal water flux */
       q += gauss->weight*Jdet*(conductivity*sqrt(dh[0]*dh[0]+dh[1]*dh[1]));
+
+		/* Compute "degree of channelization" (ratio of melt opening to opening by sliding) */
+		channelization += gauss->weight*Jdet*(meltrate/rho_ice/(meltrate/rho_ice+beta*sqrt(vx*vx+vy*vy)));
 	}
 
@@ -565,5 +578,5 @@
 	if(newgap>thickness)
 	 newgap = thickness;
-	 
+
 	/*Add new gap as an input*/
 	element->AddInput(HydrologyGapHeightEnum,&newgap,P0Enum);
@@ -573,4 +586,8 @@
 	element->AddInput(HydrologyBasalFluxEnum,&q,P0Enum);
 
+	/* Divide by connectivity, add degree of channelization as an input */
+	channelization = channelization/totalweights;
+	element->AddInput(DegreeOfChannelizationEnum,&channelization,P0Enum);
+
 	/*Clean up and return*/
 	xDelete<IssmDouble>(xyz_list);
Index: /issm/trunk/src/c/analyses/LevelsetAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/LevelsetAnalysis.cpp	(revision 22757)
+++ /issm/trunk/src/c/analyses/LevelsetAnalysis.cpp	(revision 22758)
@@ -60,8 +60,23 @@
 			iomodel->FetchDataToInput(elements,"md.calving.meltingrate",CalvinglevermannMeltingrateEnum);
 			break;
-		case CalvingDevEnum:
+		case CalvingVonmisesEnum:
+			iomodel->FetchDataToInput(elements,"md.calving.stress_threshold_groundedice",CalvingStressThresholdGroundediceEnum);
+			iomodel->FetchDataToInput(elements,"md.calving.stress_threshold_floatingice",CalvingStressThresholdFloatingiceEnum);
 			iomodel->FetchDataToInput(elements,"md.calving.meltingrate",CalvingMeltingrateEnum);
 			break;
 		case CalvingMinthicknessEnum:
+			iomodel->FetchDataToInput(elements,"md.calving.meltingrate",CalvingMeltingrateEnum);
+			break;
+		case CalvingHabEnum:
+			iomodel->FetchDataToInput(elements,"md.calving.meltingrate",CalvingMeltingrateEnum);
+			iomodel->FetchDataToInput(elements,"md.calving.flotation_fraction",CalvingHabFractionEnum);
+			break;
+		case CalvingCrevasseDepthEnum:
+			iomodel->FetchDataToInput(elements,"md.calving.meltingrate",CalvingMeltingrateEnum);
+			iomodel->FetchDataToInput(elements,"md.calving.water_height",WaterheightEnum);
+			break;
+		case CalvingDev2Enum:
+			iomodel->FetchDataToInput(elements,"md.calving.stress_threshold_groundedice",CalvingStressThresholdGroundediceEnum);
+			iomodel->FetchDataToInput(elements,"md.calving.stress_threshold_floatingice",CalvingStressThresholdFloatingiceEnum);
 			iomodel->FetchDataToInput(elements,"md.calving.meltingrate",CalvingMeltingrateEnum);
 			break;
@@ -80,11 +95,16 @@
 		case DefaultCalvingEnum:
 		case CalvingLevermannEnum:
-			break;
-		case CalvingDevEnum:
-			parameters->AddObject(iomodel->CopyConstantObject("md.calving.stress_threshold_groundedice",CalvingStressThresholdGroundediceEnum));
-			parameters->AddObject(iomodel->CopyConstantObject("md.calving.stress_threshold_floatingice",CalvingStressThresholdFloatingiceEnum));
+		case CalvingVonmisesEnum:
 			break;
 		case CalvingMinthicknessEnum:
 			parameters->AddObject(iomodel->CopyConstantObject("md.calving.min_thickness",CalvingMinthicknessEnum));
+			break;
+		case CalvingHabEnum:
+			break;
+		case CalvingCrevasseDepthEnum:
+			parameters->AddObject(iomodel->CopyConstantObject("md.calving.critical_fraction",CalvingCrevasseDepthEnum));
+			break;
+		case CalvingDev2Enum:
+			parameters->AddObject(iomodel->CopyConstantObject("md.calving.height_above_floatation",CalvingHeightAboveFloatationEnum));
 			break;
 		default:
@@ -136,11 +156,11 @@
 	/*Intermediaries */
 	int  stabilization,dim, domaintype, calvinglaw;
-	int i, row, col;
+	int i,j,k,row, col;
 	IssmDouble kappa;
 	IssmDouble Jdet, dt, D_scalar;
 	IssmDouble h,hx,hy,hz;
-	IssmDouble vel;
+	IssmDouble vel,v[3],w[3],c[3],m[3],dlsf[3];
 	IssmDouble norm_dlsf, norm_calving, calvingrate, meltingrate, groundedice;
-	IssmDouble calvingmax;
+	IssmDouble calvingmax, calvinghaf, heaviside, haf_eps;
 	IssmDouble* xyz_list = NULL;
 
@@ -164,12 +184,9 @@
 	ElementMatrix* Ke       = basalelement->NewElementMatrix();
 	IssmDouble*    basis    = xNew<IssmDouble>(numnodes);
-	IssmDouble*    B        = xNew<IssmDouble>(dim*numnodes);
-	IssmDouble*    Bprime   = xNew<IssmDouble>(dim*numnodes);
-	IssmDouble*    D        = xNew<IssmDouble>(dim*dim);
-	IssmDouble*    v        = xNew<IssmDouble>(dim);
-	IssmDouble*    w        = xNew<IssmDouble>(dim);
-	IssmDouble*    c        = xNewZeroInit<IssmDouble>(dim);
-	IssmDouble*    m        = xNewZeroInit<IssmDouble>(dim);
-	IssmDouble*    dlsf     = xNew<IssmDouble>(dim);
+	IssmDouble*    dbasis   = xNew<IssmDouble>(2*numnodes);
+	IssmDouble*    Bprime = NULL;
+	if(stabilization==2){
+		Bprime   = xNew<IssmDouble>(dim*numnodes);
+	}
 
 	/*Retrieve all inputs and parameters*/
@@ -208,5 +225,5 @@
 	switch(calvinglaw){
 		case DefaultCalvingEnum:
-		case CalvingDevEnum:
+		case CalvingVonmisesEnum:
 			lsf_slopex_input  = basalelement->GetInput(LevelsetfunctionSlopeXEnum); _assert_(lsf_slopex_input);
 			if(dim==2) lsf_slopey_input  = basalelement->GetInput(LevelsetfunctionSlopeYEnum); _assert_(lsf_slopey_input);
@@ -236,4 +253,21 @@
 			meltingrate_input = basalelement->GetInput(CalvingMeltingrateEnum);     _assert_(meltingrate_input);
 			break;
+		case CalvingHabEnum:
+			lsf_slopex_input  = basalelement->GetInput(LevelsetfunctionSlopeXEnum); _assert_(lsf_slopex_input);
+			if(dim==2) lsf_slopey_input  = basalelement->GetInput(LevelsetfunctionSlopeYEnum); _assert_(lsf_slopey_input);
+			meltingrate_input = basalelement->GetInput(CalvingMeltingrateEnum);     _assert_(meltingrate_input);
+			break;
+		case CalvingCrevasseDepthEnum:
+			lsf_slopex_input  = basalelement->GetInput(LevelsetfunctionSlopeXEnum); _assert_(lsf_slopex_input);
+			if(dim==2) lsf_slopey_input  = basalelement->GetInput(LevelsetfunctionSlopeYEnum); _assert_(lsf_slopey_input);
+			meltingrate_input = basalelement->GetInput(CalvingMeltingrateEnum);     _assert_(meltingrate_input);
+			break;
+		case CalvingDev2Enum:
+			basalelement->FindParam(&calvinghaf,CalvingHeightAboveFloatationEnum);
+			lsf_slopex_input  = basalelement->GetInput(LevelsetfunctionSlopeXEnum); _assert_(lsf_slopex_input);
+			if(dim==2) lsf_slopey_input  = basalelement->GetInput(LevelsetfunctionSlopeYEnum); _assert_(lsf_slopey_input);
+			calvingrate_input = basalelement->GetInput(CalvingCalvingrateEnum);     _assert_(calvingrate_input);
+			meltingrate_input = basalelement->GetInput(CalvingMeltingrateEnum);     _assert_(meltingrate_input);
+			break;
 		default:
 			_error_("Calving law "<<EnumToStringx(calvinglaw)<<" not supported yet");
@@ -246,19 +280,19 @@
 
 		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctions(basis,gauss);
+		basalelement->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
 		D_scalar=gauss->weight*Jdet;
 
 		/* Transient */
 		if(dt!=0.){
-			basalelement->NodalFunctions(basis,gauss);
-			TripleMultiply(basis,numnodes,1,0,
-						&D_scalar,1,1,0,
-						basis,1,numnodes,0,
-						&Ke->values[0],1);
-			D_scalar*=dt;
+			for(i=0;i<numnodes;i++){
+				for(j=0;j<numnodes;j++){
+					Ke->values[i*numnodes+j] += D_scalar*basis[j]*basis[i];
+				}
+			}
+			D_scalar=D_scalar*dt;
 		}
 
 		/* Advection */
-		GetB(B,basalelement,xyz_list,gauss); 
-		GetBprime(Bprime,basalelement,xyz_list,gauss); 
 		vx_input->GetInputValue(&v[0],gauss);
 		vy_input->GetInputValue(&v[1],gauss); 
@@ -268,5 +302,5 @@
 		switch(calvinglaw){
 			case DefaultCalvingEnum:
-			case CalvingDevEnum:
+			case CalvingVonmisesEnum:
 				lsf_slopex_input->GetInputValue(&dlsf[0],gauss);
 				if(dim==2) lsf_slopey_input->GetInputValue(&dlsf[1],gauss);
@@ -292,5 +326,5 @@
 				 }
 				break;
-
+				
 			case CalvingLevermannEnum:
 				calvingratex_input->GetInputValue(&c[0],gauss);
@@ -323,4 +357,93 @@
 				 }
 				break;
+			
+			case CalvingHabEnum:
+				lsf_slopex_input->GetInputValue(&dlsf[0],gauss);
+				if(dim==2) lsf_slopey_input->GetInputValue(&dlsf[1],gauss);
+				meltingrate_input->GetInputValue(&meltingrate,gauss);
+
+				norm_dlsf=0.;
+				for(i=0;i<dim;i++) norm_dlsf+=pow(dlsf[i],2);
+				norm_dlsf=sqrt(norm_dlsf);
+
+				if(norm_dlsf>1.e-10)
+				 for(i=0;i<dim;i++){ 
+					 c[i]=0.;
+					 m[i]=meltingrate*dlsf[i]/norm_dlsf;
+				 }
+				else
+				 for(i=0;i<dim;i++){
+					 c[i]=0.;
+					 m[i]=0.;
+				 }
+				break;
+			
+			case CalvingCrevasseDepthEnum:
+				lsf_slopex_input->GetInputValue(&dlsf[0],gauss);
+				if(dim==2) lsf_slopey_input->GetInputValue(&dlsf[1],gauss);
+				meltingrate_input->GetInputValue(&meltingrate,gauss);
+
+				if(groundedice<0) meltingrate = 0.;
+				
+				norm_dlsf=0.;
+				for(i=0;i<dim;i++) norm_dlsf+=pow(dlsf[i],2);
+				norm_dlsf=sqrt(norm_dlsf);
+
+				if(norm_dlsf>1.e-10)
+				 for(i=0;i<dim;i++){ 
+					 c[i]=0.;
+					 m[i]=meltingrate*dlsf[i]/norm_dlsf;
+				 }
+				else
+				 for(i=0;i<dim;i++){
+					 c[i]=0.;
+					 m[i]=0.;
+				 }
+				break;
+
+			case CalvingDev2Enum:
+				{
+				lsf_slopex_input->GetInputValue(&dlsf[0],gauss);
+				if(dim==2) lsf_slopey_input->GetInputValue(&dlsf[1],gauss);
+				calvingrate_input->GetInputValue(&calvingrate,gauss);
+				meltingrate_input->GetInputValue(&meltingrate,gauss);
+				gr_input->GetInputValue(&groundedice,gauss);
+
+				//idea: no retreat on ice above critical calving height "calvinghaf" . Limit using regularized Heaviside function.
+				vel=sqrt(v[0]*v[0] + v[1]*v[1]);
+				haf_eps=10.;
+				if(groundedice-calvinghaf<=-haf_eps){
+					// ice floats freely below calvinghaf: calve freely
+					// undercutting has no effect:
+					meltingrate=0.;
+				}
+				else if(groundedice-calvinghaf>=haf_eps){ 
+					// ice is well above calvinghaf -> no calving back, i.e. limit calving rate to ice velocity
+					calvingrate=min(calvingrate,vel);
+					// ice is almost grounded: frontal undercutting has maximum effect (do nothing).
+				}
+				else{ // ice is close to calvinghaf: smooth transition between limitation and free calving.
+					//heaviside: 0 for floating, 1 for grounded
+					heaviside=(groundedice-calvinghaf+haf_eps)/(2.*haf_eps) + sin(PI*(groundedice-calvinghaf)/haf_eps)/(2.*PI); 
+					calvingrate=heaviside*(min(calvingrate,vel)-calvingrate)+calvingrate;
+					meltingrate=heaviside*meltingrate+0.;
+				}
+
+				norm_dlsf=0.;
+				for(i=0;i<dim;i++) norm_dlsf+=pow(dlsf[i],2);
+				norm_dlsf=sqrt(norm_dlsf);
+
+				if(norm_dlsf>1.e-10)
+				 for(i=0;i<dim;i++){ 
+					 c[i]=calvingrate*dlsf[i]/norm_dlsf; 
+					 m[i]=meltingrate*dlsf[i]/norm_dlsf;
+				 }
+				else
+				 for(i=0;i<dim;i++){
+					 c[i]=0.; 
+					 m[i]=0.;
+				 }
+				break;
+				}
 
 			default:
@@ -332,17 +455,11 @@
 
 		/*Compute D*/
-		for(row=0;row<dim;row++){
-			for(col=0;col<dim;col++){
-				if(row==col)
-				 D[row*dim+col]=D_scalar*w[row];
-				else
-				 D[row*dim+col]=0.;
+		for(i=0;i<numnodes;i++){
+			for(j=0;j<numnodes;j++){
+				for(k=0;k<dim;k++){
+					Ke->values[i*numnodes+j] += D_scalar*w[k]*dbasis[k*numnodes+j]*basis[i];
+				}
 			}
 		}
-
-		TripleMultiply(B,dim,numnodes,1,
-					D,dim,dim,0,
-					Bprime,dim,numnodes,0,
-					&Ke->values[0],1);
 
 		/* Stabilization */
@@ -359,28 +476,28 @@
 				h=sqrt( pow(hx*w[0]/vel,2) + pow(hy*w[1]/vel,2) ); 
 				kappa=h*vel/2.;
-				for(row=0;row<dim;row++)
-					for(col=0;col<dim;col++)
-					if(row==col)
-						D[row*dim+col]=D_scalar*kappa;
-					else
-						D[row*dim+col]=0.;
-
-				TripleMultiply(Bprime,dim,numnodes,1,
-							D,dim,dim,0,
-							Bprime,dim,numnodes,0,
-							&Ke->values[0],1);
+				for(i=0;i<numnodes;i++){
+					for(j=0;j<numnodes;j++){
+						for(k=0;k<dim;k++){
+							Ke->values[i*numnodes+j] += D_scalar*kappa*dbasis[k*numnodes+j]*dbasis[k*numnodes+i];
+						}
+					}
+				}
 				break;	
 			case 2:
+				  {
 				/* Streamline Upwinding */
 				basalelement->ElementSizes(&hx,&hy,&hz);
 				h=sqrt( pow(hx*w[0]/vel,2) + pow(hy*w[1]/vel,2) );
+				IssmDouble D[9];
 				for(row=0;row<dim;row++) 
 					for(col=0;col<dim;col++) 
 						D[row*dim+col] = D_scalar*h/(2.*vel)*w[row]*w[col];
+				GetBprime(Bprime,basalelement,xyz_list,gauss);
 
 				TripleMultiply(Bprime,dim,numnodes,1,
-							D,dim,dim,0,
+							&D[0],dim,dim,0,
 							Bprime,dim,numnodes,0,
 							&Ke->values[0],1);
+				  }
 				break;
 			default:
@@ -392,12 +509,6 @@
 	xDelete<IssmDouble>(xyz_list);
 	xDelete<IssmDouble>(basis);
-	xDelete<IssmDouble>(B);
-	xDelete<IssmDouble>(D);
+	xDelete<IssmDouble>(dbasis);
 	xDelete<IssmDouble>(Bprime);
-	xDelete<IssmDouble>(v);
-	xDelete<IssmDouble>(w);
-	xDelete<IssmDouble>(c);
-	xDelete<IssmDouble>(m);
-	xDelete<IssmDouble>(dlsf);
 	delete gauss;
 	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
@@ -552,60 +663,4 @@
 	}
 }/*}}}*/
-void           LevelsetAnalysis::SetDistanceOnIntersectedElements(FemModel* femmodel){/*{{{*/
-
-	/* Intermediaries */
-	int i,k;
-	IssmDouble dmaxp=0.,dmaxm=0,val=0.;
-
-	/*Initialize vector with number of vertices*/
-	int numvertices=femmodel->vertices->NumberOfVertices();
-	Element* element;
-
-	Vector<IssmDouble>* vec_dist_zerolevelset = NULL;
-	GetVectorFromInputsx(&vec_dist_zerolevelset, femmodel, MaskIceLevelsetEnum, VertexPIdEnum);
-	
-	/* set NaN on elements intersected by zero levelset */
-	for(i=0;i<femmodel->elements->Size();i++){
-		element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
-		if(element->IsZeroLevelset(MaskIceLevelsetEnum))
-			for(k=0;k<element->GetNumberOfVertices();k++)
-				vec_dist_zerolevelset->SetValue(element->vertices[k]->Sid(),NAN,INS_VAL); 
-	}
-
-	/* set distance on elements intersected by zero levelset */
-	for(i=0;i<femmodel->elements->Size();i++){
-		element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
-		if(element->IsZeroLevelset(MaskIceLevelsetEnum)){
-			SetDistanceToZeroLevelsetElement(vec_dist_zerolevelset, element);
-
-			/* Get maximum distance to interface along vertices */
-			for(k=0;k<element->GetNumberOfVertices();k++){
-					vec_dist_zerolevelset->GetValue(&val,element->vertices[k]->Sid()); 
-					if((val>0.) && (val>dmaxp))
-						 dmaxp=val;
-					else if((val<0.) && (val<dmaxm))
-						 dmaxm=val;
-			}
-		}
-	}
-
-	/* set all none intersected vertices to max/min distance */
-	for(i=0;i<numvertices;i++){
-		vec_dist_zerolevelset->GetValue(&val,i);
-		if(val==1.) //FIXME: improve check
-			vec_dist_zerolevelset->SetValue(i,3.*dmaxp,INS_VAL);
-		else if(val==-1.)
-			vec_dist_zerolevelset->SetValue(i,3.*dmaxm,INS_VAL);
-	}
-
-	/*Assemble vector and serialize */
-	vec_dist_zerolevelset->Assemble();
-	IssmDouble* dist_zerolevelset=vec_dist_zerolevelset->ToMPISerial();
-	InputUpdateFromVectorx(femmodel,dist_zerolevelset,MaskIceLevelsetEnum,VertexSIdEnum);
-
-	/*Clean up and return*/
-	delete vec_dist_zerolevelset;
-	delete dist_zerolevelset;
-}/*}}}*/
 void           LevelsetAnalysis::SetDistanceToZeroLevelsetElement(Vector<IssmDouble>* vec_signed_dist, Element* element){/*{{{*/
 
@@ -665,5 +720,9 @@
 	/*Intermediaries*/
 	int         calvinglaw;
-	IssmDouble  min_thickness,thickness; 
+	IssmDouble  min_thickness,thickness,hab_fraction,crevassedepth;
+	IssmDouble  rho_ice,rho_water;
+	IssmDouble  bed,water_depth;
+	IssmDouble  levelset;
+	
 	femmodel->parameters->FindParam(&calvinglaw,CalvingLawEnum);
 
@@ -697,4 +756,157 @@
 		}
 	}
+	
+	if(calvinglaw==CalvingHabEnum){
+
+		/*Get the fraction of the flotation thickness at the terminus*/
+		femmodel->elements->InputDuplicate(MaskIceLevelsetEnum, DistanceToCalvingfrontEnum);
+		femmodel->DistanceToFieldValue(MaskIceLevelsetEnum,0,DistanceToCalvingfrontEnum);
+		
+		/*Loop over all elements of this partition*/
+		for(int i=0;i<femmodel->elements->Size();i++){
+			Element* element  = xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
+			
+			rho_ice = element->GetMaterialParameter(MaterialsRhoIceEnum);
+			rho_water = element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+
+			int      numnodes           = element->GetNumberOfNodes();
+			Gauss*   gauss              = element->NewGauss();
+			Input*   H_input            = element->GetInput(ThicknessEnum); _assert_(H_input);
+			Input*   bed_input          = element->GetInput(BedEnum); _assert_(bed_input);
+			Input*   hab_fraction_input = element->GetInput(CalvingHabFractionEnum); _assert_(hab_fraction_input);
+			Input*   ls_input           = element->GetInput(DistanceToCalvingfrontEnum); _assert_(ls_input);
+
+			/*Potentially constrain nodes of this element*/
+			for(int in=0;in<numnodes;in++){
+				gauss->GaussNode(element->GetElementType(),in);
+				Node* node=element->GetNode(in);
+				H_input->GetInputValue(&thickness,gauss);
+				bed_input->GetInputValue(&water_depth,gauss);
+				ls_input->GetInputValue(&levelset,gauss);
+				hab_fraction_input->GetInputValue(&hab_fraction,gauss);
+
+				if(thickness<((rho_water/rho_ice)*(1+hab_fraction)*-water_depth) && levelset>-300. && levelset<0.){
+					node->ApplyConstraint(0,+1.);
+				}
+				else {
+					/* no ice, set no spc */
+					node->DofInFSet(0); 
+				}
+			}
+			delete gauss;
+		}
+	}
+	
+	if(calvinglaw==CalvingCrevasseDepthEnum){
+	
+		int                 nflipped,local_nflipped;
+		Vector<IssmDouble>* vec_constraint_nodes = NULL;
+		IssmDouble* constraint_nodes = NULL;
+		
+		/*Get the DistanceToCalvingfront*/
+		femmodel->elements->InputDuplicate(MaskIceLevelsetEnum,DistanceToCalvingfrontEnum);
+		femmodel->DistanceToFieldValue(MaskIceLevelsetEnum,0,DistanceToCalvingfrontEnum);
+
+		/*Vector of size number of nodes*/
+		vec_constraint_nodes=new Vector<IssmDouble>(femmodel->nodes->NumberOfNodes(LevelsetAnalysisEnum));
+
+		for(int i=0;i<femmodel->elements->Size();i++){
+			Element* element  = xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
+			int      numnodes = element->GetNumberOfNodes();
+			Gauss*   gauss    = element->NewGauss();
+			Input*   crevassedepth_input = element->GetInput(CrevasseDepthEnum); _assert_(crevassedepth_input);
+			Input*   bed_input = element->GetInput(BedEnum); _assert_(bed_input);
+
+			/*First, look at ice front and figure out if any of the nodes will be calved*/
+			if(element->IsIcefront()){
+				for(int in=0;in<numnodes;in++){
+					gauss->GaussNode(element->GetElementType(),in);
+					Node* node=element->GetNode(in);
+					crevassedepth_input->GetInputValue(&crevassedepth,gauss);
+					bed_input->GetInputValue(&bed,gauss);
+					if(crevassedepth>0. && bed<0.){
+						vec_constraint_nodes->SetValue(node->Sid(),1.0,INS_VAL);
+					}
+				}
+			}
+			delete gauss;
+		}
+		/*Assemble vector and serialize: */
+		vec_constraint_nodes->Assemble();
+		constraint_nodes=vec_constraint_nodes->ToMPISerial();
+
+		nflipped=1;
+		while(nflipped){
+			local_nflipped=0;
+			for(int i=0;i<femmodel->elements->Size();i++){
+				Element* element  = xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
+				int      numnodes = element->GetNumberOfNodes();
+				Gauss*   gauss    = element->NewGauss();
+				Input*   levelset_input  = element->GetInput(DistanceToCalvingfrontEnum); _assert_(levelset_input);
+				Input*   crevassedepth_input = element->GetInput(CrevasseDepthEnum); _assert_(crevassedepth_input);
+				Input*   bed_input = element->GetInput(BedEnum); _assert_(bed_input);
+
+				/*Is this element connected to a node that should be calved*/
+				bool isconnected = false;
+				for(int in=0;in<numnodes;in++){
+					Node* node=element->GetNode(in);
+					if(constraint_nodes[node->Sid()]==1.){
+						isconnected = true;
+						break;
+					}
+				}
+
+				/*Check status if connected*/
+				if(isconnected){
+					for(int in=0;in<numnodes;in++){
+						gauss->GaussNode(element->GetElementType(),in);
+						Node* node=element->GetNode(in);
+						levelset_input->GetInputValue(&levelset,gauss);
+						crevassedepth_input->GetInputValue(&crevassedepth,gauss);
+						bed_input->GetInputValue(&bed,gauss);
+
+						if(crevassedepth>0. && bed<0. && levelset>-300. && levelset<0. && constraint_nodes[node->Sid()]==0.){
+							local_nflipped++;
+							vec_constraint_nodes->SetValue(node->Sid(),1.0,INS_VAL);
+						}
+					}
+				}
+			}
+
+			/*Count how many new nodes were found*/
+			ISSM_MPI_Allreduce(&local_nflipped,&nflipped,1,ISSM_MPI_INT,ISSM_MPI_SUM,IssmComm::GetComm());
+			//_printf0_("Found "<<nflipped<<" to flip\n");
+
+			/*Assemble and serialize flag vector*/
+			vec_constraint_nodes->Assemble();
+			xDelete<IssmDouble>(constraint_nodes);
+			constraint_nodes=vec_constraint_nodes->ToMPISerial();
+		}
+		/*Free ressources:*/
+		delete vec_constraint_nodes;
+
+		/*Contrain the nodes that will be calved*/
+		for(int i=0;i<femmodel->elements->Size();i++){
+			Element* element  = xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
+			int      numnodes = element->GetNumberOfNodes();
+			Gauss*   gauss    = element->NewGauss();
+			/*Potentially constrain nodes of this element*/
+			for(int in=0;in<numnodes;in++){
+				gauss->GaussNode(element->GetElementType(),in);
+				Node* node=element->GetNode(in);
+				
+				if(constraint_nodes[node->Sid()]>0.){
+					node->ApplyConstraint(0,+1.);
+				}
+				else {
+					/* no ice, set no spc */
+					node->DofInFSet(0);
+				}
+			}
+			delete gauss;
+		}
+		xDelete<IssmDouble>(constraint_nodes);
+	}
+
 	/*Default, do nothing*/
 	return;
Index: /issm/trunk/src/c/analyses/LevelsetAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/LevelsetAnalysis.h	(revision 22757)
+++ /issm/trunk/src/c/analyses/LevelsetAnalysis.h	(revision 22758)
@@ -32,5 +32,4 @@
 		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
 		void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
-		void           SetDistanceOnIntersectedElements(FemModel* femmodel);
 		void           SetDistanceToZeroLevelsetElement(Vector<IssmDouble>* vec_signed_dist, Element* element);
 		void           UpdateConstraints(FemModel* femmodel);
Index: /issm/trunk/src/c/analyses/LoveAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/LoveAnalysis.cpp	(revision 22758)
+++ /issm/trunk/src/c/analyses/LoveAnalysis.cpp	(revision 22758)
@@ -0,0 +1,57 @@
+#include "./LoveAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+void LoveAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+}/*}}}*/
+void LoveAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+}/*}}}*/
+void LoveAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+}/*}}}*/
+int  LoveAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	_error_("not needed!");
+}/*}}}*/
+void LoveAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+}/*}}}*/
+void LoveAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+}/*}}}*/
+void LoveAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/*Default, do nothing*/
+	return;
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           LoveAnalysis::Core(FemModel* femmodel){/*{{{*/
+	_error_(" not needed!");
+}/*}}}*/
+ElementVector* LoveAnalysis::CreateDVector(Element* element){/*{{{*/
+	_error_(" not needed!");
+}/*}}}*/
+ElementMatrix* LoveAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+	_error_(" not needed!");
+}/*}}}*/
+ElementMatrix* LoveAnalysis::CreateKMatrix(Element* element){/*{{{*/
+	_error_(" not needed!");
+}/*}}}*/
+ElementVector* LoveAnalysis::CreatePVector(Element* element){/*{{{*/
+	_error_("not supported");
+}/*}}}*/
+void           LoveAnalysis::GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	_error_("not supported");
+}/*}}}*/
+void           LoveAnalysis::GetBprime(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	_error_("not supported");
+}/*}}}*/
+void           LoveAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void           LoveAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void           LoveAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+	_error_("not supported");
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/LoveAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/LoveAnalysis.h	(revision 22758)
+++ /issm/trunk/src/c/analyses/LoveAnalysis.h	(revision 22758)
@@ -0,0 +1,35 @@
+/*! \file LoveAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _LoveAnalysis_
+#define _LoveAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class LoveAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		void           GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetBprime(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void           UpdateConstraints(FemModel* femmodel);
+};
+#endif
Index: /issm/trunk/src/c/analyses/MasstransportAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/MasstransportAnalysis.cpp	(revision 22757)
+++ /issm/trunk/src/c/analyses/MasstransportAnalysis.cpp	(revision 22758)
@@ -122,4 +122,5 @@
 	bool   isgroundingline;
 	bool   ismovingfront;
+	bool   isoceancoupling;
 	bool   issmb;
 
@@ -129,4 +130,5 @@
 	iomodel->FindConstant(&isgroundingline,"md.transient.isgroundingline");
 	iomodel->FindConstant(&ismovingfront,"md.transient.ismovingfront");
+	iomodel->FindConstant(&isoceancoupling,"md.transient.isoceancoupling");
 	iomodel->FindConstant(&issmb,"md.transient.issmb");
 
@@ -154,8 +156,31 @@
 	iomodel->FetchDataToInput(elements,"md.mask.groundedice_levelset",MaskGroundediceLevelsetEnum);
 	iomodel->FetchDataToInput(elements,"md.basalforcings.groundedice_melting_rate",BasalforcingsGroundediceMeltingRateEnum);
-	iomodel->FetchDataToInput(elements,"md.basalforcings.floatingice_melting_rate",BasalforcingsFloatingiceMeltingRateEnum);
 	iomodel->FetchDataToInput(elements,"md.initialization.vx",VxEnum);
 	iomodel->FetchDataToInput(elements,"md.initialization.vy",VyEnum);
 
+	/*Get what we need for ocean-induced basal melting*/
+	int basalforcing_model;
+	iomodel->FindConstant(&basalforcing_model,"md.basalforcings.model");
+	switch(basalforcing_model){
+		case FloatingMeltRateEnum:
+			iomodel->FetchDataToInput(elements,"md.basalforcings.floatingice_melting_rate",BasalforcingsFloatingiceMeltingRateEnum);
+			break;
+		case LinearFloatingMeltRateEnum:
+			break;
+		case MismipFloatingMeltRateEnum:
+			break;
+		case MantlePlumeGeothermalFluxEnum:
+			break;
+		case BasalforcingsPicoEnum:
+			iomodel->FetchDataToInput(elements,"md.basalforcings.basin_id",BasalforcingsPicoBasinIdEnum);
+			break;
+		default:
+			_error_("Basal forcing model "<<EnumToStringx(basalforcing_model)<<" not supported yet");
+	}
+
+	if(isoceancoupling){
+		iomodel->FetchDataToInput(elements,"md.mesh.lat",MeshLatEnum);
+		iomodel->FetchDataToInput(elements,"md.mesh.long",MeshLongEnum);
+	}
 	if(!issmb){
 		iomodel->FetchDataToInput(elements,"md.smb.mass_balance",SmbMassBalanceEnum);
@@ -172,4 +197,5 @@
 		iomodel->FetchDataToInput(elements,"md.mesh.vertexonsurface",MeshVertexonsurfaceEnum);
 	}
+	
 }/*}}}*/
 void MasstransportAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
@@ -269,5 +295,7 @@
 	Input* vxaverage_input=element->GetInput(VxAverageEnum); _assert_(vxaverage_input);
 	Input* vyaverage_input=NULL;
-	if(dim==2) vyaverage_input=element->GetInput(VyAverageEnum); _assert_(vyaverage_input);
+	if(dim==2){
+		vyaverage_input=element->GetInput(VyAverageEnum); _assert_(vyaverage_input);
+	}
 
 	h = element->CharacteristicLength();
@@ -469,7 +497,12 @@
 
 	/*Intermediaries */
+	int         migration_style,point1;
+	bool        mainlyfloating;
+	IssmDouble  fraction1,fraction2;
 	IssmDouble  Jdet,dt;
-	IssmDouble  ms,mb,gmb,fmb,thickness,phi;
+	IssmDouble  ms,mb,gmb,fmb,thickness;
+	IssmDouble  gllevelset,phi=1.;
 	IssmDouble* xyz_list = NULL;
+	Gauss*      gauss     = NULL;
 
 	/*Fetch number of nodes and dof for this finite element*/
@@ -482,13 +515,24 @@
 	/*Retrieve all inputs and parameters*/
 	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&migration_style,GroundinglineMigrationEnum);
 	element->FindParam(&dt,TimesteppingTimeStepEnum);
 	Input* gmb_input           = element->GetInput(BasalforcingsGroundediceMeltingRateEnum);  _assert_(gmb_input);
 	Input* fmb_input           = element->GetInput(BasalforcingsFloatingiceMeltingRateEnum);  _assert_(fmb_input);
-	Input* groundedice_input   = element->GetInput(MaskGroundediceLevelsetEnum);              _assert_(groundedice_input);
+	Input* gllevelset_input   = element->GetInput(MaskGroundediceLevelsetEnum);              _assert_(gllevelset_input);
 	Input* ms_input            = element->GetInput(SmbMassBalanceEnum);                       _assert_(ms_input);
 	Input* thickness_input     = element->GetInput(ThicknessEnum);                            _assert_(thickness_input);
 
+	/*Recover portion of element that is grounded*/
+	phi=element->GetGroundedPortion(xyz_list);
+	if(migration_style==SubelementMigration2Enum){
+		gllevelset_input=element->GetInput(MaskGroundediceLevelsetEnum); _assert_(gllevelset_input);
+		element->GetGroundedPart(&point1,&fraction1,&fraction2,&mainlyfloating);
+	   gauss = element->NewGauss(point1,fraction1,fraction2,3);
+	}
+	else{
+		gauss = element->NewGauss(3);
+	}
+
 	/* Start  looping on the number of gaussian points: */
-	Gauss* gauss=element->NewGauss(2);
 	for(int ig=gauss->begin();ig<gauss->end();ig++){
 		gauss->GaussPoint(ig);
@@ -500,8 +544,23 @@
 		gmb_input->GetInputValue(&gmb,gauss);
 		fmb_input->GetInputValue(&fmb,gauss);
-		groundedice_input->GetInputValue(&phi,gauss);
+		gllevelset_input->GetInputValue(&gllevelset,gauss);
 		thickness_input->GetInputValue(&thickness,gauss);
-		if(phi>0.) mb=gmb;
-		else mb=fmb;
+
+		if(migration_style==SubelementMigrationEnum){
+			if (phi>0.999999999) mb=gmb;
+			else mb=(1-phi)*fmb+phi*gmb; // phi is the fraction of grounded ice so (1-phi) is floating
+		}
+		else if(migration_style==SubelementMigration2Enum){
+			if(gllevelset>0.) mb=gmb;
+			else mb=fmb;
+		}
+		else if(migration_style==SubelementMigration3Enum){
+			if (phi<0.00000001) mb=fmb;
+			else mb=gmb;
+		}
+		else{
+			if(gllevelset>0) mb=gmb;
+			else mb=fmb;
+		}
 
 		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(thickness+dt*(ms-mb))*basis[i];
@@ -521,5 +580,5 @@
 	/*Intermediaries */
 	IssmDouble  Jdet,dt;
-	IssmDouble  ms,mb,gmb,fmb,thickness,phi;
+	IssmDouble  ms,mb,gmb,fmb,thickness,phi=1.;
 	IssmDouble* xyz_list = NULL;
 
@@ -537,5 +596,5 @@
 	Input* fmb_input           = element->GetInput(BasalforcingsFloatingiceMeltingRateEnum); _assert_(fmb_input);
 	Input* ms_input            = element->GetInput(SmbMassBalanceEnum);          _assert_(ms_input);
-	Input* groundedice_input   = element->GetInput(MaskGroundediceLevelsetEnum);             _assert_(groundedice_input);
+	Input* gllevelset_input   = element->GetInput(MaskGroundediceLevelsetEnum);             _assert_(gllevelset_input);
 	Input* thickness_input     = element->GetInput(ThicknessEnum);                           _assert_(thickness_input);
 
@@ -551,7 +610,8 @@
 		gmb_input->GetInputValue(&gmb,gauss);
 		fmb_input->GetInputValue(&fmb,gauss);
-		groundedice_input->GetInputValue(&phi,gauss);
+		gllevelset_input->GetInputValue(&phi,gauss);
 		thickness_input->GetInputValue(&thickness,gauss);
-		if(phi>0) mb=gmb;
+
+		if(phi>0.) mb=gmb;
 		else mb=fmb;
 
Index: /issm/trunk/src/c/analyses/MeltingAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/MeltingAnalysis.cpp	(revision 22757)
+++ /issm/trunk/src/c/analyses/MeltingAnalysis.cpp	(revision 22758)
@@ -38,6 +38,4 @@
 }/*}}}*/
 void MeltingAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
-
-	int frictionlaw;
 
 	/*Now, is the model 3d? otherwise, do nothing: */
Index: sm/trunk/src/c/analyses/MeshdeformationAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/MeshdeformationAnalysis.cpp	(revision 22757)
+++ 	(revision )
@@ -1,56 +1,0 @@
-#include "./MeshdeformationAnalysis.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../modules/modules.h"
-
-/*Model processing*/
-void MeshdeformationAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
-	   _error_("not implemented yet");
-}/*}}}*/
-void MeshdeformationAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
-	   _error_("not implemented yet");
-}/*}}}*/
-void MeshdeformationAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
-	   _error_("not implemented yet");
-}/*}}}*/
-int  MeshdeformationAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
-	_error_("not implemented");
-}/*}}}*/
-void MeshdeformationAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
-	   _error_("not implemented yet");
-}/*}}}*/
-void MeshdeformationAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
-	   _error_("not implemented yet");
-}/*}}}*/
-
-/*Finite Element Analysis*/
-void           MeshdeformationAnalysis::Core(FemModel* femmodel){/*{{{*/
-	_error_("not implemented");
-}/*}}}*/
-ElementVector* MeshdeformationAnalysis::CreateDVector(Element* element){/*{{{*/
-	/*Default, return NULL*/
-	return NULL;
-}/*}}}*/
-ElementMatrix* MeshdeformationAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
-_error_("Not implemented");
-}/*}}}*/
-ElementMatrix* MeshdeformationAnalysis::CreateKMatrix(Element* element){/*{{{*/
-	_error_("not implemented yet");
-}/*}}}*/
-ElementVector* MeshdeformationAnalysis::CreatePVector(Element* element){/*{{{*/
-_error_("not implemented yet");
-}/*}}}*/
-void           MeshdeformationAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
-	   _error_("not implemented yet");
-}/*}}}*/
-void           MeshdeformationAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
-	_error_("Not implemented yet");
-}/*}}}*/
-void           MeshdeformationAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
-	_error_("not implemented yet");
-}/*}}}*/
-void           MeshdeformationAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
-	/*Default, do nothing*/
-	return;
-}/*}}}*/
Index: sm/trunk/src/c/analyses/MeshdeformationAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/MeshdeformationAnalysis.h	(revision 22757)
+++ 	(revision )
@@ -1,33 +1,0 @@
-/*! \file MeshdeformationAnalysis.h 
- *  \brief: header file for generic external result object
- */
-
-#ifndef _MeshdeformationAnalysis_
-#define _MeshdeformationAnalysis_
-
-/*Headers*/
-#include "./Analysis.h"
-
-class MeshdeformationAnalysis: public Analysis{
-
-	public:
-		/*Model processing*/
-		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
-		void CreateLoads(Loads* loads, IoModel* iomodel);
-		void CreateNodes(Nodes* nodes,IoModel* iomodel);
-		int  DofsPerNode(int** doflist,int domaintype,int approximation);
-		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-
-		/*Finite element Analysis*/
-		void           Core(FemModel* femmodel);
-		ElementVector* CreateDVector(Element* element);
-		ElementMatrix* CreateJacobianMatrix(Element* element);
-		ElementMatrix* CreateKMatrix(Element* element);
-		ElementVector* CreatePVector(Element* element);
-		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-		void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
-		void           UpdateConstraints(FemModel* femmodel);
-};
-#endif
Index: /issm/trunk/src/c/analyses/SealevelriseAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/SealevelriseAnalysis.cpp	(revision 22757)
+++ /issm/trunk/src/c/analyses/SealevelriseAnalysis.cpp	(revision 22758)
@@ -36,4 +36,5 @@
 	iomodel->FetchDataToInput(elements,"md.slr.deltathickness",SealevelriseDeltathicknessEnum);
 	iomodel->FetchDataToInput(elements,"md.slr.sealevel",SealevelEnum,0);
+	iomodel->FetchDataToInput(elements,"md.slr.steric_rate",SealevelriseStericRateEnum);
 
 }/*}}}*/
@@ -90,14 +91,32 @@
 		iomodel->FetchData(&degacc,"md.slr.degacc");
 		M=reCast<int,IssmDouble>(180./degacc+1.);
+
+		// AD performance is sensitive to calls to ensurecontiguous.
+		// // Providing "t" will cause ensurecontiguous to be called.
+		#ifdef _HAVE_AD_
+		G_elastic=xNew<IssmDouble>(M,"t");
+		U_elastic=xNew<IssmDouble>(M,"t");
+		H_elastic=xNew<IssmDouble>(M,"t");
+		#else
 		G_elastic=xNew<IssmDouble>(M);
 		U_elastic=xNew<IssmDouble>(M);
 		H_elastic=xNew<IssmDouble>(M);
+		#endif
+
 		
 		/*compute combined legendre + love number (elastic green function:*/
 		m=DetermineLocalSize(M,IssmComm::GetComm());
 		GetOwnershipBoundariesFromRange(&lower_row,&upper_row,m,IssmComm::GetComm());
+		// AD performance is sensitive to calls to ensurecontiguous.
+		// // Providing "t" will cause ensurecontiguous to be called.
+		#ifdef _HAVE_AD_
+		G_elastic_local=xNew<IssmDouble>(m,"t");
+		U_elastic_local=xNew<IssmDouble>(m,"t");
+		H_elastic_local=xNew<IssmDouble>(m,"t");
+		#else
 		G_elastic_local=xNew<IssmDouble>(m);
 		U_elastic_local=xNew<IssmDouble>(m);
 		H_elastic_local=xNew<IssmDouble>(m);
+		#endif
 
 		for(int i=lower_row;i<upper_row;i++){
@@ -108,6 +127,11 @@
 			U_elastic_local[i-lower_row]= (love_h[nl-1])/2.0/sin(alpha/2.0);
 			H_elastic_local[i-lower_row]= 0; 
-			IssmDouble Pn,Pn1,Pn2;
-			IssmDouble Pn_p,Pn_p1,Pn_p2;
+			IssmDouble Pn = 0.; 
+			IssmDouble Pn1 = 0.; 
+			IssmDouble Pn2 = 0.; 
+			IssmDouble Pn_p = 0.; 
+			IssmDouble Pn_p1 = 0.; 
+			IssmDouble Pn_p2 = 0.; 
+
 			for (int n=0;n<nl;n++) {
 				IssmDouble deltalove_G;
@@ -195,5 +219,4 @@
 	/*Requested outputs*/
 	iomodel->FindConstant(&requestedoutputs,&numoutputs,"md.slr.requested_outputs");
-	parameters->AddObject(new IntParam(SealevelriseNumRequestedOutputsEnum,numoutputs));
 	if(numoutputs)parameters->AddObject(new StringArrayParam(SealevelriseRequestedOutputsEnum,requestedoutputs,numoutputs));
 	iomodel->DeleteData(&requestedoutputs,numoutputs,"md.slr.requested_outputs");
Index: /issm/trunk/src/c/analyses/SmbAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/SmbAnalysis.cpp	(revision 22757)
+++ /issm/trunk/src/c/analyses/SmbAnalysis.cpp	(revision 22758)
@@ -21,5 +21,5 @@
 	
 	int    smb_model;
-	bool   isdelta18o,ismungsm,isd18opd;
+	bool   isdelta18o,ismungsm,isd18opd,issetpddfac;
 	
 	/*Update elements: */
@@ -69,4 +69,6 @@
 			iomodel->FetchDataToInput(elements,"md.smb.Tini",SmbTiniEnum);
 			iomodel->FetchDataToInput(elements,"md.smb.Sizeini",SmbSizeiniEnum);
+			iomodel->FetchDataToInput(elements,"md.smb.aValue",SmbAValueEnum);
+			iomodel->FetchDataToInput(elements,"md.smb.teValue",SmbTeValueEnum);
 			break;
 		case SMBpddEnum:
@@ -90,4 +92,5 @@
 			iomodel->FindConstant(&ismungsm,"md.smb.ismungsm");
 			iomodel->FindConstant(&isd18opd,"md.smb.isd18opd");
+			iomodel->FindConstant(&issetpddfac,"md.smb.issetpddfac");
 			iomodel->FetchDataToInput(elements,"md.thermal.spctemperature",ThermalSpctemperatureEnum);
 			iomodel->FetchDataToInput(elements,"md.smb.s0p",SmbS0pEnum);
@@ -97,5 +100,8 @@
 				iomodel->FetchDataToInput(elements,"md.smb.precipitations_presentday",SmbPrecipitationsPresentdayEnum);
 			}
-
+			if(issetpddfac){
+				iomodel->FetchDataToInput(elements,"md.smb.pddfac_snow",SmbPddfacSnowEnum,-1.);
+				iomodel->FetchDataToInput(elements,"md.smb.pddfac_ice",SmbPddfacIceEnum,-1.);
+			}
 			break;
 		case SMBgradientsEnum:
@@ -137,5 +143,5 @@
 	int     numoutputs;
 	char**  requestedoutputs = NULL;
-	bool    isdelta18o,ismungsm,isd18opd,interp;
+	bool    isdelta18o,ismungsm,isd18opd,issetpddfac,interp;
 	int     smb_model;
 	IssmDouble *temp = NULL;
@@ -155,5 +161,4 @@
 			parameters->AddObject(iomodel->CopyConstantObject("md.smb.swIdx",SmbSwIdxEnum));
 			parameters->AddObject(iomodel->CopyConstantObject("md.smb.denIdx",SmbDenIdxEnum));
-			parameters->AddObject(iomodel->CopyConstantObject("md.smb.outputFreq",SmbOutputFreqEnum));
 			parameters->AddObject(iomodel->CopyConstantObject("md.smb.cldFrac",SmbCldFracEnum));
 			parameters->AddObject(iomodel->CopyConstantObject("md.smb.t0wet",SmbT0wetEnum));
@@ -172,11 +177,11 @@
 			parameters->AddObject(iomodel->CopyConstantObject("md.smb.isturbulentflux",SmbIsturbulentfluxEnum));
 			parameters->AddObject(iomodel->CopyConstantObject("md.smb.InitDensityScaling",SmbInitDensityScalingEnum));
+			parameters->AddObject(iomodel->CopyConstantObject("md.smb.ThermoDeltaTScaling",SmbThermoDeltaTScalingEnum));
+			parameters->AddObject(iomodel->CopyConstantObject("md.smb.adThresh",SmbAdThreshEnum));
 			break;
 		case SMBpddEnum:
 			parameters->AddObject(iomodel->CopyConstantObject("md.smb.isdelta18o",SmbIsdelta18oEnum));
 			parameters->AddObject(iomodel->CopyConstantObject("md.smb.ismungsm",SmbIsmungsmEnum));
-			parameters->AddObject(iomodel->CopyConstantObject("md.smb.desfac",SmbDesfacEnum));
-			parameters->AddObject(iomodel->CopyConstantObject("md.smb.rlaps",SmbRlapsEnum));
-			parameters->AddObject(iomodel->CopyConstantObject("md.smb.rlapslgm",SmbRlapslgmEnum));
+			parameters->AddObject(iomodel->CopyConstantObject("md.smb.issetpddfac",SmbIssetpddfacEnum));
 			iomodel->FindConstant(&isdelta18o,"md.smb.isdelta18o");
 			iomodel->FindConstant(&ismungsm,"md.smb.ismungsm");
@@ -208,16 +213,14 @@
 			parameters->AddObject(iomodel->CopyConstantObject("md.smb.ismungsm",SmbIsmungsmEnum));
 			parameters->AddObject(iomodel->CopyConstantObject("md.smb.isd18opd",SmbIsd18opdEnum));
-			parameters->AddObject(iomodel->CopyConstantObject("md.smb.desfac",SmbDesfacEnum));
-			parameters->AddObject(iomodel->CopyConstantObject("md.smb.rlaps",SmbRlapsEnum));
-			parameters->AddObject(iomodel->CopyConstantObject("md.smb.rlapslgm",SmbRlapslgmEnum));
+			parameters->AddObject(iomodel->CopyConstantObject("md.smb.issetpddfac",SmbIssetpddfacEnum));
 			iomodel->FindConstant(&ismungsm,"md.smb.ismungsm");
 			iomodel->FindConstant(&isd18opd,"md.smb.isd18opd");
+			iomodel->FindConstant(&issetpddfac,"md.smb.issetpddfac");
 			if(isd18opd){
+				parameters->AddObject(iomodel->CopyConstantObject("md.smb.f",SmbFEnum));
+				parameters->AddObject(iomodel->CopyConstantObject("md.smb.istemperaturescaled",SmbIstemperaturescaledEnum));
 				iomodel->FetchData(&temp,&N,&M,"md.smb.delta18o"); _assert_(N==2);
 				parameters->AddObject(new TransientParam(SmbDelta18oEnum,&temp[0],&temp[M],interp,M));
 				iomodel->DeleteData(temp,"md.smb.delta18o");
-				
-				parameters->AddObject(iomodel->CopyConstantObject("md.smb.dpermil",SmbDpermilEnum));
-			   parameters->AddObject(iomodel->CopyConstantObject("md.smb.f",SmbFEnum));
 			}
 			break;
Index: /issm/trunk/src/c/analyses/StressbalanceAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/StressbalanceAnalysis.cpp	(revision 22757)
+++ /issm/trunk/src/c/analyses/StressbalanceAnalysis.cpp	(revision 22758)
@@ -7,5 +7,5 @@
 #include "../cores/cores.h"
 
-//#define FSANALYTICAL 12
+//#define FSANALYTICAL 10
 //#define LATERALFRICTION 1
 
@@ -781,7 +781,11 @@
 	switch(frictionlaw){
 		case 1:
+			iomodel->FindConstant(&FrictionCoupling,"md.friction.coupling");
 			iomodel->FetchDataToInput(elements,"md.friction.coefficient",FrictionCoefficientEnum);
 			iomodel->FetchDataToInput(elements,"md.friction.p",FrictionPEnum);
 			iomodel->FetchDataToInput(elements,"md.friction.q",FrictionQEnum);
+			if(FrictionCoupling==1){
+				iomodel->FetchDataToInput(elements,"md.friction.effective_pressure",FrictionEffectivePressureEnum);
+			}
 			break;
 		case 2:
@@ -794,5 +798,5 @@
 			iomodel->FetchDataToInput(elements,"md.friction.As",FrictionAsEnum);
 			iomodel->FetchDataToInput(elements,"md.friction.q",FrictionQEnum);
-			if(FrictionCoupling==0){
+			if(FrictionCoupling==1){
 				iomodel->FetchDataToInput(elements,"md.friction.effective_pressure",FrictionEffectivePressureEnum);
 			}
@@ -818,8 +822,12 @@
 			break;
 		case 7:
+			iomodel->FindConstant(&FrictionCoupling,"md.friction.coupling");
 			iomodel->FetchDataToInput(elements,"md.friction.coefficient",FrictionCoefficientEnum);
 			iomodel->FetchDataToInput(elements,"md.friction.coefficientcoulomb",FrictionCoefficientcoulombEnum);
 			iomodel->FetchDataToInput(elements,"md.friction.p",FrictionPEnum);
 			iomodel->FetchDataToInput(elements,"md.friction.q",FrictionQEnum);
+			if(FrictionCoupling==1){
+				iomodel->FetchDataToInput(elements,"md.friction.effective_pressure",FrictionEffectivePressureEnum);
+			}
 			break;
 		case 9:
@@ -865,5 +873,4 @@
 	parameters->AddObject(iomodel->CopyConstantObject("md.stressbalance.FSreconditioning",StressbalanceFSreconditioningEnum));
 	parameters->AddObject(iomodel->CopyConstantObject("md.stressbalance.shelf_dampening",StressbalanceShelfDampeningEnum));
-	parameters->AddObject(iomodel->CopyConstantObject("md.stressbalance.viscosity_overshoot",StressbalanceViscosityOvershootEnum));
 	parameters->AddObject(iomodel->CopyConstantObject("md.friction.law",FrictionLawEnum));
 
@@ -893,5 +900,5 @@
 	iomodel->FindConstant(&frictionlaw,"md.friction.law");
 	if(frictionlaw==4 || frictionlaw==6) parameters->AddObject(iomodel->CopyConstantObject("md.friction.gamma",FrictionGammaEnum));
-	if(frictionlaw==3) parameters->AddObject(iomodel->CopyConstantObject("md.friction.coupling",FrictionCouplingEnum));
+	if(frictionlaw==3 || frictionlaw==1 || frictionlaw==7) parameters->AddObject(iomodel->CopyConstantObject("md.friction.coupling",FrictionCouplingEnum));
 	if(frictionlaw==5) parameters->AddObject(iomodel->CopyConstantObject("md.friction.f",FrictionFEnum));
 	if(frictionlaw==9) parameters->AddObject(iomodel->CopyConstantObject("md.friction.gamma",FrictionGammaEnum));
@@ -1199,5 +1206,5 @@
 		thickness_input->GetInputValue(&thickness, gauss);
 		basalelement->StrainRateSSA(&epsilon[0],xyz_list,gauss,vx_input,vy_input);
-		basalelement->material->ViscositySSADerivativeEpsSquare(&mu_prime,&epsilon[0]);
+		basalelement->material->ViscositySSADerivativeEpsSquare(&mu_prime,&epsilon[0],gauss);
 		eps1[0]=2*epsilon[0]+epsilon[1];   eps2[0]=epsilon[2];
 		eps1[1]=epsilon[2];                eps2[1]=epsilon[0]+2*epsilon[1];
@@ -1299,6 +1306,5 @@
 	/*Initialize Element matrix and vectors*/
 	ElementMatrix* Ke = element->NewElementMatrix(SSAApproximationEnum);
-	IssmDouble*    B  = xNew<IssmDouble>(dim*numdof);
-	IssmDouble*    D  = xNewZeroInit<IssmDouble>(dim*dim);
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
 
 	/*Retrieve all inputs and parameters*/
@@ -1333,12 +1339,22 @@
 		}
 
-		this->GetBSSAFriction(B,element,dim,xyz_list,gauss);
+		element->NodalFunctions(basis,gauss);
 		element->JacobianDeterminant(&Jdet, xyz_list,gauss);
-		for(int i=0;i<dim;i++) D[i*dim+i]=alpha2*gauss->weight*Jdet;
-
-		TripleMultiply(B,dim,numdof,1,
-					D,dim,dim,0,
-					B,dim,numdof,0,
-					&Ke->values[0],1);
+
+		if(dim==2){
+			for(int i=0;i<numnodes;i++){
+				for(int j=0;j<numnodes;j++){
+					Ke->values[2*i*2*numnodes+2*j]       += alpha2*gauss->weight*Jdet*basis[i]*basis[j];
+					Ke->values[(2*i+1)*2*numnodes+2*j+1] += alpha2*gauss->weight*Jdet*basis[i]*basis[j];
+				}
+			}
+		}
+		else{
+			for(int i=0;i<numnodes;i++){
+				for(int j=0;j<numnodes;j++){
+					Ke->values[i*numnodes+j] += alpha2*gauss->weight*Jdet*basis[i]*basis[j];
+				}
+			}
+		}
 	}
 
@@ -1350,6 +1366,5 @@
 	delete friction;
 	xDelete<IssmDouble>(xyz_list);
-	xDelete<IssmDouble>(B);
-	xDelete<IssmDouble>(D);
+	xDelete<IssmDouble>(basis);
 	return Ke;
 }/*}}}*/
@@ -1426,8 +1441,6 @@
 
 	/*Intermediaries*/
-	int         dim,domaintype,bsize;
-	IssmDouble  viscosity,newviscosity,oldviscosity;
-	IssmDouble  viscosity_overshoot,thickness,Jdet;
-	IssmDouble  D_scalar;
+	int         dim,domaintype;
+	IssmDouble  viscosity,thickness,Jdet;
 	IssmDouble *xyz_list = NULL;
 
@@ -1435,7 +1448,7 @@
 	element->FindParam(&domaintype,DomainTypeEnum);
 	switch(domaintype){
-		case Domain2DverticalEnum:   dim = 1; bsize = 1; break;
-		case Domain2DhorizontalEnum: dim = 2; bsize = 3; break;
-		case Domain3DEnum:           dim = 2; bsize = 3; break;
+		case Domain2DverticalEnum:   dim = 1; break;
+		case Domain2DhorizontalEnum: dim = 2; break;
+		case Domain3DEnum:           dim = 2; break;
 		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
 	}
@@ -1447,7 +1460,5 @@
 	/*Initialize Element matrix and vectors*/
 	ElementMatrix* Ke     = element->NewElementMatrix(SSAApproximationEnum);
-	IssmDouble*    B      = xNew<IssmDouble>(bsize*numdof);
-	IssmDouble*    Bprime = xNew<IssmDouble>(bsize*numdof);
-	IssmDouble*    D      = xNewZeroInit<IssmDouble>(bsize*bsize);
+	IssmDouble*    dbasis = xNew<IssmDouble>(2*numnodes);
 
 	/*Retrieve all inputs and parameters*/
@@ -1455,12 +1466,8 @@
 	Input* thickness_input=element->GetInput(ThicknessEnum); _assert_(thickness_input);
 	Input* vx_input=element->GetInput(VxEnum);               _assert_(vx_input);
-	Input* vxold_input=element->GetInput(VxPicardEnum);      _assert_(vxold_input);
 	Input* vy_input    = NULL;
-	Input* vyold_input = NULL;
 	if(dim==2){
 		vy_input    = element->GetInput(VyEnum);       _assert_(vy_input);
-		vyold_input = element->GetInput(VyPicardEnum); _assert_(vyold_input);
-	}
-	element->FindParam(&viscosity_overshoot,StressbalanceViscosityOvershootEnum);
+	}
 
 	/* Start  looping on the number of gaussian points: */
@@ -1470,19 +1477,36 @@
 
 		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
-		this->GetBSSA(B,element,dim,xyz_list,gauss);
-		this->GetBSSAprime(Bprime,element,dim,xyz_list,gauss);
-
+		element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+		thickness_input->GetInputValue(&thickness, gauss);
 		element->material->ViscositySSA(&viscosity,dim,xyz_list,gauss,vx_input,vy_input);
-		element->material->ViscositySSA(&oldviscosity,dim,xyz_list,gauss,vxold_input,vyold_input);
-		thickness_input->GetInputValue(&thickness, gauss);
-
-		newviscosity=viscosity+viscosity_overshoot*(viscosity-oldviscosity);
-		D_scalar=2.*newviscosity*thickness*gauss->weight*Jdet;
-		for(int i=0;i<bsize;i++) D[i*bsize+i]=D_scalar;
-
-		TripleMultiply(B,bsize,numdof,1,
-					D,bsize,bsize,0,
-					Bprime,bsize,numdof,0,
-					&Ke->values[0],1);
+
+		if(dim==2){
+			for(int i=0;i<numnodes;i++){
+				for(int j=0;j<numnodes;j++){
+					Ke->values[2*i*2*numnodes+2*j] += gauss->weight*Jdet*viscosity*thickness*(
+								4.*dbasis[0*numnodes+j]*dbasis[0*numnodes+i] + dbasis[1*numnodes+j]*dbasis[1*numnodes+i]
+								);
+					Ke->values[2*i*2*numnodes+2*j+1] += gauss->weight*Jdet*viscosity*thickness*(
+								2.*dbasis[1*numnodes+j]*dbasis[0*numnodes+i] + dbasis[0*numnodes+j]*dbasis[1*numnodes+i]
+								);
+					Ke->values[(2*i+1)*2*numnodes+2*j] += gauss->weight*Jdet*viscosity*thickness*(
+								2.*dbasis[0*numnodes+j]*dbasis[1*numnodes+i] + dbasis[1*numnodes+j]*dbasis[0*numnodes+i]
+								);
+					Ke->values[(2*i+1)*2*numnodes+2*j+1] += gauss->weight*Jdet*viscosity*thickness*(
+								dbasis[0*numnodes+j]*dbasis[0*numnodes+i] + 4.*dbasis[1*numnodes+j]*dbasis[1*numnodes+i]
+								);
+				}
+			}
+		}
+		else{
+			for(int i=0;i<numnodes;i++){
+				for(int j=0;j<numnodes;j++){
+					Ke->values[i*numnodes+j] += gauss->weight*Jdet*viscosity*thickness*(
+								4.*dbasis[0*numnodes+j]*dbasis[0*numnodes+i]
+								);
+				}
+			}
+		}
 	}
 
@@ -1493,7 +1517,5 @@
 	delete gauss;
 	xDelete<IssmDouble>(xyz_list);
-	xDelete<IssmDouble>(D);
-	xDelete<IssmDouble>(Bprime);
-	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(dbasis);
 	return Ke;
 }/*}}}*/
@@ -1878,9 +1900,4 @@
 	}
 
-	/*Now, we have to move the previous Vx and Vy inputs  to old 
-	 * status, otherwise, we'll wipe them off: */
-	element->InputChangeName(VxEnum,VxPicardEnum);
-	if(dim==2)element->InputChangeName(VyEnum,VyPicardEnum);
-
 	/*Add vx and vy as inputs to the tria element: */
 	element->AddBasalInput(VxEnum,vx,element->GetElementType());
@@ -2206,9 +2223,4 @@
 	for(i=0;i<numnodes;i++) vel[i]=sqrt(vx[i]*vx[i] + vy[i]*vy[i] + vz[i]*vz[i]);
 
-	/*Now, we have to move the previous Vx and Vy inputs  to old 
-	 * status, otherwise, we'll wipe them off: */
-	element->InputChangeName(VxEnum,VxPicardEnum);
-	element->InputChangeName(VyEnum,VyPicardEnum);
-
 	/*Add vx and vy as inputs to the tria element: */
 	element->AddBasalInput(VxEnum,vx,element->GetElementType());
@@ -2260,5 +2272,5 @@
 
 		element->StrainRateHO(&epsilon[0],xyz_list,gauss,vx_input,vy_input);
-		element->material->ViscosityHODerivativeEpsSquare(&mu_prime,&epsilon[0]);
+		element->material->ViscosityHODerivativeEpsSquare(&mu_prime,&epsilon[0],gauss);
 		eps1[0]=2*epsilon[0]+epsilon[1];   eps2[0]=epsilon[2];
 		eps1[1]=epsilon[2];                eps2[1]=epsilon[0]+2*epsilon[1];
@@ -2328,7 +2340,6 @@
 
 	/*Initialize Element matrix and vectors*/
-	ElementMatrix* Ke = element->NewElementMatrix(HOApproximationEnum);
-	IssmDouble*    B  = xNew<IssmDouble>((dim-1)*numdof);
-	IssmDouble*    D  = xNewZeroInit<IssmDouble>((dim-1)*(dim-1));
+	ElementMatrix* Ke     = element->NewElementMatrix(HOApproximationEnum);
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
 
 	/*Retrieve all inputs and parameters*/
@@ -2362,12 +2373,22 @@
 		}
 
-		this->GetBHOFriction(B,element,dim,xyz_list_base,gauss);
 		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
-		for(int i=0;i<dim-1;i++) D[i*(dim-1)+i]=alpha2*gauss->weight*Jdet;
-
-		TripleMultiply(B,dim-1,numdof,1,
-					D,dim-1,dim-1,0,
-					B,dim-1,numdof,0,
-					&Ke->values[0],1);
+		element->NodalFunctions(basis,gauss);
+
+		if(dim==3){
+			for(int i=0;i<numnodes;i++){
+				for(int j=0;j<numnodes;j++){
+					Ke->values[2*i*2*numnodes+2*j]       += alpha2*gauss->weight*Jdet*basis[i]*basis[j];
+					Ke->values[(2*i+1)*2*numnodes+2*j+1] += alpha2*gauss->weight*Jdet*basis[i]*basis[j];
+				}
+			}
+		}
+		else{
+			for(int i=0;i<numnodes;i++){
+				for(int j=0;j<numnodes;j++){
+					Ke->values[i*numnodes+j] += alpha2*gauss->weight*Jdet*basis[i]*basis[j];
+				}
+			}
+		}
 	}
 
@@ -2379,6 +2400,5 @@
 	delete friction;
 	xDelete<IssmDouble>(xyz_list_base);
-	xDelete<IssmDouble>(B);
-	xDelete<IssmDouble>(D);
+	xDelete<IssmDouble>(basis);
 	return Ke;
 }/*}}}*/
@@ -2390,13 +2410,9 @@
 	/*Intermediaries*/
 	int         dim,bsize;
-	IssmDouble  viscosity,newviscosity,oldviscosity;
-	IssmDouble  viscosity_overshoot,thickness,Jdet;
-	IssmDouble  D_scalar;
+	IssmDouble  viscosity,thickness,Jdet;
 	IssmDouble *xyz_list = NULL;
 
 	/*Get problem dimension*/
 	element->FindParam(&dim,DomainDimensionEnum);
-	if(dim==2) bsize = 2;
-	else       bsize = 5;
 
 	/*Fetch number of nodes and dof for this finite element*/
@@ -2406,19 +2422,13 @@
 	/*Initialize Element matrix and vectors*/
 	ElementMatrix* Ke     = element->NewElementMatrix(HOApproximationEnum);
-	IssmDouble*    B      = xNew<IssmDouble>(bsize*numdof);
-	IssmDouble*    Bprime = xNew<IssmDouble>(bsize*numdof);
-	IssmDouble*    D      = xNewZeroInit<IssmDouble>(bsize*bsize);
+	IssmDouble*    dbasis = xNew<IssmDouble>(dim*numnodes);
 
 	/*Retrieve all inputs and parameters*/
 	element->GetVerticesCoordinates(&xyz_list);
 	Input* vx_input    = element->GetInput(VxEnum);       _assert_(vx_input);
-	Input* vxold_input = element->GetInput(VxPicardEnum); _assert_(vxold_input);
 	Input* vy_input    = NULL;
-	Input* vyold_input = NULL;
 	if(dim==3){
 		vy_input=element->GetInput(VyEnum);          _assert_(vy_input);
-		vyold_input=element->GetInput(VyPicardEnum); _assert_(vyold_input);
-	}
-	element->FindParam(&viscosity_overshoot,StressbalanceViscosityOvershootEnum);
+	}
 
 	/* Start  looping on the number of gaussian points: */
@@ -2428,18 +2438,34 @@
 
 		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
-		this->GetBHO(B,element,dim,xyz_list,gauss);
-		this->GetBHOprime(Bprime,element,dim,xyz_list,gauss);
-
+		element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
 		element->material->ViscosityHO(&viscosity,dim,xyz_list,gauss,vx_input,vy_input);
-		element->material->ViscosityHO(&oldviscosity,dim,xyz_list,gauss,vxold_input,vyold_input);
-
-		newviscosity=viscosity+viscosity_overshoot*(viscosity-oldviscosity);
-		D_scalar=2.*newviscosity*gauss->weight*Jdet;
-		for(int i=0;i<bsize;i++) D[i*bsize+i]=D_scalar;
-
-		TripleMultiply(B,bsize,numdof,1,
-					D,bsize,bsize,0,
-					Bprime,bsize,numdof,0,
-					&Ke->values[0],1);
+
+		if(dim==3){
+			for(int i=0;i<numnodes;i++){
+				for(int j=0;j<numnodes;j++){
+					Ke->values[2*i*2*numnodes+2*j] += gauss->weight*Jdet*viscosity*(
+								4.*dbasis[0*numnodes+j]*dbasis[0*numnodes+i] + dbasis[1*numnodes+j]*dbasis[1*numnodes+i] + dbasis[2*numnodes+j]*dbasis[2*numnodes+i]
+								);
+					Ke->values[2*i*2*numnodes+2*j+1] += gauss->weight*Jdet*viscosity*(
+								2.*dbasis[1*numnodes+j]*dbasis[0*numnodes+i] + dbasis[0*numnodes+j]*dbasis[1*numnodes+i]
+								);
+					Ke->values[(2*i+1)*2*numnodes+2*j] += gauss->weight*Jdet*viscosity*(
+								2.*dbasis[0*numnodes+j]*dbasis[1*numnodes+i] + dbasis[1*numnodes+j]*dbasis[0*numnodes+i]
+								);
+					Ke->values[(2*i+1)*2*numnodes+2*j+1] += gauss->weight*Jdet*viscosity*(
+								dbasis[0*numnodes+j]*dbasis[0*numnodes+i] + 4.*dbasis[1*numnodes+j]*dbasis[1*numnodes+i] + dbasis[2*numnodes+j]*dbasis[2*numnodes+i]
+								);
+				}
+			}
+		}
+		else{
+			for(int i=0;i<numnodes;i++){
+				for(int j=0;j<numnodes;j++){
+					Ke->values[i*numnodes+j] += gauss->weight*Jdet*viscosity*(
+								4.*dbasis[0*numnodes+j]*dbasis[0*numnodes+i] + dbasis[1*numnodes+j]*dbasis[1*numnodes+i]
+								);
+				}
+			}
+		}
 	}
 
@@ -2450,7 +2476,5 @@
 	delete gauss;
 	xDelete<IssmDouble>(xyz_list);
-	xDelete<IssmDouble>(D);
-	xDelete<IssmDouble>(Bprime);
-	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(dbasis);
 	return Ke;
 }/*}}}*/
@@ -2856,9 +2880,4 @@
 	}
 
-	/*Now, we have to move the previous Vx and Vy inputs  to old 
-	 * status, otherwise, we'll wipe them off: */
-	element->InputChangeName(VxEnum,VxPicardEnum);
-	if(dim==3)element->InputChangeName(VyEnum,VyPicardEnum);
-
 	/*Add vx and vy as inputs to the element: */
 	element->AddInput(VxEnum,vx,element->GetElementType());
@@ -2950,5 +2969,5 @@
 		eps1[1]=epsilon[2];   eps2[1]=epsilon[1];   eps3[1]=epsilon[4];
 		eps1[2]=epsilon[3];   eps2[2]=epsilon[4];   eps3[2]= -epsilon[0] -epsilon[1];
-		element->material->ViscosityFSDerivativeEpsSquare(&mu_prime,&epsilon[0]);
+		element->material->ViscosityFSDerivativeEpsSquare(&mu_prime,&epsilon[0],gauss);
 
 		for(i=0;i<vnumnodes;i++){
@@ -3085,5 +3104,5 @@
 
 	/*Intermediaries*/
-	int         i,dim,epssize;
+	int         i,dim;
 	IssmDouble  viscosity,FSreconditioning,Jdet;
 	IssmDouble *xyz_list = NULL;
@@ -3091,6 +3110,4 @@
 	/*Get problem dimension*/
 	element->FindParam(&dim,DomainDimensionEnum);
-	if(dim==2) epssize = 3;
-	else       epssize = 6;
 
 	/*Fetch number of nodes and dof for this finite element*/
@@ -3098,5 +3115,4 @@
 	int pnumnodes = element->NumberofNodesPressure();
 	int numdof    = vnumnodes*dim + pnumnodes;
-	int bsize     = epssize + 2;
 
 	/*Prepare coordinate system list*/
@@ -3107,8 +3123,7 @@
 
 	/*Initialize Element matrix and vectors*/
-	ElementMatrix* Ke     = element->NewElementMatrix(FSvelocityEnum);
-	IssmDouble*    B      = xNew<IssmDouble>(bsize*numdof);
-	IssmDouble*    Bprime = xNew<IssmDouble>(bsize*numdof);
-	IssmDouble*    D      = xNewZeroInit<IssmDouble>(bsize*bsize);
+	ElementMatrix* Ke   = element->NewElementMatrix(FSvelocityEnum);
+	IssmDouble* vdbasis = xNew<IssmDouble>(dim*vnumnodes);
+	IssmDouble* pbasis  = xNew<IssmDouble>(pnumnodes);
 
 	/*Retrieve all inputs and parameters*/
@@ -3117,5 +3132,5 @@
 	Input* vx_input=element->GetInput(VxEnum);     _assert_(vx_input);
 	Input* vy_input=element->GetInput(VyEnum);     _assert_(vy_input);
-	Input* vz_input;
+	Input* vz_input = NULL;
 	if(dim==3){vz_input=element->GetInput(VzEnum); _assert_(vz_input);}
 
@@ -3126,15 +3141,59 @@
 
 		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
-		this->GetBFS(B,element,dim,xyz_list,gauss);
-		this->GetBFSprime(Bprime,element,dim,xyz_list,gauss);
-
+		element->NodalFunctionsDerivativesVelocity(vdbasis,xyz_list,gauss);
+		element->NodalFunctionsPressure(pbasis,gauss);
 		element->material->ViscosityFS(&viscosity,dim,xyz_list,gauss,vx_input,vy_input,vz_input);
-		for(i=0;i<epssize;i++)     D[i*bsize+i] = + 2.*viscosity*gauss->weight*Jdet;
-		for(i=epssize;i<bsize;i++) D[i*bsize+i] = - FSreconditioning*gauss->weight*Jdet;
-
-		TripleMultiply(B,bsize,numdof,1,
-					D,bsize,bsize,0,
-					Bprime,bsize,numdof,0,
-					&Ke->values[0],1);
+
+		if(dim==3){
+			/*Stress balance*/
+			for(int i=0;i<vnumnodes;i++){
+				for(int j=0;j<vnumnodes;j++){
+					Ke->values[(3*i+0)*numdof+3*j+0] += gauss->weight*Jdet*viscosity*(2.*vdbasis[0*vnumnodes+j]*vdbasis[0*vnumnodes+i] + vdbasis[1*vnumnodes+j]*vdbasis[1*vnumnodes+i] + vdbasis[2*vnumnodes+j]*vdbasis[2*vnumnodes+i]);
+					Ke->values[(3*i+0)*numdof+3*j+1] += gauss->weight*Jdet*viscosity*(vdbasis[0*vnumnodes+j]*vdbasis[1*vnumnodes+i]);
+					Ke->values[(3*i+0)*numdof+3*j+2] += gauss->weight*Jdet*viscosity*(vdbasis[0*vnumnodes+j]*vdbasis[2*vnumnodes+i]);
+					Ke->values[(3*i+1)*numdof+3*j+0] += gauss->weight*Jdet*viscosity*(vdbasis[1*vnumnodes+j]*vdbasis[0*vnumnodes+i]);
+					Ke->values[(3*i+1)*numdof+3*j+1] += gauss->weight*Jdet*viscosity*(vdbasis[0*vnumnodes+j]*vdbasis[0*vnumnodes+i] + 2.*vdbasis[1*vnumnodes+j]*vdbasis[1*vnumnodes+i] + vdbasis[2*vnumnodes+j]*vdbasis[2*vnumnodes+i]);
+					Ke->values[(3*i+1)*numdof+3*j+2] += gauss->weight*Jdet*viscosity*(vdbasis[1*vnumnodes+j]*vdbasis[2*vnumnodes+i]);
+					Ke->values[(3*i+2)*numdof+3*j+0] += gauss->weight*Jdet*viscosity*(vdbasis[2*vnumnodes+j]*vdbasis[0*vnumnodes+i]);
+					Ke->values[(3*i+2)*numdof+3*j+1] += gauss->weight*Jdet*viscosity*(vdbasis[2*vnumnodes+j]*vdbasis[1*vnumnodes+i]);
+					Ke->values[(3*i+2)*numdof+3*j+2] += gauss->weight*Jdet*viscosity*(vdbasis[0*vnumnodes+j]*vdbasis[0*vnumnodes+i] + vdbasis[1*vnumnodes+j]*vdbasis[1*vnumnodes+i] + 2.*vdbasis[2*vnumnodes+j]*vdbasis[2*vnumnodes+i]);
+				}
+				for(int k=0;k<pnumnodes;k++){
+					Ke->values[(3*i+0)*numdof+3*vnumnodes+k] += gauss->weight*Jdet*FSreconditioning*(-pbasis[k]*vdbasis[0*vnumnodes+i]);
+					Ke->values[(3*i+1)*numdof+3*vnumnodes+k] += gauss->weight*Jdet*FSreconditioning*(-pbasis[k]*vdbasis[1*vnumnodes+i]);
+					Ke->values[(3*i+2)*numdof+3*vnumnodes+k] += gauss->weight*Jdet*FSreconditioning*(-pbasis[k]*vdbasis[2*vnumnodes+i]);
+				}
+			}
+			/*Incompressibility*/
+			for(int k=0;k<pnumnodes;k++){
+				for(int j=0;j<vnumnodes;j++){
+					Ke->values[(3*vnumnodes+k)*numdof+3*j+0] += gauss->weight*Jdet*(-FSreconditioning*vdbasis[0*vnumnodes+j]*pbasis[k]);
+					Ke->values[(3*vnumnodes+k)*numdof+3*j+1] += gauss->weight*Jdet*(-FSreconditioning*vdbasis[1*vnumnodes+j]*pbasis[k]);
+					Ke->values[(3*vnumnodes+k)*numdof+3*j+2] += gauss->weight*Jdet*(-FSreconditioning*vdbasis[2*vnumnodes+j]*pbasis[k]);
+				}
+			}
+		}
+		else{
+			/*Stress balance*/
+			for(int i=0;i<vnumnodes;i++){
+				for(int j=0;j<vnumnodes;j++){
+					Ke->values[(2*i+0)*numdof+2*j+0] += gauss->weight*Jdet*viscosity*(2.*vdbasis[0*vnumnodes+j]*vdbasis[0*vnumnodes+i] + vdbasis[1*vnumnodes+j]*vdbasis[1*vnumnodes+i]);
+					Ke->values[(2*i+0)*numdof+2*j+1] += gauss->weight*Jdet*viscosity*(vdbasis[0*vnumnodes+j]*vdbasis[1*vnumnodes+i]);
+					Ke->values[(2*i+1)*numdof+2*j+0] += gauss->weight*Jdet*viscosity*(vdbasis[1*vnumnodes+j]*vdbasis[0*vnumnodes+i]);
+					Ke->values[(2*i+1)*numdof+2*j+1] += gauss->weight*Jdet*viscosity*(vdbasis[0*vnumnodes+j]*vdbasis[0*vnumnodes+i] + 2.*vdbasis[1*vnumnodes+j]*vdbasis[1*vnumnodes+i]);
+				}
+				for(int k=0;k<pnumnodes;k++){
+					Ke->values[(2*i+0)*numdof+2*vnumnodes+k] += gauss->weight*Jdet*FSreconditioning*(-pbasis[k]*vdbasis[0*vnumnodes+i]);
+					Ke->values[(2*i+1)*numdof+2*vnumnodes+k] += gauss->weight*Jdet*FSreconditioning*(-pbasis[k]*vdbasis[1*vnumnodes+i]);
+				}
+			}
+			/*Incompressibility*/
+			for(int k=0;k<pnumnodes;k++){
+				for(int j=0;j<vnumnodes;j++){
+					Ke->values[(2*vnumnodes+k)*numdof+2*j+0] += gauss->weight*Jdet*(-FSreconditioning*vdbasis[0*vnumnodes+j]*pbasis[k]);
+					Ke->values[(2*vnumnodes+k)*numdof+2*j+1] += gauss->weight*Jdet*(-FSreconditioning*vdbasis[1*vnumnodes+j]*pbasis[k]);
+				}
+			}
+		}
 	}
 
@@ -3145,7 +3204,6 @@
 	delete gauss;
 	xDelete<IssmDouble>(xyz_list);
-	xDelete<IssmDouble>(D);
-	xDelete<IssmDouble>(Bprime);
-	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(pbasis);
+	xDelete<IssmDouble>(vdbasis);
 	xDelete<int>(cs_list);
 	return Ke;
@@ -3494,4 +3552,6 @@
 ElementVector* StressbalanceAnalysis::CreatePVectorFSStress(Element* element){/*{{{*/
 
+	/*Skipping for now*/
+	return NULL;
 	if(!element->IsOnBase()) return NULL;
 
@@ -3654,6 +3714,5 @@
 	/*Initialize Element matrix and vectors*/
 	ElementMatrix* Ke = element->NewElementMatrix(FSvelocityEnum);
-	IssmDouble*    B  = xNew<IssmDouble>(dim*numdof);
-	IssmDouble*    D  = xNewZeroInit<IssmDouble>(dim*dim);
+	IssmDouble* vbasis=xNew<IssmDouble>(vnumnodes);
 
 	/*Retrieve all inputs and parameters*/
@@ -3689,12 +3748,26 @@
 		}
 
-		this->GetBFSFriction(B,element,dim,xyz_list_base,gauss);
 		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
-		for(int i=0;i<dim;i++) D[i*dim+i] = alpha2*gauss->weight*Jdet; //taub_x = -alpha2 v_x (same for y)
-
-		TripleMultiply(B,dim,numdof,1,
-					D,dim,dim,0,
-					B,dim,numdof,0,
-					&Ke->values[0],1);
+		element->NodalFunctionsVelocity(vbasis,gauss);
+
+		if(dim==3){
+			/*Stress balance*/
+			for(int i=0;i<vnumnodes;i++){
+				for(int j=0;j<vnumnodes;j++){
+					Ke->values[(3*i+0)*numdof+3*j+0] += alpha2*gauss->weight*Jdet*vbasis[i]*vbasis[j];
+					Ke->values[(3*i+1)*numdof+3*j+1] += alpha2*gauss->weight*Jdet*vbasis[i]*vbasis[j];
+					Ke->values[(3*i+2)*numdof+3*j+2] += alpha2*gauss->weight*Jdet*vbasis[i]*vbasis[j];
+				}
+			}
+		}
+		else{
+			/*Stress balance*/
+			for(int i=0;i<vnumnodes;i++){
+				for(int j=0;j<vnumnodes;j++){
+					Ke->values[(2*i+0)*numdof+2*j+0] += alpha2*gauss->weight*Jdet*vbasis[i]*vbasis[j];
+					Ke->values[(2*i+1)*numdof+2*j+1] += alpha2*gauss->weight*Jdet*vbasis[i]*vbasis[j];
+				}
+			}
+		}
 	}
 
@@ -3705,6 +3778,5 @@
 	delete friction;
 	xDelete<IssmDouble>(xyz_list_base);
-	xDelete<IssmDouble>(B);
-	xDelete<IssmDouble>(D);
+	xDelete<IssmDouble>(vbasis);
 	return Ke;
 }/*}}}*/
@@ -4982,15 +5054,8 @@
 	else       for(i=0;i<vnumnodes;i++) vel[i] = sqrt(vx[i]*vx[i] + vy[i]*vy[i]);
 
-	/*Now, we have to move the previous inputs  to old 
-	 * status, otherwise, we'll wipe them off: */
-	element->InputChangeName(VxEnum,VxPicardEnum);
-	element->InputChangeName(VyEnum,VyPicardEnum);
-	if(pnumdof>0) element->InputChangeName(PressureEnum,PressurePicardEnum);
-	if(dim==3) element->InputChangeName(VzEnum,VzPicardEnum);
-
 	/*Add vx and vy as inputs to the tria element: */
-	element->AddInput(VxEnum,      vx,      element->VelocityInterpolation());
-	element->AddInput(VyEnum,      vy,      element->VelocityInterpolation());
-	element->AddInput(VelEnum,     vel,     element->VelocityInterpolation());
+	element->AddInput(VxEnum, vx, element->VelocityInterpolation());
+	element->AddInput(VyEnum, vy, element->VelocityInterpolation());
+	element->AddInput(VelEnum,vel,element->VelocityInterpolation());
 	if(pnumdof>0) element->AddInput(PressureEnum,pressure,element->PressureInterpolation());
 	if(dim==3) element->AddInput(VzEnum,vz, element->VelocityInterpolation());
@@ -5358,4 +5423,7 @@
 ElementMatrix* StressbalanceAnalysis::CreateKMatrixCouplingHOFS(Element* element){/*{{{*/
 
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
 	/*Constants*/
 	int numnodes       = 3*6+1;
@@ -5435,4 +5503,7 @@
 }/*}}}*/
 ElementMatrix* StressbalanceAnalysis::CreateKMatrixCouplingSSAFSFriction(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
 
 	/*Constants*/
@@ -5558,4 +5629,7 @@
 ElementMatrix* StressbalanceAnalysis::CreateKMatrixCouplingSSAFSViscous(Element* element){/*{{{*/
 
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
 	/*Constants*/
 	const int numdofm     = 2 *3;
@@ -5676,4 +5750,7 @@
 ElementMatrix* StressbalanceAnalysis::CreateKMatrixCouplingSSAHOFriction(Element* element){/*{{{*/
 
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
 	if(element->IsFloating() || !element->IsOnBase()) return NULL;
 
@@ -5753,4 +5830,7 @@
 ElementMatrix* StressbalanceAnalysis::CreateKMatrixCouplingSSAHOViscous(Element* element){/*{{{*/
 
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
 	/*Constants*/
 	int numnodes    = element->GetNumberOfNodes();
@@ -5761,5 +5841,5 @@
 	/*Intermediaries */
 	int         i,j;
-	IssmDouble  Jdet,viscosity,oldviscosity,newviscosity,viscosity_overshoot; //viscosity
+	IssmDouble  Jdet,viscosity;
 	IssmDouble  *xyz_list      = NULL;
 	IssmDouble* B              = xNew<IssmDouble>(3*numdofp);
@@ -5791,9 +5871,6 @@
 	/* Get node coordinates and dof list: */
 	element->GetVerticesCoordinates(&xyz_list);
-	element->FindParam(&viscosity_overshoot,StressbalanceViscosityOvershootEnum);
 	Input* vx_input   =element->GetInput(VxEnum);       _assert_(vx_input);
 	Input* vy_input   =element->GetInput(VyEnum);       _assert_(vy_input);
-	Input* vxold_input=element->GetInput(VxPicardEnum); _assert_(vxold_input);
-	Input* vyold_input=element->GetInput(VyPicardEnum); _assert_(vyold_input);
 
 	/* Start  looping on the number of gaussian points: */
@@ -5809,8 +5886,6 @@
 		this->GetBSSAprime(Bprime,basaltria,2,xyz_list, gauss_tria); 
 		element->material->ViscosityHO(&viscosity,3,xyz_list,gauss,vx_input,vy_input);
-		element->material->ViscosityHO(&oldviscosity,3,xyz_list,gauss,vxold_input,vyold_input);
-
-		newviscosity=viscosity+viscosity_overshoot*(viscosity-oldviscosity);
-		D_scalar=2*newviscosity*gauss->weight*Jdet;
+
+		D_scalar=2*viscosity*gauss->weight*Jdet;
 		for (i=0;i<3;i++) D[i][i]=D_scalar;
 
@@ -5906,4 +5981,7 @@
 ElementMatrix* StressbalanceAnalysis::CreateKMatrixSSA3dFriction(Element* element){/*{{{*/
 
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
 	/*Initialize Element matrix and return if necessary*/
 	if(element->IsFloating() || !element->IsOnBase()) return NULL;
@@ -5921,4 +5999,7 @@
 ElementMatrix* StressbalanceAnalysis::CreateKMatrixSSA3dViscous(Element* element){/*{{{*/
 
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
 	/*Constants*/
 	const int    numdof2d=2*3;
@@ -5927,5 +6008,5 @@
 	int         i,j,approximation;
 	int         dim=3;
-	IssmDouble  Jdet,viscosity,oldviscosity,newviscosity,viscosity_overshoot;
+	IssmDouble  Jdet,viscosity;
 	IssmDouble  epsilon[5],oldepsilon[5];       /* epsilon=[exx,eyy,exy,exz,eyz];*/
 	IssmDouble  epsilons[6];                    //6 for FS
@@ -5947,9 +6028,6 @@
 	/*Retrieve all inputs and parameters*/
 	element->GetVerticesCoordinates(&xyz_list);
-	element->FindParam(&viscosity_overshoot,StressbalanceViscosityOvershootEnum);
 	Input* vx_input   =element->GetInput(VxEnum);       _assert_(vx_input);
 	Input* vy_input   =element->GetInput(VyEnum);       _assert_(vy_input);
-	Input* vxold_input=element->GetInput(VxPicardEnum); _assert_(vxold_input);
-	Input* vyold_input=element->GetInput(VyPicardEnum); _assert_(vyold_input);
 	Input* vz_input   =element->GetInput(VzEnum);       _assert_(vz_input);
 
@@ -5968,13 +6046,11 @@
 		if(approximation==SSAHOApproximationEnum){
 			element->material->ViscosityHO(&viscosity,dim,xyz_list,gauss,vx_input,vy_input);
-			element->material->ViscosityHO(&oldviscosity,dim,xyz_list,gauss,vxold_input,vyold_input);
-			newviscosity=viscosity+viscosity_overshoot*(viscosity-oldviscosity);
 		}
 		else if (approximation==SSAFSApproximationEnum){
-			element->material->ViscosityFS(&newviscosity,dim,xyz_list,gauss,vx_input,vy_input,vz_input);
+			element->material->ViscosityFS(&viscosity,dim,xyz_list,gauss,vx_input,vy_input,vz_input);
 		}
 		else _error_("approximation " << approximation << " (" << EnumToStringx(approximation) << ") not supported yet");
 
-		D_scalar=2*newviscosity*gauss->weight*Jdet;
+		D_scalar=2*viscosity*gauss->weight*Jdet;
 		for (i=0;i<3;i++) D[i][i]=D_scalar;
 
@@ -6012,4 +6088,7 @@
 }/*}}}*/
 ElementVector* StressbalanceAnalysis::CreatePVectorCouplingHOFSFriction(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
 
 	/*Intermediaries*/
@@ -6096,4 +6175,7 @@
 ElementVector* StressbalanceAnalysis::CreatePVectorCouplingHOFSViscous(Element* element){/*{{{*/
 
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
 	/*Intermediaries */
 	int         i,approximation;
@@ -6176,4 +6258,7 @@
 }/*}}}*/
 ElementVector* StressbalanceAnalysis::CreatePVectorCouplingSSAFSFriction(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
 
 	/*Intermediaries*/
@@ -6256,4 +6341,7 @@
 }/*}}}*/
 ElementVector* StressbalanceAnalysis::CreatePVectorCouplingSSAFSViscous(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
 
 	/*Intermediaries */
@@ -6882,11 +6970,4 @@
 	}
 
-	/*Now, we have to move the previous Vx and Vy inputs  to old 
-	 * status, otherwise, we'll wipe them off: */
-	element->InputChangeName(VxEnum,VxPicardEnum);
-	element->InputChangeName(VyEnum,VyPicardEnum);
-	element->InputChangeName(VzEnum,VzPicardEnum);
-	element->InputChangeName(PressureEnum,PressurePicardEnum);
-
 	/*Add vx and vy as inputs to element: */
 	element->AddInput(VxEnum,vx,P1Enum);
@@ -6992,11 +7073,4 @@
 	}
 
-	/*Now, we have to move the previous Vx and Vy inputs  to old 
-	 * status, otherwise, we'll wipe them off: */
-	element->InputChangeName(VxEnum,VxPicardEnum);
-	element->InputChangeName(VyEnum,VyPicardEnum);
-	element->InputChangeName(VzEnum,VzPicardEnum);
-	element->InputChangeName(PressureEnum,PressurePicardEnum);
-
 	/*Add vx and vy as inputs to element: */
 	element->AddInput(VxEnum,vx,P1Enum);
@@ -7092,10 +7166,4 @@
 	for(i=0;i<numnodes;i++) pressure[i]=rho_ice*g*(surface[i]-xyz_list[i*3+2]);
 
-	/*Now, we have to move the previous Vx and Vy inputs  to old 
-	 * status, otherwise, we'll wipe them off: */
-	element->InputChangeName(VxEnum,VxPicardEnum);
-	element->InputChangeName(VyEnum,VyPicardEnum);
-	element->InputChangeName(PressureEnum,PressurePicardEnum);
-
 	/*Add vx and vy as inputs to element: */
 	element->AddInput(VxEnum,vx,P1Enum);
Index: /issm/trunk/src/c/analyses/StressbalanceSIAAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/StressbalanceSIAAnalysis.cpp	(revision 22757)
+++ /issm/trunk/src/c/analyses/StressbalanceSIAAnalysis.cpp	(revision 22758)
@@ -331,5 +331,6 @@
 	IssmDouble  gravity    = element->GetMaterialParameter(ConstantsGEnum);
 	IssmDouble  n          = element->GetMaterialParameter(MaterialsRheologyNEnum);
-	IssmDouble  B          = element->GetMaterialParameter(MaterialsRheologyBbarEnum);
+	IssmDouble B;
+	Input* B_input         = element->GetInput(MaterialsRheologyBbarEnum);_assert_(B_input);
 	Input* slopex_input    = element->GetInput(SurfaceSlopeXEnum);        _assert_(slopex_input);
 	Input* slopey_input    = element->GetInput(SurfaceSlopeYEnum);        _assert_(slopey_input);
@@ -347,4 +348,5 @@
 		connectivity=(IssmDouble)element->VertexConnectivity(iv);
 
+		B_input->GetInputValue(&B,gauss);
 		thickness_input->GetInputValue(&thickness,gauss);
 		surface_input->GetInputValue(&surface,gauss);
@@ -418,5 +420,6 @@
 	IssmDouble  gravity    = element->GetMaterialParameter(ConstantsGEnum);
 	IssmDouble  n          = element->GetMaterialParameter(MaterialsRheologyNEnum);
-	IssmDouble  B          = element->GetMaterialParameter(MaterialsRheologyBEnum);
+	IssmDouble B;
+	Input* B_input         = element->GetInput(MaterialsRheologyBEnum);   _assert_(B_input);
 	Input* surface_input   = element->GetInput(SurfaceEnum);              _assert_(surface_input);
 	Input* slopex_input    = element->GetInput(SurfaceSlopeXEnum);        _assert_(slopex_input);
@@ -448,4 +451,5 @@
 			gauss->GaussPoint(ig);
 
+			B_input->GetInputValue(&B,gauss);
 			slopex_input->GetInputValue(&slope[0],gauss);
 			slopey_input->GetInputValue(&slope[1],gauss);
@@ -617,10 +621,4 @@
 	}
 
-	/*Now, we have to move the previous Vx and Vy inputs  to old 
-	 * status, otherwise, we'll wipe them off: */
-	element->InputChangeName(VxEnum,VxPicardEnum);
-	element->InputChangeName(VyEnum,VyPicardEnum);
-	element->InputChangeName(PressureEnum,PressurePicardEnum);
-
 	/*Add vx and vy as inputs to the tria element: */
 	element->AddInput(VxEnum,vx,P1Enum);
Index: /issm/trunk/src/c/analyses/StressbalanceVerticalAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/StressbalanceVerticalAnalysis.cpp	(revision 22757)
+++ /issm/trunk/src/c/analyses/StressbalanceVerticalAnalysis.cpp	(revision 22758)
@@ -112,5 +112,5 @@
 	}
 	iomodel->FetchDataToInput(elements,"md.basalforcings.groundedice_melting_rate",BasalforcingsGroundediceMeltingRateEnum);
-	iomodel->FetchDataToInput(elements,"md.basalforcings.floatingice_melting_rate",BasalforcingsFloatingiceMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,"md.basalforcings.floatingice_melting_rate",BasalforcingsFloatingiceMeltingRateEnum,0.);
 	//iomodel->FetchDataToInput(elements,"md.smb.mass_balance",SmbMassBalanceEnum);
 	iomodel->FetchDataToInput(elements,"md.initialization.vx",VxEnum,0.);
@@ -138,4 +138,7 @@
 }/*}}}*/
 ElementMatrix* StressbalanceVerticalAnalysis::CreateKMatrix(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
 
 	bool hack = false;
@@ -239,5 +242,5 @@
 
 	/*Intermediaries*/
-	IssmDouble  D,Jdet;
+	IssmDouble  Jdet;
 	IssmDouble *xyz_list = NULL;
 
@@ -247,6 +250,6 @@
 	/*Initialize Element matrix and vectors*/
 	ElementMatrix* Ke     = element->NewElementMatrix(NoneApproximationEnum);
-	IssmDouble*    B      = xNew<IssmDouble>(numnodes);
-	IssmDouble*    Bprime = xNew<IssmDouble>(numnodes);
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble*    dbasis = xNew<IssmDouble>(3*numnodes);
 
 	/*Retrieve all inputs and parameters*/
@@ -259,12 +262,14 @@
 
 		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
-		this->GetB(B,element,xyz_list,gauss);
-		this->GetBprime(Bprime,element,xyz_list,gauss);
-		D=gauss->weight*Jdet;
-
-		TripleMultiply(B,1,numnodes,1,
-					&D,1,1,0,
-					Bprime,1,numnodes,0,
-					&Ke->values[0],1);
+		element->NodalFunctions(basis,gauss);
+		element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+		for(int i=0;i<numnodes;i++){
+			for(int j=0;j<numnodes;j++){
+				Ke->values[i*numnodes+j] += gauss->weight*Jdet*(
+							basis[j]*dbasis[2*numnodes+i]
+							);
+			}
+		}
 	}
 
@@ -272,10 +277,13 @@
 	delete gauss;
 	xDelete<IssmDouble>(xyz_list);
-	xDelete<IssmDouble>(Bprime);
-	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(dbasis);
+	xDelete<IssmDouble>(basis);
 	return Ke;
 
 }/*}}}*/
 ElementVector* StressbalanceVerticalAnalysis::CreatePVector(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
 
 	bool hack = false;
@@ -471,28 +479,4 @@
 	return pe;
 }/*}}}*/
-void           StressbalanceVerticalAnalysis::GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-	/*	Compute B  matrix. B=[dh1/dz dh2/dz dh3/dz dh4/dz dh5/dz dh6/dz];
-		where hi is the interpolation function for node i.*/
-
-	/*Fetch number of nodes for this finite element*/
-	int numnodes = element->GetNumberOfNodes();
-
-	/*Get nodal functions derivatives*/
-	IssmDouble* dbasis=xNew<IssmDouble>(3*numnodes);
-	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
-
-	/*Build B: */
-	for(int i=0;i<numnodes;i++){
-		B[i] = dbasis[2*numnodes+i];  
-	}
-
-	/*Clean-up*/
-	xDelete<IssmDouble>(dbasis);
-}/*}}}*/
-void           StressbalanceVerticalAnalysis::GetBprime(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-
-	element->NodalFunctions(Bprime,gauss);
-
-}/*}}}*/
 void           StressbalanceVerticalAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 	element->GetSolutionFromInputsOneDof(solution,VzEnum);
@@ -583,11 +567,5 @@
 		for(i=0;i<numnodes;i++) pressure[i]=rho_ice*g*(surface[i]-xyz_list[i*3+2]);
 	}
-
-	/*Now, we have to move the previous Vz inputs to old 
-	 * status, otherwise, we'll wipe them off and add the new inputs: */
-	element->InputChangeName(VzEnum,VzPicardEnum);
-
 	if(approximation!=HOFSApproximationEnum && approximation!=SSAFSApproximationEnum){
-		element->InputChangeName(PressureEnum,PressurePicardEnum);
 		element->AddInput(PressureEnum,pressure,element->GetElementType());
 	}
@@ -617,4 +595,5 @@
 void           StressbalanceVerticalAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
 	/*Default, do nothing*/
+	SetActiveNodesLSMx(femmodel);
 	return;
 }/*}}}*/
Index: /issm/trunk/src/c/analyses/StressbalanceVerticalAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/StressbalanceVerticalAnalysis.h	(revision 22757)
+++ /issm/trunk/src/c/analyses/StressbalanceVerticalAnalysis.h	(revision 22758)
@@ -32,6 +32,4 @@
 		ElementVector* CreatePVectorSurface(Element* element);
 		ElementVector* CreatePVectorVolume(Element* element);
-		void           GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
-		void           GetBprime(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
 		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
 		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
Index: /issm/trunk/src/c/analyses/ThermalAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/ThermalAnalysis.cpp	(revision 22757)
+++ /issm/trunk/src/c/analyses/ThermalAnalysis.cpp	(revision 22758)
@@ -9,7 +9,13 @@
 
 	/*Intermediary*/
+	int        M,N;
 	int finiteelement;
 	iomodel->FindConstant(&finiteelement,"md.thermal.fe");
 	_assert_(finiteelement==P1Enum); 
+
+	/*Output*/
+	IssmDouble *spcvector  = NULL;
+	IssmDouble *spcvectorstatic  = NULL;
+	IssmDouble *issurface = NULL;
 
 	/*Only 3d mesh supported*/
@@ -34,10 +40,32 @@
 	}
 
+	/*Fetch data: */
+	iomodel->FetchData(&issurface,&M,&N,"md.mesh.vertexonsurface"); _assert_(N>0); _assert_(M==iomodel->numberofvertices);
+	iomodel->FetchData(&spcvector,&M,&N,"md.thermal.spctemperature");
+	iomodel->FetchData(&spcvectorstatic,&M,&N,"md.thermal.spctemperature");
+
+	/*Convert spcs from temperatures to enthalpy*/
+	_assert_(N>0); _assert_(M>=iomodel->numberofvertices);
+	for(int i=0;i<iomodel->numberofvertices;i++){
+		for(int j=0;j<N;j++){
+			if (isdynamic){
+				if (issurface[i]==1)spcvectorstatic[i*N+j] = NAN;
+				else spcvector[i*N+j] = NAN;
+			}
+		}
+	}
+
 	if(isdynamic){
-		IoModelToDynamicConstraintsx(constraints,iomodel,"md.thermal.spctemperature",ThermalAnalysisEnum,finiteelement);
+		IoModelToDynamicConstraintsx(constraints,iomodel,spcvector,iomodel->numberofvertices,1,ThermalAnalysisEnum,finiteelement);
+		IoModelToConstraintsx(constraints,iomodel,spcvectorstatic,M,N,ThermalAnalysisEnum,finiteelement);
 	}
 	else{
-		IoModelToConstraintsx(constraints,iomodel,"md.thermal.spctemperature",ThermalAnalysisEnum,finiteelement);
-	}
+		IoModelToConstraintsx(constraints,iomodel,spcvector,M,N,ThermalAnalysisEnum,finiteelement);
+	}
+
+	/*Free ressources:*/
+	iomodel->DeleteData(spcvector,"md.thermal.spctemperature");
+	iomodel->DeleteData(spcvectorstatic,"md.thermal.spctemperature");
+	iomodel->DeleteData(issurface,"md.mesh.vertexonsurface");
 
 }/*}}}*/
@@ -157,7 +185,11 @@
 	switch(frictionlaw){
 		case 1:
+			iomodel->FindConstant(&FrictionCoupling,"md.friction.coupling");
 			iomodel->FetchDataToInput(elements,"md.friction.coefficient",FrictionCoefficientEnum);
 			iomodel->FetchDataToInput(elements,"md.friction.p",FrictionPEnum);
 			iomodel->FetchDataToInput(elements,"md.friction.q",FrictionQEnum);
+			if (FrictionCoupling==1){
+				iomodel->FetchDataToInput(elements,"md.friction.effective_pressure",FrictionEffectivePressureEnum);
+			}
 			break;
 		case 2:
@@ -170,5 +202,5 @@
 			iomodel->FetchDataToInput(elements,"md.friction.As",FrictionAsEnum);
 			iomodel->FetchDataToInput(elements,"md.friction.q",FrictionQEnum);
-			if (FrictionCoupling==0){
+			if (FrictionCoupling==1){
 				iomodel->FetchDataToInput(elements,"md.friction.effective_pressure",FrictionEffectivePressureEnum);
 			}
@@ -193,6 +225,22 @@
 			iomodel->FetchDataToInput(elements,"md.initialization.temperature",TemperatureEnum);
 			break;
+		case 7:
+			iomodel->FindConstant(&FrictionCoupling,"md.friction.coupling");
+			iomodel->FetchDataToInput(elements,"md.friction.coefficient",FrictionCoefficientEnum);
+			iomodel->FetchDataToInput(elements,"md.friction.coefficientcoulomb",FrictionCoefficientcoulombEnum);
+			iomodel->FetchDataToInput(elements,"md.friction.p",FrictionPEnum);
+			iomodel->FetchDataToInput(elements,"md.friction.q",FrictionQEnum);
+			if (FrictionCoupling==1){
+				iomodel->FetchDataToInput(elements,"md.friction.effective_pressure",FrictionEffectivePressureEnum);
+			}
+			break;
+		case 9:
+			iomodel->FetchDataToInput(elements,"md.friction.coefficient",FrictionCoefficientEnum);
+			iomodel->FetchDataToInput(elements,"md.friction.pressure_adjusted_temperature",FrictionPressureAdjustedTemperatureEnum);
+			InputUpdateFromConstantx(elements,1.,FrictionPEnum);
+			InputUpdateFromConstantx(elements,1.,FrictionQEnum);
+			break;
 		default:
-			_error_("not supported");
+			_error_("friction law not supported");
 	}
 }/*}}}*/
@@ -219,6 +267,15 @@
 	int frictionlaw;
 	iomodel->FindConstant(&frictionlaw,"md.friction.law");
-	if(frictionlaw==4 || frictionlaw==6) parameters->AddObject(iomodel->CopyConstantObject("md.friction.gamma",FrictionGammaEnum));
-	if(frictionlaw==3) parameters->AddObject(iomodel->CopyConstantObject("md.friction.coupling",FrictionCouplingEnum));
+	if(frictionlaw==4 || frictionlaw==6){
+		parameters->AddObject(iomodel->CopyConstantObject("md.friction.gamma",FrictionGammaEnum));
+	}
+	if(frictionlaw==3 || frictionlaw==1 || frictionlaw==7){
+		parameters->AddObject(iomodel->CopyConstantObject("md.friction.coupling",FrictionCouplingEnum));
+	}
+	if(frictionlaw==9){
+		parameters->AddObject(iomodel->CopyConstantObject("md.friction.gamma",FrictionGammaEnum));
+		parameters->AddObject(new IntParam(FrictionCouplingEnum,0));
+	}
+
 }/*}}}*/
 
@@ -311,7 +368,6 @@
 	int         stabilization;
 	IssmDouble  Jdet,dt,u,v,w,um,vm,wm,vel;
-	IssmDouble  h,hx,hy,hz,vx,vy,vz;
+	IssmDouble  h,hx,hy,hz,vx,vy,vz,D_scalar;
 	IssmDouble  tau_parameter,diameter;
-	IssmDouble  D_scalar;
 	IssmDouble* xyz_list = NULL;
 
@@ -323,7 +379,5 @@
 	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
 	IssmDouble*    dbasis = xNew<IssmDouble>(3*numnodes);
-	IssmDouble*    B      = xNew<IssmDouble>(3*numnodes);
 	IssmDouble*    Bprime = xNew<IssmDouble>(3*numnodes);
-	IssmDouble     D[3][3]={0.};
 	IssmDouble     K[3][3];
 
@@ -352,39 +406,39 @@
 
 		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis,gauss);
+		element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
 		D_scalar=gauss->weight*Jdet;
 		if(dt!=0.) D_scalar=D_scalar*dt;
 
 		/*Conduction: */
-		GetBConduct(B,element,xyz_list,gauss); 
-		D[0][0]=D_scalar*kappa;
-		D[1][1]=D_scalar*kappa;
-		D[2][2]=D_scalar*kappa;
-		TripleMultiply(B,3,numnodes,1,
-					&D[0][0],3,3,0,
-					B,3,numnodes,0,
-					&Ke->values[0],1);
+		for(int i=0;i<numnodes;i++){
+			for(int j=0;j<numnodes;j++){
+				Ke->values[i*numnodes+j] += D_scalar*kappa*(
+							dbasis[0*numnodes+j]*dbasis[0*numnodes+i] + dbasis[1*numnodes+j]*dbasis[1*numnodes+i] + dbasis[2*numnodes+j]*dbasis[2*numnodes+i]
+							);
+			}
+		}
 
 		/*Advection: */
-		GetBAdvec(B,element,xyz_list,gauss); 
-		GetBAdvecprime(Bprime,element,xyz_list,gauss); 
 		vx_input->GetInputValue(&u,gauss); vxm_input->GetInputValue(&um,gauss); vx=u-um;
 		vy_input->GetInputValue(&v,gauss); vym_input->GetInputValue(&vm,gauss); vy=v-vm;
 		vz_input->GetInputValue(&w,gauss); vzm_input->GetInputValue(&wm,gauss); vz=w-wm;
-		D[0][0]=D_scalar*vx;
-		D[1][1]=D_scalar*vy;
-		D[2][2]=D_scalar*vz;
-		TripleMultiply(B,3,numnodes,1,
-					&D[0][0],3,3,0,
-					Bprime,3,numnodes,0,
-					&Ke->values[0],1);
+		for(int i=0;i<numnodes;i++){
+			for(int j=0;j<numnodes;j++){
+				Ke->values[i*numnodes+j] += D_scalar*(
+							vx*dbasis[0*numnodes+j]*basis[i] + vy*dbasis[1*numnodes+j]*basis[i] +vz*dbasis[2*numnodes+j]*basis[i]
+							);
+			}
+		}
 
 		/*Transient: */
 		if(dt!=0.){
 			D_scalar=gauss->weight*Jdet;
-			element->NodalFunctions(basis,gauss);
-			TripleMultiply(basis,numnodes,1,0,
-						&D_scalar,1,1,0,
-						basis,1,numnodes,0,
-						&Ke->values[0],1);
+			for(int i=0;i<numnodes;i++){
+				for(int j=0;j<numnodes;j++){
+					Ke->values[i*numnodes+j] += D_scalar*basis[j]*basis[i];
+				}
+			}
 			D_scalar=D_scalar*dt;
 		}
@@ -399,5 +453,4 @@
 			K[2][0]=h/(2.*vel)*fabs(vz*vx);  K[2][1]=h/(2.*vel)*fabs(vz*vy); K[2][2]=h/(2.*vel)*fabs(vz*vz);
 			for(int i=0;i<3;i++) for(int j=0;j<3;j++) K[i][j] = D_scalar*K[i][j];
-
 			GetBAdvecprime(Bprime,element,xyz_list,gauss); 
 
@@ -408,5 +461,4 @@
 		}
 		else if(stabilization==2){
-			element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
 			tau_parameter=element->StabilizationParameter(u-um,v-vm,w-wm,diameter,kappa);
 			for(int i=0;i<numnodes;i++){
@@ -429,5 +481,4 @@
 	/*Clean up and return*/
 	xDelete<IssmDouble>(xyz_list);
-	xDelete<IssmDouble>(B);
 	xDelete<IssmDouble>(Bprime);
 	xDelete<IssmDouble>(basis);
@@ -790,5 +841,5 @@
 		/*Update Rheology only if converged (we must make sure that the temperature is below melting point
 		 * otherwise the rheology could be negative*/
-		element->FindParam(&rheology_law,MaterialsRheologyLawEnum);
+		rheology_law=element->GetIntegerMaterialParameter(MaterialsRheologyLawEnum);
 		element->GetInputListOnNodes(&surface[0],SurfaceEnum);
 		switch(rheology_law){
Index: /issm/trunk/src/c/analyses/analyses.h
===================================================================
--- /issm/trunk/src/c/analyses/analyses.h	(revision 22757)
+++ /issm/trunk/src/c/analyses/analyses.h	(revision 22758)
@@ -24,4 +24,5 @@
 #include "./FreeSurfaceTopAnalysis.h"
 #include "./GiaIvinsAnalysis.h"
+#include "./LoveAnalysis.h"
 #include "./EsaAnalysis.h"
 #include "./HydrologyDCEfficientAnalysis.h"
@@ -34,5 +35,4 @@
 #include "./SealevelriseAnalysis.h"
 #include "./MeltingAnalysis.h"
-#include "./MeshdeformationAnalysis.h"
 #include "./SmoothAnalysis.h"
 #include "./StressbalanceAnalysis.h"
Index: /issm/trunk/src/c/bamg/AdjacentTriangle.cpp
===================================================================
--- /issm/trunk/src/c/bamg/AdjacentTriangle.cpp	(revision 22757)
+++ /issm/trunk/src/c/bamg/AdjacentTriangle.cpp	(revision 22758)
@@ -34,5 +34,5 @@
 	}
 	/*}}}*/
-	Icoor2 & AdjacentTriangle::det() const {/*{{{*/
+	long long & AdjacentTriangle::det() const {/*{{{*/
 		return t->det;
 	}
Index: /issm/trunk/src/c/bamg/AdjacentTriangle.h
===================================================================
--- /issm/trunk/src/c/bamg/AdjacentTriangle.h	(revision 22757)
+++ /issm/trunk/src/c/bamg/AdjacentTriangle.h	(revision 22758)
@@ -37,5 +37,5 @@
 			AdjacentTriangle Adj() const;
 			BamgVertex* EdgeVertex(const int & i) const;
-			Icoor2& det() const;
+			long long& det() const;
 	};
 }
Index: /issm/trunk/src/c/bamg/BamgOpts.cpp
===================================================================
--- /issm/trunk/src/c/bamg/BamgOpts.cpp	(revision 22757)
+++ /issm/trunk/src/c/bamg/BamgOpts.cpp	(revision 22758)
@@ -5,28 +5,25 @@
 BamgOpts::BamgOpts(){/*{{{*/
 
-	this->anisomax=0;
-	this->cutoff=0;
-	this->coeff=0;
-	this->errg=0;
-	this->gradation=0;
-	this->Hessiantype=0;
-	this->MaxCornerAngle=0;
-	this->maxnbv=0;
-	this->maxsubdiv=0;
-	this->Metrictype=0;
-	this->nbjacobi=0;
-	this->nbsmooth=0;
-	this->omega=0;
-	this->power=0;
-	this->random=0;
-	this->verbose=0;
+	this->anisomax          = 0;
+	this->cutoff            = 0;
+	this->coeff             = 0;
+	this->errg              = 0;
+	this->gradation         = 0;
+	this->Hessiantype       = 0;
+	this->maxnbv            = 0;
+	this->maxsubdiv         = 0;
+	this->Metrictype        = 0;
+	this->nbjacobi          = 0;
+	this->nbsmooth          = 0;
+	this->omega             = 0;
+	this->power             = 0;
+	this->verbose           = 0;
 
-	this->Crack=0;
-	this->geometricalmetric=0;
-	this->KeepVertices=0;
-	this->splitcorners=0;
+	this->Crack             = 0;
+	this->KeepVertices      = 0;
+	this->splitcorners      = 0;
 
-	this->hmin=0;
-	this->hmax=0;
+	this->hmin              = 0;
+	this->hmax              = 0;
 	this->hminVertices=NULL; this->hminVerticesSize[0]=this->hminVerticesSize[1]=0;
 	this->hmaxVertices=NULL; this->hmaxVerticesSize[0]=this->hmaxVerticesSize[1]=0;
@@ -68,5 +65,4 @@
 	if (this->Crack!=0  && this->Crack!=1) _error_("'Crack' supported options are 0 and 1");
 	if (this->KeepVertices!=0 && this->KeepVertices!=1) _error_("'KeepVertices' supported options are 0 and 1");
-	if (this->geometricalmetric!=0  && this->geometricalmetric!=1) _error_("'geometricalmetric' supported options are 0 and 1");
 
 	if (this->hmin<=0) _error_("'hmin' option should be >0");
Index: /issm/trunk/src/c/bamg/BamgOpts.h
===================================================================
--- /issm/trunk/src/c/bamg/BamgOpts.h	(revision 22757)
+++ /issm/trunk/src/c/bamg/BamgOpts.h	(revision 22758)
@@ -17,5 +17,4 @@
 		double  gradation;
 		int     Hessiantype;
-		double  MaxCornerAngle;
 		int     maxnbv;
 		double  maxsubdiv;
@@ -25,10 +24,8 @@
 		double  omega;
 		double  power;
-		bool    random;
 		int     verbose;
 
 		/*Flags*/
 		int     Crack;
-		int     geometricalmetric;
 		int     KeepVertices;
 		int     splitcorners;
Index: /issm/trunk/src/c/bamg/BamgVertex.cpp
===================================================================
--- /issm/trunk/src/c/bamg/BamgVertex.cpp	(revision 22757)
+++ /issm/trunk/src/c/bamg/BamgVertex.cpp	(revision 22758)
@@ -114,5 +114,5 @@
 		if ( t && (IndexInTriangle >= 0 ) && (IndexInTriangle <3) ){
 			ret = t->Optim(IndexInTriangle,koption);
-			if(!i){
+			if(i==0){
 				t =0; // for no future optim
 				IndexInTriangle= 0;
@@ -122,5 +122,5 @@
 	}
 	/*}}}*/
-	double  BamgVertex::Smoothing(Mesh &Th,const Mesh &BTh,Triangle* &tstart ,double omega){/*{{{*/
+	double  BamgVertex::Smoothing(Mesh &Th,Mesh &BTh,Triangle* &tstart ,double omega){/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Smoothing)*/
 
@@ -157,5 +157,5 @@
 		double delta=Norme2_2(Xmove); 
 
-		Icoor2 deta[3];
+		long long deta[3];
 		I2 IBTh  = BTh.R2ToI2(PNew);
 
@@ -194,5 +194,4 @@
 				tria->det =  bamg::det( (*tria)[0],(*tria)[1]  ,(*tria)[2]);
 				if (loop) {
-					BamgVertex *v0,*v1,*v2,*v3;
 					if (tria->det<0) ok =1;			       
 					else if ( (double)tria->det < detold/2 ) ok=1;
Index: /issm/trunk/src/c/bamg/BamgVertex.h
===================================================================
--- /issm/trunk/src/c/bamg/BamgVertex.h	(revision 22757)
+++ /issm/trunk/src/c/bamg/BamgVertex.h	(revision 22758)
@@ -42,5 +42,5 @@
 			/*methods (No constructor and no destructors...)*/
 			BamgVertex();
-			double Smoothing(Mesh & ,const Mesh & ,Triangle  * & ,double =1);
+			double Smoothing(Mesh & ,Mesh & ,Triangle  * & ,double =1);
 			void   MetricFromHessian(const double Hxx,const double Hyx, const double Hyy, const double smin,const double smax,const double s,const double err,BamgOpts* bamgopts);
 			void   Echo();
Index: /issm/trunk/src/c/bamg/GeomEdge.cpp
===================================================================
--- /issm/trunk/src/c/bamg/GeomEdge.cpp	(revision 22757)
+++ /issm/trunk/src/c/bamg/GeomEdge.cpp	(revision 22758)
@@ -63,75 +63,4 @@
 		return type &16; 
 	}/*}}}*/
-	double GeomEdge::R1tg(double theta,R2 & t) const{/*{{{*/
-		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/R1tg)*/
-		// 1/R of radius of cuvature
-
-		R2 A=v[0]->r,B=v[1]->r;
-		double dca,dcb,dcta,dctb;
-		double ddca,ddcb,ddcta,ddctb;
-		double tt = theta*theta;
-
-		//check theta
-		_assert_(theta>=0 && theta<=1);
-
-		if (TgA()){ 
-			if (TgB()){
-				// Tangent A and B provided:
-				// interpolation d'hermite
-				dcb = 6*theta*(1-theta);
-				ddcb = 6*(1-2*theta);
-				dca = -dcb;
-				ddca = -ddcb;
-				dcta =  (3*theta - 4)*theta + 1;
-				ddcta=6*theta-4;
-				dctb = 3*tt - 2*theta;
-				ddctb = 6*theta-2;
-			}
-			else {
-				//Tangent A provided but tangent B not provided
-				// 1-t*t, t-t*t, t*t
-				double t = theta;
-				dcb = 2*t;
-				ddcb = 2;
-				dca = -dcb;
-				ddca = -2;
-				dcta = 1-dcb;
-				ddcta = -ddcb;
-				dctb=0;    
-				ddctb=0;    
-			}
-		}
-		else{
-			if (TgB()){
-				//Tangent B provided but tangent A not provided
-				double t = 1-theta;
-				dca = -2*t;
-				ddca = 2;
-				dcb = -dca;
-				ddcb = -2;
-				dctb = 1+dca;
-				ddctb= ddca;
-				dcta =0;
-				ddcta =0;
-			}
-			else {
-				//Neither thangent A nor tangent B provided
-				// lagrange P1
-				t=B-A;
-				return 0;
-			} 
-		}
-		R2 d  =  A*dca  + B*dcb  + tg[0]* dcta  + tg[1] * dctb;
-		R2 dd =  A*ddca + B*ddcb + tg[0]* ddcta + tg[1] * ddctb;
-		double d2=(d,d);
-		double sd2 = sqrt(d2);
-		t=d;
-		if(d2>1.0e-20){
-			t/=sd2;
-			return Abs(Det(d,dd))/(d2*sd2);
-		}
-		else return 0;
-	}
-	/*}}}*/
 	int    GeomEdge::Required()       {/*{{{*/
 		return type &64; 
Index: /issm/trunk/src/c/bamg/GeomEdge.h
===================================================================
--- /issm/trunk/src/c/bamg/GeomEdge.h	(revision 22757)
+++ /issm/trunk/src/c/bamg/GeomEdge.h	(revision 22758)
@@ -27,5 +27,4 @@
 			//Methods
 			R2     F(double theta) const ; // parametrization of the curve edge
-			double R1tg(double theta,R2 &t) const ; // 1/radius of curvature + tangente
 			int    Cracked() const;
 			int    TgA()     const;
Index: /issm/trunk/src/c/bamg/Geometry.cpp
===================================================================
--- /issm/trunk/src/c/bamg/Geometry.cpp	(revision 22757)
+++ /issm/trunk/src/c/bamg/Geometry.cpp	(revision 22758)
@@ -187,10 +187,4 @@
 		}
 
-		//MaxCornerAngle
-		if (bamgopts->MaxCornerAngle){
-			if(verbose>5) _printf_("      processing MaxCornerAngle\n");
-			MaxCornerAngle=bamgopts->MaxCornerAngle*Pi/180;
-		}
-
 		//TangentAtEdges
 		if (bamggeom->TangentAtEdges){
@@ -401,5 +395,4 @@
 		_printf_("   pmax (x,y): (" << pmax.x << " " << pmax.y << ")\n");
 		_printf_("   coefIcoor: " << coefIcoor << "\n");
-		_printf_("   MaxCornerAngle: " << MaxCornerAngle << "\n");
 
 		return;
@@ -419,5 +412,4 @@
 		nbcurves=0;
 		subdomains=NULL;
-		MaxCornerAngle = 10*Pi/180; //default is 10 degres
 	}
 	/*}}}*/
@@ -446,5 +438,5 @@
 		return c - curves;
 	}/*}}}*/
-	void Geometry::PostRead(){/*{{{*/
+	void Geometry::PostRead(bool checkcurve){/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/AfterRead)*/
 
@@ -481,5 +473,5 @@
 				delete [] head_v;
 				delete [] eangle;
-				_error_("two points of the geometry are very closed to each other (see reference numbers above)");
+				_error_("two points of the geometry are very close to each other (see reference numbers above)");
 			}
 
@@ -614,26 +606,45 @@
 			}
 
-			// angular test on current vertex to guess whether it is a corner (ord = number of edges holding i)
-			if(ord==2) { 
-				long  n1 = head_v[i];
-				long  n2 = next_p[n1];
-				long  i1 = n1/2, i2 = n2/2; // edge number
-				long  j1 = n1%2, j2 = n2%2; // vertex in the edge 
-				float angle1=  j1 ? OppositeAngle(eangle[i1]) : eangle[i1];
-				float angle2= !j2 ? OppositeAngle(eangle[i2]) : eangle[i2];
-				float da12 = Abs(angle2-angle1);
-				if (( da12 >= MaxCornerAngle ) && (da12 <= 2*Pi -MaxCornerAngle)) {
-					vertices[i].SetCorner() ; 
-				}
-				// if the edge type/referencenumber a changing then is SetRequired();
-				if (edges[i1].type != edges[i2].type || edges[i1].Required()){
-					vertices[i].SetRequired();
-				}
-				if (edges[i1].ReferenceNumber != edges[i2].ReferenceNumber) {
-					vertices[i].SetRequired();
-				}
-			}
-			if(ord != 2) {
-				vertices[i].SetCorner();
+			/*Do we want to check for curve? Default is no, but if we are reconstructing, it's better to turn it on with a small threshold*/
+			if(checkcurve){
+				/*angular test on current vertex to guess whether it is a corner (ord = number of edges holding i) */
+				if(ord==2){
+					IssmDouble MaxCornerAngle = 1*Pi/180; /*default is 1 degree*/
+					long  n1 = head_v[i];
+					long  n2 = next_p[n1];
+					long  i1 = n1/2, i2 = n2/2; // edge number
+					long  j1 = n1%2, j2 = n2%2; // vertex in the edge
+					float angle1=  j1 ? OppositeAngle(eangle[i1]) : eangle[i1];
+					float angle2= !j2 ? OppositeAngle(eangle[i2]) : eangle[i2];
+					float da12 = Abs(angle2-angle1);
+					if (( da12 >= MaxCornerAngle ) && (da12 <= 2*Pi -MaxCornerAngle)) {
+						vertices[i].SetCorner() ;
+					}
+					/* if the edge type/referencenumber a changing then is SetRequired();*/
+					if(edges[i1].type != edges[i2].type || edges[i1].Required()){
+						vertices[i].SetRequired();
+					}
+					if(edges[i1].ReferenceNumber != edges[i2].ReferenceNumber) {
+						vertices[i].SetRequired();
+					}
+				}
+				if(ord!=2) vertices[i].SetCorner();
+			}
+			else{
+				/*all vertices provided in geometry are corners (ord = number of edges holding i)*/
+				vertices[i].SetCorner() ; 
+				if(ord==2){ 
+					long  n1 = head_v[i];
+					long  n2 = next_p[n1];
+					long  i1 = n1/2, i2 = n2/2; // edge number
+					long  j1 = n1%2, j2 = n2%2; // vertex in the edge
+					/* if the edge type/referencenumber a changing then is SetRequired();*/
+					if (edges[i1].type != edges[i2].type || edges[i1].Required()){
+						vertices[i].SetRequired();
+					}
+					if (edges[i1].ReferenceNumber != edges[i2].ReferenceNumber) {
+						vertices[i].SetRequired();
+					}
+				}
 			}
 
Index: /issm/trunk/src/c/bamg/Geometry.h
===================================================================
--- /issm/trunk/src/c/bamg/Geometry.h	(revision 22757)
+++ /issm/trunk/src/c/bamg/Geometry.h	(revision 22758)
@@ -32,5 +32,4 @@
 			R2             pmin,pmax;             // domain extrema coordinates
 			double         coefIcoor;             // coef to integer coordinates;
-			double         MaxCornerAngle;
 
 			//Constructor/Destructors
@@ -53,5 +52,5 @@
 			void             ReadGeometry(BamgGeom *bamggeom, BamgOpts*bamgopts);
 			void             Init(void);
-			void             PostRead();
+			void             PostRead(bool checkcurve=false);
 			long             GetId(const GeomVertex &t) const;
 			long             GetId(const GeomVertex *t) const;
Index: /issm/trunk/src/c/bamg/ListofIntersectionTriangles.cpp
===================================================================
--- /issm/trunk/src/c/bamg/ListofIntersectionTriangles.cpp	(revision 22757)
+++ /issm/trunk/src/c/bamg/ListofIntersectionTriangles.cpp	(revision 22758)
@@ -188,10 +188,10 @@
 	}
 	/*}}}*/
-	void ListofIntersectionTriangles::SplitEdge(const Mesh & Bh, const R2 &A,const R2  &B,int nbegin) {/*{{{*/
+	void ListofIntersectionTriangles::SplitEdge(Mesh & Bh, const R2 &A,const R2  &B,int nbegin) {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ListofIntersectionTriangles)*/
 
 		Triangle *tbegin, *t;
 
-		Icoor2 deta[3], deti,detj;
+		long long deta[3], deti,detj;
 		double ba[3];
 		int ifirst=-1,ilast;
@@ -199,5 +199,5 @@
 		int ocut,i,j,k=-1;
 		//  int OnAVertices =0;
-		Icoor2 dt[3];
+		long long dt[3];
 		I2 a = Bh.R2ToI2(A) ,b= Bh.R2ToI2(B);// compute  the Icoor a,b
 		I2 vi,vj;  
@@ -356,5 +356,5 @@
 				k = OppositeVertex[ocut];
 
-				Icoor2 detbij = bamg::det((*t)[i],(*t)[j],b);
+				long long detbij = bamg::det((*t)[i],(*t)[j],b);
 
 				if (detbij >= 0) { //we find the triangle contening b
Index: /issm/trunk/src/c/bamg/ListofIntersectionTriangles.h
===================================================================
--- /issm/trunk/src/c/bamg/ListofIntersectionTriangles.h	(revision 22757)
+++ /issm/trunk/src/c/bamg/ListofIntersectionTriangles.h	(revision 22758)
@@ -63,5 +63,5 @@
 			int    NewItem(Triangle *tt,double d0,double d1,double d2);
 			int    NewItem(R2 ,const Metric &);
-			void   SplitEdge(const Mesh &,const R2 &,const R2 &,int nbegin=0);
+			void   SplitEdge(Mesh &,const R2 &,const R2 &,int nbegin=0);
 			double Length();
 			long   NewPoints(BamgVertex *,long &nbv,long maxnbv);
Index: /issm/trunk/src/c/bamg/Mesh.cpp
===================================================================
--- /issm/trunk/src/c/bamg/Mesh.cpp	(revision 22757)
+++ /issm/trunk/src/c/bamg/Mesh.cpp	(revision 22758)
@@ -30,5 +30,5 @@
 			_printf_("WARNING: mesh present but no geometry found. Reconstructing...\n");
 			BuildGeometryFromMesh(bamgopts);
-			Gh.PostRead();
+			Gh.PostRead(true);
 		}
 
@@ -37,17 +37,17 @@
 
 		/*Fill holes and generate mesh properties*/
-		ReconstructExistingMesh();
-	}
-	/*}}}*/
-	Mesh::Mesh(int* index,double* x,double* y,int nods,int nels):Gh(*(new Geometry())),BTh(*this){/*{{{*/
+		ReconstructExistingMesh(bamgopts);
+	}
+	/*}}}*/
+	Mesh::Mesh(int* index,double* x,double* y,int nods,int nels,BamgOpts* bamgopts):Gh(*(new Geometry())),BTh(*this){/*{{{*/
 
 		Init(0);
-		ReadMesh(index,x,y,nods,nels);
+		ReadMesh(index,x,y,nods,nels,bamgopts);
 		SetIntCoor();
-		ReconstructExistingMesh();
-	}
-	/*}}}*/
-	Mesh::Mesh(double* x,double* y,int nods):Gh(*(new Geometry())),BTh(*this){/*{{{*/
-		Triangulate(x,y,nods);
+		ReconstructExistingMesh(bamgopts);
+	}
+	/*}}}*/
+	Mesh::Mesh(double* x,double* y,int nods,BamgOpts* bamgopts):Gh(*(new Geometry())),BTh(*this){/*{{{*/
+		Triangulate(x,y,nods,bamgopts);
 	}
 	/*}}}*/
@@ -133,5 +133,6 @@
 				nbt++;           
 			  }
-		  if (nbt==0 && nbv==0) {
+		  if (nbt==0 && nbv==0){
+			  delete [] refv;
 			  _error_("All triangles have been removed");
 		  }
@@ -142,5 +143,5 @@
 		  Gh.PostRead(); 
 		  SetIntCoor();
-		  ReconstructExistingMesh();
+		  ReconstructExistingMesh(bamgopts);
 
 		  /*Final checks*/
@@ -246,5 +247,5 @@
 
 	/*IO*/
-	void Mesh::ReadMesh(int* index,double* x,double* y,int nods,int nels){/*{{{*/
+	void Mesh::ReadMesh(int* index,double* x,double* y,int nods,int nels,BamgOpts* bamgopts){/*{{{*/
 
 		long i1,i2,i3;
@@ -257,4 +258,5 @@
 		maxnbv=nbv;
 		nbt=nels;
+		if(bamgopts) verbose=bamgopts->verbose;
 
 		//Vertices
@@ -309,5 +311,5 @@
 	void Mesh::ReadMesh(BamgMesh* bamgmesh, BamgOpts* bamgopts){/*{{{*/
 
-		int    verbose;
+		int    verbose=0;
 		double Hmin = HUGE_VAL;    // the infinie value
 		long   i1,i2,i3;
@@ -315,5 +317,8 @@
 		Metric M1(1);
 
-		verbose=bamgopts->verbose;
+		/*Check needed pointer*/
+		_assert_(bamgmesh);
+
+		if(bamgopts) verbose=bamgopts->verbose;
 
 		nbv=bamgmesh->VerticesSize[0];
@@ -495,7 +500,11 @@
 		int* connectivitysize_1=NULL;
 		int  connectivitymax_1=0;
+		int verbose=0;
+	
+		/*Check needed pointer*/
+		_assert_(bamgmesh);
 
 		/*Get options*/
-		int verbose=bamgopts->verbose;
+		if(bamgopts) verbose=bamgopts->verbose;
 
 		/*Build reft that holds the number the subdomain number of each triangle, and the real numbering of the elements*/
@@ -698,5 +707,5 @@
 			for (i=0;i<nbsubdomains;i++){
 				bamgmesh->SubDomains[i*4+0]=3;
-				bamgmesh->SubDomains[i*4+1]=reft[GetId(subdomains[i].head)];
+				bamgmesh->SubDomains[i*4+1]=reft[GetId(subdomains[i].head)]+1;//MATLAB indexing
 				bamgmesh->SubDomains[i*4+2]=1;
 				bamgmesh->SubDomains[i*4+3]=subdomains[i].ReferenceNumber;
@@ -897,6 +906,13 @@
 		/*Intermediary*/
 		int  i,j;
-
-		if(bamgopts->verbose>3) _printf_("      processing metric\n");
+		int verbose=0;
+
+		/*Check pointer*/
+		_assert_(bamgopts);
+
+		/*Get options*/
+		verbose=bamgopts->verbose;
+
+		if(verbose>3) _printf_("      processing metric\n");
 		double hmin = Max(bamgopts->hmin,MinimalHmin());
 		double hmax = Min(bamgopts->hmax,MaximalHmax());
@@ -932,4 +948,5 @@
 	void Mesh::WriteMetric(BamgOpts* bamgopts) {/*{{{*/
 		int i;
+		_assert_(bamgopts);
 		xDelete<double>(bamgopts->metric);
 		bamgopts->metric=xNew<double>(3*nbv);
@@ -980,59 +997,11 @@
 
 	/*Methods*/
-	void Mesh::AddGeometryMetric(BamgOpts* bamgopts){/*{{{*/
-		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/IntersectGeomMetric)*/
-
-		/*Get options*/
-		double anisomax = bamgopts->anisomax;
-		double errg     = bamgopts->errg;
-
-		double ss[2]={0.00001,0.99999};
-		double errC = 2*sqrt(2*errg);
-		double hmax = Gh.MaximalHmax();
-		double hmin = Gh.MinimalHmin();
-
-		//check that hmax is positive
-		_assert_(hmax>0); 
-
-		//errC cannot be higher than 1
-		if(errC>1) errC=1;
-
-		//Set all vertices to "on"
-		SetVertexFieldOn();
-
-		//loop over all the vertices on edges
-		for(int  i=0;i<nbe;i++){
-			for (int j=0;j<2;j++){
-
-				BamgVertex V;
-				VertexOnGeom GV;
-				Gh.ProjectOnCurve(edges[i],ss[j],V,GV);
-
-				GeomEdge* eg = GV;
-				double s = GV;
-				R2 tg;
-				double  R1= eg->R1tg(s,tg);
-				double  ht=hmax;
-				// err relative to the length of the edge
-				if (R1>1.0e-20) {  
-					ht = Min(Max(errC/R1,hmin),hmax);
-				}
-				double hn=Min(hmax,ht*anisomax);
-
-				if (ht<=0 || hn<=0){
-					_error_("ht<=0 || hn<=0");
-				}
-				EigenMetric Vp(1/(ht*ht),1/(hn*hn),tg);
-				Metric MVp(Vp);
-				edges[i][j].m.IntersectWith(MVp);
-			}
-		}
-		// the problem is for the vertex on vertex 
-	}
-	/*}}}*/
 	void Mesh::AddMetric(BamgOpts* bamgopts){/*{{{*/
 		//  Hessiantype = 0 =>  H is computed using double L2 projection
 		//  Hessiantype = 1 =>  H is computed with green formula
 
+		/*Check pointer*/
+		_assert_(bamgopts);
+
 		/*Options*/
 		int Hessiantype=bamgopts->Hessiantype;
@@ -1049,5 +1018,5 @@
 	}
 	/*}}}*/
-	void Mesh::AddVertex( BamgVertex &s,Triangle* t, Icoor2* det3){/*{{{*/
+	void Mesh::AddVertex( BamgVertex &s,Triangle* t, long long* det3){/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Add)*/
 		// -------------------------------
@@ -1068,5 +1037,5 @@
 		/*Intermediaries*/
 		Triangle* tt[3];       //the three triangles
-		Icoor2 det3local[3];   //three determinants (integer)
+		long long det3local[3];   //three determinants (integer)
 		int nbzerodet =0;      //number of zeros in det3
 		int izerodet=-1;       //egde containing the vertex s
@@ -1079,5 +1048,5 @@
 
 		//determinant of t
-		Icoor2 detOld=t->det;
+		long long detOld=t->det;
 
 		/* infvertexindex = index of the infinite vertex (NULL)
@@ -1184,10 +1153,13 @@
 
 	}/*}}}*/
-	void  Mesh::BoundAnisotropy(double anisomax,double hminaniso) {/*{{{*/
+	void Mesh::BoundAnisotropy(BamgOpts* bamgopts,double anisomax,double hminaniso) {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/BoundAnisotropy)*/
 
-		long int verbose=0;
-		double lminaniso = 1/ (Max(hminaniso*hminaniso,1e-100));
-
+		int verbose=0;
+		double lminaniso = 1./ (Max(hminaniso*hminaniso,1e-100));
+	
+		//Get options
+		if(bamgopts) verbose=bamgopts->verbose;
+			
 		//display info
 		if (verbose > 1)  _printf_("   BoundAnisotropy by " << anisomax << "\n");
@@ -1231,11 +1203,7 @@
 		int i,j,k,kk,it,jt;
 		int    verbose=0;
-		double cutoffradian=10*Pi/180;
 
 		/*Recover options*/
-		if (bamgopts){
-			verbose=bamgopts->verbose;
-			cutoffradian=bamgopts->MaxCornerAngle*Pi/180;
-		}
+		if(bamgopts) verbose=bamgopts->verbose;
 
 		//display info
@@ -1243,25 +1211,20 @@
 
 		//check that the mesh is not empty
-		if (nbt<=0 || nbv <=0 ) {
-			_error_("nbt or nbv is negative (Mesh empty?)");
-		}
-
-		//Gh is the geometry of the mesh (this), initialize MaxCornerAngle
-		if (cutoffradian>=0) Gh.MaxCornerAngle = cutoffradian;
+		if(nbt<=0 || nbv <=0 ) _error_("nbt or nbv is negative (Mesh empty?)");
 
 		/*Construction of the edges*/
 
-		//initialize st and edge4
+		/*initialize st and edge4*/
 		SetOfEdges4* edge4= new SetOfEdges4(nbt*3,nbv);
 		long*        st   = new long[nbt*3];
 
-		//initialize st as -1 (chaining algorithm)
+		/*initialize st as -1 (chaining algorithm)*/
 		for (i=0;i<nbt*3;i++) st[i]=-1;
 
-		//build edge4 (chain)
+		/*build edge4 (chain)*/
 		for (i=0;i<nbe;i++){
 			edge4->SortAndAdd(GetId(edges[i][0]),GetId(edges[i][1]));
 		}
-		//check that there is no double edge
+		/*check that there is no double edge*/
 		if (nbe !=  edge4->nb()){ 
 			delete [] st;
@@ -1271,5 +1234,5 @@
 		long nbeold = nbe;
 
-		//Go through the triangles and ass the edges in edge4 if they are not there yet
+		//Go through the triangles and add the edges in edge4 if they are not there yet
 		for (i=0;i<nbt;i++){
 			//3 edges per triangle
@@ -1288,16 +1251,16 @@
 						_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
+					/*OK, the element is not on boundary, is belongs to 2 triangles -> build Adjacent triangles list*/
 					triangles[i].SetAdj2(j,triangles + st[k] / 3,(int) (st[k]%3));
 					if (invisible)  triangles[i].SetHidden(j);
-					// if k < nbe mark the edge as on Boundary (Locked)
+					/* if k < nbe mark the edge as on Boundary (Locked)*/
 					if (k<nbe) {
 						triangles[i].SetLocked(j);
 					}
-					//set st[k] as negative so that the edge should not be called again
+					/*set st[k] as negative so that the edge should not be called again*/
 					st[k]=-2-st[k]; 
 				}
-				//else (see 3 lines above), the edge has been called more than twice: return error
 				else {
+					/*else (see 3 lines above), the edge has been called more than twice: return error*/
 					_printf_("The edge (" << GetId(triangles[i][VerticesOfTriangularEdge[j][0]]) << "," << GetId(triangles[i][VerticesOfTriangularEdge[j][1]]) << ") belongs to more than 2 triangles (" << k << ")\n");
 					_printf_("Edge " << j << " of triangle " << i << "\n");
@@ -1323,5 +1286,5 @@
 		}
 
-		// check consistency of edge[].adj and geometrical required  vertices
+		/*check consistency of edge[].adj and geometrical required  vertices*/
 		k=0; kk=0;
 		for (i=0;i<nbedges;i++){
@@ -1341,5 +1304,4 @@
 
 		/*Constructions of edges*/
-
 		k += kk;
 		kk=0;
@@ -1447,7 +1409,5 @@
 
 		//check that nbsubdomains is empty
-		if (nbsubdomains){
-			_error_("nbsubdomains should be 0");
-		}
+		if(nbsubdomains) _error_("nbsubdomains should be 0");
 		nbsubdomains=0;
 
@@ -1575,5 +1535,5 @@
 
 		//Build Gh.coefIcoor
-		int MaxICoord = 1073741823; //2^30 - 1 = =111...111 (29 times one)
+		long MaxICoord = 1073741823; //2^30 - 1 = =111...111 (29 times one)
 		Gh.coefIcoor= (MaxICoord)/(Max(Gh.pmax.x-Gh.pmin.x,Gh.pmax.y-Gh.pmin.y));
 		if (Gh.coefIcoor<=0){
@@ -1653,5 +1613,8 @@
 			long i1 = GetId(triangles[it][VerticesOfTriangularEdge[j][1]]);
 			k = edge4->SortAndFind(i0,i1);
-			_assert_(k>=0);
+			if(k<0){
+				delete [] colorV;
+				_error_("This should not happen");
+			}
 			subdomains[i].direction = (vertices + i0 == edges[k].v[0]) ? 1 : -1;
 			subdomains[i].edge = edges+k;
@@ -1678,8 +1641,11 @@
 		double* s=NULL;
 		long    nbsol;
-		int     verbose;
+		int     verbose=0;
 
 		int   i,j,k,iA,iB,iC;
 		int   iv;
+
+		/*Check pointer*/
+		_assert_(bamgopts);
 
 		/*Recover options*/
@@ -1886,4 +1852,7 @@
 		int verbose;
 
+		/*Check pointer*/
+		_assert_(bamgopts);
+		
 		/*Recover options*/
 		verbose=bamgopts->verbose;
@@ -2113,5 +2082,13 @@
 					else if (xy==1) dd=dxdy;
 					else if (xy==2) dd=dydy;
-					else    _error_("not supported yet");
+					else{
+						delete [] detT;
+						delete [] Mmass;
+						delete [] workT;
+						delete [] workV;
+						delete [] Mmassxx;
+						delete [] OnBoundary;
+						_error_("not supported yet");
+					}
 					// do leat 2 iteration for boundary problem
 					for (int ijacobi=0;ijacobi<Max(NbJacobi,2);ijacobi++){
@@ -2162,8 +2139,8 @@
 		delete [] dxdy;
 		delete [] dydy;
-		delete []  workT;
+		delete [] workT;
 		delete [] workV;
 		delete [] Mmassxx;
-		delete []  OnBoundary;
+		delete [] OnBoundary;
 
 	}
@@ -2176,7 +2153,8 @@
 		int i1,i2;
 		int j1,j2;
+		int verbose=0;
 
 		/*Options*/
-		int verbose=bamgopts->verbose;
+		if(bamgopts) verbose=bamgopts->verbose;
 
 		//  computed the number of cracked edge
@@ -2338,10 +2316,13 @@
 	}
 	/*}}}*/
-	void Mesh::ForceBoundary() {/*{{{*/
+	void Mesh::ForceBoundary(BamgOpts* bamgopts) {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ForceBoundary)*/
 
-		long int verbose=2;
+		int verbose=0;
 		int k=0;
 		int nbfe=0,nbswp=0,Nbswap=0;
+
+		/*Get options*/
+		if(bamgopts) verbose=bamgopts->verbose;
 
 		//display
@@ -2380,13 +2361,16 @@
 	}
 	/*}}}*/
-	void Mesh::FindSubDomain(int OutSide) {/*{{{*/
+	void Mesh::FindSubDomain(BamgOpts* bamgopts,int OutSide) {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/FindSubDomain)*/
 
-		long int verbose=0;
+		int verbose=0;
+
+		/*Get options*/
+		if(bamgopts) verbose=bamgopts->verbose;
 
 		if (verbose >2){
 			if (OutSide) _printf_("   Find all external sub-domain\n"); 
 			else _printf_("   Find all internal sub-domain\n");
-		  }
+		}
 		short * HeapArete = new short[nbt];
 		Triangle  **  HeapTriangle = new Triangle*  [nbt];
@@ -2394,10 +2378,10 @@
 		long k,it;
 
-		for (int itt=0;itt<nbt;itt++) 
-		 triangles[itt].link=0; // par defaut pas de couleur
+		/*No color by default*/
+		for(int itt=0;itt<nbt;itt++) triangles[itt].link=0;
 
 		long  NbSubDomTot =0;
-		for ( it=0;it<nbt;it++)  { 
-			if ( ! triangles[it].link  ) {
+		for(it=0;it<nbt;it++)  { 
+			if( !triangles[it].link ){
 				t = triangles + it;
 				NbSubDomTot++;; // new composante connexe
@@ -2408,6 +2392,6 @@
 				HeapArete[i] = 3;
 
-				while (i >= 0) // boucle sur la pile
-				  { while ( HeapArete[i]--) // boucle sur les 3 aretes 
+				while(i >= 0) // boucle sur la pile
+				  { while (HeapArete[i]--) // boucle sur les 3 aretes 
 					  { 
 						int na =  HeapArete[i];
@@ -2453,4 +2437,5 @@
 			if (nbt == nbtout ||  !NbSubDomTot) {
 				delete [] HeapArete;
+				delete [] HeapTriangle;
 				_error_("The boundary is not close: all triangles are outside");
 			}
@@ -2492,9 +2477,8 @@
 							_error_("k!=nbsubdomains");
 						}
-						if(OutSide) 
-						  {
+						if(OutSide){
 							//  to remove all the sub domain by parity adjacents
 							//  because in this case we have only the true boundary edge
-							// so teh boundary is manifold
+							//  so the boundary is manifold
 							long nbk = nbsubdomains;
 							while (nbk)
@@ -2649,49 +2633,49 @@
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/PreInit)*/
 
-		/* initialize random seed: */
-		srand(19999999);
-
 		/*Initialize fields*/
-		NbRef=0;
-		quadtree=NULL;
-		nbv=0;
-		nbt=0;
-		nbe=0;
-		edges=NULL;
-		nbsubdomains=0;
-		subdomains=NULL;
-		maxnbv=maxnbv_in;
-		maxnbt=2 *maxnbv_in-2;
-		NbVertexOnBThVertex=0;
-		VertexOnBThVertex=NULL;
-		NbVertexOnBThEdge=0;
-		VertexOnBThEdge=NULL;
-		NbCrackedVertices=0;
-		CrackedVertices =NULL;
-		NbCrackedEdges =0;
-		CrackedEdges =NULL;
-		NbVerticesOnGeomVertex=0;
-		VerticesOnGeomVertex=NULL;
-		NbVerticesOnGeomEdge=0;
-		VerticesOnGeomEdge=NULL;
+		this->NbRef                  = 0;
+		this->quadtree               = NULL;
+		this->nbv                    = 0;
+		this->nbt                    = 0;
+		this->nbe                    = 0;
+		this->edges                  = NULL;
+		this->nbsubdomains           = 0;
+		this->subdomains             = NULL;
+		this->maxnbv                 = maxnbv_in;
+		this->maxnbt                 = 2 *maxnbv_in-2;
+		this->NbVertexOnBThVertex    = 0;
+		this->VertexOnBThVertex      = NULL;
+		this->NbVertexOnBThEdge      = 0;
+		this->VertexOnBThEdge        = NULL;
+		this->NbCrackedVertices      = 0;
+		this->CrackedVertices        = NULL;
+		this->NbCrackedEdges         = 0;
+		this->CrackedEdges           = NULL;
+		this->NbVerticesOnGeomVertex = 0;
+		this->VerticesOnGeomVertex   = NULL;
+		this->NbVerticesOnGeomEdge   = 0;
+		this->VerticesOnGeomEdge     = NULL;
+
+		/*Initialize random seed*/
+		this->randomseed = 1;
 
 		/*Allocate if maxnbv_in>0*/
 		if(maxnbv_in){
-			vertices=new BamgVertex[maxnbv];
-			_assert_(vertices);
-			orderedvertices=new BamgVertex* [maxnbv];
-			_assert_(orderedvertices);
-			triangles=new Triangle[maxnbt];
-			_assert_(triangles);
+			this->vertices=new BamgVertex[this->maxnbv];
+			this->orderedvertices=new BamgVertex* [this->maxnbv];
+			this->triangles=new Triangle[this->maxnbt];
+         _assert_(this->vertices);
+         _assert_(this->orderedvertices);
+			_assert_(this->triangles);
 		}
 		else{
-			vertices=NULL;
-			orderedvertices=NULL;
-			triangles=NULL;
-			maxnbt=0;
+			this->vertices        = NULL;
+			this->orderedvertices = NULL;
+			this->triangles       = NULL;
+			this->maxnbt          = 0;
 		} 
 	}
 	/*}}}*/
-	void Mesh::Insert(bool random) {/*{{{*/
+	void Mesh::Insert(BamgOpts* bamgopts){/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Insert)*/
 
@@ -2699,8 +2683,9 @@
 
 		//Intermediary
-		int i;
+		long i;
+		int verbose=0;
 
 		/*Get options*/
-		long int verbose=2;
+		if(bamgopts) verbose=bamgopts->verbose;
 
 		//Display info
@@ -2740,7 +2725,8 @@
 		//Get Prime number
 		const long PrimeNumber= BigPrimeNumber(nbv);
-		int temp = rand(); if(!random) temp = 756804110;
-		int  k0=temp%nbv; 
-
+		long k0=this->RandomNumber(nbv);
+		if (verbose>4) _printf_("      Prime Number = "<<PrimeNumber<<"\n");
+		if (verbose>4) _printf_("      k0 = "<<k0<<"\n");
+		
 		//Build orderedvertices
 		for (i=0; i<nbv; i++){
@@ -2756,4 +2742,5 @@
 			if  (++i>=nbv) _error_("all the vertices are aligned");
 		}
+		if (verbose>4) _printf_("      i = "<<i<<"\n");
 		// exchange i et 2 in "orderedvertices" so that
 		// the first 3 vertices are not aligned (real triangle)
@@ -2798,6 +2785,7 @@
 		long NbSwap=0;
 		if (verbose>3) _printf_("   Begining of insertion process...\n");
-
-		for (int icount=2; icount<nbv; icount++) {
+		if (verbose>4) _printf_("      nbv = "<<nbv<<"\n");
+
+		for (long icount=2; icount<nbv; icount++) {
 
 			//Get new vertex
@@ -2805,5 +2793,5 @@
 
 			//Find the triangle in which newvertex is located
-			Icoor2 det3[3];
+			long long det3[3];
 			Triangle* tcvi = TriangleFindFromCoord(newvertex->i,det3); //(newvertex->i = integer coordinates)
 
@@ -2825,12 +2813,15 @@
 	}
 	/*}}}*/
-	long Mesh::InsertNewPoints(long nbvold,long & NbTSwap,bool random) {/*{{{*/
+	long Mesh::InsertNewPoints(long nbvold,long & NbTSwap,BamgOpts* bamgopts) {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/InsertNewPoints)*/
 
-		long int verbose=0;
-		double seuil= 1.414/2 ;// for two close point 
+		int verbose=0;
+		double seuil= 1.414/2.;// for two close point 
 		long i;
 		long NbSwap=0;
-		Icoor2 det3[3];
+		long long det3[3];
+
+		/*Get options*/
+		if(bamgopts) verbose=bamgopts->verbose;
 
 		//number of new points
@@ -2845,7 +2836,5 @@
 		/*construction of a random order*/
 		const long PrimeNumber= BigPrimeNumber(nbv)  ;
-		//remainder of the division of rand() by nbvnew
-		int  temp = rand(); if(!random) temp = 1098566905;
-		long k3 = temp%nbvnew;
+		long k3 = this->RandomNumber(nbvnew);
 		//loop over the new points
 		for (int is3=0; is3<nbvnew; is3++){
@@ -2945,5 +2934,8 @@
 			}
 		}
-		if(kk) _error_("See above");
+		if(kk){
+			delete [] e;
+			_error_("See above");
+		}
 
 		return e;
@@ -2959,8 +2951,12 @@
 	}
 	/*}}}*/
-	void  Mesh::MaxSubDivision(double maxsubdiv) {/*{{{*/
+	void  Mesh::MaxSubDivision(BamgOpts* bamgopts,double maxsubdiv) {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/MaxSubDivision)*/
-
-		long int verbose=0;
+		
+		/*Intermediaries*/
+		int verbose=0;
+
+		/*Get options*/
+		if(bamgopts) verbose=bamgopts->verbose;
 
 		const  double maxsubdiv2 = maxsubdiv*maxsubdiv;
@@ -3013,9 +3009,9 @@
 	}
 	/*}}}*/
-	Metric Mesh::MetricAt(const R2 & A) const { /*{{{*/
+	Metric Mesh::MetricAt(const R2 & A){ /*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/MetricAt)*/
 
 		I2 a = R2ToI2(A);
-		Icoor2 deta[3];
+		long long deta[3];
 		Triangle * t =TriangleFindFromCoord(a,deta);
 		if (t->det <0) { // outside
@@ -3046,4 +3042,5 @@
 
 		int i,j,k;
+		int verbose=0;
 		long NbTSwap=0;
 		long nbtold=nbt;
@@ -3055,5 +3052,5 @@
 
 		/*Recover options*/
-		int verbose=bamgopts->verbose;
+		if(bamgopts) verbose=bamgopts->verbose;
 
 		/*First, insert old points if requested*/
@@ -3086,7 +3083,7 @@
 				}
 			}
-			if(pointsoutside) _printf_("WARNING: One or more points of the initial mesh fall outside of the geometric boundary\n");
+			//if(pointsoutside) _printf_("WARNING: One or more points of the initial mesh fall outside of the geometric boundary\n");
 			Bh.CreateSingleVertexToTriangleConnectivity();     
-			InsertNewPoints(nbvold,NbTSwap,bamgopts->random);
+			InsertNewPoints(nbvold,NbTSwap,bamgopts);
 		}
 		else Bh.CreateSingleVertexToTriangleConnectivity();     
@@ -3131,5 +3128,5 @@
 					Triangle* ta=tadjj;
 
-					//if the adjacent triangle is a boundary triangle, continur
+					//if the adjacent triangle is a boundary triangle, continue
 					if (ta->det<0) continue;	  
 
@@ -3146,5 +3143,5 @@
 			}// for triangle   
 
-			if (!InsertNewPoints(nbvold,NbTSwap,bamgopts->random)) break;
+			if (!InsertNewPoints(nbvold,NbTSwap,bamgopts)) break;
 			for (i=nbtold;i<nbt;i++) first_np_or_next_t[i]=iter;
 			Headt = nbt; // empty list 
@@ -3303,5 +3300,5 @@
 	}                  
 	/*}}}*/
-	void Mesh::ReconstructExistingMesh(){/*{{{*/
+	void Mesh::ReconstructExistingMesh(BamgOpts* bamgopts){/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/FillHoleInMesh)*/
 
@@ -3316,4 +3313,7 @@
 		/*Intermediary*/
 		int verbose=0;
+
+		/*Get options*/
+		if(bamgopts) verbose=bamgopts->verbose;
 
 		// generation of the integer coordinate
@@ -3476,5 +3476,5 @@
 		for (int icount=2; icount<nbvb; icount++) {
 			BamgVertex *vi  = orderedvertices[icount];
-			Icoor2 det3[3];
+			long long det3[3];
 			Triangle *tcvi = TriangleFindFromCoord(vi->i,det3);
 			quadtree->Add(*vi); 
@@ -3499,5 +3499,5 @@
 		}
 
-		FindSubDomain(1);
+		FindSubDomain(bamgopts,1);
 		// remove all the hole 
 		// remove all the good sub domain
@@ -3573,5 +3573,5 @@
 			_error_("number of triangles edges alone = " << k);
 		}
-		FindSubDomain();
+		FindSubDomain(bamgopts);
 
 		delete edge4;
@@ -3696,5 +3696,5 @@
 
 		//Compute coefIcoor
-		int MaxICoord = 1073741823; //2^30 - 1 = =111...111 (29 times one)
+		long MaxICoord = 1073741823; //2^30 - 1 = =111...111 (29 times one)
 		coefIcoor= (MaxICoord)/(Max(pmax.x-pmin.x,pmax.y-pmin.y));
 		if (coefIcoor<=0){
@@ -3738,8 +3738,13 @@
 	}
 	/*}}}*/
-	void Mesh::SmoothingVertex(int nbiter,double omega ) { /*{{{*/
+	void Mesh::SmoothingVertex(BamgOpts* bamgopts,int nbiter,double omega ) { /*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/SmoothingVertex)*/
-
-		long int verbose=0;
+		
+		/*Intermediaries*/
+		int verbose=0;
+	
+		/*Get options*/
+		if(bamgopts) verbose=bamgopts->verbose;
+
 		//  if quatree exist remove it end reconstruct
 		if (quadtree) delete quadtree;
@@ -3778,8 +3783,12 @@
 	}
 	/*}}}*/
-	void Mesh::SmoothMetric(double raisonmax) { /*{{{*/
+	void Mesh::SmoothMetric(BamgOpts* bamgopts,double raisonmax) { /*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/SmoothMetric)*/
-
-		long int verbose=0;
+		
+		/*Intermediaries*/
+		int verbose=0;
+
+		/*Get options*/
+		if(bamgopts) verbose=bamgopts->verbose;
 
 		if(raisonmax<1.1) return;
@@ -3893,5 +3902,5 @@
 			long  iv = nbvold;
 			long NbSwap = 0;
-			Icoor2 det3[3];  
+			long long det3[3];  
 			for (int i=nbvold;i<nbv;i++) {// for all the new point
 				BamgVertex & vi = vertices[i];
@@ -3934,5 +3943,5 @@
 	}
 	/*}}}*/
-	Triangle * Mesh::TriangleFindFromCoord(const I2 & B,Icoor2 det3[3], Triangle *tstart) const {/*{{{*/
+	Triangle * Mesh::TriangleFindFromCoord(const I2 & B,long long det3[3], Triangle *tstart){/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/FindTriangleContening)*/
 
@@ -3963,5 +3972,5 @@
 		}
 
-		Icoor2  detop ;
+		long long  detop ;
 
 		/*initialize number of test triangle*/
@@ -4009,5 +4018,5 @@
 
 			if (k==0) break;
-			if (k==2 && BinaryRand()) Exchange(ii[0],ii[1]);
+			if (k==2 && this->RandomNumber(1)) Exchange(ii[0],ii[1]);
 			_assert_(k<3);
 			AdjacentTriangle t1 = t->Adj(jj=ii[0]);
@@ -4073,9 +4082,12 @@
 	}
 	/*}}}*/
-	void Mesh::Triangulate(double* x,double* y,int nods){/*{{{*/
+	void Mesh::Triangulate(double* x,double* y,int nods,BamgOpts* bamgopts){/*{{{*/
 
 		int verbose=0;
 		int i;
 		Metric M1(1);
+	
+		/*Get options*/
+		if(bamgopts) verbose=bamgopts->verbose;
 
 		/*Initialize mesh*/
@@ -4095,5 +4107,5 @@
 
 		/*Insert Vertices*/
-		Insert(true);
+		Insert(bamgopts);
 	}
 	/*}}}*/
@@ -4104,4 +4116,5 @@
 		/*Intermediaries*/
 		int                i,k;
+		int					 verbose=0;
 		int                nbcurves    = 0;
 		int                NbNewPoints,NbEdgeCurve;
@@ -4118,5 +4131,5 @@
 
 		/*Get options*/
-		int verbose=bamgopts->verbose;
+		if(bamgopts) verbose=bamgopts->verbose;
 
 		//build background mesh flag (1 if background, else 0)
@@ -4396,13 +4409,13 @@
 		if (verbose>3) _printf_("      Creating initial Constrained Delaunay Triangulation...\n");
 		if (verbose>3) _printf_("         Inserting boundary points\n");
-		Insert(bamgopts->random);
+		Insert(bamgopts);
 
 		//Force the boundary
 		if (verbose>3) _printf_("         Forcing boundaries\n");
-		ForceBoundary();
+		ForceBoundary(bamgopts);
 
 		//Extract SubDomains
 		if (verbose>3) _printf_("         Extracting subdomains\n");
-		FindSubDomain();
+		FindSubDomain(bamgopts);
 
 		if (verbose>3) _printf_("      Inserting internal points\n");
@@ -4414,6 +4427,9 @@
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/GeomToTriangles1)*/
 
+		/*Intermediaries*/
+		int verbose=0;
+
 		/*Get options*/
-		int verbose=bamgopts->verbose;
+		if(bamgopts) verbose=bamgopts->verbose;
 
 		Gh.NbRef++;// add a ref to Gh
@@ -4460,4 +4476,5 @@
 		printf("\n");
 		if(NbVerticesOnGeomVertex >= maxnbv){
+			delete [] bcurve;
 			_error_("too many vertices on geometry: " << NbVerticesOnGeomVertex << " >= " << maxnbv);
 		}
@@ -4722,17 +4739,186 @@
 		if (verbose>3) _printf_("      Creating initial Constrained Delaunay Triangulation...\n");
 		if (verbose>3) _printf_("         Inserting boundary points\n");
-		Insert(bamgopts->random);
+		Insert(bamgopts);
 
 		//Force the boundary
 		if (verbose>3) _printf_("         Forcing boundaries\n");
-		ForceBoundary();
+		ForceBoundary(bamgopts);
 
 		//Extract SubDomains
 		if (verbose>3) _printf_("         Extracting subdomains\n");
-		FindSubDomain();
+		FindSubDomain(bamgopts);
 
 		if (verbose>3) _printf_("      Inserting internal points\n");
 		NewPoints(BTh,bamgopts,KeepVertices) ;
 		if (verbose>4) _printf_("      -- current number of vertices = " << nbv << "\n");
+	}
+	/*}}}*/
+	long  Mesh::RandomNumber(long max){/*{{{*/
+		/*  Generate a random number from 0 to max-1 using linear congruential
+		 *  random number generator*/
+
+		this->randomseed = (this->randomseed * 1366l + 150889l) % 714025l;
+		return this->randomseed / (714025l / max + 1);
+	} /*}}}*/
+	int Mesh::ForceEdge(BamgVertex &a, BamgVertex & b,AdjacentTriangle & taret)  { /*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ForceEdge)*/
+
+		int NbSwap =0;
+		if (!a.t || !b.t){ // the 2 vertex is in a mesh
+			_error_("!a.t || !b.t");
+		}
+		int k=0;
+		taret=AdjacentTriangle(0,0); // erreur 
+
+		AdjacentTriangle tta(a.t,EdgesVertexTriangle[a.IndexInTriangle][0]);
+		BamgVertex   *v1, *v2 = tta.EdgeVertex(0),*vbegin =v2;
+		// we turn around a in the  direct direction  
+
+		long long det2 = v2 ? det(*v2,a,b): -1 , det1;
+		if(v2) // normal case 
+		 det2 = det(*v2,a,b);
+		else { // no chance infini vertex try the next
+			tta= Previous(Adj(tta));
+			v2 = tta.EdgeVertex(0);
+			vbegin =v2;
+			if (!v2){
+				_error_("!v2");
+			}
+			det2 = det(*v2,a,b);
+		}
+
+		while (v2 != &b) {
+			AdjacentTriangle tc = Previous(Adj(tta));    
+			v1 = v2; 
+			v2 = tc.EdgeVertex(0);
+			det1 = det2;
+			det2 =  v2 ? det(*v2,a,b): det2; 
+
+			if((det1 < 0) && (det2 >0)) { 
+				// try to force the edge 
+				BamgVertex * va = &a, *vb = &b;
+				tc = Previous(tc);
+				if (!v1 || !v2){
+					_error_("!v1 || !v2");
+				}
+				long long detss = 0,l=0;
+				while ((this->SwapForForcingEdge(  va,  vb, tc, detss, det1,det2,NbSwap)))
+				 if(l++ > 10000000) {
+					 _error_("Loop in forcing Egde, nb de swap=" << NbSwap << ", nb of try swap (" << l << ") too big");
+				 }
+				BamgVertex *aa = tc.EdgeVertex(0), *bb = tc.EdgeVertex(1);
+				if (((aa == &a ) && (bb == &b)) ||((bb ==  &a ) && (aa == &b))){
+					tc.SetLock();
+					a.Optim(1,0);
+					b.Optim(1,0);
+					taret = tc;
+					return NbSwap;
+				}
+				else 
+				  {
+					taret = tc;
+					return -2; // error  boundary is crossing
+				  }
+			}
+			tta = tc;
+			k++;
+			if (k>=2000){
+				_error_("k>=2000");
+			}
+			if ( vbegin == v2 ) return -1;// error 
+		}
+
+		tta.SetLock();
+		taret=tta;
+		a.Optim(1,0);
+		b.Optim(1,0);
+		return NbSwap; 
+	}
+	/*}}}*/
+	int Mesh::SwapForForcingEdge(BamgVertex   *  & pva ,BamgVertex  * &   pvb ,AdjacentTriangle & tt1,long long & dets1, long long & detsa,long long & detsb, int & NbSwap) {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/SwapForForcingEdge)*/
+		// l'arete ta coupe l'arete pva pvb
+		// de cas apres le swap sa coupe toujours
+		// on cherche l'arete suivante 
+		// on suppose que detsa >0 et detsb <0
+		// attention la routine echange pva et pvb 
+
+		if(tt1.Locked()) return 0; // frontiere croise 
+
+		AdjacentTriangle tt2 = Adj(tt1);
+		Triangle *t1=tt1,*t2=tt2;// les 2 triangles adjacent
+		short a1=tt1,a2=tt2;// les 2 numero de l arete dans les 2 triangles
+		if ( a1<0 || a1>=3 ){
+			_error_("a1<0 || a1>=3");
+		}
+
+		BamgVertex & sa= (* t1)[VerticesOfTriangularEdge[a1][0]];
+		BamgVertex & s1= (*t1)[OppositeVertex[a1]];
+		BamgVertex & s2= (*t2)[OppositeVertex[a2]];
+
+		long long dets2 = det(*pva,*pvb,s2);
+		long long det1=t1->det , det2=t2->det ;
+		long long detT = det1+det2;
+		if ((det1<=0 ) || (det2<=0)){
+			_error_("(det1<=0 ) || (det2<=0)");
+		}
+		if ( (detsa>=0) || (detsb<=0) ){ // [a,b] cut infinite line va,bb
+			_error_("(detsa>=0) || (detsb<=0)");
+		}
+		long long ndet1 = bamg::det(s1,sa,s2);
+		long long ndet2 = detT - ndet1;
+
+		int ToSwap =0; //pas de swap
+		if ((ndet1 >0) && (ndet2 >0)) 
+		  { // on peut swaper  
+			if ((dets1 <=0 && dets2 <=0) || (dets2 >=0 && detsb >=0))
+			 ToSwap =1; 
+			else // swap alleatoire 
+			 if (this->RandomNumber(1)) 
+			  ToSwap =2; 
+		  }
+		if (ToSwap) NbSwap++,
+		 bamg::swap(t1,a1,t2,a2,&s1,&s2,ndet1,ndet2);
+
+		int ret=1;
+
+		if (dets2 < 0) {// haut
+			dets1 = ToSwap ? dets1 : detsa ;
+			detsa = dets2; 
+			tt1 =  Previous(tt2) ;}
+		else if (dets2 > 0){// bas 
+			dets1 = ToSwap ? dets1 : detsb ;
+			detsb = dets2;
+			//xxxx tt1 = ToSwap ? tt1 : Next(tt2);
+			if(!ToSwap) tt1 =  Next(tt2);
+		}
+		else { // changement de direction 
+			ret = -1;
+			Exchange(pva,pvb);
+			Exchange(detsa,detsb);
+			Exchange(dets1,dets2);
+			Exchange(tt1,tt2);
+			dets1=-dets1;
+			dets2=-dets2;
+			detsa=-detsa;
+			detsb=-detsb;
+
+			if(ToSwap){
+				if (dets2 < 0) {// haut
+					dets1 = (ToSwap ? dets1 : detsa) ;
+					detsa = dets2; 
+					tt1 =  Previous(tt2) ;}
+				else if(dets2 > 0){// bas 
+					dets1 = (ToSwap ? dets1 : detsb) ;
+					detsb =  dets2;
+					if(!ToSwap) tt1 =  Next(tt2);
+				}
+				else {// on a fin ???
+					tt1 = Next(tt2);
+					ret =0;}
+			}
+
+		}
+		return ret;
 	}
 	/*}}}*/
@@ -4748,5 +4934,5 @@
 		}
 		int kkk=0;  
-		Icoor2 IJ_IA,IJ_AJ;
+		long long IJ_IA,IJ_AJ;
 		AdjacentTriangle edge(t,OppositeEdge[k]);          
 		for (;;edge = dir >0 ? Next(Adj(Next(edge))) : Previous(Adj(Previous(edge)))) {  
@@ -4778,80 +4964,5 @@
 	}
 	/*}}}*/
-	int ForceEdge(BamgVertex &a, BamgVertex & b,AdjacentTriangle & taret)  { /*{{{*/
-		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ForceEdge)*/
-
-		int NbSwap =0;
-		if (!a.t || !b.t){ // the 2 vertex is in a mesh
-			_error_("!a.t || !b.t");
-		}
-		int k=0;
-		taret=AdjacentTriangle(0,0); // erreur 
-
-		AdjacentTriangle tta(a.t,EdgesVertexTriangle[a.IndexInTriangle][0]);
-		BamgVertex   *v1, *v2 = tta.EdgeVertex(0),*vbegin =v2;
-		// we turn around a in the  direct direction  
-
-		Icoor2 det2 = v2 ? det(*v2,a,b): -1 , det1;
-		if(v2) // normal case 
-		 det2 = det(*v2,a,b);
-		else { // no chance infini vertex try the next
-			tta= Previous(Adj(tta));
-			v2 = tta.EdgeVertex(0);
-			vbegin =v2;
-			if (!v2){
-				_error_("!v2");
-			}
-			det2 = det(*v2,a,b);
-		}
-
-		while (v2 != &b) {
-			AdjacentTriangle tc = Previous(Adj(tta));    
-			v1 = v2; 
-			v2 = tc.EdgeVertex(0);
-			det1 = det2;
-			det2 =  v2 ? det(*v2,a,b): det2; 
-
-			if((det1 < 0) && (det2 >0)) { 
-				// try to force the edge 
-				BamgVertex * va = &a, *vb = &b;
-				tc = Previous(tc);
-				if (!v1 || !v2){
-					_error_("!v1 || !v2");
-				}
-				Icoor2 detss = 0,l=0;
-				while ((SwapForForcingEdge(  va,  vb, tc, detss, det1,det2,NbSwap)))
-				 if(l++ > 10000000) {
-					 _error_("Loop in forcing Egde, nb de swap=" << NbSwap << ", nb of try swap (" << l << ") too big");
-				 }
-				BamgVertex *aa = tc.EdgeVertex(0), *bb = tc.EdgeVertex(1);
-				if (((aa == &a ) && (bb == &b)) ||((bb ==  &a ) && (aa == &b))){
-					tc.SetLock();
-					a.Optim(1,0);
-					b.Optim(1,0);
-					taret = tc;
-					return NbSwap;
-				}
-				else 
-				  {
-					taret = tc;
-					return -2; // error  boundary is crossing
-				  }
-			}
-			tta = tc;
-			k++;
-			if (k>=2000){
-				_error_("k>=2000");
-			}
-			if ( vbegin == v2 ) return -1;// error 
-		}
-
-		tta.SetLock();
-		taret=tta;
-		a.Optim(1,0);
-		b.Optim(1,0);
-		return NbSwap; 
-	}
-	/*}}}*/
-	void  swap(Triangle *t1,short a1, Triangle *t2,short a2, BamgVertex *s1,BamgVertex *s2,Icoor2 det1,Icoor2 det2){ /*{{{*/
+	void  swap(Triangle *t1,short a1, Triangle *t2,short a2, BamgVertex *s1,BamgVertex *s2,long long det1,long long det2){ /*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/swap)*/
 		// --------------------------------------------------------------
@@ -4897,90 +5008,3 @@
 	} // end swap 
 	/*}}}*/
-	int SwapForForcingEdge(BamgVertex   *  & pva ,BamgVertex  * &   pvb ,AdjacentTriangle & tt1,Icoor2 & dets1, Icoor2 & detsa,Icoor2 & detsb, int & NbSwap) {/*{{{*/
-		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/SwapForForcingEdge)*/
-		// l'arete ta coupe l'arete pva pvb
-		// de cas apres le swap sa coupe toujours
-		// on cherche l'arete suivante 
-		// on suppose que detsa >0 et detsb <0
-		// attention la routine echange pva et pvb 
-
-		if(tt1.Locked()) return 0; // frontiere croise 
-
-		AdjacentTriangle tt2 = Adj(tt1);
-		Triangle *t1=tt1,*t2=tt2;// les 2 triangles adjacent
-		short a1=tt1,a2=tt2;// les 2 numero de l arete dans les 2 triangles
-		if ( a1<0 || a1>=3 ){
-			_error_("a1<0 || a1>=3");
-		}
-
-		BamgVertex & sa= (* t1)[VerticesOfTriangularEdge[a1][0]];
-		BamgVertex & s1= (*t1)[OppositeVertex[a1]];
-		BamgVertex & s2= (*t2)[OppositeVertex[a2]];
-
-		Icoor2 dets2 = det(*pva,*pvb,s2);
-		Icoor2 det1=t1->det , det2=t2->det ;
-		Icoor2 detT = det1+det2;
-		if ((det1<=0 ) || (det2<=0)){
-			_error_("(det1<=0 ) || (det2<=0)");
-		}
-		if ( (detsa>=0) || (detsb<=0) ){ // [a,b] cut infinite line va,bb
-			_error_("(detsa>=0) || (detsb<=0)");
-		}
-		Icoor2 ndet1 = bamg::det(s1,sa,s2);
-		Icoor2 ndet2 = detT - ndet1;
-
-		int ToSwap =0; //pas de swap
-		if ((ndet1 >0) && (ndet2 >0)) 
-		  { // on peut swaper  
-			if ((dets1 <=0 && dets2 <=0) || (dets2 >=0 && detsb >=0))
-			 ToSwap =1; 
-			else // swap alleatoire 
-			 if (BinaryRand()) 
-			  ToSwap =2; 
-		  }
-		if (ToSwap) NbSwap++,
-		 bamg::swap(t1,a1,t2,a2,&s1,&s2,ndet1,ndet2);
-
-		int ret=1;
-
-		if (dets2 < 0) {// haut
-			dets1 = ToSwap ? dets1 : detsa ;
-			detsa = dets2; 
-			tt1 =  Previous(tt2) ;}
-		else if (dets2 > 0){// bas 
-			dets1 = ToSwap ? dets1 : detsb ;
-			detsb = dets2;
-			//xxxx tt1 = ToSwap ? tt1 : Next(tt2);
-			if(!ToSwap) tt1 =  Next(tt2);
-		}
-		else { // changement de direction 
-			ret = -1;
-			Exchange(pva,pvb);
-			Exchange(detsa,detsb);
-			Exchange(dets1,dets2);
-			Exchange(tt1,tt2);
-			dets1=-dets1;
-			dets2=-dets2;
-			detsa=-detsa;
-			detsb=-detsb;
-
-			if(ToSwap){
-				if (dets2 < 0) {// haut
-					dets1 = (ToSwap ? dets1 : detsa) ;
-					detsa = dets2; 
-					tt1 =  Previous(tt2) ;}
-				else if(dets2 > 0){// bas 
-					dets1 = (ToSwap ? dets1 : detsb) ;
-					detsb =  dets2;
-					if(!ToSwap) tt1 =  Next(tt2);
-				}
-				else {// on a fin ???
-					tt1 = Next(tt2);
-					ret =0;}
-			}
-
-		}
-		return ret;
-	}
-	/*}}}*/
 }
Index: /issm/trunk/src/c/bamg/Mesh.h
===================================================================
--- /issm/trunk/src/c/bamg/Mesh.h	(revision 22757)
+++ /issm/trunk/src/c/bamg/Mesh.h	(revision 22758)
@@ -38,6 +38,7 @@
 
 			R2                            pmin,pmax;             // extrema
-			double                        coefIcoor;             // coef to integer Icoor1;
+			double                        coefIcoor;             // coef to integer
 			ListofIntersectionTriangles   lIntTria;
+			long									randomseed;            //used for random number generation
 
 			long                          NbVerticesOnGeomVertex;
@@ -56,6 +57,6 @@
 			//Constructors/Destructors
 			Mesh(BamgGeom* bamggeom,BamgMesh* bamgmesh,BamgOpts* bamgopts);
-			Mesh(int* index,double* x,double* y,int nods,int nels);/*MeshConvert*/
-			Mesh(double* x,double* y,int nods); /*BamgTriangulate*/
+			Mesh(int* index,double* x,double* y,int nods,int nels,BamgOpts* bamgopts);/*MeshConvert*/
+			Mesh(double* x,double* y,int nods,BamgOpts* bamgopts); /*BamgTriangulate*/
 			Mesh(Mesh &,Geometry * pGh=0,Mesh* pBTh=0,long maxnbv_in=0 ); //copy operator
 			Mesh(const Mesh &,const int *flag,const int *bb,BamgOpts* bamgopts); // truncature
@@ -76,23 +77,23 @@
 			I2 R2ToI2(const R2 & P) const;
 			R2 I2ToR2(const I2 & P) const;
-			void AddVertex(BamgVertex & s,Triangle * t,Icoor2 *  =0) ;
-			void Insert(bool random);
+			void AddVertex(BamgVertex & s,Triangle * t,long long *  =0) ;
+			void Insert(BamgOpts* bamgopts);
 			void Echo(void);
-			void ForceBoundary();
-			void FindSubDomain(int OutSide=0);
+			void ForceBoundary(BamgOpts* bamgopts);
+			void FindSubDomain(BamgOpts* bamgopts,int OutSide=0);
 			long TriangleReferenceList(long*) const;
 			void TriangleIntNumbering(long* renumbering);
 			void CrackMesh(BamgOpts* bamgopts);
-			void SmoothMetric(double raisonmax) ;
-			void BoundAnisotropy(double anisomax,double hminaniso= 1e-100) ;
+			void SmoothMetric(BamgOpts* bamgopts,double raisonmax) ;
+			void BoundAnisotropy(BamgOpts* bamgopts,double anisomax,double hminaniso= 1e-100) ;
 			Edge** MakeGeomEdgeToEdge();
 			long SplitInternalEdgeWithBorderVertices();
 			void MakeBamgQuadtree();
-			void MaxSubDivision(double maxsubdiv);
+			void MaxSubDivision(BamgOpts* bamgopts,double maxsubdiv);
 			void NewPoints(Mesh &,BamgOpts* bamgopts,int KeepVertices=1);
-			long InsertNewPoints(long nbvold,long & NbTSwap,bool random); 
+			long InsertNewPoints(long nbvold,long & NbTSwap,BamgOpts* bamgopts); 
 			void TrianglesRenumberBySubDomain(bool justcompress=false);
-			void SmoothingVertex(int =3,double=0.3);
-			Metric MetricAt (const R2 &) const;
+			void SmoothingVertex(BamgOpts* bamgopts,int =3,double=0.3);
+			Metric MetricAt (const R2 &);
 			GeomEdge* ProjectOnCurve( Edge & AB, BamgVertex &  A, BamgVertex & B,double theta, BamgVertex & R,VertexOnEdge & BR,VertexOnGeom & GR);
 			long GetId(const Triangle & t) const;
@@ -103,6 +104,6 @@
 			long GetId(const Edge * t) const;
 			BamgVertex* NearestVertex(int i,int j) ;
-			Triangle* TriangleFindFromCoord(const I2 & ,Icoor2 [3],Triangle *tstart=0) const;
-			void ReadMesh(int* index,double* x,double* y,int nods,int nels);
+			Triangle* TriangleFindFromCoord(const I2 & ,long long [3],Triangle *tstart=0);
+			void ReadMesh(int* index,double* x,double* y,int nods,int nels,BamgOpts* bamgopts);
 			void ReadMesh(BamgMesh* bamgmesh, BamgOpts* bamgopts);
 			void WriteMesh(BamgMesh* bamgmesh,BamgOpts* bamgopts);
@@ -113,7 +114,7 @@
 			void BuildMetric0(BamgOpts* bamgopts);
 			void BuildMetric1(BamgOpts* bamgopts);
-			void AddGeometryMetric(BamgOpts* bamgopts);
 			void BuildGeometryFromMesh(BamgOpts* bamgopts=NULL);
-			void ReconstructExistingMesh();
+			long RandomNumber(long max);
+			void ReconstructExistingMesh(BamgOpts* bamgopts);
 
 			//Inline methods
@@ -141,6 +142,10 @@
 			void TriangulateFromGeom1(BamgOpts* bamgopts,int KeepVertices=1);// the real constructor mesh adaption
 			void TriangulateFromGeom0(BamgOpts* bamgopts);// the real constructor mesh generator
-			void Triangulate(double* x,double* y,int nods);
+			void Triangulate(double* x,double* y,int nods,BamgOpts* bamgopts);
 			void Init(long);
+			int ForceEdge(BamgVertex &a, BamgVertex & b,AdjacentTriangle & taret) ;
+			int SwapForForcingEdge(BamgVertex   *  & pva ,BamgVertex  * &   pvb ,
+						AdjacentTriangle & tt1,long long & dets1,
+						long long & detsa,long long & detsb, int & nbswap);
 	};
 
@@ -149,9 +154,6 @@
 	void  swap(Triangle *t1,short a1,
 				Triangle *t2,short a2,
-				BamgVertex *s1,BamgVertex *s2,Icoor2 det1,Icoor2 det2);
-	int SwapForForcingEdge(BamgVertex   *  & pva ,BamgVertex  * &   pvb ,
-				AdjacentTriangle & tt1,Icoor2 & dets1,
-				Icoor2 & detsa,Icoor2 & detsb, int & nbswap);
-	int ForceEdge(BamgVertex &a, BamgVertex & b,AdjacentTriangle & taret) ;
+				BamgVertex *s1,BamgVertex *s2,long long det1,long long det2);
+
 	inline AdjacentTriangle Previous(const AdjacentTriangle & ta){
 		return AdjacentTriangle(ta.t,PreviousEdge[ta.a]);
@@ -166,21 +168,4 @@
 		int j=i;i=on->AdjVertexIndex[i];on=on->Adj[j];
 	}
-	inline double qualite(const BamgVertex &va,const BamgVertex &vb,const BamgVertex &vc){
-		double ret; 
-		I2 ia=va,ib=vb,ic=vc;
-		I2 ab=ib-ia,bc=ic-ib,ac=ic-ia;
-		Icoor2 deta=Det(ab,ac);
-		if (deta <=0) ret = -1;
-		else {
-			double a = sqrt((double) (ac,ac)),
-					 b = sqrt((double) (bc,bc)),
-					 c = sqrt((double) (ab,ab)),
-					 p = a+b+c;
-			double h= Max(Max(a,b),c),ro=deta/p;
-			ret = ro/h;
-		}
-		return ret;
-	}
-
 }
 #endif
Index: /issm/trunk/src/c/bamg/Triangle.cpp
===================================================================
--- /issm/trunk/src/c/bamg/Triangle.cpp	(revision 22757)
+++ /issm/trunk/src/c/bamg/Triangle.cpp	(revision 22758)
@@ -238,8 +238,8 @@
 		BamgVertex  *s2=t2->vertices[OppositeVertex[a2]];
 
-		Icoor2 det1=t1->det , det2=t2->det ;
-		Icoor2 detT = det1+det2;
-		Icoor2 detA = Abs(det1) + Abs(det2);
-		Icoor2 detMin = Min(det1,det2);
+		long long det1=t1->det , det2=t2->det ;
+		long long detT = det1+det2;
+		long long detA = Abs(det1) + Abs(det2);
+		long long detMin = Min(det1,det2);
 
 		int OnSwap = 0;       
@@ -256,6 +256,5 @@
 			OnSwap = (Abs(det1) + Abs(det2)) < detA;
 
-			Icoor2 detMinNew=Min(det1,det2);
-			//     if (detMin<0 && (Abs(det1) + Abs(det2) == detA)) OnSwap=BinaryRand();// just for test   
+			long long detMinNew=Min(det1,det2);
 			if (! OnSwap &&(detMinNew>0)) {
 				OnSwap = detMin ==0;
@@ -265,5 +264,5 @@
 					 if(kopt) {
 						 // critere de Delaunay pure isotrope
-						 Icoor2 xb1 = sb->i.x - s1->i.x,
+						 long long xb1 = sb->i.x - s1->i.x,
 								  x21 = s2->i.x - s1->i.x,
 								  yb1 = sb->i.y - s1->i.y,
Index: /issm/trunk/src/c/bamg/Triangle.h
===================================================================
--- /issm/trunk/src/c/bamg/Triangle.h	(revision 22757)
+++ /issm/trunk/src/c/bamg/Triangle.h	(revision 22758)
@@ -21,5 +21,5 @@
 
 		public: 
-			Icoor2 det; //Integer determinant (twice its area)
+			long long det; //Integer determinant (twice its area)
 			union { 
 				Triangle *link;
@@ -60,5 +60,4 @@
 
 			//Inline methods
-			double qualite() ;
 			void  Set(const Triangle &,const Mesh &,Mesh &);
 			int   In(BamgVertex *v) const { return vertices[0]==v || vertices[1]==v || vertices[2]==v ;}
Index: /issm/trunk/src/c/bamg/det.h
===================================================================
--- /issm/trunk/src/c/bamg/det.h	(revision 22757)
+++ /issm/trunk/src/c/bamg/det.h	(revision 22758)
@@ -6,7 +6,7 @@
 namespace bamg {
 
-	Icoor2 inline det(const I2 &a,const I2 & b,const I2 &c){
-		Icoor2 bax = b.x - a.x ,bay = b.y - a.y; 
-		Icoor2 cax = c.x - a.x ,cay = c.y - a.y; 
+	long long inline det(const I2 &a,const I2 & b,const I2 &c){
+		long long bax = b.x - a.x ,bay = b.y - a.y; 
+		long long cax = c.x - a.x ,cay = c.y - a.y; 
 		return  bax*cay - bay*cax;
 	}
Index: /issm/trunk/src/c/bamg/typedefs.h
===================================================================
--- /issm/trunk/src/c/bamg/typedefs.h	(revision 22757)
+++ /issm/trunk/src/c/bamg/typedefs.h	(revision 22758)
@@ -7,9 +7,7 @@
 
 	/*Integer coordinates types*/
-	typedef int  Icoor1; 
-	typedef long long Icoor2;
 
 	/*I2 and R2*/
-	typedef P2<Icoor1,Icoor2>  I2;
+	typedef P2<int,long long>  I2;
 	typedef P2<double,double>  R2;
 }
Index: /issm/trunk/src/c/classes/AdaptiveMeshRefinement.cpp
===================================================================
--- /issm/trunk/src/c/classes/AdaptiveMeshRefinement.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/AdaptiveMeshRefinement.cpp	(revision 22758)
@@ -11,4 +11,6 @@
 #include "./AdaptiveMeshRefinement.h"
 
+using namespace pzgeom;
+
 /*Constructor, copy, clean up and destructor*/
 AdaptiveMeshRefinement::AdaptiveMeshRefinement(){/*{{{*/
@@ -17,5 +19,5 @@
 /*}}}*/
 AdaptiveMeshRefinement::AdaptiveMeshRefinement(const AdaptiveMeshRefinement &cp){/*{{{*/
-   this->Initialize(); 
+	this->Initialize(); 
 	this->operator =(cp);
 }
@@ -25,30 +27,31 @@
 	/*Clean all attributes*/
 	this->CleanUp();
-
 	/*Copy all data*/
-	this->fathermesh     = new TPZGeoMesh(*cp.fathermesh);
-	this->previousmesh   = new TPZGeoMesh(*cp.previousmesh); 
-	this->levelmax       = cp.levelmax;
-	this->elementswidth  = cp.elementswidth;
-	this->regionlevel1   = cp.regionlevel1;
-	this->regionlevelmax = cp.regionlevelmax;
+	this->fathermesh						= new TPZGeoMesh(*cp.fathermesh);
+	this->previousmesh					= new TPZGeoMesh(*cp.previousmesh);
+	this->refinement_type				= cp.refinement_type;
+	this->level_max						= cp.level_max;
+	this->gradation						= cp.gradation;
+	this->lag								= cp.lag;
+   this->groundingline_distance		= cp.groundingline_distance;
+	this->icefront_distance				= cp.icefront_distance;
+	this->thicknesserror_threshold	= cp.thicknesserror_threshold;
+	this->deviatoricerror_threshold	= cp.deviatoricerror_threshold;
+	this->deviatoricerror_maximum		= cp.deviatoricerror_maximum;
+	this->thicknesserror_maximum		= cp.thicknesserror_maximum;
+	this->sid2index.clear();
+	this->sid2index.resize(cp.sid2index.size());
+	for(int i=0;i<cp.sid2index.size();i++) this->sid2index[i]=cp.sid2index[i];
+	this->index2sid.clear();
+	this->index2sid.resize(cp.index2sid.size());
+	for(int i=0;i<cp.index2sid.size();i++) this->index2sid[i]=cp.index2sid[i];
+	this->specialelementsindex.clear();
+	this->specialelementsindex.resize(cp.specialelementsindex.size());
+	for(int i=0;i<cp.specialelementsindex.size();i++) this->specialelementsindex[i]=cp.specialelementsindex[i];
+
 	return *this;
-
 }
 /*}}}*/
 AdaptiveMeshRefinement::~AdaptiveMeshRefinement(){/*{{{*/
-	
-	bool ismismip = true;
-	if(ismismip){//itapopo
-		TPZFileStream fstr;
-		std::stringstream ss;
-	    
-		ss << this->levelmax;
-		std::string AMRfile	= "/home/santos/Misomip2/L" + ss.str() + "_tsai/amr.txt"; 
-	
-		fstr.OpenWrite(AMRfile.c_str());
-		int withclassid = 1;
-		this->Write(fstr,withclassid);
-	}
 	this->CleanUp();
 	gRefDBase.clear();
@@ -57,11 +60,20 @@
 void AdaptiveMeshRefinement::CleanUp(){/*{{{*/
 
-    /*Verify and delete all data*/
+	/*Verify and delete all data*/
 	if(this->fathermesh)    delete this->fathermesh;
-   if(this->previousmesh)  delete this->previousmesh;
-	this->levelmax			= -1;
-	this->elementswidth  = -1;
-	this->regionlevel1	= -1;
-	this->regionlevelmax = -1;
+	if(this->previousmesh)  delete this->previousmesh;
+	this->refinement_type				= -1;
+	this->level_max						= -1;
+	this->gradation						= -1;
+	this->lag								= -1;
+   this->groundingline_distance		= -1;
+	this->icefront_distance				= -1;
+	this->thicknesserror_threshold	= -1;
+	this->deviatoricerror_threshold	= -1;
+	this->deviatoricerror_maximum		= -1;
+	this->thicknesserror_maximum		= -1;
+	this->sid2index.clear();
+	this->index2sid.clear();
+	this->specialelementsindex.clear();
 }
 /*}}}*/
@@ -69,432 +81,488 @@
 
 	/*Set pointers to NULL*/
-	this->fathermesh		= NULL;
-	this->previousmesh	= NULL;
-	this->levelmax			= -1;
-	this->elementswidth	= -1;
-	this->regionlevel1	= -1;
-	this->regionlevelmax = -1;
-}
-/*}}}*/
-int AdaptiveMeshRefinement::ClassId() const{/*{{{*/
-    return 13829430; //Antartic area with ice shelves (km^2)
-}
-/*}}}*/
-void AdaptiveMeshRefinement::Read(TPZStream &buf, void *context){/*{{{*/
-
-    try
-    {
-        /* Read the id context*/
-        TPZSaveable::Read(buf,context);
-
-        /* Read class id*/
-        int classid;
-        buf.Read(&classid,1);
-        
-        /* Verify the class id*/
-        if (classid != this->ClassId() )
-        {
-            std::cout << "Error in restoring AdaptiveMeshRefinement!\n";
-            std::cout.flush();
-            DebugStop();
-        }
-        
-        /* Read simple attributes */
-        buf.Read(&this->levelmax,1);
-        buf.Read(&this->elementswidth,1);
-        buf.Read(&this->regionlevel1,1);
-        buf.Read(&this->regionlevelmax,1);
-        
-		/* Read geometric mesh*/
-        TPZSaveable *sv1 = TPZSaveable::Restore(buf,0);
-        this->fathermesh = dynamic_cast<TPZGeoMesh*>(sv1);
-        
-        TPZSaveable *sv2 = TPZSaveable::Restore(buf,0);
-        this->previousmesh = dynamic_cast<TPZGeoMesh*>(sv2);
-    }
-    catch(const std::exception& e)
-    {
-        std::cout << "Exception catched! " << e.what() << std::endl;
-        std::cout.flush();
-        DebugStop();
-    }
-}
-/*}}}*/
-template class TPZRestoreClass<AdaptiveMeshRefinement,13829430>;/*{{{*/
-/*}}}*/
-void AdaptiveMeshRefinement::Write(TPZStream &buf, int withclassid){/*{{{*/
-    
-    try
-    {
-        /* Write context (this class) class ID*/
-        TPZSaveable::Write(buf,withclassid);
-
-        /* Write this class id*/
-        int classid = ClassId();
-        buf.Write(&classid,1);
-
-        /* Write simple attributes */
-        buf.Write(&this->levelmax,1);
-        buf.Write(&this->elementswidth,1);
-        buf.Write(&this->regionlevel1,1);
-        buf.Write(&this->regionlevelmax,1);
-			
-        /* Write the geometric mesh*/
-        this->fathermesh->Write(buf, this->ClassId());
-        this->previousmesh->Write(buf, this->ClassId());
-    }
-    catch(const std::exception& e)
-    {
-        std::cout << "Exception catched! " << e.what() << std::endl;
-        std::cout.flush();
-        DebugStop();
-    }
+	this->fathermesh						= NULL;
+	this->previousmesh					= NULL;
+	this->refinement_type				= -1;
+	this->level_max						= -1;
+	this->gradation						= -1;
+	this->lag								= -1;
+   this->groundingline_distance		= -1;
+	this->icefront_distance				= -1;
+	this->thicknesserror_threshold	= -1;
+	this->deviatoricerror_threshold	= -1;
+	this->deviatoricerror_maximum		= -1;
+	this->thicknesserror_maximum		= -1;
+	this->sid2index.clear();
+	this->index2sid.clear();
+	this->specialelementsindex.clear();
 }
 /*}}}*/
 
 /*Mesh refinement methods*/
-#include "TPZVTKGeoMesh.h" //itapopo
-#include "../shared/shared.h" //itapopo
-void AdaptiveMeshRefinement::ExecuteRefinement(int &type_process,double *vx, double *vy, double *masklevelset, int &nvertices, int &nelements, int &nsegments, double** px, double** py, double** pz, int** pelements, int** psegments){/*{{{*/
-
-	/*IMPORTANT! pelements (and psegments) are in Matlab indexing*/
+void AdaptiveMeshRefinement::ExecuteRefinement(double* gl_distance,double* if_distance,double* deviatoricerror,double* thicknesserror,int* pnewnumberofvertices,int* pnewnumberofelements,double** px,double** py,int** pelementslist){/*{{{*/
+	
+	/*IMPORTANT! pelementslist are in Matlab indexing*/
 	/*NEOPZ works only in C indexing*/
-
-    _assert_(this->fathermesh);
-    _assert_(this->previousmesh);
-    
-    /*Calculate the position of the grounding line using previous mesh*/
-    std::vector<TPZVec<REAL> > GLvec;
-    this->CalcGroundingLinePosition(masklevelset, GLvec);
-    
-   // std::ofstream file1("/home/santos/mesh0.vtk");
-   // TPZVTKGeoMesh::PrintGMeshVTK(this->fathermesh,file1 );
-    
-    /*run refinement or unrefinement process*/
-    TPZGeoMesh *newmesh;
-    switch (type_process) {
-        case 0: newmesh = this->previousmesh; break;                    // refine previous mesh
-        case 1: newmesh = new TPZGeoMesh(*this->fathermesh); break;     // refine mesh 0 (unrefine process)
-        default: DebugStop(); break;//itapopo verificar se irá usar _assert_
-    }
-    
-    this->RefinementProcess(newmesh,GLvec);
-	
-    //std::ofstream file2("/home/santos/mesh1.vtk");
-    //TPZVTKGeoMesh::PrintGMeshVTK(this->previousmesh,file2 );
-    
-    /*Set new mesh pointer. Previous mesh just have uniform elements*/
-    if(type_process==1){
-        if(this->previousmesh) delete this->previousmesh;
-        this->previousmesh = newmesh;
-    }
-    
-    /*Refine elements to avoid hanging nodes*/
-	//TPZGeoMesh *nohangingnodesmesh = new TPZGeoMesh(*newmesh);//itapopo testando, este era o original
-   TPZGeoMesh *nohangingnodesmesh = this->CreateRefPatternMesh(newmesh);//itapopo testando, este eh novo metodo
-    
-    //std::ofstream file3("/home/santos/mesh2.vtk");
-    //TPZVTKGeoMesh::PrintGMeshVTK(this->previousmesh,file3);
-    
-    this->RefineMeshToAvoidHangingNodes(nohangingnodesmesh);
-    
-	 //std::ofstream file4("/home/santos/mesh3.vtk");
-    //TPZVTKGeoMesh::PrintGMeshVTK(nohangingnodesmesh,file4);
-    
-    /*Get new geometric mesh in ISSM data structure*/
-    this->GetMesh(nohangingnodesmesh,nvertices,nelements,nsegments,px,py,pz,pelements,psegments);
+	if(!this->fathermesh || !this->previousmesh) _error_("Impossible to execute refinement: fathermesh or previousmesh is NULL!\n");
+	if(this->refinement_type!=0 && this->refinement_type!=1) _error_("Impossible to execute refinement: refinement type is not defined!\n");
+
+	/*Input verifications*/
+	if(this->deviatoricerror_threshold>0	&& !deviatoricerror) _error_("deviatoricerror is NULL!\n");
+	if(this->thicknesserror_threshold>0		&& !thicknesserror)	_error_("thicknesserror is NULL!\n");
+	if(this->groundingline_distance>0		&& !gl_distance)		_error_("gl_distance is NULL!\n");
+	if(this->icefront_distance>0				&& !if_distance)		_error_("if_distance is NULL!\n");
+	/*Attributes verifications*/
+	if(this->deviatoricerror_threshold>0	&& this->deviatoricerror_groupthreshold<DBL_EPSILON)	_error_("group threshold is too small!");
+	if(this->thicknesserror_threshold>0		&& this->thicknesserror_groupthreshold<DBL_EPSILON)	_error_("group threshold is too small!");
+
+	/*Intermediaries*/
+	bool verbose=VerboseSolution();
+	
+	/*Execute refinement*/
+	this->RefineMeshOneLevel(verbose,gl_distance,if_distance,deviatoricerror,thicknesserror);
+   
+	/*Get new geometric mesh in ISSM data structure*/
+	this->GetMesh(this->previousmesh,pnewnumberofvertices,pnewnumberofelements,px,py,pelementslist);
+
+	/*Verify the new geometry*/
+	this->CheckMesh(pnewnumberofvertices,pnewnumberofelements,px,py,pelementslist);
+}
+/*}}}*/
+void AdaptiveMeshRefinement::RefineMeshOneLevel(bool &verbose,double* gl_distance,double* if_distance,double* deviatoricerror,double* thicknesserror){/*{{{*/
+	
+	/*Intermediaries*/
+	int nelem							=-1;
+	int side2D							= 6;
+	int sid								=-1;
+	int count							=-1;
+	int criteria						=-1;
+	int numberofcriteria				=-1;
+	int nconformelements				= this->sid2index.size();
+	double gl_distance_h				=-1;
+	double gl_distance_hmax			= this->groundingline_distance;
+	double if_distance_h				=-1;
+	double if_distance_hmax			= this->icefront_distance;
+	double gl_groupdistance			=-1;
+	double if_groupdistance			=-1;
+	double d_maxerror					=-1;
+	double t_maxerror					=-1;
+	double deviatoric_grouperror	=-1;
+	double thickness_grouperror	=-1;
+	TPZGeoMesh* gmesh					= NULL; 
+	TPZVec<REAL> qsi(2,0.),cp(3,0.);
+	TPZVec<TPZGeoEl*> sons;
+	std::vector<int> index;
+
+	/*Calculate the number of criteria{{{*/
+	numberofcriteria=0;
+	if(this->deviatoricerror_threshold>0)	numberofcriteria++;
+	if(this->thicknesserror_threshold>0)	numberofcriteria++;
+	if(this->groundingline_distance>0)		numberofcriteria++;
+	if(this->icefront_distance>0)				numberofcriteria++;
+	/*}}}*/
+
+	/*Calculate the maximum of the estimators, if requested{{{*/
+	if(this->deviatoricerror_threshold>0 && this->deviatoricerror_maximum<DBL_EPSILON){ 
+		for(int i=0;i<nconformelements;i++) this->deviatoricerror_maximum=max(this->deviatoricerror_maximum,deviatoricerror[i]);
+	}
+	if(this->thicknesserror_threshold>0 && this->thicknesserror_maximum<DBL_EPSILON){
+		for(int i=0;i<nconformelements;i++) this->thicknesserror_maximum=max(this->thicknesserror_maximum,thicknesserror[i]);
+	}
+	/*}}}*/
+
+	/*First, verify if special elements have min distance or high errors{{{*/
+	gmesh=this->previousmesh;
+	for(int i=0;i<this->specialelementsindex.size();i++){
+		if(this->specialelementsindex[i]==-1) _error_("index is -1!\n");
+		if(!gmesh->Element(this->specialelementsindex[i])) _error_("element is null!\n");
+		if(!gmesh->Element(this->specialelementsindex[i])->Father()) _error_("father is null!\n");
+		if(gmesh->Element(this->specialelementsindex[i])->HasSubElement()) _error_("special element has sub elements!\n");
+		sons.clear();
+		gmesh->Element(this->specialelementsindex[i])->Father()->GetHigherSubElements(sons);
+		/*Limits*/
+		gl_distance_h	= gl_distance_hmax*std::pow(this->gradation,this->level_max-gmesh->Element(this->specialelementsindex[i])->Level());
+		if_distance_h	= if_distance_hmax*std::pow(this->gradation,this->level_max-gmesh->Element(this->specialelementsindex[i])->Level());
+		d_maxerror		= this->deviatoricerror_threshold*this->deviatoricerror_maximum;
+		t_maxerror		= this->thicknesserror_threshold*this->thicknesserror_maximum;
+		/*Calculate the distance and error of the group (sons)*/
+		gl_groupdistance=INFINITY;if_groupdistance=INFINITY;deviatoric_grouperror=0;thickness_grouperror=0;
+		for(int s=0;s<sons.size();s++){
+			sid=this->index2sid[sons[s]->Index()];
+			if(sid<0) continue;
+			if(this->groundingline_distance>0)		gl_groupdistance=std::min(gl_groupdistance,gl_distance[sid]); 
+			if(this->icefront_distance>0)				if_groupdistance=std::min(if_groupdistance,if_distance[sid]); 
+			if(this->deviatoricerror_threshold>0)	deviatoric_grouperror+=deviatoricerror[sid];
+			if(this->thicknesserror_threshold>0)	thickness_grouperror+=thicknesserror[sid];
+		}	
+		criteria=0;
+		if(this->groundingline_distance>0		&& gl_groupdistance<gl_distance_h+DBL_EPSILON)		criteria++;
+		if(this->icefront_distance>0				&& if_groupdistance<if_distance_h+DBL_EPSILON)		criteria++;
+		if(this->deviatoricerror_threshold>0	&& deviatoric_grouperror>d_maxerror-DBL_EPSILON)	criteria++;
+		if(this->thicknesserror_threshold>0		&& thickness_grouperror>t_maxerror-DBL_EPSILON)		criteria++;
+		/*Finally, it keeps the father index if it must be refine*/
+		if(criteria) index.push_back(gmesh->Element(this->specialelementsindex[i])->FatherIndex());
+	}
+	/*}}}*/
+	
+	/*Now, detele the special elements{{{*/
+	if(this->refinement_type==1) this->DeleteSpecialElements(verbose,gmesh);
+	else this->specialelementsindex.clear();
+	/*}}}*/
+
+	/*Set the mesh and delete previousmesh if refinement type is 0{{{*/
+	if(this->refinement_type==0){
+		delete this->previousmesh;	
+		gmesh=this->fathermesh;
+	}
+	/*}}}*/
+	
+	/*Unrefinement process: loop over level of refinements{{{*/
+	if(verbose) _printf_("\tunrefinement process...\n");
+	if(verbose) _printf_("\ttotal: ");
+	count=0;
 	 
-    /*Verify the new geometry*/
-    this->CheckMesh(nvertices,nelements,nsegments,this->elementswidth,px,py,pz,pelements,psegments);
-
-	 _printf_("\trefinement process done!\n\n");
-
-    delete nohangingnodesmesh;
-}
-/*}}}*/
-void AdaptiveMeshRefinement::RefinementProcess(TPZGeoMesh *gmesh,std::vector<TPZVec<REAL> > &GLvec){/*{{{*/
-    
-    /*Refine mesh levelmax times*/
-   _printf_("\n\trefinement process (level max = " << this->levelmax << ")\n");
-	_printf_("\tprogress:  ");
-	for(int hlevel=1;hlevel<=this->levelmax;hlevel++){
-        
-        /*Set elements to be refined using some criteria*/
-        std::vector<int> ElemVec; //elements without children
-        this->SetElementsToRefine(gmesh,GLvec,hlevel,ElemVec);
-        
-        /*Refine the mesh*/
-        this->RefineMesh(gmesh, ElemVec);
-		  
-		  _printf_("*  ");
-    }
-    _printf_("\n");
-}
-/*}}}*/
-void AdaptiveMeshRefinement::RefineMesh(TPZGeoMesh *gmesh, std::vector<int> &ElemVec){/*{{{*/
-
-	/*Refine elements in ElemVec: uniform pattern refinement*/
-	for(int i = 0; i < ElemVec.size(); i++){
+	nelem=gmesh->NElements();//must keep here
+	for(int i=0;i<nelem;i++){
+		if(!gmesh->Element(i)) continue;
+		if(gmesh->Element(i)->MaterialId()!=this->GetElemMaterialID()) continue;
+		if(gmesh->Element(i)->HasSubElement()) continue;
+		if(gmesh->Element(i)->Level()==0) continue;
+		if(!gmesh->Element(i)->Father()) _error_("father is NULL!\n");
+		/*Limits with lag*/
+		gl_distance_h = this->lag*gl_distance_hmax*std::pow(this->gradation,this->level_max-gmesh->Element(i)->Level());
+		if_distance_h = this->lag*if_distance_hmax*std::pow(this->gradation,this->level_max-gmesh->Element(i)->Level());
+		d_maxerror	  = this->deviatoricerror_groupthreshold*this->deviatoricerror_maximum;
+		t_maxerror	  = this->thicknesserror_groupthreshold*this->thicknesserror_maximum;
+		/*Get the sons of the father (sibilings)*/	
+		sons.clear();
+		gmesh->Element(i)->Father()->GetHigherSubElements(sons);
+		if(sons.size()!=4) continue;//delete just group of 4 elements. This avoids big holes in the mesh
+		/*Find the minimal distance and the error of the group*/	
+		gl_groupdistance=INFINITY;if_groupdistance=INFINITY;deviatoric_grouperror=0;thickness_grouperror=0;
+		for(int s=0;s<sons.size();s++){
+			sid=this->index2sid[sons[s]->Index()];
+			/*Verify if this group have solutions*/
+			if(sid<0){gl_groupdistance=INFINITY;if_groupdistance=INFINITY;deviatoric_grouperror=INFINITY;thickness_grouperror=INFINITY;continue;} 
+			/*Distance and error of the group*/
+			if(this->groundingline_distance>0)		gl_groupdistance=std::min(gl_groupdistance,gl_distance[sid]); 
+			if(this->icefront_distance>0)				if_groupdistance=std::min(if_groupdistance,if_distance[sid]); 
+			if(this->deviatoricerror_threshold>0)	deviatoric_grouperror+=deviatoricerror[sid]; 
+			if(this->thicknesserror_threshold>0)	thickness_grouperror+=thicknesserror[sid]; 
+		}
+		/*Verify the criteria*/
+		criteria=0;
+		if(this->groundingline_distance>0		&& gl_groupdistance>gl_distance_h-DBL_EPSILON)		criteria++;
+		if(this->icefront_distance>0				&& if_groupdistance>if_distance_h-DBL_EPSILON)		criteria++;
+		if(this->deviatoricerror_threshold>0	&& deviatoric_grouperror<d_maxerror+DBL_EPSILON)	criteria++;
+		if(this->thicknesserror_threshold>0		&& thickness_grouperror<t_maxerror+DBL_EPSILON)		criteria++;
+		/*Now, if the group attends the criteria, unrefine it*/
+		if(criteria==numberofcriteria){ 
+			gmesh->Element(i)->Father()->ResetSubElements(); count++;
+			for(int s=0;s<sons.size();s++){this->index2sid[sons[s]->Index()]=-1;gmesh->DeleteElement(sons[s],sons[s]->Index());}
+		}
+	}
+	if(verbose) _printf_(""<<count<<"\n");
+	/*Adjust the connectivities before continue*/
+	gmesh->BuildConnectivity();
+	/*}}}*/
+	
+	/*Refinement process: loop over level of refinements{{{*/
+	if(verbose) _printf_("\trefinement process (level max = "<<this->level_max<<")\n");
+	if(verbose) _printf_("\ttotal: ");
+	count=0;
+	nelem=gmesh->NElements();//must keep here
+	for(int i=0;i<nelem;i++){
+		if(!gmesh->Element(i)) continue;
+		if(gmesh->Element(i)->MaterialId()!=this->GetElemMaterialID()) continue;
+		if(gmesh->Element(i)->HasSubElement()) continue;
+		if(gmesh->Element(i)->Level()==this->level_max) continue;
+		/*Verify if this element has solutions*/
+		sid=this->index2sid[gmesh->Element(i)->Index()];
+		if(sid<0) continue;
+		/*Set the distance for level h*/
+		gl_distance_h	= gl_distance_hmax*std::pow(this->gradation,this->level_max-(gmesh->Element(i)->Level()+1));//+1: current element level is <level_max
+		if_distance_h	= if_distance_hmax*std::pow(this->gradation,this->level_max-(gmesh->Element(i)->Level()+1));//+1: current element level is <level_max
+		d_maxerror		= this->deviatoricerror_threshold*this->deviatoricerror_maximum;
+		t_maxerror		= this->thicknesserror_threshold*this->thicknesserror_maximum;
+		/*Verify distance and error of the element, if requested*/
+		criteria=0;
+		if(this->groundingline_distance>0		&& gl_distance[sid]<gl_distance_h+DBL_EPSILON)	criteria++; 
+		if(this->icefront_distance>0				&& if_distance[sid]<if_distance_h+DBL_EPSILON)	criteria++; 
+		if(this->deviatoricerror_threshold>0	&& deviatoricerror[sid]>d_maxerror-DBL_EPSILON)	criteria++; 
+		if(this->thicknesserror_threshold>0		&& thicknesserror[sid]>t_maxerror-DBL_EPSILON)	criteria++; 
+		/*Now, if it attends any criterion, keep the element index to refine in next step*/
+		if(criteria)index.push_back(i);
+	}
+	/*Now, refine the elements*/
+	for(int i=0;i<index.size();i++){ 
+		if(!gmesh->Element(index[i])) DebugStop();
+		if(!gmesh->Element(index[i])->HasSubElement()){gmesh->Element(index[i])->Divide(sons);count++;}
+	}
+	if(verbose) _printf_(""<<count<<"\n");
+	/*Adjust the connectivities before continue*/
+	gmesh->BuildConnectivity();
+	/*}}}*/
+
+	/*Now, apply smoothing and insert special elements to avoid hanging nodes{{{*/
+	this->RefineMeshWithSmoothing(verbose,gmesh);
+	if(this->refinement_type==0) this->previousmesh=this->CreateRefPatternMesh(gmesh);//in this case, gmesh==this->fathermesh
+	gmesh=this->previousmesh;//previous mesh is always refined to avoid hanging nodes
+	this->RefineMeshToAvoidHangingNodes(verbose,gmesh);
+	/*}}}*/
+}
+/*}}}*/
+int AdaptiveMeshRefinement::VerifyRefinementType(TPZGeoEl* geoel){/*{{{*/
+
+	/*
+	 * 0 : no refinement
+	 * 1 : special refinement (to avoid hanging nodes)
+	 * 2 : uniform refinment
+	 * */
+	if(!geoel) _error_("geoel is NULL!\n");
+	
+	/*Output*/
+	int type=0;
+	int count=0;
+	
+	/*Intermediaries*/
+	TPZVec<TPZGeoEl*> sons;
+	
+	/*Loop over neighboors (sides 3, 4 and 5)*/
+	for(int j=3;j<6;j++){
+		sons.clear();
+		geoel->Neighbour(j).Element()->GetHigherSubElements(sons);
+		if(sons.size()) count++; //if neighbour was refined
+		if(sons.size()>4) count++; //if neighbour's level is > element level+1
+	}
+	
+	/*Verify and return*/
+	if(count>1) type=2;
+	else type=count;
+	
+	return type;
+}
+/*}}}*/
+void AdaptiveMeshRefinement::RefineMeshWithSmoothing(bool &verbose,TPZGeoMesh* gmesh){/*{{{*/
+
+	/*Intermediaries*/
+	int nelem		=-1;
+	int count		=-1;
+	int type			=-1;
+	int typecount	=-1;
+
+	TPZVec<TPZGeoEl*> sons;
+
+	/*Refinement process: loop over level of refinements*/
+	if(verbose) _printf_("\tsmoothing process (level max = "<<this->level_max<<")\n");
+	if(verbose) _printf_("\ttotal: ");
+
+	count=1;
+	while(count>0){
+		count=0;
+		nelem=gmesh->NElements();//must keep here
+		for(int i=0;i<nelem;i++){
+			if(!gmesh->Element(i)) continue;
+			if(gmesh->Element(i)->MaterialId()!=this->GetElemMaterialID()) continue;
+			if(gmesh->Element(i)->HasSubElement()) continue;
+			if(gmesh->Element(i)->Level()==this->level_max) continue;
+			/*loop over neighboors (sides 3, 4 and 5). Important: neighbours has the same dimension of the element*/
+			type=this->VerifyRefinementType(gmesh->Element(i));
+			if(type<2){
+				typecount=0;
+				for(int j=3;j<6;j++){
+					if(gmesh->Element(i)->Neighbour(j).Element()->HasSubElement()) continue;
+					if(gmesh->Element(i)->Neighbour(j).Element()->Index()==i) typecount++;//neighbour==this element, element at the border
+					if(this->VerifyRefinementType(gmesh->Element(i)->Neighbour(j).Element())==1) typecount++;
+				}
+				if(typecount>1 && type==1) type=2;
+				else if(typecount>2 && type==0) type=2;
+			}
+			/*refine the element if requested*/
+			if(type==2){gmesh->Element(i)->Divide(sons);	count++;}
+		}
+		if(verbose){
+			if(count==0) _printf_(""<<count<<"\n");
+			else _printf_(""<<count<<", ");
+		}
+		/*Adjust the connectivities before continue*/
+		gmesh->BuildConnectivity();
+	}
+}
+/*}}}*/
+void AdaptiveMeshRefinement::RefineMeshToAvoidHangingNodes(bool &verbose,TPZGeoMesh* gmesh){/*{{{*/
+   
+	/*Now, insert special elements to avoid hanging nodes*/
+	if(verbose) _printf_("\trefining to avoid hanging nodes (total: ");
+	
+	/*Intermediaries*/
+	int nelem=-1;
+	int count= 1;
+	
+	while(count>0){
+		nelem=gmesh->NElements();//must keep here
+		count=0;
+		for(int i=0;i<nelem;i++){
+			/*Get geometric element and verify if it has already been refined. Geoel may not have been previously refined*/
+			TPZGeoEl * geoel=gmesh->Element(i);
+			if(!geoel) continue;
+			if(geoel->HasSubElement()) continue;
+			if(geoel->MaterialId() != this->GetElemMaterialID()) continue;
+			/*Get the refinement pattern for this element and refine it*/
+			TPZAutoPointer<TPZRefPattern> refp=TPZRefPatternTools::PerfectMatchRefPattern(geoel);
+			if(refp){
+				/*Non-uniform refinement*/
+				TPZVec<TPZGeoEl *> sons;
+				geoel->SetRefPattern(refp);
+				geoel->Divide(sons);
+				count++;
+				/*Keep the index of the special elements*/
+				for(int j=0;j<sons.size();j++) this->specialelementsindex.push_back(sons[j]->Index());
+			}
+		}
+		if(verbose){
+			if(count==0) _printf_(""<<count<<")\n");
+			else _printf_(""<<count<<", ");
+		}
+		gmesh->BuildConnectivity();
+	}
+}
+/*}}}*/
+void AdaptiveMeshRefinement::DeleteSpecialElements(bool &verbose,TPZGeoMesh* gmesh){/*{{{*/
+
+	/*Intermediaries*/
+	int count=0;
+
+	if(verbose) _printf_("\tdelete "<<this->specialelementsindex.size()<<" special elements (total: ");
+	for(int i=0;i<this->specialelementsindex.size();i++){
+		if(this->specialelementsindex[i]==-1) continue;
+		if(!gmesh->Element(this->specialelementsindex[i])) continue;
+		if(gmesh->Element(this->specialelementsindex[i])->Father()) gmesh->Element(this->specialelementsindex[i])->Father()->ResetSubElements();
+		gmesh->DeleteElement(gmesh->Element(this->specialelementsindex[i]),this->specialelementsindex[i]);
+      this->index2sid[this->specialelementsindex[i]]=-1;
+		count++;
+	}
+	if(verbose) _printf_(""<<count<<")\n");
+	/*Cleanup*/
+	this->specialelementsindex.clear();
+	/*Adjust connectivities*/
+	gmesh->BuildConnectivity();
+}
+/*}}}*/
+void AdaptiveMeshRefinement::GetMesh(TPZGeoMesh* gmesh,int* nvertices,int* nelements,double** px,double** py, int** pelements){/*{{{*/
+
+	/* IMPORTANT! pelements are in Matlab indexing
+	   NEOPZ works only in C indexing.
+		This method cleans up and updated the this->sid2index
+		and this->index2sid and fills in it with the new mesh.
+		Avoid to call this method before Refinement Process.*/
+
+	/*Intermediaries */
+	long sid,nodeindex;
+	int nconformelements,nconformvertices;
+	int ntotalvertices		= gmesh->NNodes();
+	int* newelements			= NULL;
+	double* newmeshX			= NULL;
+	double* newmeshY			= NULL;
+	TPZGeoEl* geoel			= NULL;
+	long* vertex_index2sid 	= xNew<long>(ntotalvertices);
+	this->index2sid.clear(); this->index2sid.resize(gmesh->NElements());
+	this->sid2index.clear();
+	
+	/*Fill in the vertex_index2sid vector with non usual index value*/
+	for(int i=0;i<gmesh->NNodes();i++) vertex_index2sid[i]=-1;
+	
+	/*Fill in the this->index2sid vector with non usual index value*/
+	for(int i=0;i<gmesh->NElements();i++) this->index2sid[i]=-1;
+	
+	/*Get elements without sons and fill in the vertex_index2sid with used vertices (indexes) */
+	sid=0;
+	for(int i=0;i<gmesh->NElements();i++){//over gmesh elements index 
+		geoel=gmesh->ElementVec()[i];
+		if(!geoel) continue;
+		if(geoel->HasSubElement()) continue;
+		if(geoel->MaterialId() != this->GetElemMaterialID()) continue;
+		this->sid2index.push_back(geoel->Index());//keep the element index
+		this->index2sid[geoel->Index()]=this->sid2index.size()-1;//keep the element sid
+		for(int j=0;j<this->GetNumberOfNodes();j++){
+      	nodeindex=geoel->NodeIndex(j);
+      	if(nodeindex<0) _error_("nodeindex is <0\n");
+			if(vertex_index2sid[nodeindex]==-1){
+      		vertex_index2sid[nodeindex]=sid; 
+				sid++;
+			}
+      }	
+	}
+
+	nconformelements	= (int)this->sid2index.size();
+	nconformvertices	= (int)sid;
+	newelements			= xNew<int>(nconformelements*this->GetNumberOfNodes());
+	newmeshX				= xNew<double>(nconformvertices);
+   newmeshY				= xNew<double>(nconformvertices);
+
+	for(int i=0;i<ntotalvertices;i++){//over the TPZNode index (fill in the ISSM vertices coords)
+		sid=vertex_index2sid[i];
+		if(sid==-1) continue;//skip this index (node no used)
+		TPZVec<REAL> coords(3,0.);
+		gmesh->NodeVec()[i].GetCoordinates(coords);
+		newmeshX[sid] = coords[0];
+		newmeshY[sid] = coords[1];
+	}
 		
-        /*Get geometric element and verify if it has already been refined*/
-        int index = ElemVec[i];
-        TPZGeoEl * geoel = gmesh->Element(index);
-        if(geoel->HasSubElement()) DebugStop();                              //itapopo _assert_(!geoel->HasSubElement());
-        if(geoel->MaterialId() != this->GetElemMaterialID()) DebugStop();   //itapopo verificar se usará _assert_
-        
-        /*Divide geoel*/
-        TPZVec<TPZGeoEl *> Sons;
-		  geoel->Divide(Sons);
-        
-        /*If a 1D segment is neighbor, it must be divided too*/
-        if(this->elementswidth != 3) DebugStop(); //itapopo verificar o segment para malha 3D
-        
-        std::vector<int> sides(3);
-        sides[0] = 3; sides[1] = 4; sides[2] = 5;
-        for(int j = 0; j < sides.size(); j++ ){
-            
-            TPZGeoElSide Neighbour = geoel->Neighbour(sides[j]);
-            
-            if( Neighbour.Element()->MaterialId() == this->GetBoundaryMaterialID() && !Neighbour.Element()->HasSubElement() ){
-                TPZVec<TPZGeoEl *> pv2;
-                Neighbour.Element()->Divide(pv2);
-            }
-        }
-	}
-    
-    gmesh->BuildConnectivity();
-
-}
-/*}}}*/
-void AdaptiveMeshRefinement::RefineMeshToAvoidHangingNodes(TPZGeoMesh *gmesh){/*{{{*/
+	for(int i=0;i<this->sid2index.size();i++){//over the sid (fill the ISSM elements)
+		for(int j=0;j<this->GetNumberOfNodes();j++) {
+			geoel	= gmesh->ElementVec()[this->sid2index[i]];
+			sid	= vertex_index2sid[geoel->NodeIndex(j)];
+			newelements[i*this->GetNumberOfNodes()+j]=(int)sid+1;//C to Matlab indexing
+		}
+		/*Verify the Jacobian determinant. If detJ<0, swap the 2 first postions:
+		  a -> b
+		  b -> a */
+		double detJ,xa,xb,xc,ya,yb,yc;
+		int a,b,c;
+
+		a=newelements[i*this->GetNumberOfNodes()+0]-1;
+		b=newelements[i*this->GetNumberOfNodes()+1]-1;
+		c=newelements[i*this->GetNumberOfNodes()+2]-1;
+
+		xa=newmeshX[a]; ya=newmeshY[a];
+		xb=newmeshX[b]; yb=newmeshY[b];
+		xc=newmeshX[c]; yc=newmeshY[c];
+
+		detJ=(xb-xa)*(yc-ya)-(xc-xa)*(yb-ya);
+	
+		/*verify and swap, if necessary*/
+		if(detJ<0) {
+			newelements[i*this->GetNumberOfNodes()+0]=b+1;//a->b
+			newelements[i*this->GetNumberOfNodes()+1]=a+1;//b->a
+		}
+	}
+
+	/*Setting outputs*/
+	*nvertices	= nconformvertices;
+	*nelements	= nconformelements;
+	*px			= newmeshX;
+	*py		   = newmeshY;
+	*pelements	= newelements;
    
-	 _printf_("\trefine to avoid hanging nodes...\n");
-    /*Refine elements to avoid hanging nodes: non-uniform refinement*/
-	 const int NElem = gmesh->NElements();
-    for(int i = 0; i < NElem; i++){
-        
-        /*Get geometric element and verify if it has already been refined. Geoel may not have been previously refined*/
-        TPZGeoEl * geoel = gmesh->Element(i);
-        if(!geoel) continue;
-        if(geoel->HasSubElement()) continue;
-        if(geoel->MaterialId() != this->GetElemMaterialID()) continue;
-        
-        /*Get the refinement pattern for this element and refine it*/
-        TPZAutoPointer<TPZRefPattern> refp = TPZRefPatternTools::PerfectMatchRefPattern(geoel);
-        if(refp){
-            TPZVec<TPZGeoEl *> Sons;
-            geoel->SetRefPattern(refp);
-            geoel->Divide(Sons);
-        }
-        
-    }
-    
-    gmesh->BuildConnectivity();
-    
-}
-/*}}}*/
-void AdaptiveMeshRefinement::GetMesh(TPZGeoMesh *gmesh,int &nvertices,int &nelements,int &nsegments,double** px,double** py,double** pz, int** pelements, int** psegments){/*{{{*/
-
-	/*IMPORTANT! pelements (and psegments) are in Matlab indexing*/
-	/*NEOPZ works only in C indexing*/
-
-	/* vertices */
-    int ntotalvertices = gmesh->NNodes();//total
-    
-    /* mesh coords */
-	 double* newmeshX = xNew<IssmDouble>(ntotalvertices);
-    double* newmeshY = xNew<IssmDouble>(ntotalvertices);
-    double* newmeshZ = xNew<IssmDouble>(ntotalvertices);
-   	
-   /* getting mesh coords */
-    for(int i = 0; i < ntotalvertices; i++ ){
-        TPZVec<REAL> coords(3,0.);
-        gmesh->NodeVec()[i].GetCoordinates(coords);
-        newmeshX[i] = coords[0];
-        newmeshY[i] = coords[1];
-        newmeshZ[i] = coords[2];
-    }
-    
-	/* elements */
-    std::vector<TPZGeoEl*> GeoVec; GeoVec.clear();
-    for(int i = 0; i < gmesh->NElements(); i++){ 
-        if( gmesh->ElementVec()[i]->HasSubElement() ) continue;
-        if( gmesh->ElementVec()[i]->MaterialId() != this->GetElemMaterialID() ) continue;
-        GeoVec.push_back( gmesh->ElementVec()[i]);
-    }
-    
-    int ntotalelements = (int)GeoVec.size();
-    int* newelements = xNew<int>(ntotalelements*this->elementswidth);
-
-    if ( !(this->elementswidth == 3) && !(this->elementswidth == 4) && !(this->elementswidth == 6) ) DebugStop();
-
-    for(int i=0;i<GeoVec.size();i++){
-        for(int j=0;j<this->elementswidth;j++) newelements[i*this->elementswidth+j]=(int)GeoVec[i]->NodeIndex(j)+1;//C to Matlab indexing
-	 }
-    
-    /* segments */
-    std::vector<TPZGeoEl*> SegVec; SegVec.clear();
-    for(int i = 0; i < gmesh->NElements(); i++){
-        if( gmesh->ElementVec()[i]->HasSubElement() ) continue;
-        if( gmesh->ElementVec()[i]->MaterialId() != this->GetBoundaryMaterialID() ) continue;
-        SegVec.push_back( gmesh->ElementVec()[i]);
-    }
-    
-    int ntotalsegments = (int)SegVec.size();
-    int *newsegments=NULL;
-	 if(ntotalsegments>0) newsegments=xNew<int>(ntotalsegments*3);
-    
-    for(int i=0;i<SegVec.size();i++){
-        
-        for(int j=0;j<2;j++) newsegments[i*3+j]=(int)SegVec[i]->NodeIndex(j)+1;//C to Matlab indexing
-        
-        int neighborindex = SegVec[i]->Neighbour(2).Element()->Index();
-        int neighbourid = -1;
-        
-        for(int j = 0; j < GeoVec.size(); j++){
-            if( GeoVec[j]->Index() == neighborindex || GeoVec[j]->FatherIndex() == neighborindex){
-                neighbourid = j;
-                break;
-            }
-        }
-        
-        if(neighbourid==-1) DebugStop(); //itapopo talvez passar para _assert_
-        newsegments[i*3+2] = neighbourid+1;//C to Matlab indexing
-    }
-    
-    //setting outputs
-    nvertices  = ntotalvertices;
-    nelements  = ntotalelements;
-    nsegments  = ntotalsegments;
-    *px		   = newmeshX;
-    *py		   = newmeshY;
-    *pz		   = newmeshZ;
-    *pelements = newelements;
-    *psegments = newsegments;
-    
-}
-/*}}}*/
-void AdaptiveMeshRefinement::CalcGroundingLinePosition(double *masklevelset,std::vector<TPZVec<REAL> > &GLvec){/*{{{*/
-    
-    /* Find grounding line using elments center point */
-    GLvec.clear();
-    for(int i=0;i<this->previousmesh->NElements();i++){
-        
-        if(this->previousmesh->Element(i)->MaterialId()!=this->GetElemMaterialID()) continue;
-        if(this->previousmesh->Element(i)->HasSubElement()) continue;
-        
-        //itapopo apenas malha 2D triangular!
-        int vertex0 = this->previousmesh->Element(i)->NodeIndex(0);
-        int vertex1 = this->previousmesh->Element(i)->NodeIndex(1);
-        int vertex2 = this->previousmesh->Element(i)->NodeIndex(2);
-        
-		  //itapopo inserir uma verificação para não acessar fora da memória
-        double mls0 = masklevelset[vertex0];
-        double mls1 = masklevelset[vertex1];
-        double mls2 = masklevelset[vertex2];
-        
-        if( mls0*mls1 < 0. || mls1*mls2 < 0. ){
-            const int side = 6;
-            TPZVec<double> qsi(2,0.);
-            TPZVec<double> X(3,0.);
-            this->previousmesh->Element(i)->CenterPoint(side, qsi);
-            this->previousmesh->Element(i)->X(qsi, X);
-            GLvec.push_back(X);
-        }
-    }
-    
-//    itapopo apenas para debugar
-//    std::ofstream fileGL("/Users/santos/Desktop/gl.nb");
-//    fileGL << "ListPlot[{";
-//    for(int i = 0; i < GLvec.size(); i++){
-//        fileGL << "{" << GLvec[i][0] << "," << GLvec[i][1] << /*"," << 0. << */"}";
-//        if(i != GLvec.size()-1) fileGL << ",";
-//    }
-//    fileGL << "}]";
-//    fileGL.flush();
-//    fileGL.close();
-    
-}
-/*}}}*/
-void AdaptiveMeshRefinement::SetElementsToRefine(TPZGeoMesh *gmesh,std::vector<TPZVec<REAL> > &GLvec,int &hlevel,std::vector<int> &ElemVec){/*{{{*/
-
-    if(!gmesh) DebugStop(); //itapopo verificar se usará _assert_
-
-    ElemVec.clear();
-    
-    // itapopo inserir modo de encontrar criterio TESTING!!!! Come to false!
-	 if(false) this->TagAllElements(gmesh,ElemVec); //uniform, refine all elements!
-
-    /* Adaptive refinement. This refines some elements following some criteria*/
-    this->TagElementsNearGroundingLine(gmesh, GLvec, hlevel, ElemVec);
-
-}
-/*}}}*/
-void AdaptiveMeshRefinement::TagAllElements(TPZGeoMesh *gmesh,std::vector<int> &ElemVec){/*{{{*/
-    
-    /* Uniform refinement. This refines the entire mesh */
-    int nelements = gmesh->NElements();
-    for(int i=0;i<nelements;i++){
-        if(gmesh->Element(i)->MaterialId()!=this->GetElemMaterialID()) continue;
-        if(gmesh->Element(i)->HasSubElement()) continue;
-        ElemVec.push_back(i);
-    }
-}
-/*}}}*/
-void AdaptiveMeshRefinement::TagElementsNearGroundingLine(TPZGeoMesh *gmesh,std::vector<TPZVec<REAL> > &GLvec,int &hlevel,std::vector<int> &ElemVec){/*{{{*/
-    
-    /* Tag elements near grounding line */ 
-	 double D1		= this->regionlevel1;
-	 double Dhmax  = this->regionlevelmax;
-	 int hmax		= this->levelmax;
-    double alpha	= (hmax==1) ? 0. : log(D1/Dhmax)/(hmax-1.);
-	 double Di		= D1/exp(alpha*(hlevel-1));
-    
-    for(int i=0;i<gmesh->NElements();i++){
-        
-        if(gmesh->Element(i)->MaterialId()!=this->GetElemMaterialID()) continue;
-        if(gmesh->Element(i)->HasSubElement()) continue;
-        if(gmesh->Element(i)->Level()>=hlevel) continue;
-        
-        const int side2D = 6;
-        TPZVec<REAL> qsi(2,0.);
-        TPZVec<REAL> centerPoint(3,0.);
-        gmesh->Element(i)->CenterPoint(side2D, qsi);
-        gmesh->Element(i)->X(qsi, centerPoint);
-        
-        REAL distance = Di;
-        
-        for (int j = 0; j < GLvec.size(); j++) {
-            
-            REAL value = ( GLvec[j][0] - centerPoint[0] ) * ( GLvec[j][0] - centerPoint[0] ); // (x2-x1)^2
-            value += ( GLvec[j][1] - centerPoint[1] ) * ( GLvec[j][1] - centerPoint[1] );// (y2-y1)^2
-            value = std::sqrt(value); //Radius
-            
-            //finding the min distance to the grounding line
-            if(value < distance) distance = value;
-            
-        }
-        
-        if(distance < Di) ElemVec.push_back(i);
-    }
-    
-}
-/*}}}*/
-void AdaptiveMeshRefinement::CreateInitialMesh(int &nvertices,int &nelements,int &nsegments,int &width,double* x,double* y,double* z,int* elements,int* segments){/*{{{*/
-
-	/*IMPORTANT! elements come in Matlab indexing*/
-	/*NEOPZ works only in C indexing*/
-	
-	_assert_(nvertices>0);
-   _assert_(nelements>0);
-	this->SetElementWidth(width);
+	/*Cleanup*/
+	xDelete<long>(vertex_index2sid);
+}
+/*}}}*/
+void AdaptiveMeshRefinement::CreateInitialMesh(int &nvertices,int &nelements,double* x,double* y,int* elements){/*{{{*/
+
+	/* IMPORTANT! elements come in Matlab indexing
+		NEOPZ works only in C indexing*/
+	
+	if(nvertices<=0) _error_("Impossible to create initial mesh: nvertices is <= 0!\n");
+   if(nelements<=0) _error_("Impossible to create initial mesh: nelements is <= 0!\n");
+	if(this->refinement_type!=0 && this->refinement_type!=1) _error_("Impossible to create initial mesh: refinement type is not defined!\n");
 
     /*Verify and creating initial mesh*/
-   if(this->fathermesh) _error_("Initial mesh already exists!");
+   if(this->fathermesh || this->previousmesh) _error_("Initial mesh already exists!");
     
    this->fathermesh = new TPZGeoMesh();
-	this->fathermesh->NodeVec().Resize( nvertices );
-
-    /*Set the vertices (geometric nodes in NeoPZ context)*/
+	this->fathermesh->NodeVec().Resize(nvertices);
+
+	/*Set the vertices (geometric nodes in NeoPZ context)*/
 	for(int i=0;i<nvertices;i++){  
       /*x,y,z coords*/
@@ -502,5 +570,5 @@
       coord[0]= x[i];
       coord[1]= y[i];
-      coord[2]= z[i];
+      coord[2]= 0.;
       /*Insert in the mesh*/
       this->fathermesh->NodeVec()[i].SetCoord(coord);
@@ -511,47 +579,27 @@
 	long index;
    const int mat = this->GetElemMaterialID();
-   TPZManVector<long> elem(this->elementswidth,0);
-    
-	for(int iel=0;iel<nelements;iel++){
-
-		for(int jel=0;jel<this->elementswidth;jel++) elem[jel]=elements[iel*this->elementswidth+jel]-1;//Convert Matlab to C indexing
-
-      /*reftype = 0: uniform, fast / reftype = 1: uniform and non-uniform (avoid hanging nodes), it is not too fast */
-      const int reftype = 0;
-      switch(this->elementswidth){
-			case 3: this->fathermesh->CreateGeoElement(ETriangle, elem, mat, index, reftype);	break;
-         case 4: this->fathermesh->CreateGeoElement(ETetraedro, elem, mat, index, reftype); DebugStop(); break;
-			case 6: this->fathermesh->CreateGeoElement(EPrisma, elem, mat, index, reftype); DebugStop(); break;
-         default:	DebugStop();//itapopo _error_("mesh not supported yet");
-		}
-        
+   TPZManVector<long> elem(this->GetNumberOfNodes(),0);
+	this->index2sid.clear(); this->index2sid.resize(nelements);
+   this->sid2index.clear();
+
+	for(int i=0;i<nelements;i++){
+		for(int j=0;j<this->GetNumberOfNodes();j++) elem[j]=elements[i*this->GetNumberOfNodes()+j]-1;//Convert Matlab to C indexing
+      switch(this->GetNumberOfNodes()){
+			case 3: this->fathermesh->CreateGeoElement(ETriangle,elem,mat,index,this->refinement_type);	break;
+         default:	_error_("mesh not supported yet");
+		}
       /*Define the element ID*/        
-      this->fathermesh->ElementVec()[index]->SetId(iel); 
-	}
-    
-   /*Generate the 1D segments elements (boundary)*/
-   const int matboundary = this->GetBoundaryMaterialID();
-   TPZManVector<long> boundary(2,0.);
-    
-   for(int iel=nelements;iel<nelements+nsegments;iel++){     
-		boundary[0] = segments[(iel-nelements)*2+0]-1;//Convert Matlab to C indexing
-      boundary[1] = segments[(iel-nelements)*2+1]-1;//Convert Matlab to C indexing
-      /*reftype = 0: uniform, fast / reftype = 1: uniform and non-uniform (avoid hanging nodes), it is not too fast */
-      const int reftype = 0;
-      this->fathermesh->CreateGeoElement(EOned, boundary, matboundary, index, reftype);//cria elemento unidimensional
-      this->fathermesh->ElementVec()[index]->SetId(iel);
-	}
-    
+      this->fathermesh->ElementVec()[index]->SetId(i);
+		/*Initialize sid2index and index2sid*/
+		this->sid2index.push_back((int)index);
+		this->index2sid[(int)index]=this->sid2index.size()-1;//keep the element sid
+	}
    /*Build element and node connectivities*/
    this->fathermesh->BuildConnectivity();
-    
-	/*Create previous mesh as a copy of father mesh*/
-   this->previousmesh = new TPZGeoMesh(*this->fathermesh);
-
-}
-/*}}}*/
-#include "pzgeotriangle.h" //itapopo
-#include "pzreftriangle.h" //itapopo
-using namespace pzgeom;
+	/*Set previous mesh*/
+	if(this->refinement_type==1) this->previousmesh=new TPZGeoMesh(*this->fathermesh);
+	else this->previousmesh=this->CreateRefPatternMesh(this->fathermesh); 
+}
+/*}}}*/
 TPZGeoMesh* AdaptiveMeshRefinement::CreateRefPatternMesh(TPZGeoMesh* gmesh){/*{{{*/
 	
@@ -564,5 +612,5 @@
    int reftype = 1;
    long index; 
-   
+
 	//nodes
 	newgmesh->NodeVec().Resize(nnodes);
@@ -572,9 +620,16 @@
    for(int i=0;i<nelem;i++){
    	TPZGeoEl * geoel = gmesh->Element(i);
-      TPZManVector<long> elem(3,0);
+		
+		if(!geoel){
+			index=newgmesh->ElementVec().AllocateNewElement();
+			newgmesh->ElementVec()[index] = NULL;
+			continue;
+		}
+      
+		TPZManVector<long> elem(3,0);
       for(int j=0;j<3;j++) elem[j] = geoel->NodeIndex(j);
      
       newgmesh->CreateGeoElement(ETriangle,elem,mat,index,reftype);
-      newgmesh->ElementVec()[index]->SetId(geoel->Id());
+		newgmesh->ElementVec()[index]->SetId(geoel->Id());
         
       TPZGeoElRefPattern<TPZGeoTriangle>* newgeoel = dynamic_cast<TPZGeoElRefPattern<TPZGeoTriangle>*>(newgmesh->ElementVec()[index]);
@@ -631,4 +686,6 @@
       }
    }
+
+	/*Now, build connectivities*/
 	newgmesh->BuildConnectivity();
     
@@ -636,48 +693,185 @@
 }
 /*}}}*/
-void AdaptiveMeshRefinement::SetLevelMax(int &h){/*{{{*/
-    this->levelmax = h;
-}
-/*}}}*/
-void AdaptiveMeshRefinement::SetRegions(double &D1,double Dhmax){/*{{{*/
-    this->regionlevel1	 = D1;
-    this->regionlevelmax = Dhmax;
-}
-/*}}}*/
-void AdaptiveMeshRefinement::SetElementWidth(int &width){/*{{{*/
-    this->elementswidth = width;
-}
-/*}}}*/
-void AdaptiveMeshRefinement::CheckMesh(int &nvertices,int &nelements,int &nsegments,int &width,double** px,double** py,double** pz,int** pelements, int** psegments){/*{{{*/
-
-    /*Basic verification*/
-    if( !(nvertices > 0) || !(nelements > 0) ) DebugStop(); //itapopo verificar se irá usar o _assert_
+void AdaptiveMeshRefinement::CheckMesh(int* nvertices,int* nelements,double** px,double** py,int** pelements){/*{{{*/
+
+	/*Basic verification*/
+	if(nvertices<=0) _error_("Impossible to continue: nvertices <=0!\n");
+	if(nelements<=0) _error_("Impossible to continue: nelements <=0!\n");
+	if(!px) _error_("Impossible to continue: px is NULL!\n");
+	if(!py) _error_("Impossible to continue: py is NULL!\n");
+	if(!pelements) _error_("Impossible to continue: pelements is NULL!\n");
+
+	/*Verify if there are orphan nodes*/
+	std::set<int> elemvertices;
+	elemvertices.clear(); 
+	for(int i=0;i<*nelements;i++){
+		for(int j=0;j<this->GetNumberOfNodes();j++) {
+			elemvertices.insert((*pelements)[i*this->GetNumberOfNodes()+j]);
+		}
+	}
+	if(elemvertices.size()!=*nvertices) _error_("Impossible to continue: elemvertices.size() != nvertices!\n");
+	
+	//Verify if there are inf or NaN in coords
+	for(int i=0;i<*nvertices;i++){
+		if(std::isnan((*px)[i]) || std::isinf((*px)[i])) _error_("Impossible to continue: px i=" << i <<" is NaN or Inf!\n"); 
+		if(std::isnan((*py)[i]) || std::isinf((*py)[i])) _error_("Impossible to continue: py i=" << i <<" is NaN or Inf!\n");
+	}
+	for(int i=0;i<*nelements;i++){
+		for(int j=0;j<this->GetNumberOfNodes();j++){
+			if(std::isnan((*pelements)[i*GetNumberOfNodes()+j])) _error_("Impossible to continue: px i=" << i <<" is NaN!\n");
+			if(std::isinf((*pelements)[i*GetNumberOfNodes()+j])) _error_("Impossible to continue: px i=" << i <<" is Inf!\n");
+		}
+	}
     
-    if ( !(width == 3) && !(width == 4) && !(width == 6) ) DebugStop(); // itapopo verifcar se irá usar o _assert_
+}
+/*}}}*/
+void AdaptiveMeshRefinement::PrintGMeshVTK(TPZGeoMesh* gmesh,std::ofstream &file,bool matColor){/*{{{*/
     
-    if( !px || !py || !pz || !pelements ) DebugStop(); // itapopo verifcar se irá usar o _assert_
+	file.clear();
+	long nelements = gmesh->NElements();
+	TPZGeoEl *gel;
+	std::stringstream node, connectivity, type, material;
+
+	//Header
+	file << "# vtk DataFile Version 3.0" << std::endl;
+	file << "TPZGeoMesh VTK Visualization" << std::endl;
+	file << "ASCII" << std::endl << std::endl;
+	file << "DATASET UNSTRUCTURED_GRID" << std::endl;
+	file << "POINTS ";
+
+	long actualNode = -1, size = 0, nVALIDelements = 0;
+	for(long el = 0; el < nelements; el++){
+	  gel = gmesh->ElementVec()[el];
+	  if(!gel )//|| (gel->Type() == EOned && !gel->IsLinearMapping()))//Exclude Arc3D and Ellipse3D
+	  {
+			continue;
+	  }
+	  if(gel->HasSubElement())
+	  {
+			continue;
+	  }
+	  MElementType elt = gel->Type();
+	  int elNnodes = MElementType_NNodes(elt);
+	  
+	  size += (1+elNnodes);
+	  connectivity << elNnodes;
+	  
+	  for(int t = 0; t < elNnodes; t++)
+	  {
+			for(int c = 0; c < 3; c++)
+			{
+				 double coord = gmesh->NodeVec()[gel->NodeIndex(t)].Coord(c);
+				 node << coord << " ";
+			}
+			node << std::endl;
+			
+			actualNode++;
+			connectivity << " " << actualNode;
+	  }
+	  connectivity << std::endl;
+	  
+	  int elType = this->GetVTK_ElType(gel);
+	  type << elType << std::endl;
+	  
+	  if(matColor == true)
+	  {
+			material << gel->MaterialId() << std::endl;
+	  }
+	  else
+	  {
+			material << gel->Index() << std::endl;
+	  }
+	  
+	  nVALIDelements++;
+	}
+	node << std::endl;
+	actualNode++;
+	file << actualNode << " float" << std::endl << node.str();
+
+	file << "CELLS " << nVALIDelements << " ";
+
+	file << size << std::endl;
+	file << connectivity.str() << std::endl;
+
+	file << "CELL_TYPES " << nVALIDelements << std::endl;
+	file << type.str() << std::endl;
+
+	file << "CELL_DATA" << " " << nVALIDelements << std::endl;
+	file << "FIELD FieldData 1" << std::endl;
+	if(matColor == true)
+	{
+	  file << "material 1 " << nVALIDelements << " int" << std::endl;
+	}
+	else
+	{
+	  file << "ElementIndex 1 " << nVALIDelements << " int" << std::endl;
+	}
+	file << material.str();
+	file.close();
+}
+/*}}}*/
+int AdaptiveMeshRefinement::GetVTK_ElType(TPZGeoEl * gel){/*{{{*/
     
-    /*Verify if there are orphan nodes*/
-    std::set<int> elemvertices;
-    elemvertices.clear(); 
-    for(int i = 0; i < nelements; i++){
-        for(int j = 0; j < width; j++) {
-            elemvertices.insert((*pelements)[i*width+j]);
-		  }
-	 }
+	MElementType pzElType = gel->Type();
     
-    if( elemvertices.size() != nvertices ) DebugStop();//itapopo verificar se irá usar o _assert_
-	
-    //Verify if there are inf or NaN in coords
-    for(int i = 0; i < nvertices; i++) if(isnan((*px)[i]) || isinf((*px)[i])) DebugStop();
-    for(int i = 0; i < nvertices; i++) if(isnan((*py)[i]) || isinf((*py)[i])) DebugStop();
-    for(int i = 0; i < nvertices; i++) if(isnan((*pz)[i]) || isinf((*pz)[i])) DebugStop();
-   
-	 for(int i = 0; i < nelements; i++){
-        for(int j = 0; j < width; j++){
-            if( isnan((*pelements)[i*width+j]) || isinf((*pelements)[i*width+j]) ) DebugStop();
+    int elType = -1;
+    switch (pzElType)
+    {
+        case(EPoint):
+        {
+            elType = 1;
+            break;
+        }
+        case(EOned):
+        {
+            elType = 3;    
+            break;
+        }
+        case (ETriangle):
+        {
+            elType = 5;
+            break;                
+        }
+        case (EQuadrilateral):
+        {
+            elType = 9;
+            break;                
+        }
+        case (ETetraedro):
+        {
+            elType = 10;
+            break;                
+        }
+        case (EPiramide):
+        {
+            elType = 14;
+            break;                
+        }
+        case (EPrisma):
+        {
+            elType = 13;
+            break;                
+        }
+        case (ECube):
+        {
+            elType = 12;
+            break;                
+        }
+        default:
+        {
+            std::cout << "Element type not found on " << __PRETTY_FUNCTION__ << std::endl;
+            DebugStop();
+            break;    
         }
     }
+    if(elType == -1)
+    {
+        std::cout << "Element type not found on " << __PRETTY_FUNCTION__ << std::endl;
+        std::cout << "MIGHT BE CURVED ELEMENT (quadratic or quarter point)" << std::endl;
+        DebugStop();
+    }
     
-}
-/*}}}*/
+    return elType;
+}
+/*}}}*/
+
Index: /issm/trunk/src/c/classes/AdaptiveMeshRefinement.h
===================================================================
--- /issm/trunk/src/c/classes/AdaptiveMeshRefinement.h	(revision 22757)
+++ /issm/trunk/src/c/classes/AdaptiveMeshRefinement.h	(revision 22758)
@@ -8,21 +8,10 @@
 #include <fstream>
 #include <string>
+#include <climits>
+#include <cfloat>
 
 /*NeoPZ includes*/
-/*REAL and STATE definitions, NeoPZ variables itapopo should be read by NeoPZ's config.h*/
-#ifndef REFPATTERNDIR
-	# define REFPATTERNDIR "/home/santos/trunk-jpl/externalpackages/neopz/install/include/refpatterns"
-#endif
-
-#ifndef REALdouble
-	#define REALdouble
-#endif
-
-#ifndef STATEdouble
-	#define STATEdouble
-#endif
-
+#include <pz_config.h>
 #include <pzreal.h>
-#include <pzsave.h>
 #include <pzgmesh.h>
 #include <pzvec.h>
@@ -36,55 +25,73 @@
 #include <TPZGeoElement.h>
 #include <pzreftriangle.h>
+#include <pzgeotriangle.h>
 #include <tpzgeoelrefpattern.h>
+#include <pzgraphmesh.h>
+#include <TPZVTKGeoMesh.h>
+
+#include "../shared/shared.h"
+
 /*}}}*/
 
-class AdaptiveMeshRefinement : public TPZSaveable {
+class AdaptiveMeshRefinement{
 
 public:
-
-	/*Public methods*/
+	/*Public attributes{{{*/
+	/* 
+	 * to refine:
+	 * distance_h = initial_distance * gradation ^ (level_max-h)
+	 * to unrefine:
+	 * distance_h = lag * initial_distance * gradation ^ (level_max-h)
+	 */
+	int refinement_type;						//0 uniform (faster); 1 refpattern  
+	int level_max;								//max level of refinement
+	double gradation;							//geometric progression ratio to calculate radius of level h
+	double lag;									//lag used in the unrefine process
+	/*Target and estimators*/
+	double groundingline_distance;		//all elements with distance from grounding line <= groundingline_distance will be refined
+	double icefront_distance;				//all elements with distance from ice front <= icefront_distance will be refined
+	double thicknesserror_threshold;		//if ==0, it will not be used
+	double thicknesserror_groupthreshold;//group threshold
+	double thicknesserror_maximum;		//max value of the error estimator; in general, it is defined in the first time step. Attention with restart
+	double deviatoricerror_threshold;	//if ==0, it will not be used
+	double deviatoricerror_groupthreshold;//group threshold
+	double deviatoricerror_maximum;		//max value of the error estimator; in general, it is defined in the first time step. Attention with restart
+	/*}}}*/
+	/*Public methods{{{*/
 	/* Constructor, destructor etc*/
-	AdaptiveMeshRefinement();																// Default constructor
-	AdaptiveMeshRefinement(const AdaptiveMeshRefinement &cp); 					// Copy constructor
-	AdaptiveMeshRefinement & operator= (const AdaptiveMeshRefinement &cp);	// Operator of copy
-	virtual ~AdaptiveMeshRefinement();													// Destructor
-
-    /*Savable methods*/
-	virtual int ClassId() const;                                            // ClassId to save the class
-   virtual void Read(TPZStream &buf, void *context);								// Read this class
-   virtual void Write(TPZStream &buf, int withclassid);                    // Write this class, using ClassId to identify
-    
+	AdaptiveMeshRefinement();															
+	AdaptiveMeshRefinement(const AdaptiveMeshRefinement &cp); 					
+	AdaptiveMeshRefinement & operator= (const AdaptiveMeshRefinement &cp);	
+	virtual ~AdaptiveMeshRefinement();												
 	/*General methods*/
-	void CleanUp();																			// Clean all attributes
-	void Initialize();																		// Initialize the attributes with NULL and values out of usually range
-	void SetLevelMax(int &h);                                               // Define the max level of refinement
-   void SetRegions(double &D1,double Dhmax);										// Define the regions which will be refined
-	void SetElementWidth(int &width);                                       // Define elements width
-	void ExecuteRefinement(int &type_process,double *vx,double *vy,double *masklevelset,int &nvertices,int &nelements,int &nsegments,double** px,double** py,double** pz,int** pelements,int** psegments=NULL);					// A new mesh will be created and refined. This returns the new mesh
-	void CreateInitialMesh(int &nvertices,int &nelements,int &nsegments,int &width,double* x,double* y,double* z,int* elements,int* segments=NULL); // Create a NeoPZ geometric mesh by coords and elements
+	void CleanUp();
+	void Initialize();
+	void ExecuteRefinement(int numberofpoints,double* xylist,int* pnewnumberofvertices,int* pnewnumberofelements,double** px,double** py,int** pelementslist);
+	void ExecuteRefinement(int numberofpoints,double* xylist,double* deviatoricerror,double* thicknesserror,int* pnewnumberofvertices,int* pnewnumberofelements,double** px,double** py,int** pelementslist);
+   void ExecuteRefinement(double* gl_distance,double* if_distance,double* deviatoricerror,double* thicknesserror,int* pnewnumberofvertices,int* pnewnumberofelements,double** px,double** py,int** pelementslist);
+	void CreateInitialMesh(int &nvertices,int &nelements,double* x,double* y,int* elements);
+	void CheckMesh(int* nvertices,int* nelements,double** px,double** py,int** pelements);
+	/*}}}*/
+private:
+	/*Private attributes{{{*/
+	std::vector<int> sid2index;					// Vector that keeps index of PZGeoMesh elements used in the ISSM mesh (sid) 
+	std::vector<int> index2sid;					// Vector that keeps sid of issm mesh elements used in the neopz mesh (index) 
+	std::vector<int> specialelementsindex;		// Vector that keeps index of the special elements (created to avoid haning nodes) 
+	TPZGeoMesh *fathermesh;							// Entire mesh without refinement if refinement_type==1; refined with hanging nodes if efinement_type==0
+	TPZGeoMesh *previousmesh;						// Refined mesh without hanging nodes (it is always refpattern type), used to generate ISSM mesh
+	/*}}}*/
+	/*Private methods{{{*/
+   void RefineMeshOneLevel(bool &verbose,double* gl_distance,double* if_distance,double* deviatoricerror,double* thicknesserror);
+	void RefineMeshWithSmoothing(bool &verbose,TPZGeoMesh* gmesh);
+	void RefineMeshToAvoidHangingNodes(bool &verbose,TPZGeoMesh* gmesh);
+	void DeleteSpecialElements(bool &verbose,TPZGeoMesh* gmesh);
+	void GetMesh(TPZGeoMesh* gmesh,int* nvertices,int* nelements,double** px,double** py,int** pelements);
 	TPZGeoMesh* CreateRefPatternMesh(TPZGeoMesh* gmesh);
-	void CheckMesh(int &nvertices,int &nelements,int &nsegments,int &width,double** px,double** py,double** pz,int** pelements,int** psegments=NULL); // Check the consistency of the mesh
-
-private:
-
-	/*Private attributes*/
-   int elementswidth;                                                      // Geometric nodes for element: 3 == Tria, 4 == Tetra, 6 == Penta
-   int levelmax;                                                           // Max level of refinement
-	double regionlevel1;																		// Region which will be refined with level 1
-	double regionlevelmax;																	// Region which will be refined with level max
-	TPZGeoMesh *fathermesh;																	// Father Mesh is the entire mesh without refinement
-	TPZGeoMesh *previousmesh;																// Previous mesh is a refined mesh of last step
-
-	/*Private methods*/
-   void RefinementProcess(TPZGeoMesh *gmesh,std::vector<TPZVec<REAL> > &GLvec);  // Start the refinement process
-	void RefineMesh(TPZGeoMesh *gmesh, std::vector<int> &ElemVec); 					// Refine the elements in ElemVec
-   void RefineMeshToAvoidHangingNodes(TPZGeoMesh *gmesh);                        // Refine the elements to avoid hanging nodes
-	void SetElementsToRefine(TPZGeoMesh *gmesh,std::vector<TPZVec<REAL> > &GLvec,int &hlevel, std::vector<int> &ElemVec); 	//Define wich elements will be refined
-   void TagAllElements(TPZGeoMesh *gmesh,std::vector<int> &ElemVec);				 // This tag all elements to be refined, that is, refine all elements
-   void TagElementsNearGroundingLine(TPZGeoMesh *gmesh,std::vector<TPZVec<REAL> > &GLvec,int &hlevel,std::vector<int> &ElemVec);    // This tag elements near the grounding line
-   void CalcGroundingLinePosition(double *masklevelset,std::vector<TPZVec<REAL> > &GLvec);	// Calculate the grounding line position using previous mesh
-	void GetMesh(TPZGeoMesh *gmesh,int &nvertices,int &nelements,int &nsegments,double** px,double** py,double** pz,int** pelements,int** psegments=NULL); // Return coords and elements in ISSM data structure
-   inline int GetElemMaterialID(){return 1;}                               // Return element material ID
-   inline int GetBoundaryMaterialID(){return 2;}                           // Return segment (2D boundary) material ID
+   inline int GetElemMaterialID(){return 1;} 
+	inline int GetNumberOfNodes(){return 3;}
+	void PrintGMeshVTK(TPZGeoMesh *gmesh,std::ofstream &file,bool matColor=true);
+	int GetVTK_ElType(TPZGeoEl* gel);
+	int VerifyRefinementType(TPZGeoEl* geoel);
+	/*}}}*/
 };
 
Index: /issm/trunk/src/c/classes/AmrBamg.cpp
===================================================================
--- /issm/trunk/src/c/classes/AmrBamg.cpp	(revision 22758)
+++ /issm/trunk/src/c/classes/AmrBamg.cpp	(revision 22758)
@@ -0,0 +1,186 @@
+/*!\file AmrBamg.cpp
+ * \brief: implementation of the adaptive mesh refinement tool based on bamg
+ */
+
+#ifdef HAVE_CONFIG_H
+    #include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./AmrBamg.h"
+#include "../bamg/bamgobjects.h"
+#include "../modules/Bamgx/Bamgx.h"
+
+using namespace bamg;
+using namespace std;
+
+/*Constructor, copy, clean up and destructor*/
+AmrBamg::AmrBamg(){/*{{{*/
+
+	/*These attributes MUST be setup by FemModel*/
+	this->fieldenum								= -1;
+	this->keepmetric								= -1;
+	this->groundingline_resolution			= -1;
+	this->groundingline_distance				= -1;
+	this->icefront_resolution					= -1;
+	this->icefront_distance						= -1;
+	this->thicknesserror_resolution			= -1;
+	this->thicknesserror_threshold			= -1;
+	this->thicknesserror_groupthreshold 	= -1;
+	this->thicknesserror_maximum				= -1;
+	this->deviatoricerror_resolution			= -1;
+	this->deviatoricerror_threshold			= -1;
+	this->deviatoricerror_groupthreshold	= -1;
+	this->deviatoricerror_maximum				= -1;
+	
+	/*Geometry and mesh as NULL*/
+	this->geometry									= NULL;
+	this->fathermesh								= NULL;
+	this->previousmesh							= NULL;
+
+	/*Only initialize options for now (same as bamg.m)*/
+	this->options									= new BamgOpts();
+	this->options->anisomax						= 10.e30;
+	this->options->cutoff						= 10.e-5;
+	this->options->coeff							= 1;
+	this->options->errg							= 0.1;
+	this->options->gradation					= -1; //MUST be setup by the FemModel 
+	this->options->Hessiantype					= 0;
+	this->options->maxnbv						= 1e6;
+	this->options->maxsubdiv					= 10;
+	this->options->Metrictype					= 0;
+	this->options->nbjacobi						= 1;
+	this->options->nbsmooth						= 3;
+	this->options->omega							= 1.8;
+	this->options->power							= 1;
+	this->options->verbose						= 0;
+	this->options->Crack							= 0;
+	this->options->KeepVertices				= 1; /*!!!!! VERY IMPORTANT !!!!! This avoid numerical errors when remeshing*/
+	this->options->splitcorners				= 1;
+	this->options->hmin							= -1;/*MUST be setup by the FemModel*/
+	this->options->hmax							= -1;/*MUST be setup by the FemModel*/
+	this->options->err							= xNew<IssmDouble>(1);
+	this->options->err[0]						= -1;/*MUST be setup by the FemModel*/
+	this->options->errSize[0]					= 1;
+	this->options->errSize[1]					= 1;
+}
+/*}}}*/
+AmrBamg::~AmrBamg(){/*{{{*/
+
+	if(this->geometry) delete this->geometry;
+	if(this->fathermesh) delete this->fathermesh;
+	if(this->previousmesh) delete this->previousmesh;
+	if(this->options) delete this->options;
+
+}
+/*}}}*/
+
+/*Methods*/
+void AmrBamg::Initialize(int* elements,IssmDouble* x,IssmDouble* y,int numberofvertices,int numberofelements){/*{{{*/
+
+	/*Check options*/
+	_assert_(this->options);
+	this->options->Check();
+
+	/*Read father mesh and create geometry*/
+	Mesh* Th=new Mesh(elements,x,y,numberofvertices,numberofelements,this->options);
+
+	/*Write geometry*/
+	this->geometry = new BamgGeom();
+	Th->Gh.WriteGeometry(this->geometry,this->options);
+
+	/*Write father mesh*/
+	this->fathermesh = new BamgMesh();
+	Th->WriteMesh(this->fathermesh,this->options);
+
+	/*Cleanup and return*/
+	delete Th;
+}/*}}}*/
+void AmrBamg::ExecuteRefinementBamg(IssmDouble* field,IssmDouble* hmaxVertices,int* pnewnumberofvertices,int *pnewnumberofelements,IssmDouble** px,IssmDouble** py,IssmDouble** pz,int** pelementslist){/*{{{*/
+
+	/*Intermediaries*/
+	BamgGeom* geomout=new BamgGeom();
+	BamgMesh* meshout=new BamgMesh();
+
+	/*Some checks*/
+	_assert_(this->geometry);
+	_assert_(this->options);
+	_assert_(this->fathermesh);
+	_assert_(field || hmaxVertices);//at least one is necessary
+
+	/*Prepare field for metric*/
+	this->options->field			 = field;
+	this->options->hmaxVertices = hmaxVertices;
+
+	/*remesh*/
+	if(this->previousmesh){
+		this->options->fieldSize[0]			= this->previousmesh->VerticesSize[0];
+		this->options->fieldSize[1]			= 1;
+		this->options->hmaxVerticesSize[0]	= this->previousmesh->VerticesSize[0];
+		this->options->hmaxVerticesSize[1]	= 1;
+		Bamgx(meshout,geomout,this->previousmesh,this->geometry,this->options);
+	}
+	else{
+		this->options->fieldSize[0]			= this->fathermesh->VerticesSize[0];
+		this->options->fieldSize[1]			= 1;
+		this->options->hmaxVerticesSize[0]	= this->fathermesh->VerticesSize[0];
+		this->options->hmaxVerticesSize[1]	= 1;
+		Bamgx(meshout,geomout,this->fathermesh,this->geometry,this->options);
+	}
+
+	/*remove field and hmaxVertices for memory management (FemModel is taking care of deleting it)*/
+	this->options->field = NULL;
+	this->options->fieldSize[0] = 0;
+	this->options->fieldSize[1] = 0;
+	this->options->hmaxVertices = NULL;
+	this->options->hmaxVerticesSize[0] = 0;
+	this->options->hmaxVerticesSize[1] = 0;
+	
+	/*verify if the metric will be reseted or not*/
+	if(this->keepmetric==0){
+		if(this->options->metric) xDelete<IssmDouble>(this->options->metric);
+		this->options->metricSize[0] = 0;
+		this->options->metricSize[1] = 0;
+	}
+
+	/*Change previous mesh*/
+	if(this->previousmesh) delete this->previousmesh;
+	this->previousmesh = meshout;
+
+	/*Prepare output*/
+	int nbv = meshout->VerticesSize[0];
+	int nbt = meshout->TrianglesSize[0];
+	IssmDouble *x = xNew<IssmDouble>(nbv);
+	IssmDouble *y = xNew<IssmDouble>(nbv);
+	IssmDouble *z = xNew<IssmDouble>(nbv);
+	for(int i=0;i<nbv;i++){
+		x[i] = meshout->Vertices[i*3+0];
+		y[i] = meshout->Vertices[i*3+1];
+		z[i] = 0.;
+	}
+	int* elementslist= xNew<int>(nbt*3);
+	for(int i=0;i<nbt;i++){
+		elementslist[3*i+0] = reCast<int>(meshout->Triangles[4*i+0]);
+		elementslist[3*i+1] = reCast<int>(meshout->Triangles[4*i+1]);
+		elementslist[3*i+2] = reCast<int>(meshout->Triangles[4*i+2]);
+	}
+
+	/*Cleanup and return*/
+	delete geomout;
+	*pnewnumberofvertices = nbv;
+	*pnewnumberofelements = nbt;
+	*px = x;
+	*py = y;
+	*pz = z;
+	*pelementslist = elementslist;
+}/*}}}*/
+void AmrBamg::SetBamgOpts(IssmDouble hmin_in,IssmDouble hmax_in,IssmDouble err_in,IssmDouble gradation_in){/*{{{*/
+
+	if(!this->options) _error_("AmrBamg->options is NULL!");
+	
+	this->options->hmin     = hmin_in; 
+	this->options->hmax     = hmax_in; 
+	this->options->err[0]	= err_in; 
+	this->options->gradation= gradation_in; 
+}/*}}}*/
Index: /issm/trunk/src/c/classes/AmrBamg.h
===================================================================
--- /issm/trunk/src/c/classes/AmrBamg.h	(revision 22758)
+++ /issm/trunk/src/c/classes/AmrBamg.h	(revision 22758)
@@ -0,0 +1,47 @@
+#ifndef AMRBAMG
+#define AMRBAMG
+
+/*Includes*/
+#include "../shared/shared.h"
+#include "../toolkits/toolkits.h"
+
+#include "../bamg/BamgMesh.h"
+#include "../bamg/BamgGeom.h"
+#include "../bamg/BamgOpts.h"
+
+class AmrBamg{
+
+	public:
+		int fieldenum;
+		int keepmetric;
+		IssmDouble groundingline_resolution;
+		IssmDouble groundingline_distance;
+		IssmDouble icefront_resolution;
+		IssmDouble icefront_distance;
+		IssmDouble thicknesserror_resolution;
+		IssmDouble thicknesserror_threshold;
+		IssmDouble thicknesserror_groupthreshold;
+		IssmDouble thicknesserror_maximum;
+		IssmDouble deviatoricerror_resolution;
+		IssmDouble deviatoricerror_threshold;
+		IssmDouble deviatoricerror_groupthreshold;
+		IssmDouble deviatoricerror_maximum;
+
+		/* Constructor, destructor etc*/
+		AmrBamg();
+		
+		~AmrBamg();
+
+		/*General methods*/
+		void Initialize(int* elements,IssmDouble* x,IssmDouble* y,int numberofvertices,int numberofelements);
+		void ExecuteRefinementBamg(IssmDouble* field,IssmDouble* hmaxVertices,int* pnewnumberofvertices,int *pnewnumberofelements,IssmDouble** px,IssmDouble** py,IssmDouble** pz,int** pelementslist);
+		void SetBamgOpts(IssmDouble hmin_in,IssmDouble hmax_in,IssmDouble err_in,IssmDouble gradation_in);
+
+	private:
+		BamgGeom* geometry;
+		BamgMesh* fathermesh;
+		BamgMesh* previousmesh;
+		BamgOpts* options;
+};
+
+#endif
Index: /issm/trunk/src/c/classes/Cfdragcoeffabsgrad.cpp
===================================================================
--- /issm/trunk/src/c/classes/Cfdragcoeffabsgrad.cpp	(revision 22758)
+++ /issm/trunk/src/c/classes/Cfdragcoeffabsgrad.cpp	(revision 22758)
@@ -0,0 +1,195 @@
+/*!\file Cfdragcoeffabsgrad.cpp
+ * \brief: Cfdragcoeffabsgrad Object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+   #include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./classes.h"
+#include "./ExternalResults/ExternalResult.h"
+#include "./ExternalResults/Results.h"
+#include "../datastructures/datastructures.h"
+#include "./Elements/Element.h"
+#include "./Elements/Elements.h"
+#include "./FemModel.h"
+#include "../modules/SurfaceAreax/SurfaceAreax.h"
+#include "../classes/Params/Parameters.h"
+#include "../classes/Inputs/Input.h"
+#include "../classes/gauss/Gauss.h"
+/*}}}*/
+		
+/*Cfdragcoeffabsgrad constructors, destructors :*/
+Cfdragcoeffabsgrad::Cfdragcoeffabsgrad(){/*{{{*/
+
+	this->definitionenum = -1;
+	this->name = NULL;
+	this->weights_enum = UNDEF;
+	this->misfit=0;
+	this->lock=0;
+	this->datatime=0.;
+	this->timepassedflag = false;
+	this->last_time = 0.;
+
+}
+/*}}}*/
+Cfdragcoeffabsgrad::Cfdragcoeffabsgrad(char* in_name, int in_definitionenum, int in_weights_enum, IssmDouble in_datatime, bool in_timepassedflag){/*{{{*/
+
+	this->definitionenum=in_definitionenum;
+	
+	this->name		= xNew<char>(strlen(in_name)+1);
+	xMemCpy<char>(this->name,in_name,strlen(in_name)+1);
+
+	this->weights_enum=in_weights_enum;
+	this->datatime=in_datatime;
+	this->timepassedflag=in_timepassedflag;
+	
+	this->misfit=0;
+	this->lock=0;
+}
+/*}}}*/
+Cfdragcoeffabsgrad::~Cfdragcoeffabsgrad(){/*{{{*/
+	if(this->name)xDelete(this->name);
+	this->misfit=0;
+	this->lock=0;
+}
+/*}}}*/
+/*Object virtual function resolutoin: */
+Object* Cfdragcoeffabsgrad::copy() {/*{{{*/
+	Cfdragcoeffabsgrad* mf = new Cfdragcoeffabsgrad(this->name,this->definitionenum, this->weights_enum,this->datatime,this->timepassedflag);
+	mf->misfit=this->misfit;
+	mf->lock=this->lock;
+	return (Object*) mf;
+}
+/*}}}*/
+void Cfdragcoeffabsgrad::DeepEcho(void){/*{{{*/
+	this->Echo();
+}
+/*}}}*/
+void Cfdragcoeffabsgrad::Echo(void){/*{{{*/
+	_printf_(" Cfdragcoeffabsgrad: " << name << " " << this->definitionenum << "\n");
+	_printf_("    weights_enum: " << weights_enum << " " << EnumToStringx(weights_enum) << "\n");
+	_printf_("    datatime: " << datatime << "\n");
+	_printf_("	  timepassedflag: "<<timepassedflag<<"\n");
+}
+/*}}}*/
+int Cfdragcoeffabsgrad::Id(void){/*{{{*/
+	return -1;
+}
+/*}}}*/
+void Cfdragcoeffabsgrad::Marshall(char** pmarshalled_data,int* pmarshalled_data_size, int marshall_direction){/*{{{*/
+	_error_("not implemented yet!"); 
+} 
+/*}}}*/
+int Cfdragcoeffabsgrad::ObjectEnum(void){/*{{{*/
+	return CfdragcoeffabsgradEnum;
+}
+/*}}}*/
+/*Definition virtual function resolutoin: */
+int Cfdragcoeffabsgrad::DefinitionEnum(){/*{{{*/
+	return this->definitionenum;
+}
+/*}}}*/
+char* Cfdragcoeffabsgrad::Name(){/*{{{*/
+	char* name2=xNew<char>(strlen(this->name)+1);
+	xMemCpy(name2,this->name,strlen(this->name)+1);
+
+	return name2;
+}
+/*}}}*/
+IssmDouble Cfdragcoeffabsgrad::Response(FemModel* femmodel){/*{{{*/
+	 /*diverse: */
+	 IssmDouble time;
+	 
+	 /*recover time parameters: */
+	 femmodel->parameters->FindParam(&time,TimeEnum);
+	 if(time < last_time) timepassedflag = false;
+	 last_time = time;
+
+		 int i;
+		 IssmDouble J=0.;
+		 IssmDouble J_sum=0.;
+
+	 if(datatime<=time && !timepassedflag){
+		 for(i=0;i<femmodel->elements->Size();i++){
+			 Element* element=(Element*)femmodel->elements->GetObjectByOffset(i);
+			 J+=this->Cfdragcoeffabsgrad_Calculation(element,weights_enum);
+		 }
+
+		 ISSM_MPI_Allreduce ( (void*)&J,(void*)&J_sum,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
+		 ISSM_MPI_Bcast(&J_sum,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+		 J=J_sum;
+		
+		 timepassedflag = true;
+		 return J;
+	}
+	 else return J;
+ }
+	/*}}}*/
+IssmDouble Cfdragcoeffabsgrad::Cfdragcoeffabsgrad_Calculation(Element* element, int weights_enum){/*{{{*/
+
+	int        domaintype,numcomponents;
+	IssmDouble Jelem=0.;
+	IssmDouble misfit,Jdet;
+	IssmDouble dp[2],weight;
+	IssmDouble* xyz_list = NULL;
+
+	/*Get basal element*/
+	if(!element->IsOnBase()) return 0.;
+
+	/*If on water, return 0: */
+	if(!element->IsIceInElement()) return 0.;
+
+	/*Get problem dimension*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DverticalEnum:   numcomponents   = 1; break;
+		case Domain3DEnum:           numcomponents   = 2; break;
+		case Domain2DhorizontalEnum: numcomponents   = 2; break;
+		default: _error_("not supported yet");
+	}
+
+	/*Spawn surface element*/
+	Element* basalelement = element->SpawnBasalElement();
+
+	/* Get node coordinates*/
+	basalelement->GetVerticesCoordinates(&xyz_list);
+
+	/*Get input if it already exists*/
+	Input*  tempinput = basalelement->GetInput(definitionenum);
+	/*Cast it to a Datasetinput*/
+	if(tempinput->ObjectEnum()!=DatasetInputEnum) _error_("don't know what to do! confused!");
+	DatasetInput* datasetinput = (DatasetInput*)tempinput;
+
+	/*Get the drag from the model*/
+	Input* drag_input=basalelement->GetInput(FrictionCoefficientEnum);	_assert_(drag_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+
+		/*Get all parameters at gaussian point*/
+		datasetinput->GetInputValue(&weight,gauss,WeightsSurfaceObservationEnum);
+		drag_input->GetInputDerivativeValue(&dp[0],xyz_list,gauss);
+
+		/*Add to cost function*/
+		Jelem+=weight*.5*dp[0]*dp[0]*Jdet*gauss->weight;
+		if(numcomponents==2) Jelem+=weight*.5*dp[1]*dp[1]*Jdet*gauss->weight;
+	}
+
+	/*clean up and Return: */
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	xDelete<IssmDouble>(xyz_list);
+	delete gauss;
+	return Jelem;
+}/*}}}*/
+
Index: /issm/trunk/src/c/classes/Cfdragcoeffabsgrad.h
===================================================================
--- /issm/trunk/src/c/classes/Cfdragcoeffabsgrad.h	(revision 22758)
+++ /issm/trunk/src/c/classes/Cfdragcoeffabsgrad.h	(revision 22758)
@@ -0,0 +1,48 @@
+/*!\file Cfdragcoeffabsgrad.h
+ * \brief: header file for Cfdragcoeffabsgrad object
+ */
+
+#ifndef _CFDRAGCOEFFABSGRAD_H_
+#define _CFDRAGCOEFFABSGRAD_H_
+
+/*Headers:*/
+#include "./Definition.h"
+#include "./FemModel.h"
+
+IssmDouble OutputDefinitionsResponsex(FemModel* femmodel,int output_enum);
+void  GetVectorFromInputsx( IssmDouble** pvector, int* pvector_size, FemModel* femmodel,int name);
+
+class Cfdragcoeffabsgrad: public Object, public Definition{
+
+	public: 
+
+		int         definitionenum;
+		char*       name;
+		int         weights_enum;
+		IssmDouble	datatime;
+		bool			timepassedflag;
+		IssmDouble	last_time;
+		
+		int         lock; // if lock is on, we just return the value stored in "misfit".  this is used so we don't compute misfit past the final_time
+		IssmDouble  misfit; //value carried over in time.
+		
+		/*Cfdragcoeffabsgrad constructors, destructors :*/
+		Cfdragcoeffabsgrad();
+		Cfdragcoeffabsgrad(char* in_name, int in_definitionenum, int in_weights_enum, IssmDouble in_datatime, bool timepassedflag);
+		~Cfdragcoeffabsgrad();
+		
+		/*Object virtual function resolutoin: */
+		Object* copy();
+		void DeepEcho(void);
+		void Echo(void);
+		int Id(void);
+		void Marshall(char** pmarshalled_data,int* pmarshalled_data_size, int marshall_direction);
+		int ObjectEnum(void);
+		
+		/*Definition virtual function resolutoin: */
+		int DefinitionEnum();
+		char* Name();
+		IssmDouble Response(FemModel* femmodel);
+		IssmDouble Cfdragcoeffabsgrad_Calculation(Element* element, int weights_enum);
+};
+#endif  /* _CFDRAGCOEFFABSGRAD_H_ */
Index: /issm/trunk/src/c/classes/Cfsurfacelogvel.cpp
===================================================================
--- /issm/trunk/src/c/classes/Cfsurfacelogvel.cpp	(revision 22758)
+++ /issm/trunk/src/c/classes/Cfsurfacelogvel.cpp	(revision 22758)
@@ -0,0 +1,224 @@
+/*!\file Cfsurfacelogvel.cpp
+ * \brief: Cfsurfacelogvel Object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+   #include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./classes.h"
+#include "./ExternalResults/ExternalResult.h"
+#include "./ExternalResults/Results.h"
+#include "../datastructures/datastructures.h"
+#include "./Elements/Element.h"
+#include "./Elements/Elements.h"
+#include "./FemModel.h"
+#include "../modules/SurfaceAreax/SurfaceAreax.h"
+#include "../classes/Params/Parameters.h"
+#include "../classes/Inputs/Input.h"
+#include "../classes/gauss/Gauss.h"
+/*}}}*/
+		
+/*Cfsurfacelogvel constructors, destructors :*/
+Cfsurfacelogvel::Cfsurfacelogvel(){/*{{{*/
+
+	this->definitionenum = -1;
+	this->name = NULL;
+	this->misfit=0;
+	this->lock=0;
+	this->datatime=0.;
+	this->timepassedflag = false;
+	this->last_time=0.;
+
+}
+/*}}}*/
+Cfsurfacelogvel::Cfsurfacelogvel(char* in_name, int in_definitionenum, IssmDouble in_datatime, bool in_timepassedflag){/*{{{*/
+
+	this->definitionenum=in_definitionenum;
+	
+	this->name		= xNew<char>(strlen(in_name)+1);
+	xMemCpy<char>(this->name,in_name,strlen(in_name)+1);
+
+	this->datatime=in_datatime;
+	this->timepassedflag=in_timepassedflag;
+	
+	this->misfit=0;
+	this->lock=0;
+}
+/*}}}*/
+Cfsurfacelogvel::~Cfsurfacelogvel(){/*{{{*/
+	if(this->name)xDelete(this->name);
+	this->misfit=0;
+	this->lock=0;
+}
+/*}}}*/
+/*Object virtual function resolutoin: */
+Object* Cfsurfacelogvel::copy() {/*{{{*/
+	Cfsurfacelogvel* mf = new Cfsurfacelogvel(this->name,this->definitionenum,this->datatime,this->timepassedflag);
+	mf->misfit=this->misfit;
+	mf->lock=this->lock;
+	return (Object*) mf;
+}
+/*}}}*/
+void Cfsurfacelogvel::DeepEcho(void){/*{{{*/
+	this->Echo();
+}
+/*}}}*/
+void Cfsurfacelogvel::Echo(void){/*{{{*/
+	_printf_(" Cfsurfacelogvel: " << name << " " << this->definitionenum << "\n");
+	_printf_("    datatime: " << datatime << "\n");
+	_printf_("	  timepassedflag: "<<timepassedflag<<"\n");
+}
+/*}}}*/
+int Cfsurfacelogvel::Id(void){/*{{{*/
+	return -1;
+}
+/*}}}*/
+void Cfsurfacelogvel::Marshall(char** pmarshalled_data,int* pmarshalled_data_size, int marshall_direction){/*{{{*/
+	_error_("not implemented yet!"); 
+} 
+/*}}}*/
+int Cfsurfacelogvel::ObjectEnum(void){/*{{{*/
+	return CfsurfacelogvelEnum;
+}
+/*}}}*/
+/*Definition virtual function resolutoin: */
+int Cfsurfacelogvel::DefinitionEnum(){/*{{{*/
+	return this->definitionenum;
+}
+/*}}}*/
+char* Cfsurfacelogvel::Name(){/*{{{*/
+	char* name2=xNew<char>(strlen(this->name)+1);
+	xMemCpy(name2,this->name,strlen(this->name)+1);
+
+	return name2;
+}
+/*}}}*/
+IssmDouble Cfsurfacelogvel::Response(FemModel* femmodel){/*{{{*/
+		 
+	 /*diverse: */
+	 IssmDouble time;
+	 
+	 /*recover time parameters: */
+	 femmodel->parameters->FindParam(&time,TimeEnum);
+	 if(time < last_time) timepassedflag = false;
+	 last_time = time;
+
+		 int i;
+		 IssmDouble J=0.;
+		 IssmDouble J_sum=0.;
+	
+	 if(datatime<=time && !timepassedflag){
+		 for(i=0;i<femmodel->elements->Size();i++){
+			 Element* element=(Element*)femmodel->elements->GetObjectByOffset(i);
+			 J+=this->Cfsurfacelogvel_Calculation(element,definitionenum);
+		 }
+
+		 ISSM_MPI_Allreduce ( (void*)&J,(void*)&J_sum,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
+		 ISSM_MPI_Bcast(&J_sum,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+		 J=J_sum;
+		
+		 timepassedflag = true;
+		 return J;
+		}
+	 else return J;
+ }
+	/*}}}*/
+IssmDouble Cfsurfacelogvel::Cfsurfacelogvel_Calculation(Element* element, int definitionenum){/*{{{*/
+
+	int        domaintype,numcomponents;
+	IssmDouble Jelem=0.;
+	IssmDouble epsvel=2.220446049250313e-16;
+	IssmDouble meanvel=3.170979198376458e-05; /*1000 m/yr*/
+	IssmDouble velocity_mag,obs_velocity_mag;
+	IssmDouble misfit,Jdet;
+	IssmDouble vx,vy,vxobs,vyobs,weight;
+	IssmDouble* xyz_list = NULL;
+	
+	/*Get basal element*/
+	if(!element->IsOnSurface()) return 0.;
+
+	/*If on water, return 0: */
+	if(!element->IsIceInElement()) return 0.;
+
+	/*Get problem dimension*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DverticalEnum:   numcomponents   = 1; break;
+		case Domain3DEnum:           numcomponents   = 2; break;
+		case Domain2DhorizontalEnum: numcomponents   = 2; break;
+		default: _error_("not supported yet");
+	}
+
+	/*Spawn surface element*/
+	Element* topelement = element->SpawnTopElement();
+
+	/* Get node coordinates*/
+	topelement->GetVerticesCoordinates(&xyz_list);
+	
+	/*Get model values*/
+	Input* vx_input     =topelement->GetInput(VxEnum);                                 _assert_(vx_input);
+	Input* vy_input	  =NULL;
+	if(numcomponents==2){
+	      vy_input    =topelement->GetInput(VyEnum);							              _assert_(vy_input);
+	}
+
+	/*Retrieve all inputs we will be needing: */
+	DatasetInput*    datasetinput = NULL;
+	Input*  tempinput = topelement->GetInput(definitionenum);
+	/*Cast it to a Datasetinput*/
+	if(tempinput->ObjectEnum()!=DatasetInputEnum) _error_("don't know what to do");
+	datasetinput = (DatasetInput*)tempinput;
+
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=topelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		topelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+
+		/*Get all parameters at gaussian point*/
+		datasetinput->GetInputValue(&weight,gauss,WeightsSurfaceObservationEnum);
+		vx_input->GetInputValue(&vx,gauss);
+		datasetinput->GetInputValue(&vxobs,gauss,VxObsEnum);
+		if(numcomponents==2){
+			vy_input->GetInputValue(&vy,gauss);
+			datasetinput->GetInputValue(&vyobs,gauss,VyObsEnum);
+		}
+
+		/*Compute SurfaceLogVelMisfit:
+		 *        *                 [        vel + eps     ] 2
+		 *               * J = 4 \bar{v}^2 | log ( -----------  ) |
+		 *                      *                 [       vel   + eps    ]
+		 *                             *                            obs
+		 *                                    */
+		if(numcomponents==1){
+			velocity_mag    =fabs(vx)+epsvel;
+			obs_velocity_mag=fabs(vxobs)+epsvel;
+		}
+		else{
+			velocity_mag    =sqrt(vx*vx+vy*vy)+epsvel;
+			obs_velocity_mag=sqrt(vxobs*vxobs+vyobs*vyobs)+epsvel;
+		}
+
+		misfit=4*pow(meanvel,2)*pow(log(velocity_mag/obs_velocity_mag),2);
+
+		/*Add to cost function*/
+		Jelem+=misfit*weight*Jdet*gauss->weight;
+
+	}
+
+	/*clean up and Return: */
+	if(domaintype!=Domain2DhorizontalEnum){topelement->DeleteMaterials(); delete topelement;};
+	xDelete<IssmDouble>(xyz_list);
+	delete gauss;
+	return Jelem;
+}/*}}}*/
+
Index: /issm/trunk/src/c/classes/Cfsurfacelogvel.h
===================================================================
--- /issm/trunk/src/c/classes/Cfsurfacelogvel.h	(revision 22758)
+++ /issm/trunk/src/c/classes/Cfsurfacelogvel.h	(revision 22758)
@@ -0,0 +1,47 @@
+/*!\file Cfsurfacelogvel.h
+ * \brief: header file for Cfsurfacelogvel object
+ */
+
+#ifndef _CFSURFACELOGVEL_H_
+#define _CFSURFACELOGVEL_H_
+
+/*Headers:*/
+#include "./Definition.h"
+#include "./FemModel.h"
+
+IssmDouble OutputDefinitionsResponsex(FemModel* femmodel,int output_enum);
+void  GetVectorFromInputsx( IssmDouble** pvector, int* pvector_size, FemModel* femmodel,int name);
+
+class Cfsurfacelogvel: public Object, public Definition{
+
+	public: 
+
+		int         definitionenum;
+		char*       name;
+		IssmDouble	datatime;
+		bool			timepassedflag;
+		IssmDouble	last_time;
+		
+		int         lock; // if lock is on, we just return the value stored in "misfit".  this is used so we don't compute misfit past the final_time
+		IssmDouble  misfit; //value carried over in time.
+		
+		/*Cfsurfacelogvel constructors, destructors :*/
+		Cfsurfacelogvel();
+		Cfsurfacelogvel(char* in_name, int in_definitionenum, IssmDouble in_datatime, bool timepassedflag);
+		~Cfsurfacelogvel();
+		
+		/*Object virtual function resolutoin: */
+		Object* copy();
+		void DeepEcho(void);
+		void Echo(void);
+		int Id(void);
+		void Marshall(char** pmarshalled_data,int* pmarshalled_data_size, int marshall_direction);
+		int ObjectEnum(void);
+		
+		/*Definition virtual function resolutoin: */
+		int DefinitionEnum();
+		char* Name();
+		IssmDouble Response(FemModel* femmodel);
+		IssmDouble Cfsurfacelogvel_Calculation(Element* element, int definitionenum);
+};
+#endif  /* _CFSURFACELOGVEL_H_ */
Index: /issm/trunk/src/c/classes/Cfsurfacesquare.cpp
===================================================================
--- /issm/trunk/src/c/classes/Cfsurfacesquare.cpp	(revision 22758)
+++ /issm/trunk/src/c/classes/Cfsurfacesquare.cpp	(revision 22758)
@@ -0,0 +1,216 @@
+/*!\file Cfsurfacesquare.cpp
+ * \brief: Cfsurfacesquare Object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+   #include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./classes.h"
+#include "./ExternalResults/ExternalResult.h"
+#include "./ExternalResults/Results.h"
+#include "../datastructures/datastructures.h"
+#include "./Elements/Element.h"
+#include "./Elements/Elements.h"
+#include "./FemModel.h"
+#include "../modules/SurfaceAreax/SurfaceAreax.h"
+#include "../classes/Params/Parameters.h"
+#include "../classes/Inputs/Input.h"
+#include "../classes/gauss/Gauss.h"
+/*}}}*/
+		
+/*Cfsurfacesquare constructors, destructors :*/
+Cfsurfacesquare::Cfsurfacesquare(){/*{{{*/
+
+	this->definitionenum = -1;
+	this->name = NULL;
+	this->model_enum = UNDEF;
+	this->observation_enum = UNDEF;
+	this->weights_enum = UNDEF;
+	this->misfit=0;
+	this->lock=0;
+	this->datatime=0.;
+	this->timepassedflag = false;
+	this->last_time = 0.;
+
+}
+/*}}}*/
+Cfsurfacesquare::Cfsurfacesquare(char* in_name, int in_definitionenum, int in_model_enum, int in_observation_enum, int in_weights_enum, IssmDouble in_datatime, bool in_timepassedflag){/*{{{*/
+
+	this->definitionenum=in_definitionenum;
+	
+	this->name		= xNew<char>(strlen(in_name)+1);
+	xMemCpy<char>(this->name,in_name,strlen(in_name)+1);
+
+	this->model_enum=in_model_enum;
+	this->observation_enum=in_observation_enum;
+	this->weights_enum=in_weights_enum;
+	this->datatime=in_datatime;
+	this->timepassedflag=in_timepassedflag;
+	
+	this->misfit=0;
+	this->lock=0;
+}
+/*}}}*/
+Cfsurfacesquare::~Cfsurfacesquare(){/*{{{*/
+	if(this->name)xDelete(this->name);
+	this->misfit=0;
+	this->lock=0;
+}
+/*}}}*/
+/*Object virtual function resolutoin: */
+Object* Cfsurfacesquare::copy() {/*{{{*/
+	Cfsurfacesquare* mf = new Cfsurfacesquare(this->name,this->definitionenum, this->model_enum,this->observation_enum,this->weights_enum,this->datatime,this->timepassedflag);
+	mf->misfit=this->misfit;
+	mf->lock=this->lock;
+	return (Object*) mf;
+}
+/*}}}*/
+void Cfsurfacesquare::DeepEcho(void){/*{{{*/
+	this->Echo();
+}
+/*}}}*/
+void Cfsurfacesquare::Echo(void){/*{{{*/
+	_printf_(" Cfsurfacesquare: " << name << " " << this->definitionenum << "\n");
+	_printf_("    model_enum: " << model_enum << " " << EnumToStringx(model_enum) << "\n");
+	_printf_("    observation_enum: " << observation_enum << " " << EnumToStringx(observation_enum) << "\n");
+	_printf_("    weights_enum: " << weights_enum << " " << EnumToStringx(weights_enum) << "\n");
+	_printf_("    datatime: " << datatime << "\n");
+	_printf_("	  timepassedflag: "<<timepassedflag<<"\n");
+}
+/*}}}*/
+int Cfsurfacesquare::Id(void){/*{{{*/
+	return -1;
+}
+/*}}}*/
+void Cfsurfacesquare::Marshall(char** pmarshalled_data,int* pmarshalled_data_size, int marshall_direction){/*{{{*/
+	_error_("not implemented yet!"); 
+} 
+/*}}}*/
+int Cfsurfacesquare::ObjectEnum(void){/*{{{*/
+	return CfsurfacesquareEnum;
+}
+/*}}}*/
+/*Definition virtual function resolutoin: */
+int Cfsurfacesquare::DefinitionEnum(){/*{{{*/
+	return this->definitionenum;
+}
+/*}}}*/
+char* Cfsurfacesquare::Name(){/*{{{*/
+	char* name2=xNew<char>(strlen(this->name)+1);
+	xMemCpy(name2,this->name,strlen(this->name)+1);
+
+	return name2;
+}
+/*}}}*/
+IssmDouble Cfsurfacesquare::Response(FemModel* femmodel){/*{{{*/
+	 /*diverse: */
+	 IssmDouble time;
+	 
+	 /*recover time parameters: */
+	 femmodel->parameters->FindParam(&time,TimeEnum);
+	 if(time < last_time) timepassedflag = false;
+	 last_time = time;
+
+		 int i;
+		 IssmDouble J=0.;
+		 IssmDouble J_sum=0.;
+
+	 if(datatime<=time && !timepassedflag){
+		 for(i=0;i<femmodel->elements->Size();i++){
+			 Element* element=(Element*)femmodel->elements->GetObjectByOffset(i);
+			 J+=this->Cfsurfacesquare_Calculation(element,model_enum,observation_enum,weights_enum);
+		 }
+
+		 ISSM_MPI_Allreduce ( (void*)&J,(void*)&J_sum,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
+		 ISSM_MPI_Bcast(&J_sum,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+		 J=J_sum;
+		
+		 timepassedflag = true;
+		 return J;
+	}
+	 else return J;
+ }
+	/*}}}*/
+IssmDouble Cfsurfacesquare::Cfsurfacesquare_Calculation(Element* element, int model_enum, int observation_enum, int weights_enum){/*{{{*/
+
+	int        domaintype,numcomponents;
+	IssmDouble Jelem=0.;
+	IssmDouble misfit,Jdet;
+	IssmDouble model,obs,weight;
+	IssmDouble* xyz_list = NULL;
+
+	/*Get basal element*/
+	if(!element->IsOnSurface()) return 0.;
+
+	/*If on water, return 0: */
+	if(!element->IsIceInElement()) return 0.;
+
+	/*Get problem dimension*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DverticalEnum:   numcomponents   = 1; break;
+		case Domain3DEnum:           numcomponents   = 2; break;
+		case Domain2DhorizontalEnum: numcomponents   = 2; break;
+		default: _error_("not supported yet");
+	}
+
+	/*Spawn surface element*/
+	Element* topelement = element->SpawnTopElement();
+
+	/* Get node coordinates*/
+	topelement->GetVerticesCoordinates(&xyz_list);
+
+	/*Retrieve all inputs we will be needing: */
+
+	DatasetInput*    datasetinput = NULL;
+
+	/*Get input if it already exists*/
+	Input*  tempinput = topelement->GetInput(definitionenum);
+	
+	/*Cast it to a Datasetinput*/
+	if(tempinput->ObjectEnum()!=DatasetInputEnum) _error_("don't know what to do");
+	datasetinput = (DatasetInput*)tempinput;
+
+	Input* model_input=topelement->GetInput(model_enum);												_assert_(model_input);
+	//Input* observation_input=topelement->GetInput(observation_enum);								_assert_(observation_input);
+	//Input* weights_input     =topelement->GetInput(weights_enum);									_assert_(weights_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=topelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		topelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+
+		/*Get all parameters at gaussian point*/
+		datasetinput->GetInputValue(&weight,gauss,WeightsSurfaceObservationEnum);
+		model_input->GetInputValue(&model,gauss);
+		datasetinput->GetInputValue(&obs,gauss,SurfaceObservationEnum);
+
+		/*Compute SurfaceAbsVelMisfitEnum:
+		 *        *
+		 *               *      1  [           2              2 ]
+		 *                      * J = --- | (u - u   )  +  (v - v   )  |
+		 *                             *      2  [       obs            obs   ]
+		 *                                    *
+		 *                                           */
+		misfit=0.5*(model-obs)*(model-obs);
+
+		/*Add to cost function*/
+		Jelem+=misfit*weight*Jdet*gauss->weight;
+	}
+
+	/*clean up and Return: */
+	if(domaintype!=Domain2DhorizontalEnum){topelement->DeleteMaterials(); delete topelement;};
+	xDelete<IssmDouble>(xyz_list);
+	delete gauss;
+	return Jelem;
+}/*}}}*/
+
Index: /issm/trunk/src/c/classes/Cfsurfacesquare.h
===================================================================
--- /issm/trunk/src/c/classes/Cfsurfacesquare.h	(revision 22758)
+++ /issm/trunk/src/c/classes/Cfsurfacesquare.h	(revision 22758)
@@ -0,0 +1,52 @@
+/*!\file Cfsurfacesquare.h
+ * \brief: header file for Cfsurfacesquare object
+ */
+
+#ifndef _CFSURFACESQUARE_H_
+#define _CFSURFACESQUARE_H_
+
+/*Headers:*/
+#include "./Definition.h"
+#include "./FemModel.h"
+
+IssmDouble OutputDefinitionsResponsex(FemModel* femmodel,int output_enum);
+void  GetVectorFromInputsx( IssmDouble** pvector, int* pvector_size, FemModel* femmodel,int name);
+
+class Cfsurfacesquare: public Object, public Definition{
+
+	public: 
+
+		int         definitionenum;
+		int         local;     
+		int         model_enum;
+		char*       name;
+		int         observation_enum;
+		char*       timeinterpolation;
+		int         weights_enum;
+		IssmDouble	datatime;
+		bool			timepassedflag;
+		IssmDouble	last_time;
+		
+		int         lock; // if lock is on, we just return the value stored in "misfit".  this is used so we don't compute misfit past the final_time
+		IssmDouble  misfit; //value carried over in time.
+		
+		/*Cfsurfacesquare constructors, destructors :*/
+		Cfsurfacesquare();
+		Cfsurfacesquare(char* in_name, int in_definitionenum, int in_model_enum, int in_observation_enum, int in_weights_enum, IssmDouble in_datatime, bool timepassedflag);
+		~Cfsurfacesquare();
+		
+		/*Object virtual function resolutoin: */
+		Object* copy();
+		void DeepEcho(void);
+		void Echo(void);
+		int Id(void);
+		void Marshall(char** pmarshalled_data,int* pmarshalled_data_size, int marshall_direction);
+		int ObjectEnum(void);
+		
+		/*Definition virtual function resolutoin: */
+		int DefinitionEnum();
+		char* Name();
+		IssmDouble Response(FemModel* femmodel);
+		IssmDouble Cfsurfacesquare_Calculation(Element* element, int model_enum, int observation_enum, int weights_enum);
+};
+#endif  /* _CFSURFACESQUARE_H_ */
Index: /issm/trunk/src/c/classes/Constraints/Constraint.h
===================================================================
--- /issm/trunk/src/c/classes/Constraints/Constraint.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Constraints/Constraint.h	(revision 22758)
@@ -24,4 +24,5 @@
 		virtual bool InAnalysis(int analysis_type)=0;
 		virtual void PenaltyDofAndValue(int* dof,IssmDouble* value,Nodes* nodes,Parameters* parameters)=0;
+		virtual void InputUpdateFromVectorDakota(IssmDouble* vector,Nodes* nodes,int name,int type) = 0;
 
 };
Index: /issm/trunk/src/c/classes/Constraints/SpcDynamic.cpp
===================================================================
--- /issm/trunk/src/c/classes/Constraints/SpcDynamic.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Constraints/SpcDynamic.cpp	(revision 22758)
@@ -18,7 +18,7 @@
 }
 /*}}}*/
-SpcDynamic::SpcDynamic(int spc_sid,int spc_nodeid, int spc_dof,int spc_analysis_type){/*{{{*/
+SpcDynamic::SpcDynamic(int spc_id,int spc_nodeid, int spc_dof,int spc_analysis_type){/*{{{*/
 
-	sid           = spc_sid;
+	id           = spc_id;
 	nodeid        = spc_nodeid;
 	dof           = spc_dof;
@@ -41,5 +41,5 @@
 	SpcDynamic* spcdyn = new SpcDynamic(*this); 
 
-	spcdyn->sid=this->sid;
+	spcdyn->id=this->id;
 	spcdyn->nodeid=this->nodeid;
 	spcdyn->dof=this->dof;
@@ -60,5 +60,5 @@
 
 	_printf_("SpcDynamic:\n");
-	_printf_("   sid: " << sid << "\n");
+	_printf_("   id: " << id << "\n");
 	_printf_("   nodeid: " << nodeid << "\n");
 	_printf_("   dof: " << dof << "\n");
@@ -69,5 +69,5 @@
 }
 /*}}}*/
-int     SpcDynamic::Id(void){ return sid; }/*{{{*/
+int     SpcDynamic::Id(void){ return id; }/*{{{*/
 /*}}}*/
 void    SpcDynamic::Marshall(char** pmarshalled_data,int* pmarshalled_data_size, int marshall_direction){ /*{{{*/
@@ -75,5 +75,5 @@
 	MARSHALLING_ENUM(SpcDynamicEnum);
 
-	MARSHALLING(sid);
+	MARSHALLING(id);
 	MARSHALLING(nodeid);
 	MARSHALLING(dof);
Index: /issm/trunk/src/c/classes/Constraints/SpcDynamic.h
===================================================================
--- /issm/trunk/src/c/classes/Constraints/SpcDynamic.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Constraints/SpcDynamic.h	(revision 22758)
@@ -14,5 +14,5 @@
 
 	private: 
-		int        sid;             /*! id, to track it */
+		int        id;              /*! id, to track it */
 		int        nodeid;          /*!node id          */
 		int        dof;             /*!component        */
@@ -26,5 +26,5 @@
 		/*SpcDynamic constructors, destructors*/
 		SpcDynamic();
-		SpcDynamic(int sid,int nodeid, int dof,int analysis_type);
+		SpcDynamic(int id_in,int nodeid, int dof,int analysis_type);
 		~SpcDynamic();
 
@@ -42,4 +42,5 @@
 		bool InAnalysis(int analysis_type);
 		void PenaltyDofAndValue(int* dof,IssmDouble* value,Nodes* nodes,Parameters* parameters){_error_("not implemented yet");};
+		void InputUpdateFromVectorDakota(IssmDouble* vector,Nodes* nodes,int name,int type){_error_("not implemented yet");};
 
 		/*SpcDynamic management*/
Index: /issm/trunk/src/c/classes/Constraints/SpcStatic.cpp
===================================================================
--- /issm/trunk/src/c/classes/Constraints/SpcStatic.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Constraints/SpcStatic.cpp	(revision 22758)
@@ -18,7 +18,7 @@
 }
 /*}}}*/
-SpcStatic::SpcStatic(int spc_sid,int spc_nodeid, int spc_dof,IssmDouble spc_value,int spc_analysis_type){/*{{{*/
+SpcStatic::SpcStatic(int spc_id,int spc_nodeid, int spc_dof,IssmDouble spc_value,int spc_analysis_type){/*{{{*/
 
-	sid           = spc_sid;
+	id           = spc_id;
 	nodeid        = spc_nodeid;
 	dof           = spc_dof;
@@ -40,5 +40,5 @@
 	SpcStatic* spcstat = new SpcStatic(*this); 
 
-	spcstat->sid=this->sid;
+	spcstat->id=this->id;
 	spcstat->nodeid=this->nodeid;
 	spcstat->dof=this->dof;
@@ -52,5 +52,5 @@
 
 	_printf_("SpcStatic:\n");
-	_printf_("   sid: " << sid << "\n");
+	_printf_("   id: " << id << "\n");
 	_printf_("   nodeid: " << nodeid << "\n");
 	_printf_("   dof: " << dof << "\n");
@@ -63,5 +63,5 @@
 
 	_printf_("SpcStatic:\n");
-	_printf_("   sid: " << sid << "\n");
+	_printf_("   id: " << id << "\n");
 	_printf_("   nodeid: " << nodeid << "\n");
 	_printf_("   dof: " << dof << "\n");
@@ -71,5 +71,5 @@
 }
 /*}}}*/
-int     SpcStatic::Id(void){ return sid; }/*{{{*/
+int     SpcStatic::Id(void){ return id; }/*{{{*/
 /*}}}*/
 void    SpcStatic::Marshall(char** pmarshalled_data,int* pmarshalled_data_size, int marshall_direction){ /*{{{*/
@@ -77,5 +77,5 @@
 	MARSHALLING_ENUM(SpcStaticEnum);
 
-	MARSHALLING(sid);
+	MARSHALLING(id);
 	MARSHALLING(nodeid);
 	MARSHALLING(dof);
@@ -100,8 +100,6 @@
 void SpcStatic::ConstrainNode(Nodes* nodes,Parameters* parameters){/*{{{*/
 
-	Node* node=NULL;
-
 	/*Chase through nodes and find the node to which this SpcStatic applys: */
-	node=(Node*)nodes->GetObjectById(NULL,nodeid);
+	Node* node=(Node*)nodes->GetObjectById(NULL,nodeid);
 
 	/*Apply constraint: */
@@ -114,4 +112,20 @@
 	if (in_analysis_type==this->analysis_type) return true;
 	else return false;
+}
+/*}}}*/
+void SpcStatic::InputUpdateFromVectorDakota(IssmDouble* vector,Nodes* nodes,int name,int type){/*{{{*/
+
+	/*Only update if this is a constraint parameter*/
+	if(name != BalancethicknessSpcthicknessEnum) return;
+
+	/*Chase through nodes and find the node to which this SpcStatic applys: */
+	Node* node=(Node*)nodes->GetObjectById(NULL,nodeid);
+
+	/*Apply constraint: */
+	if(node){ //in case the spc is dealing with a node on another cpu
+		int sid = node->Sid();
+		this->value = vector[sid];
+		_assert_(!xIsNan<IssmDouble>(this->value)); 
+	}
 }
 /*}}}*/
Index: /issm/trunk/src/c/classes/Constraints/SpcStatic.h
===================================================================
--- /issm/trunk/src/c/classes/Constraints/SpcStatic.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Constraints/SpcStatic.h	(revision 22758)
@@ -14,5 +14,5 @@
 
 	private: 
-		int        sid;             /*! id, to track it */
+		int        id;             /*! id, to track it */
 		int        nodeid;          /*!node id          */
 		int        dof;             /*!component        */
@@ -25,5 +25,5 @@
 		/*SpcStatic constructors, destructors:{{{*/
 		SpcStatic();
-		SpcStatic(int sid,int nodeid, int dof,IssmDouble value,int analysis_type);
+		SpcStatic(int id,int nodeid, int dof,IssmDouble value,int analysis_type);
 		~SpcStatic();
 		/*}}}*/
@@ -38,7 +38,8 @@
 		/*Constraint virtual functions definitions: {{{*/
 		void ActivatePenaltyMethod(void);
-		void   ConstrainNode(Nodes* nodes,Parameters* parameters);
-		bool   InAnalysis(int analysis_type);
-		void   PenaltyDofAndValue(int* dof,IssmDouble* value,Nodes* nodes,Parameters* parameters){_error_("not implemented yet");};
+		void ConstrainNode(Nodes* nodes,Parameters* parameters);
+		bool InAnalysis(int analysis_type);
+		void PenaltyDofAndValue(int* dof,IssmDouble* value,Nodes* nodes,Parameters* parameters){_error_("not implemented yet");};
+		void InputUpdateFromVectorDakota(IssmDouble* vector,Nodes* nodes,int name,int type);
 		/*}}}*/
 		/*SpcStatic management:{{{ */
Index: /issm/trunk/src/c/classes/Constraints/SpcTransient.cpp
===================================================================
--- /issm/trunk/src/c/classes/Constraints/SpcTransient.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Constraints/SpcTransient.cpp	(revision 22758)
@@ -16,5 +16,5 @@
 SpcTransient::SpcTransient(){/*{{{*/
 	penalty       = false;
-	sid           = -1;
+	id            = -1;
 	nodeid        = -1;
 	dof           = -1;
@@ -26,8 +26,8 @@
 }
 /*}}}*/
-SpcTransient::SpcTransient(int spc_sid,int spc_nodeid, int spc_dof,int spc_nsteps, IssmDouble* spc_times, IssmDouble* spc_values,int spc_analysis_type){/*{{{*/
+SpcTransient::SpcTransient(int spc_id,int spc_nodeid, int spc_dof,int spc_nsteps, IssmDouble* spc_times, IssmDouble* spc_values,int spc_analysis_type){/*{{{*/
 
 	penalty = false;
-	sid     = spc_sid;
+	id     = spc_id;
 	nodeid  = spc_nodeid;
 	dof     = spc_dof;
@@ -52,5 +52,5 @@
 /*Object virtual functions definitions:*/
 Object* SpcTransient::copy() {/*{{{*/
-	return new SpcTransient(sid,nodeid,dof,nsteps,times,values,analysis_type);
+	return new SpcTransient(id,nodeid,dof,nsteps,times,values,analysis_type);
 }
 /*}}}*/
@@ -63,5 +63,5 @@
 	int i;
 	_printf_("SpcTransient:\n");
-	_printf_("   sid: " << sid << "\n");
+	_printf_("   id: " << id << "\n");
 	_printf_("   nodeid: " << nodeid << "\n");
 	_printf_("   dof: " << dof << "\n");
@@ -76,5 +76,5 @@
 /*}}}*/
 int     SpcTransient::Id(void){/*{{{*/
-	return sid;
+	return id;
 }
 /*}}}*/
@@ -83,5 +83,5 @@
 	MARSHALLING_ENUM(SpcTransientEnum);
 
-	MARSHALLING(sid);
+	MARSHALLING(id);
 	MARSHALLING(nodeid);
 	MARSHALLING(dof);
Index: /issm/trunk/src/c/classes/Constraints/SpcTransient.h
===================================================================
--- /issm/trunk/src/c/classes/Constraints/SpcTransient.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Constraints/SpcTransient.h	(revision 22758)
@@ -14,5 +14,5 @@
 
 	private: 
-		int         sid;             /* id, to track it             */
+		int         id;              /* id, to track it             */
 		int         nodeid;          /*node id                      */
 		int         dof;             /*component                    */
@@ -27,5 +27,5 @@
 		/*SpcTransient constructors, destructors:{{{*/
 		SpcTransient();
-		SpcTransient(int sid,int nodeid, int dof,int nsteps, IssmDouble* times, IssmDouble* values,int analysis_type);
+		SpcTransient(int id_in,int nodeid, int dof,int nsteps, IssmDouble* times, IssmDouble* values,int analysis_type);
 		~SpcTransient();
 		/*}}}*/
@@ -43,4 +43,5 @@
 		bool   InAnalysis(int analysis_type);
 		void   PenaltyDofAndValue(int* dof,IssmDouble* value,Nodes* nodes,Parameters* parameters);
+		void InputUpdateFromVectorDakota(IssmDouble* vector,Nodes* nodes,int name,int type){_error_("not implemented yet");};
 		/*}}}*/
 		/*SpcTransient management:{{{ */
Index: /issm/trunk/src/c/classes/Dakota/IssmParallelDirectApplicInterface.cpp
===================================================================
--- /issm/trunk/src/c/classes/Dakota/IssmParallelDirectApplicInterface.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Dakota/IssmParallelDirectApplicInterface.cpp	(revision 22758)
@@ -24,5 +24,5 @@
 		if(world_rank!=0){
 			femmodel_init= new FemModel(argc,argv,evaluation_comm);
-			femmodel_init->profiler->Tag(STARTCORE);
+			femmodel_init->profiler->Start(CORE);
 		}
 
@@ -37,5 +37,5 @@
 
 			/*Wrap up: */
-			femmodel_init->profiler->Tag(FINISHCORE);
+			femmodel_init->profiler->Stop(CORE);
 			femmodel_init->CleanUp(); //only close file pointers on rank 0 of slave 1!
 
@@ -45,92 +45,97 @@
 	}
 	/*}}}*/
-			int IssmParallelDirectApplicInterface::derived_map_ac(const Dakota::String& ac_name){/*{{{*/
+	int IssmParallelDirectApplicInterface::derived_map_ac(const Dakota::String& ac_name){/*{{{*/
 
-				FemModel* femmodel;
-				
-				char     **responses_descriptors    = NULL;      //these are our! there are only numresponsedescriptors of them, not d_numresponses!!!
-				int        numresponsedescriptors;
-				int        solution_type;
-				bool       control_analysis         = false;
-				void     (*solutioncore)(FemModel*) = NULL;
-				bool       nodakotacore             = true;
+		FemModel* femmodel;
 
-				int world_rank;
-				ISSM_MPI_Comm_rank(ISSM_MPI_COMM_WORLD,&world_rank);
+		char     **responses_descriptors    = NULL;      //these are ours! there are only numresponsedescriptors of them, not d_numresponses!!!
+		char      *response_descriptor      = NULL;
+		int        numresponsedescriptors;
+		int        solution_type;
+		bool       control_analysis         = false;
+		void     (*solutioncore)(FemModel*) = NULL;
+		bool       nodakotacore             = true;
 
-				/*Only have slaves work!:*/
-				if(world_rank==0)return 0;
+		int world_rank;
+		ISSM_MPI_Comm_rank(ISSM_MPI_COMM_WORLD,&world_rank);
 
-				#ifdef MPI_DEBUG
-				Cout << "eval server id" << evalServerId << " invoking " << ac_name << " within SIM::IssmParallelDirectApplicInterface." << std::endl;
-				#endif // MPI_DEBUG
+		/*Only have slaves work!:*/
+		if(world_rank==0)return 0;
 
-				int i;
-				IssmDouble* variables=NULL;
-				char** variable_descriptors=NULL;
-				char*  variable_descriptor=NULL;
-				IssmDouble* responses=NULL;
+		#ifdef MPI_DEBUG
+		Cout << "eval server id" << evalServerId << " invoking " << ac_name << " within SIM::IssmParallelDirectApplicInterface." << std::endl;
+		#endif // MPI_DEBUG
 
-				/*Before launching evaluation, we need to transfer the dakota inputs into Issm readable variables: */
+		int i;
+		IssmDouble  *variables            = NULL;
+		char       **variable_descriptors = NULL;
+		char        *variable_descriptor  = NULL;
+		IssmDouble  *responses            = NULL;
 
-				/*First, the variables: */
-				variables=xNew<IssmDouble>(numACV);
-				for(i=0;i<numACV;i++){
-					variables[i]=xC[i];
-				}
-				/*The descriptors: */
-				variable_descriptors=xNew<char*>(numACV);
-				for(i=0;i<numACV;i++){
-					std::string label=xCLabels[i];
-					variable_descriptor=xNew<char>(strlen(label.c_str())+1);
-					memcpy(variable_descriptor,label.c_str(),(strlen(label.c_str())+1)*sizeof(char));
+		/*Before launching evaluation, we need to transfer the dakota inputs into Issm readable variables: */
 
-					variable_descriptors[i]=variable_descriptor;
-				}
+		/*First, the variables: */
+		variables=xNew<IssmDouble>(numACV);
+		for(i=0;i<numACV;i++){
+			variables[i]=xC[i];
+		}
+		/*The descriptors: */
+		variable_descriptors=xNew<char*>(numACV);
+		for(i=0;i<numACV;i++){
+			std::string label=xCLabels[i];
+			variable_descriptor=xNew<char>(strlen(label.c_str())+1);
+			memcpy(variable_descriptor,label.c_str(),(strlen(label.c_str())+1)*sizeof(char));
 
-				/*Initialize responses: */
-				responses=xNewZeroInit<IssmDouble>(numFns);
+			variable_descriptors[i]=variable_descriptor;
+		}
 
-				/*Make a copy of femmodel, so we start this new evaluation run for this specific sample with a brand 
-				 * new copy of the model, which has not been tempered with by previous evaluation runs: */
+		/*Initialize responses: */
+		responses=xNewZeroInit<IssmDouble>(numFns);
 
-				femmodel=femmodel_init->copy();
+		/*Make a copy of femmodel, so we start this new evaluation run for this specific sample with a brand 
+		 * new copy of the model, which has not been tempered with by previous evaluation runs: */
+		femmodel=femmodel_init->copy();
 
-				/*retrieve parameters: */
-				femmodel->parameters->FindParam(&responses_descriptors,&numresponsedescriptors,QmuResponsedescriptorsEnum);
-				femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
-				femmodel->parameters->FindParam(&control_analysis,InversionIscontrolEnum);
+		/*retrieve parameters: */
+		femmodel->parameters->FindParam(&responses_descriptors,&numresponsedescriptors,QmuResponsedescriptorsEnum);
+		femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+		femmodel->parameters->FindParam(&control_analysis,InversionIscontrolEnum);
 
-				/*Modify core inputs in objects contained in femmodel, to reflect the dakota variables inputs: */
-				InputUpdateFromDakotax(femmodel,variables,variable_descriptors,numACV);
+		/*Modify core inputs in objects contained in femmodel, to reflect the dakota variables inputs: */
+		InputUpdateFromDakotax(femmodel,variables,variable_descriptors,numACV);
 
-				/*Determine solution sequence: */
-				if(VerboseQmu()) _printf0_("Starting " << EnumToStringx(solution_type) << " core:\n");
-				WrapperCorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type,nodakotacore);
+		/*Determine solution sequence: */
+		if(VerboseQmu()) _printf0_("Starting " << EnumToStringx(solution_type) << " core:\n");
+		WrapperCorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type,nodakotacore);
 
-				/*Run the core solution sequence: */
-				solutioncore(femmodel);
+		/*Run the core solution sequence: */
+		solutioncore(femmodel);
 
-				/*compute responses: */
-				if(VerboseQmu()) _printf0_("compute dakota responses:\n");
-				femmodel->DakotaResponsesx(responses,responses_descriptors,numresponsedescriptors,numFns);
+		/*compute responses: */
+		if(VerboseQmu()) _printf0_("compute dakota responses:\n");
+		femmodel->DakotaResponsesx(responses,responses_descriptors,numresponsedescriptors,numFns);
 
-				/*populate responses: */
-				for(i=0;i<numFns;i++){
-					fnVals[i]=responses[i];
-				}
+		/*populate responses: */
+		for(i=0;i<numFns;i++){
+			fnVals[i]=responses[i];
+		}
 
-				/*Free ressources:*/
-				xDelete<IssmDouble>(variables);
-				for(i=0;i<numACV;i++){
-					variable_descriptor=variable_descriptors[i];
-					xDelete<char>(variable_descriptor);
-				}
-				xDelete<char*>(variable_descriptors);
-				xDelete<IssmDouble>(responses);
-				delete femmodel;
+		/*Free ressources:*/
+		xDelete<IssmDouble>(variables);
+		for(i=0;i<numACV;i++){
+			variable_descriptor=variable_descriptors[i];
+			xDelete<char>(variable_descriptor);
+		}
+		xDelete<char*>(variable_descriptors);
+		for(i=0;i<numresponsedescriptors;i++){
+			response_descriptor=responses_descriptors[i];
+			xDelete<char>(response_descriptor);
+		}
+		if(responses_descriptors) xDelete<char*>(responses_descriptors);
+		xDelete<IssmDouble>(responses);
+		delete femmodel;
 
-				return 0;
-			}/*}}}*/
+		return 0;
+	}/*}}}*/
 }
 #endif
Index: /issm/trunk/src/c/classes/DependentObject.cpp
===================================================================
--- /issm/trunk/src/c/classes/DependentObject.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/DependentObject.cpp	(revision 22758)
@@ -18,4 +18,5 @@
 	this->type=0;
 	this->index=-1;
+	this->response_value=0.;
 }
 /*}}}*/
@@ -27,4 +28,16 @@
 	if(in_type!=0 && in_type!=1)_error_("cannot create an DependentObject of type " << in_type);
 	if(in_type==1)_error_("not implemented yet!");
+	this->response_value=0.;
+
+}
+/*}}}*/
+DependentObject::DependentObject(char* in_name, int in_type,int in_index,IssmDouble in_response){/*{{{*/
+
+	this->name=xNew<char>(strlen(in_name)+1); xMemCpy<char>(this->name,in_name,strlen(in_name)+1);
+	this->type=in_type;
+	this->index=in_index;
+	if(in_type!=0 && in_type!=1)_error_("cannot create an DependentObject of type " << in_type);
+	if(in_type==1)_error_("not implemented yet!");
+	this->response_value=in_response;
 
 }
@@ -37,5 +50,5 @@
 /*Object virtual functions definitions:*/
 Object* DependentObject::copy(void) { /*{{{*/
-	return new DependentObject(name,type,index);
+	return new DependentObject(name,type,index,response_value);
 } /*}}}*/
 void DependentObject::DeepEcho(void){/*{{{*/
@@ -85,5 +98,16 @@
 	}
 	else femmodel->Responsex(poutput_value,this->name);
-
 }
 /*}}}*/
+IssmDouble DependentObject::GetValue(void){/*{{{*/
+	return this->response_value;
+}
+/*}}}*/
+void DependentObject::AddValue(IssmDouble in_value){/*{{{*/
+	this->response_value+=in_value;
+}
+/*}}}*/
+void DependentObject::ResetResponseValue(){/*{{{*/
+	this->response_value=0.;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/DependentObject.h
===================================================================
--- /issm/trunk/src/c/classes/DependentObject.h	(revision 22757)
+++ /issm/trunk/src/c/classes/DependentObject.h	(revision 22758)
@@ -20,11 +20,13 @@
 		int type;  /*0: scalar, 1: vertex*/
 		int index;  /*0: scalar, 1: vertex*/
+		IssmDouble response_value;
 
-		/*DependentObject constructors, destructors {{{*/
+		/*DependentObject constructors, destructors */
 		DependentObject();
 		DependentObject(char* name, int type,int index);
+		DependentObject(char* name, int type,int index,IssmDouble in_response);
 		~DependentObject();
-		/*}}}*/
-		/*Object virtual functions definitions:{{{ */
+
+		/*Object virtual functions definitions*/
 		Object* copy(void);
 		void  DeepEcho();
@@ -32,13 +34,12 @@
 		int   Id(); 
 		int   ObjectEnum();
-		void Marshall(char** pmarshalled_data,int* pmarshalled_data_size, int marshall_direction){/*{{{*/
-			_error_("not implemented yet!"); 
-		} 
-		/*}}}*/
-		/*}}}*/
+		void Marshall(char** pmarshalled_data,int* pmarshalled_data_size, int marshall_direction){_error_("not implemented yet!"); };
 
 		/*DependentObject methods: */
 		int  NumDependents(void);
 		void Responsex(IssmDouble* poutput_value,FemModel* femmodel);
+		IssmDouble GetValue(void);
+		void AddValue(IssmDouble in_value);
+		void ResetResponseValue(void);
 
 };
Index: /issm/trunk/src/c/classes/Elements/Element.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/Element.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Elements/Element.cpp	(revision 22758)
@@ -26,5 +26,4 @@
 	this->material   = NULL;
 	this->matpar     = NULL;
-	this->inputs     = NULL;
 	this->parameters = NULL;
 	this->element_type_list=NULL;
@@ -48,5 +47,5 @@
 	IssmDouble vx,vy,vz,vmag;
 	IssmDouble dvx[3],dvy[3],dvz[3],dvmag[3];
-	IssmDouble epseff,epsprime;
+	IssmDouble eps[3][3],epseff,epsprime;
 	int         dim;
 	IssmDouble *xyz_list = NULL;
@@ -101,5 +100,16 @@
 			dvmag[2]=1./(2*sqrt(vmag))*(2*vx*dvx[2]+2*vy*dvy[2]+2*vz*dvz[2]);
 		}
-		EstarStrainrateQuantities(&epseff,&epsprime,vx,vy,vz,vmag,&dvx[0],&dvy[0],&dvz[0],&dvmag[0]);
+
+		/*Build strain rate tensor*/
+		eps[0][0] = dvx[0];             eps[0][1] = .5*(dvx[1]+dvy[0]); eps[0][2] = .5*(dvx[2]+dvz[0]);
+		eps[1][0] = .5*(dvx[1]+dvy[0]); eps[1][1] = dvy[1];             eps[1][2] = .5*(dvy[2]+dvz[1]);
+		eps[2][0] = .5*(dvx[2]+dvz[0]); eps[2][1] = .5*(dvy[2]+dvz[1]); eps[2][2] = dvz[2];
+
+		/*effective strain rate*/
+		epseff = 0.;
+		/* eps_eff^2 = exx^2 + eyy^2 + exy^2 + exz^2 + eyz^2 + exx*eyy */
+		epseff = sqrt(eps[0][0]*eps[0][0] + eps[1][1]*eps[1][1] + eps[0][1]*eps[0][1] +  eps[0][2]*eps[0][2] + eps[1][2]*eps[1][2] + eps[0][0]*eps[1][1]);
+
+		EstarStrainrateQuantities(&epsprime,vx,vy,vz,vmag,&dvx[0],&dvy[0],&dvz[0],&dvmag[0]);
 		lambdas[iv]=EstarLambdaS(epseff,epsprime);
 	}
@@ -528,9 +538,11 @@
 	IssmDouble Delta18oTime;
 	IssmDouble dpermil,f;
-	IssmDouble time,yts,time_yr,month;
+	IssmDouble time,yts,time_yr,month,time_clim;
+	bool isTemperatureScaled=true;
 	this->parameters->FindParam(&time,TimeEnum);
 	this->parameters->FindParam(&yts,ConstantsYtsEnum);
 	this->parameters->FindParam(&f,SmbFEnum);
 	time_yr=floor(time/yts)*yts;
+	time_clim=time_yr;
 
 	/*Get some pdd parameters*/
@@ -540,4 +552,11 @@
 	Input*     input=this->inputs->GetInput(SmbTemperaturesPresentdayEnum);    _assert_(input);
 	Input*     input2=this->inputs->GetInput(SmbPrecipitationsPresentdayEnum); _assert_(input2);
+	int offset;
+
+	offset=dynamic_cast<TransientInput*>(input)->GetTimeInputOffset(time_yr);
+	if (fmod(offset,12.)!=1){
+		time_clim=floor(dynamic_cast<TransientInput*>(input)->GetTimeByOffset(offset-fmod(offset,12.)+1)/yts)*yts;
+	}
+
 	/*loop over vertices: */
 	Gauss* gauss=this->NewGauss();
@@ -545,6 +564,6 @@
 		for(int iv=0;iv<numvertices;iv++) {
 			gauss->GaussVertex(iv);
-			input->GetInputValue(&TemperaturesPresentday[iv*12+month],gauss,month/12.*yts);
-			input2->GetInputValue(&PrecipitationsPresentday[iv*12+month],gauss,month/12.*yts);
+			input->GetInputValue(&TemperaturesPresentday[iv*12+month],gauss,time_clim+month/12.*yts);
+			input2->GetInputValue(&PrecipitationsPresentday[iv*12+month],gauss,time_clim+month/12.*yts);
 
 			PrecipitationsPresentday[iv*12+month]=PrecipitationsPresentday[iv*12+month]*yts;
@@ -554,8 +573,9 @@
 	/*Recover interpolation parameters at time t*/
 	this->parameters->FindParam(&Delta18oTime,SmbDelta18oEnum,time);
+	this->parameters->FindParam(&isTemperatureScaled,SmbIstemperaturescaledEnum);
 
 	/*Compute the temperature and precipitation*/
 	for(int iv=0;iv<numvertices;iv++){
-		ComputeD18OTemperaturePrecipitationFromPD(Delta18oTime,dpermil,f,
+		ComputeD18OTemperaturePrecipitationFromPD(Delta18oTime,dpermil,isTemperatureScaled,f,
 					&PrecipitationsPresentday[iv*12], &TemperaturesPresentday[iv*12],
 					&monthlytemperatures[iv*12], &monthlyprec[iv*12]);
@@ -674,8 +694,8 @@
 	switch(materialstype){
 		case MaticeEnum:
-			material->GetViscosity_B(&dmudB,eps_eff);
+			material->GetViscosity_B(&dmudB,eps_eff,gauss);
 			break;
 		case MatestarEnum:
-			material->ViscosityBFS(&dmudB,dim,xyz_list,gauss,vx_input,vy_input,vz_input);
+			material->ViscosityBFS(&dmudB,dim,xyz_list,gauss,vx_input,vy_input,vz_input,eps_eff);
 			break;
 		default: _error_("not supported");
@@ -711,8 +731,8 @@
 	switch(materialstype){
 		case MaticeEnum:
-			material->GetViscosity_B(&dmudB,eps_eff);
+			material->GetViscosity_B(&dmudB,eps_eff,gauss);
 			break;
 		case MatestarEnum:
-			material->ViscosityBHO(&dmudB,dim,xyz_list,gauss,vx_input,vy_input);
+			material->ViscosityBHO(&dmudB,dim,xyz_list,gauss,vx_input,vy_input,eps_eff);
 			break;
 		default: _error_("not supported");
@@ -748,8 +768,8 @@
 	switch(materialstype){
 		case MaticeEnum:
-			material->GetViscosity_B(&dmudB,eps_eff);
+			material->GetViscosity_B(&dmudB,eps_eff,gauss);
 			break;
 		case MatestarEnum:
-			material->ViscosityBSSA(&dmudB,dim,xyz_list,gauss,vx_input,vy_input);
+			material->ViscosityBSSA(&dmudB,dim,xyz_list,gauss,vx_input,vy_input,eps_eff);
 			break;
 		default: _error_("not supported");
@@ -781,5 +801,5 @@
 
 	/*Get viscosity*/
-	material->GetViscosity_D(&dmudB,eps_eff);
+	material->GetViscosity_D(&dmudB,eps_eff,gauss);
 
 	/*Assign output pointer*/
@@ -843,4 +863,17 @@
 	this->parameters->FindParam(pvalues,psize,paramenum);
 }/*}}}*/
+IssmDouble Element::FloatingArea(IssmDouble* mask, bool scaled){/*{{{*/
+
+	/*Retrieve values of the mask defining the element: */
+	for(int i=0;i<this->GetNumberOfVertices();i++){
+		if(mask[this->vertices[i]->Sid()]<=0.){
+			return 0.;
+		}
+	}
+
+	/*Return: */
+	return this->FloatingArea(scaled);
+}
+/*}}}*/
 void       Element::GetDofList(int** pdoflist,int approximation_enum,int setenum){/*{{{*/
 
@@ -1104,11 +1137,11 @@
 		case MaterialsRheologyNEnum:
 			return this->material->GetN();
-		case MaterialsRheologyBEnum:
-			return this->material->GetB();
-		case MaterialsRheologyBbarEnum:
-			return this->material->GetBbar();
 		default:
 			return this->matpar->GetMaterialParameter(enum_in);
 	}
+}/*}}}*/
+int         Element::GetIntegerMaterialParameter(int enum_in){/*{{{*/
+
+	return this->matpar->GetIntegerMaterialParameter(enum_in);
 }/*}}}*/
 void       Element::GetNodesLidList(int* lidlist){/*{{{*/
@@ -1167,4 +1200,36 @@
 	 *    = 4 * mu * eps_eff ^2*/
 	*phi=4.*epsilon_eff*epsilon_eff*viscosity;
+}
+/*}}}*/
+void       Element::GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution, int enum_type){/*{{{*/
+
+	int        *doflist = NULL;
+	IssmDouble  value;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->GetNumberOfNodes();
+
+	/*Fetch dof list and allocate solution vector*/
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble* values = xNew<IssmDouble>(numnodes);
+
+	/*Get inputs*/
+	Input* enum_input=inputs->GetInput(enum_type); _assert_(enum_input);
+
+	/*Ok, we have the values, fill in the array: */
+	Gauss* gauss=this->NewGauss();
+	for(int i=0;i<numnodes;i++){
+		gauss->GaussNode(this->element_type,i);
+
+		enum_input->GetInputValue(&value,gauss);
+		values[i]=value;
+	}
+
+	solution->SetValues(numnodes,doflist,values,INS_VAL);
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+	xDelete<IssmDouble>(values);
+	delete gauss;
 }
 /*}}}*/
@@ -1322,21 +1387,53 @@
 	/*Get number of controls*/
 	int num_controls;
+	bool isautodiff;
 	parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+	parameters->FindParam(&isautodiff,AutodiffIsautodiffEnum);
+
 
 	/*Get number of vertices*/
 	int numvertices = this->GetNumberOfVertices();
-
+	if(isautodiff){
+		int* N=NULL;
+		int* M=NULL;
+		int start = 0;
+		parameters->FindParam(&N,NULL,ControlInputSizeNEnum);
+		parameters->FindParam(&M,NULL,ControlInputSizeMEnum);
+		if(control_index>0) for(int n=0;n<control_index-1;n++) start+=N[n]*M[n];
+
+		for(int n=0;n<N[control_index];n++){
+			for(int i=0;i<numvertices;i++){
+				indexing[i+n*numvertices]=this->vertices[i]->Sid() + start + n*M[control_index];
+			}
+		}
+	}
+	else{
+		int M;
+		parameters->FindParam(&M,ControlInputSizeMEnum);
 	/*get gradient indices*/
-	if(onsid){
-		for(int i=0;i<numvertices;i++){
-			indexing[i]=num_controls*this->vertices[i]->Sid() + control_index;
-		}
-	}
-	else{
-		for(int i=0;i<numvertices;i++){
-			indexing[i]=num_controls*this->vertices[i]->Pid() + control_index;
-		}
-	}
-
+		if(onsid){
+			for(int i=0;i<numvertices;i++){
+				indexing[i]=this->vertices[i]->Sid() + (control_index)*M;
+			}
+		}
+		else{
+			for(int i=0;i<numvertices;i++){
+				indexing[i]=this->vertices[i]->Pid() + (control_index)*M;
+			}
+		}
+	}
+}
+/*}}}*/
+IssmDouble Element::GroundedArea(IssmDouble* mask, bool scaled){/*{{{*/
+
+	/*Retrieve values of the mask defining the element: */
+	for(int i=0;i<this->GetNumberOfVertices();i++){
+		if(mask[this->vertices[i]->Sid()]<=0.){
+			return 0.;
+		}
+	}
+
+	/*Return: */
+	return this->GroundedArea(scaled);
 }
 /*}}}*/
@@ -1347,4 +1444,55 @@
 	return (this->inputs->Max(MeshVertexonsurfaceEnum)>0.);
 }/*}}}*/
+IssmDouble Element::IceMass(bool scaled){/*{{{*/
+
+	IssmDouble rho_ice;
+
+	if(!IsIceInElement())return 0.; //do not contribute to the volume of the ice!
+
+	/*recover ice density: */
+	rho_ice=matpar->GetMaterialParameter(MaterialsRhoIceEnum);
+
+	return rho_ice*this->IceVolume(scaled);
+}
+/*}}}*/
+IssmDouble Element::IceMass(IssmDouble* mask, bool scaled){/*{{{*/
+
+	/*Retrieve values of the mask defining the element: */
+	for(int i=0;i<this->GetNumberOfVertices();i++){
+		if(mask[this->vertices[i]->Sid()]<=0.){
+			return 0.;
+		}
+	}
+
+	/*Return: */
+	return this->IceMass(scaled);
+}
+/*}}}*/
+IssmDouble Element::IceVolume(IssmDouble* mask, bool scaled){/*{{{*/
+
+	/*Retrieve values of the mask defining the element: */
+	for(int i=0;i<this->GetNumberOfVertices();i++){
+		if(mask[this->vertices[i]->Sid()]<=0.){
+			return 0.;
+		}
+	}
+
+	/*Return: */
+	return this->IceVolume(scaled);
+}
+/*}}}*/
+IssmDouble Element::IceVolumeAboveFloatation(IssmDouble* mask, bool scaled){/*{{{*/
+
+	/*Retrieve values of the mask defining the element: */
+	for(int i=0;i<this->GetNumberOfVertices();i++){
+		if(mask[this->vertices[i]->Sid()]<=0.){
+			return 0.;
+		}
+	}
+
+	/*Return: */
+	return this->IceVolumeAboveFloatation(scaled);
+}
+/*}}}*/
 int        Element::Id(){/*{{{*/
 
@@ -1360,6 +1508,5 @@
     
     /*Intermediaries*/
-    int        i,t;
-    IssmDouble time;
+    int i,t;
     
     /*Branch on type of vector: nodal or elementary: */
@@ -1377,5 +1524,9 @@
         
         /*Are we in transient or static? */
-        if(M==iomodel->numberofvertices){
+		  if(M==1){
+			  values[0]=vector[0];
+			  this->AddInput(vector_enum,values,P0Enum);
+		  }
+		  else if(M==iomodel->numberofvertices){
             for(i=0;i<numvertices;i++) values[i]=vector[vertexids[i]-1];
             this->AddInput(vector_enum,values,P1Enum);
@@ -1398,5 +1549,21 @@
             xDelete<IssmDouble>(times);
         }
-        else _error_("nodal vector is either numberofvertices or numberofvertices+1 long. Field provided (" << EnumToStringx(vector_enum) << ") is " << M << " long");
+        else if(M==iomodel->numberofelements){
+
+			  /*This is a Patch!*/
+			  xDelete<IssmDouble>(values);
+			  values = xNew<IssmDouble>(N);
+			  for(int j=0;j<N;j++) values[j]=vector[this->Sid()*N+j];
+
+			  if     (N==this->GetNumberOfNodes(P1Enum)   ) this->AddInput(vector_enum,values,P1Enum);
+			  else if(N==this->GetNumberOfNodes(P0Enum)   ) this->AddInput(vector_enum,values,P0Enum);
+			  else if(N==this->GetNumberOfNodes(P1xP2Enum)) this->AddInput(vector_enum,values,P1xP2Enum);
+			  else if(N==this->GetNumberOfNodes(P1xP3Enum)) this->AddInput(vector_enum,values,P1xP3Enum);
+			  else _error_("Patch interpolation not supported yet");
+
+		  }
+		  else{
+			  _error_("nodal vector is either numberofvertices or numberofvertices+1 long. Field provided (" << EnumToStringx(vector_enum) << ") is " << M << " long");
+		  }
         
         xDelete<IssmDouble>(values);
@@ -1442,5 +1609,256 @@
     else if(vector_type==3){ //element vector
         
+        /*For right now we are static */
+        if(M==iomodel->numberofelements){
+            /*create transient input: */
+            IssmDouble* layers = xNewZeroInit<IssmDouble>(N);;
+            for(t=0;t<N;t++) layers[t] = vector[N*this->Sid()+t];
+            DoubleArrayInput* arrayinput=new DoubleArrayInput(vector_enum,layers,N);
+            this->inputs->AddInput(arrayinput);
+            xDelete<IssmDouble>(layers);
+        }
+        else _error_("element vector is either numberofelements or numberofelements+1 long. Field provided (" << EnumToStringx(vector_enum) << ") is " << M << " long");
+    }
+    else _error_("Cannot add input for vector type " << vector_type << " (not supported)");
+}
+/*}}}*/
+void       Element::ControlInputCreate(IssmDouble* vector,IssmDouble* min_vector,IssmDouble* max_vector,IoModel* iomodel,int M,int N,int input_enum,int id){/*{{{*/
+
+	/*Intermediaries*/
+	int         numvertices = this->GetNumberOfVertices();
+	int        *vertexids   = xNew<int>(numvertices);
+	IssmDouble *values      = xNew<IssmDouble>(numvertices);
+	IssmDouble *values_min  = xNew<IssmDouble>(numvertices);
+	IssmDouble *values_max  = xNew<IssmDouble>(numvertices);
+
+	/*Some sanity checks*/
+	_assert_(vector); 
+	_assert_(min_vector); 
+	_assert_(max_vector); 
+
+	/*For now we only support nodal vectors*/
+	//if(M!=iomodel->numberofvertices) _error_("not supported");
+	//if(N!=1) _error_("not supported");
+
+	/*Recover vertices ids needed to initialize inputs*/
+	_assert_(iomodel->elements);
+	for(int i=0;i<numvertices;i++){
+		vertexids[i]=reCast<int>(iomodel->elements[numvertices*this->Sid()+i]); //ids for vertices are in the elements array from Matlab
+	}
+
+	/*Are we in transient or static? */
+	if(M==iomodel->numberofvertices){
+		for(int i=0;i<numvertices;i++){
+			values[i]=vector[vertexids[i]-1];
+			values_min[i] = min_vector[vertexids[i]-1];
+			values_max[i] = max_vector[vertexids[i]-1];
+		}
+		this->AddControlInput(input_enum,values,min_vector,max_vector,P1Enum,id);
+	}
+
+	else if(M==iomodel->numberofvertices+1){
+            /*create transient input: */
+            IssmDouble* times = xNew<IssmDouble>(N);
+            for(int t=0;t<N;t++) times[t] = vector[(M-1)*N+t];
+				/*Create the three transient inputs for the control input*/
+            TransientInput* values_input=new TransientInput(ControlInputValuesEnum,times,N);
+				TransientInput* mins_input = new TransientInput(ControlInputMinsEnum,times,N);
+				TransientInput* maxs_input = new TransientInput(ControlInputMaxsEnum,times,N);
+			   TransientInput* grad_input = new TransientInput(ControlInputGradEnum);
+				for(int t=0;t<N;t++){
+                for(int i=0;i<numvertices;i++){ 
+						values[i]=vector[N*(vertexids[i]-1)+t];
+						values_min[i] = min_vector[N*(vertexids[i]-1)+t];
+						values_max[i] = max_vector[N*(vertexids[i]-1)+t];
+					 } 
+					switch(this->ObjectEnum()){
+                    case TriaEnum:
+									values_input->AddTimeInput(new TriaInput(ControlInputValuesEnum,values,P1Enum)); 
+									mins_input->AddTimeInput(new TriaInput(ControlInputMinsEnum,values_min,P1Enum)); 
+									maxs_input->AddTimeInput(new TriaInput(ControlInputMaxsEnum,values_max,P1Enum));
+								break;
+                    case PentaEnum:
+									values_input->AddTimeInput(new PentaInput(ControlInputValuesEnum,values,P1Enum)); 
+									mins_input->AddTimeInput(new PentaInput(ControlInputMinsEnum,values_min,P1Enum)); 
+									maxs_input->AddTimeInput(new PentaInput(ControlInputMaxsEnum,values_max,P1Enum)); 
+									break;
+                    case TetraEnum:
+									values_input->AddTimeInput(new TetraInput(ControlInputValuesEnum,values,P1Enum)); 
+									mins_input->AddTimeInput(new TetraInput(ControlInputMinsEnum,values_min,P1Enum)); 
+									maxs_input->AddTimeInput(new TetraInput(ControlInputMaxsEnum,values_max,P1Enum)); 
+									break;
+                    default: _error_("Not implemented yet");
+                }
+            }
+            this->inputs->AddInput(new ControlInput(input_enum,TransientInputEnum,values_input,mins_input,maxs_input,grad_input,P1Enum,id));
+            xDelete<IssmDouble>(times);
+        }
+		  else _error_("not currently supported type of M and N attempted");
+
+	/*clean up*/
+	xDelete<IssmDouble>(values);
+	xDelete<int>(vertexids);
+}
+/*}}}*/
+void       Element::DatasetInputAdd(int enum_type,IssmDouble* vector,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code,int input_enum){/*{{{*/
+    /*enum_type: the name of the DatasetInput (eg Outputdefinition1)
+	  * vector: information being stored (eg observations)
+	  * vector_type: is if by element or by vertex
+	  * vector_enum: is the name of the vector being stored
+	  * code: what type of data is in the vector (booleans, ints, doubles)
+	  */
+    
+	 /*Intermediaries*/
+    int					i,t;
+	 DatasetInput*		datasetinput = NULL;
+
+	 /*Get input if it already exists*/
+	 Input*  tempinput = GetInput(enum_type);
+	 if(tempinput){
+		 /*Cast it to a Datasetinput*/
+		 if(tempinput->ObjectEnum()!=DatasetInputEnum) _error_("don't know what to do");
+		 datasetinput = (DatasetInput*)tempinput;
+	 }
+	 else{
+		 datasetinput=new DatasetInput(enum_type);
+	   this->inputs->AddInput(datasetinput);
+	}
+
+
+    /*Branch on type of vector: nodal or elementary: */
+    if(vector_type==1){ //nodal vector
+        
+        int         numvertices = this->GetNumberOfVertices();
+        int        *vertexids   = xNew<int>(numvertices);
+        IssmDouble *values      = xNew<IssmDouble>(numvertices);
+        
+        /*Recover vertices ids needed to initialize inputs*/
+        _assert_(iomodel->elements);
+        for(i=0;i<numvertices;i++){
+            vertexids[i]=reCast<int>(iomodel->elements[numvertices*this->Sid()+i]); //ids for vertices are in the elements array from Matlab
+        }
+        
+        /*Are we in transient or static? */
+		  if(M==1){
+			  values[0]=vector[0];
+				switch(this->ObjectEnum()){
+                    case TriaEnum:  datasetinput->AddInput(new TriaInput(vector_enum,values,P0Enum),input_enum); break;
+                    case PentaEnum: datasetinput->AddInput(new PentaInput(vector_enum,values,P0Enum),input_enum); break;
+                    case TetraEnum: datasetinput->AddInput(new TetraInput(vector_enum,values,P0Enum),input_enum); break;
+                    default: _error_("Not implemented yet");
+				} 
+		  }
+		  else if(M==iomodel->numberofvertices){
+            for(i=0;i<numvertices;i++) values[i]=vector[vertexids[i]-1];
+				switch(this->ObjectEnum()){
+                    case TriaEnum:  datasetinput->AddInput(new TriaInput(vector_enum,values,P1Enum),input_enum); break;
+                    case PentaEnum: datasetinput->AddInput(new PentaInput(vector_enum,values,P1Enum),input_enum); break;
+                    case TetraEnum: datasetinput->AddInput(new TetraInput(vector_enum,values,P1Enum),input_enum); break;
+                    default: _error_("Not implemented yet");
+				}  }
+        else if(M==iomodel->numberofvertices+1){
+            /*create transient input: */
+            IssmDouble* times = xNew<IssmDouble>(N);
+            for(t=0;t<N;t++) times[t] = vector[(M-1)*N+t];
+            TransientInput* transientinput=new TransientInput(vector_enum,times,N);
+            for(t=0;t<N;t++){
+                for(i=0;i<numvertices;i++) values[i]=vector[N*(vertexids[i]-1)+t];
+                switch(this->ObjectEnum()){
+                    case TriaEnum:  transientinput->AddTimeInput(new TriaInput( vector_enum,values,P1Enum)); break;
+                    case PentaEnum: transientinput->AddTimeInput(new PentaInput(vector_enum,values,P1Enum)); break;
+                    case TetraEnum: transientinput->AddTimeInput(new TetraInput(vector_enum,values,P1Enum)); break;
+                    default: _error_("Not implemented yet");
+                }
+            }
+            datasetinput->AddInput(transientinput,input_enum);
+            xDelete<IssmDouble>(times);
+        }
+        else if(M==iomodel->numberofelements){
+
+			  /*This is a Patch!*/
+			  xDelete<IssmDouble>(values);
+			  values = xNew<IssmDouble>(N);
+			  for(int j=0;j<N;j++) values[j]=vector[this->Sid()*N+j];
+
+			  if     (N==this->GetNumberOfNodes(P1Enum)   ){
+				  switch(this->ObjectEnum()){
+					  case TriaEnum:  datasetinput->AddInput(new TriaInput(vector_enum,values,P1Enum),input_enum); break;
+					  case PentaEnum: datasetinput->AddInput(new PentaInput(vector_enum,values,P1Enum),input_enum); break;
+					  case TetraEnum: datasetinput->AddInput(new TetraInput(vector_enum,values,P1Enum),input_enum); break;
+					  default: _error_("Not implemented yet");
+				  }
+			  }
+			  else if(N==this->GetNumberOfNodes(P0Enum)   ){
+				  switch(this->ObjectEnum()){
+					  case TriaEnum:  datasetinput->AddInput(new TriaInput(vector_enum,values,P0Enum),input_enum); break;
+					  case PentaEnum: datasetinput->AddInput(new PentaInput(vector_enum,values,P0Enum),input_enum); break;
+					  case TetraEnum: datasetinput->AddInput(new TetraInput(vector_enum,values,P0Enum),input_enum); break;
+					  default: _error_("Not implemented yet");
+				  }	  
+			  }
+			  else if(N==this->GetNumberOfNodes(P1xP2Enum)){
+				  switch(this->ObjectEnum()){
+					  case TriaEnum:  datasetinput->AddInput(new TriaInput(vector_enum,values,P1xP2Enum),input_enum); break;
+					  case PentaEnum: datasetinput->AddInput(new PentaInput(vector_enum,values,P1xP2Enum),input_enum); break;
+					  case TetraEnum: datasetinput->AddInput(new TetraInput(vector_enum,values,P1xP2Enum),input_enum); break;
+					  default: _error_("Not implemented yet");
+				  }
+			  }
+			  else if(N==this->GetNumberOfNodes(P1xP3Enum)) {
+				 switch(this->ObjectEnum()){
+					  case TriaEnum:  datasetinput->AddInput(new TriaInput(vector_enum,values,P1xP3Enum),input_enum); break;
+					  case PentaEnum: datasetinput->AddInput(new PentaInput(vector_enum,values,P1xP3Enum),input_enum); break;
+					  case TetraEnum: datasetinput->AddInput(new TetraInput(vector_enum,values,P1xP3Enum),input_enum); break;
+					  default: _error_("Not implemented yet");
+				  }
+			  }
+			  else _error_("Patch interpolation not supported yet");
+
+		  }
+		  else{
+			  _error_("nodal vector is either numberofvertices or numberofvertices+1 long. Field provided (" << EnumToStringx(vector_enum) << ") is " << M << " long");
+		  }
+        
+        xDelete<IssmDouble>(values);
+        xDelete<int>(vertexids);
+    }
+    else if(vector_type==2){ //element vector
+        
         IssmDouble value;
+        
+        /*Are we in transient or static? */
+        if(M==iomodel->numberofelements){
+            if (code==5){ //boolean
+                datasetinput->AddInput(new BoolInput(vector_enum,reCast<bool>(vector[this->Sid()])),input_enum);
+            }
+            else if (code==6){ //integer
+                datasetinput->AddInput(new IntInput(vector_enum,reCast<int>(vector[this->Sid()])),input_enum);
+            }
+            else if (code==7){ //IssmDouble
+                datasetinput->AddInput(new DoubleInput(vector_enum,vector[this->Sid()]),input_enum);
+            }
+            else _error_("could not recognize nature of vector from code " << code);
+        }
+        else if(M==iomodel->numberofelements+1){
+            /*create transient input: */
+            IssmDouble* times = xNew<IssmDouble>(N);
+            for(t=0;t<N;t++) times[t] = vector[(M-1)*N+t];
+            TransientInput* transientinput=new TransientInput(vector_enum,times,N);
+            TriaInput* bof=NULL;
+            for(t=0;t<N;t++){
+                value=vector[N*this->Sid()+t];
+                switch(this->ObjectEnum()){
+                    case TriaEnum:  transientinput->AddTimeInput(new TriaInput( vector_enum,&value,P0Enum)); break;
+                    case PentaEnum: transientinput->AddTimeInput(new PentaInput(vector_enum,&value,P0Enum)); break;
+                    case TetraEnum: transientinput->AddTimeInput(new TetraInput(vector_enum,&value,P0Enum)); break;
+                    default: _error_("Not implemented yet");
+                }
+            }
+            datasetinput->AddInput(transientinput,input_enum);
+            xDelete<IssmDouble>(times);
+        }
+        else _error_("element vector is either numberofelements or numberofelements+1 long. Field provided (" << EnumToStringx(vector_enum) << ") is " << M << " long");
+    }
+    else if(vector_type==3){ //element vector
         
         /*For right now we are static */
@@ -1450,5 +1868,5 @@
             for(t=0;t<N;t++) layers[t] = vector[N*this->Sid()+t];
             DoubleArrayInput* arrayinput=new DoubleArrayInput(vector_enum,layers,N);
-            this->inputs->AddInput(arrayinput);
+            datasetinput->AddInput(arrayinput,input_enum);
             xDelete<IssmDouble>(layers);
         }
@@ -1537,8 +1955,20 @@
 				name==SmbRefreezeEnum ||
 				name==SmbEvaporationEnum ||
+				name==SmbCEnum ||
+				name==SmbTaEnum ||
+				name==SmbVEnum ||
+				name==SmbDswrfEnum ||
+				name==SmbDlwrfEnum ||
+				name==SmbPEnum ||
+				name==SmbEAirEnum ||
+				name==SmbPAirEnum ||
+				name==SmbVzEnum ||
+				name==SmbTzEnum ||
+				name==SmbTmeanEnum ||
 				name==SmbIsInitializedEnum ||
 				name==BasalforcingsGroundediceMeltingRateEnum ||
 				name==BasalforcingsFloatingiceMeltingRateEnum ||
 				name==BasalforcingsGeothermalfluxEnum ||
+				name==BalancethicknessSpcthicknessEnum ||
 				name==SurfaceAreaEnum||
 				name==DamageDEnum ||
@@ -1569,5 +1999,6 @@
 				name==LevelsetfunctionSlopeYEnum ||
 				name==LevelsetfunctionPicardEnum ||
-				//name==CalvingCalvingrateEnum ||
+				name==CalvingCalvingrateEnum ||
+				name==CalvingMeltingrateEnum ||
 				name==GradientEnum ||
 				name==OldGradientEnum  ||
@@ -1592,4 +2023,6 @@
 				name==EsaNmotionEnum || 
 				name==EsaEmotionEnum || 
+				name==EsaXmotionEnum || 
+				name==EsaYmotionEnum || 
 				name==EsaStrainratexxEnum ||
 				name==EsaStrainratexyEnum || 
@@ -1611,5 +2044,5 @@
 				name==HydrologydcMaskEplactiveNodeEnum ||
 				name==HydrologyHeadEnum ||
-	         name==HydrologyHeadOldEnum ||		
+				name==HydrologyHeadOldEnum ||		
 				name==StressbalanceConvergenceNumStepsEnum || 
 				name==MeshVertexonbaseEnum || 
@@ -1620,7 +2053,13 @@
 				name==LoadingforceYEnum ||
 				name==VelEnum ||
-				name==VxPicardEnum ||
-				name==VyPicardEnum
-
+				name==DeviatoricStressxxEnum ||
+				name==DeviatoricStressyyEnum ||
+				name==DeviatoricStressxyEnum ||
+				name==DeviatoricStressxzEnum ||
+				name==DeviatoricStressyzEnum ||
+				name==DeviatoricStresszzEnum ||
+				name==DeviatoricStresseffectiveEnum ||
+				name==VxAverageEnum ||
+				name==VyAverageEnum
 				) {
 					return true;
@@ -1643,8 +2082,10 @@
 	IssmDouble* base     = xNew<IssmDouble>(numvertices);
 	IssmDouble* values   = xNew<IssmDouble>(numvertices);
-
-	parameters->FindParam(&deepwaterel,BasalforcingsDeepwaterElevationEnum);
-	parameters->FindParam(&upperwaterel,BasalforcingsUpperwaterElevationEnum);
-	parameters->FindParam(&deepwatermelt,BasalforcingsDeepwaterMeltingRateEnum);
+	IssmDouble time;
+
+	parameters->FindParam(&time,TimeEnum);
+	parameters->FindParam(&deepwaterel,BasalforcingsDeepwaterElevationEnum,time);
+	parameters->FindParam(&upperwaterel,BasalforcingsUpperwaterElevationEnum,time);
+	parameters->FindParam(&deepwatermelt,BasalforcingsDeepwaterMeltingRateEnum,time);
 
 	this->GetInputListOnVertices(base,BaseEnum);
@@ -1958,5 +2399,5 @@
 }
 /*}}}*/
-void       Element::PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm,bool ismungsm){/*{{{*/
+void       Element::PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm,bool ismungsm,bool issetpddfac){/*{{{*/
 
 	int  numvertices = this->GetNumberOfVertices();
@@ -1974,4 +2415,6 @@
 	IssmDouble* s0p=xNew<IssmDouble>(numvertices);
 	IssmDouble* s0t=xNew<IssmDouble>(numvertices);
+	IssmDouble pddsnowfac = -1.;
+	IssmDouble pddicefac = -1.;
 	IssmDouble rho_water,rho_ice,desfac,rlaps,rlapslgm;
 	IssmDouble PfacTime,TdiffTime,sealevTime;
@@ -2020,4 +2463,12 @@
 	}
 
+	/*Recover pdd factors at time t. 
+	 *     This parameter is set, if the user wants to define the 
+	 *     pdd factors regionally, if issetpddfac==1 in the d18opdd method */
+	if (issetpddfac==1){
+		input=this->GetInput(SmbPddfacSnowEnum); _assert_(input);
+		input2=this->GetInput(SmbPddfacIceEnum); _assert_(input2);
+	}
+
 	/*Recover info at the vertices: */
 	GetInputListOnVertices(&h[0],ThicknessEnum);
@@ -2028,8 +2479,13 @@
 	/*measure the surface mass balance*/
 	for (int iv = 0; iv<numvertices; iv++){
+		gauss->GaussVertex(iv);
+		pddsnowfac=-1.;
+		pddicefac=-1.;
+		input->GetInputValue(&pddsnowfac,gauss);
+		input2->GetInputValue(&pddicefac,gauss);
 		agd[iv]=PddSurfaceMassBalance(&monthlytemperatures[iv*12], &monthlyprec[iv*12],
 					pdds, pds, &melt[iv], &accu[iv], signorm, yts, h[iv], s[iv],
 					desfac, s0t[iv], s0p[iv],rlaps,rlapslgm,TdiffTime,sealevTime,
-					rho_water,rho_ice);
+					pddsnowfac,pddicefac,rho_water,rho_ice);
 		/*Get yearlytemperatures */
 		for(int month=0;month<12;month++) {
@@ -2179,6 +2635,10 @@
 					this->CalvingRateLevermann();
 					break;
-				case CalvingDevEnum:
-					this->CalvingRateDev();
+				case CalvingVonmisesEnum:
+				case CalvingDev2Enum:
+					this->CalvingRateVonmises();
+					break;
+				case CalvingCrevasseDepthEnum:
+					this->CalvingCrevasseDepth();
 					break;
 				default:
@@ -2188,4 +2648,6 @@
 		case StrainRateparallelEnum: this->StrainRateparallel(); break;
 		case StrainRateperpendicularEnum: this->StrainRateperpendicular(); break;
+		case SurfaceCrevasseEnum: this->CalvingCrevasseDepth(); break;
+		case SigmaVMEnum: this->CalvingRateVonmises(); break;
 	}
 
@@ -2344,28 +2806,52 @@
 
 	/*Intermediary variables: {{{*/
-	IssmDouble isinitialized;
-	IssmDouble zTop,dzTop,zMax,zMin,zY,dzMin;
-	IssmDouble Tmean; 
-	IssmDouble C; 
-	IssmDouble Tz,Vz; 
+	IssmDouble isinitialized=0.0;
+	IssmDouble zTop=0.0;
+	IssmDouble dzTop=0.0;
+	IssmDouble zMax=0.0;
+	IssmDouble zMin=0.0;
+	IssmDouble zY=0.0;
+	IssmDouble dzMin=0.0;
+	IssmDouble Tmean=0.0;
+	IssmDouble C=0.0;
+	IssmDouble Tz,Vz=0.0;
 	IssmDouble rho_ice, rho_water,aSnow,aIce;
 	IssmDouble time,dt;
 	IssmDouble t,smb_dt;
 	IssmDouble yts;
-	IssmDouble Ta,V,dlw,dsw,P,eAir,pAir;
+	IssmDouble Ta=0.0;
+	IssmDouble V=0.0;
+	IssmDouble dlw=0.0;
+	IssmDouble dsw=0.0;
+	IssmDouble P=0.0;
+	IssmDouble eAir=0.0;
+	IssmDouble pAir=0.0;
+	IssmDouble teValue=1.0;
+	IssmDouble aValue=0.0;
 	int        aIdx=0;
 	int        denIdx=0;
 	int        swIdx=0;
 	IssmDouble cldFrac,t0wet, t0dry, K;
-	IssmDouble ulw;
-	IssmDouble netSW;
-	IssmDouble netLW;
-	IssmDouble lhf, shf, dayEC;
-	IssmDouble initMass;
-	IssmDouble sumR, sumM, sumEC, sumP, sumW,sumMassAdd;
-	IssmDouble sumdz_add;
-	IssmDouble sumMass,dMass;
+	IssmDouble ulw=0.0;
+	IssmDouble netSW=0.0;
+	IssmDouble netLW=0.0;
+	IssmDouble lhf=0.0;
+	IssmDouble shf=0.0;
+	IssmDouble dayEC=0.0;
+	IssmDouble initMass=0.0;
+	IssmDouble sumR=0.0;
+	IssmDouble sumM=0.0;
+	IssmDouble sumEC=0.0;
+	IssmDouble sumP=0.0;
+	IssmDouble sumW=0.0;
+	IssmDouble sumMassAdd=0.0;
+	IssmDouble sumdz_add=0.0;
+	IssmDouble fac=0.0;
+	IssmDouble sumMass=0.0;
+	IssmDouble dMass=0.0;
 	bool isgraingrowth,isalbedo,isshortwave,isthermal,isaccumulation,ismelt,isdensification,isturbulentflux;
-	IssmDouble init_scaling;
+	IssmDouble init_scaling=0.0;
+	IssmDouble thermo_scaling=1.0;
+	IssmDouble adThresh=1023.0;
 
 	/*}}}*/
@@ -2376,15 +2862,15 @@
 	IssmDouble* gdn = NULL;
 	IssmDouble* gsp = NULL;
-	IssmDouble  EC = 0;
+	IssmDouble  EC = 0.0;
 	IssmDouble* W = NULL;
 	IssmDouble* a = NULL;
 	IssmDouble* swf=NULL;
 	IssmDouble* T = NULL;
-	IssmDouble  T_bottom;
-	IssmDouble  M;
-	IssmDouble  R; 
-	IssmDouble  mAdd;
-	IssmDouble  dz_add;
-    
+	IssmDouble  T_bottom = 0.0;
+	IssmDouble  M = 0.0;
+	IssmDouble  R = 0.0;
+	IssmDouble  mAdd = 0.0;
+	IssmDouble  dz_add = 0.0;
+
 	IssmDouble* dzini=NULL;
 	IssmDouble* dini = NULL;
@@ -2395,6 +2881,6 @@
 	IssmDouble* aini = NULL;
 	IssmDouble* Tini = NULL;
-    
-	int         m;
+
+	int         m=0;
 	int         count=0;
 	/*}}}*/
@@ -2429,5 +2915,7 @@
 	parameters->FindParam(&isturbulentflux,SmbIsturbulentfluxEnum);
 	parameters->FindParam(&init_scaling,SmbInitDensityScalingEnum);
-    
+	parameters->FindParam(&thermo_scaling,SmbThermoDeltaTScalingEnum);
+	parameters->FindParam(&adThresh,SmbAdThreshEnum);
+
 	/*}}}*/
 	/*Retrieve inputs: {{{*/
@@ -2449,4 +2937,6 @@
 	Input* eAir_input=this->GetInput(SmbEAirEnum); _assert_(eAir_input);
 	Input* pAir_input=this->GetInput(SmbPAirEnum); _assert_(pAir_input);
+	Input* teValue_input=this->GetInput(SmbTeValueEnum); _assert_(teValue_input);
+	Input* aValue_input=this->GetInput(SmbAValueEnum); _assert_(aValue_input);
 	Input* isinitialized_input=this->GetInput(SmbIsInitializedEnum); _assert_(isinitialized_input);
 	/*Retrieve input values:*/
@@ -2463,4 +2953,6 @@
 	Tz_input->GetInputValue(&Tz,gauss);
 	Vz_input->GetInputValue(&Vz,gauss);
+	teValue_input->GetInputValue(&teValue,gauss);
+	aValue_input->GetInputValue(&aValue,gauss);
 	isinitialized_input->GetInputValue(&isinitialized);
 	/*}}}*/
@@ -2468,102 +2960,103 @@
 	/*First, check that the initial structures have been setup in GEMB. If not, initialize profile variables: layer thickness dz, * density d, temperature T, etc. {{{*/
 	if(isinitialized==0.0){
-        if(VerboseSmb() && this->Sid()==0)_printf0_("smb core: Initializing grid\n");
-        //if(this->Sid()==1) for(int i=0;i<m;i++)_printf_("z[" << i << "]=" <<
-        //dz[i] << "\n");
-        
-        DoubleArrayInput* dz_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbDziniEnum)); _assert_(dz_input);
-        DoubleArrayInput* d_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbDiniEnum));_assert_(d_input);
-        DoubleArrayInput* re_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbReiniEnum));_assert_(re_input);
-        DoubleArrayInput* gdn_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbGdniniEnum));_assert_(gdn_input);
-        DoubleArrayInput* gsp_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbGspiniEnum));_assert_(gsp_input);
-        DoubleInput* EC_input= dynamic_cast<DoubleInput*>(this->GetInput(SmbECiniEnum));_assert_(EC_input);
-        DoubleArrayInput* W_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbWiniEnum));_assert_(W_input);
-        DoubleArrayInput* a_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbAiniEnum));_assert_(a_input);
-        DoubleArrayInput* T_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbTiniEnum));_assert_(T_input);
-
-        dz_input->GetValues(&dzini,&m);
-        d_input->GetValues(&dini,&m);
-        re_input->GetValues(&reini,&m);
-        gdn_input->GetValues(&gdnini,&m);
-        gsp_input->GetValues(&gspini,&m);
-        EC_input->GetInputValue(&EC);
-        W_input->GetValues(&Wini,&m);
-        a_input->GetValues(&aini,&m);
-        T_input->GetValues(&Tini,&m);
-        
-        /*Retrive the correct value of m (without the zeroes at the end)*/
-        Input* Size_input=this->GetInput(SmbSizeiniEnum); _assert_(Size_input);
-        Size_input->GetInputValue(&m);
-        
-        if(m==2){ //Snow properties are initialized with default values. Vertical grid has to be initialized too
-//            if(VerboseSmb() && this->Sid()==0)_printf0_("Snow properties initialized w DEFAULT values\n");
-            
-            /*initialize profile variables:*/
-            GembgridInitialize(&dz, &m, zTop, dzTop, zMax, zY);
-            
-            d = xNewZeroInit<IssmDouble>(m); for(int i=0;i<m;i++)d[i]=dini[0]; //ice density [kg m-3]
-            re = xNewZeroInit<IssmDouble>(m); for(int i=0;i<m;i++)re[i]=reini[0];         //set grain size to old snow [mm]
-            gdn = xNewZeroInit<IssmDouble>(m); for(int i=0;i<m;i++)gdn[i]=gdnini[0];         //set grain dentricity to old snow
-            gsp = xNewZeroInit<IssmDouble>(m); for(int i=0;i<m;i++)gsp[i]=gspini[0];         //set grain sphericity to old snow
-            W = xNewZeroInit<IssmDouble>(m); for(int i=0;i<m;i++)W[i]=Wini[0];             //set water content to zero [kg m-2]
-            a = xNewZeroInit<IssmDouble>(m); for(int i=0;i<m;i++)a[i]=aini[0];         //set albedo equal to fresh snow [fraction]
-            T = xNewZeroInit<IssmDouble>(m); for(int i=0;i<m;i++)T[i]=Tmean;         //set initial grid cell temperature to the annual mean temperature [K]
-/*            /!\ Default value of T can not be retrived from SMBgemb.m (like other snow properties) because don't know Tmean yet when set default values.
-            Default value of 0C given in SMBgemb.m is overwritten here with value of Tmean*/
-            
-            //fixed lower temperature bounday condition - T is fixed
-            T_bottom=T[m-1];
-        }
-        else{ //Retrieve snow properties from previous run. Need to provide values for all layers
-//            if(VerboseSmb() && this->Sid()==0)_printf0_("Snow properties initialized w RESTART values\n");
-            
-            dz = xNewZeroInit<IssmDouble>(m);for(int i=0;i<m;i++)dz[i]=dzini[i];
-            d = xNewZeroInit<IssmDouble>(m);for(int i=0;i<m;i++)d[i]=dini[i];
-            re = xNewZeroInit<IssmDouble>(m);for(int i=0;i<m;i++)re[i]=reini[i];
-            gdn = xNewZeroInit<IssmDouble>(m);for(int i=0;i<m;i++)gdn[i]=gdnini[i];
-            gsp = xNewZeroInit<IssmDouble>(m);for(int i=0;i<m;i++)gsp[i]=gspini[i];
-            W = xNewZeroInit<IssmDouble>(m);for(int i=0;i<m;i++)W[i]=Wini[i];
-            a = xNewZeroInit<IssmDouble>(m);for(int i=0;i<m;i++)a[i]=aini[i];
-            T = xNewZeroInit<IssmDouble>(m);for(int i=0;i<m;i++)T[i]=Tini[i];
-
-            //fixed lower temperature bounday condition - T is fixed
-            T_bottom=T[m-1];
-        }
-        
-        /*Flag the initialization:*/
-        this->AddInput(new DoubleInput(SmbIsInitializedEnum,1.0));
-    }
-    else{
-        /*Recover inputs: */
-        DoubleArrayInput* dz_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbDzEnum)); _assert_(dz_input);
-        DoubleArrayInput* d_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbDEnum));_assert_(d_input);
-        DoubleArrayInput* re_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbReEnum));_assert_(re_input);
-        DoubleArrayInput* gdn_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbGdnEnum));_assert_(gdn_input);
-        DoubleArrayInput* gsp_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbGspEnum));_assert_(gsp_input);
-        DoubleInput* EC_input= dynamic_cast<DoubleInput*>(this->GetInput(SmbECEnum));_assert_(EC_input);
-        DoubleArrayInput* W_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbWEnum));_assert_(W_input);
-        DoubleArrayInput* a_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbAEnum));_assert_(a_input);
-        DoubleArrayInput* T_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbTEnum));_assert_(T_input);
-
-        /*Recover arrays: */
-        dz_input->GetValues(&dz,&m);
-        d_input->GetValues(&d,&m);
-        re_input->GetValues(&re,&m);
-        gdn_input->GetValues(&gdn,&m);
-        gsp_input->GetValues(&gsp,&m);
-        EC_input->GetInputValue(&EC);
-        W_input->GetValues(&W,&m);
-        a_input->GetValues(&a,&m);
-        T_input->GetValues(&T,&m);
-
-        //fixed lower temperature bounday condition - T is fixed
-        T_bottom=T[m-1];
-
-    } /*}}}*/
+		if(VerboseSmb() && this->Sid()==0)_printf0_("smb core: Initializing grid\n");
+		//if(this->Sid()==1) for(int i=0;i<m;i++)_printf_("z[" << i << "]=" <<
+		//dz[i] << "\n");
+
+		DoubleArrayInput* dz_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbDziniEnum)); _assert_(dz_input);
+		DoubleArrayInput* d_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbDiniEnum));_assert_(d_input);
+		DoubleArrayInput* re_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbReiniEnum));_assert_(re_input);
+		DoubleArrayInput* gdn_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbGdniniEnum));_assert_(gdn_input);
+		DoubleArrayInput* gsp_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbGspiniEnum));_assert_(gsp_input);
+		DoubleInput* EC_input= dynamic_cast<DoubleInput*>(this->GetInput(SmbECiniEnum));_assert_(EC_input);
+		DoubleArrayInput* W_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbWiniEnum));_assert_(W_input);
+		DoubleArrayInput* a_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbAiniEnum));_assert_(a_input);
+		DoubleArrayInput* T_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbTiniEnum));_assert_(T_input);
+
+		dz_input->GetValues(&dzini,&m);
+		d_input->GetValues(&dini,&m);
+		re_input->GetValues(&reini,&m);
+		gdn_input->GetValues(&gdnini,&m);
+		gsp_input->GetValues(&gspini,&m);
+		EC_input->GetInputValue(&EC);
+		W_input->GetValues(&Wini,&m);
+		a_input->GetValues(&aini,&m);
+		T_input->GetValues(&Tini,&m);
+
+		/*Retrive the correct value of m (without the zeroes at the end)*/
+		Input* Size_input=this->GetInput(SmbSizeiniEnum); _assert_(Size_input);
+		Size_input->GetInputValue(&m);
+
+		if(m==2){ //Snow properties are initialized with default values. Vertical grid has to be initialized too
+			//            if(VerboseSmb() && this->Sid()==0)_printf0_("Snow properties initialized w DEFAULT values\n");
+
+			/*initialize profile variables:*/
+			GembgridInitialize(&dz, &m, zTop, dzTop, zMax, zY);
+
+			d = xNewZeroInit<IssmDouble>(m); for(int i=0;i<m;i++)d[i]=dini[0]; //ice density [kg m-3]
+			re = xNewZeroInit<IssmDouble>(m); for(int i=0;i<m;i++)re[i]=reini[0];         //set grain size to old snow [mm]
+			gdn = xNewZeroInit<IssmDouble>(m); for(int i=0;i<m;i++)gdn[i]=gdnini[0];         //set grain dentricity to old snow
+			gsp = xNewZeroInit<IssmDouble>(m); for(int i=0;i<m;i++)gsp[i]=gspini[0];         //set grain sphericity to old snow
+			W = xNewZeroInit<IssmDouble>(m); for(int i=0;i<m;i++)W[i]=Wini[0];             //set water content to zero [kg m-2]
+			a = xNewZeroInit<IssmDouble>(m); for(int i=0;i<m;i++)a[i]=aini[0];         //set albedo equal to fresh snow [fraction]
+			T = xNewZeroInit<IssmDouble>(m); for(int i=0;i<m;i++)T[i]=Tmean;         //set initial grid cell temperature to the annual mean temperature [K]
+			/*/!\ Default value of T can not be retrived from SMBgemb.m (like other snow properties) 
+			 *    because don't know Tmean yet when set default values.
+			 *    Default value of 0C given in SMBgemb.m is overwritten here with value of Tmean*/
+
+			//fixed lower temperature bounday condition - T is fixed
+			T_bottom=T[m-1];
+		}
+		else{ //Retrieve snow properties from previous run. Need to provide values for all layers
+			//            if(VerboseSmb() && this->Sid()==0)_printf0_("Snow properties initialized w RESTART values\n");
+
+			dz = xNewZeroInit<IssmDouble>(m);for(int i=0;i<m;i++)dz[i]=dzini[i];
+			d = xNewZeroInit<IssmDouble>(m);for(int i=0;i<m;i++)d[i]=dini[i];
+			re = xNewZeroInit<IssmDouble>(m);for(int i=0;i<m;i++)re[i]=reini[i];
+			gdn = xNewZeroInit<IssmDouble>(m);for(int i=0;i<m;i++)gdn[i]=gdnini[i];
+			gsp = xNewZeroInit<IssmDouble>(m);for(int i=0;i<m;i++)gsp[i]=gspini[i];
+			W = xNewZeroInit<IssmDouble>(m);for(int i=0;i<m;i++)W[i]=Wini[i];
+			a = xNewZeroInit<IssmDouble>(m);for(int i=0;i<m;i++)a[i]=aini[i];
+			T = xNewZeroInit<IssmDouble>(m);for(int i=0;i<m;i++)T[i]=Tini[i];
+
+			//fixed lower temperature bounday condition - T is fixed
+			T_bottom=T[m-1];
+		}
+
+		/*Flag the initialization:*/
+		this->AddInput(new DoubleInput(SmbIsInitializedEnum,1.0));
+	}
+	else{
+		/*Recover inputs: */
+		DoubleArrayInput* dz_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbDzEnum)); _assert_(dz_input);
+		DoubleArrayInput* d_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbDEnum));_assert_(d_input);
+		DoubleArrayInput* re_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbReEnum));_assert_(re_input);
+		DoubleArrayInput* gdn_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbGdnEnum));_assert_(gdn_input);
+		DoubleArrayInput* gsp_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbGspEnum));_assert_(gsp_input);
+		DoubleInput* EC_input= dynamic_cast<DoubleInput*>(this->GetInput(SmbECEnum));_assert_(EC_input);
+		DoubleArrayInput* W_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbWEnum));_assert_(W_input);
+		DoubleArrayInput* a_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbAEnum));_assert_(a_input);
+		DoubleArrayInput* T_input= dynamic_cast<DoubleArrayInput*>(this->GetInput(SmbTEnum));_assert_(T_input);
+
+		/*Recover arrays: */
+		dz_input->GetValues(&dz,&m);
+		d_input->GetValues(&d,&m);
+		re_input->GetValues(&re,&m);
+		gdn_input->GetValues(&gdn,&m);
+		gsp_input->GetValues(&gsp,&m);
+		EC_input->GetInputValue(&EC);
+		W_input->GetValues(&W,&m);
+		a_input->GetValues(&a,&m);
+		T_input->GetValues(&T,&m);
+
+		//fixed lower temperature bounday condition - T is fixed
+		T_bottom=T[m-1];
+
+	} /*}}}*/
 
 	// determine initial mass [kg]
 	initMass=0; for(int i=0;i<m;i++) initMass += dz[i]*d[i] + W[i];
-    
-        // initialize cumulative variables
+
+	// initialize cumulative variables
 	sumR = 0; sumM = 0; sumEC = 0; sumP = 0; sumMassAdd = 0;
 	sumdz_add=0;
@@ -2587,62 +3080,66 @@
 		eAir_input->GetInputValue(&eAir,gauss,t);  //screen level vapor pressure [Pa]
 		pAir_input->GetInputValue(&pAir,gauss,t);  // screen level air pressure [Pa]
+		teValue_input->GetInputValue(&teValue,gauss);  // screen level air pressure [Pa]
+		aValue_input->GetInputValue(&aValue,gauss);  // screen level air pressure [Pa]
 		//_printf_("Time: " << t << " Ta: " << Ta << " V: " << V << " dlw: " << dlw << " dsw: " << dsw << " P: " << P << " eAir: " << eAir << " pAir: " << pAir << "\n");
 		/*}}}*/
 
 		/*Snow grain metamorphism:*/
-		if(isgraingrowth)grainGrowth(re, gdn, gsp, T, dz, d, W, smb_dt, m, aIdx,this->Sid());
+		if(isgraingrowth)grainGrowth(&re, &gdn, &gsp, T, dz, d, W, smb_dt, m, aIdx,this->Sid());
 
 		/*Snow, firn and ice albedo:*/
-		if(isalbedo)albedo(a,aIdx,re,d,cldFrac,aIce, aSnow,T,W,P,EC,t0wet,t0dry,K,smb_dt,m,this->Sid());
-		
-					
+		if(isalbedo)albedo(&a,aIdx,re,d,cldFrac,aIce,aSnow,aValue,adThresh,T,W,P,EC,t0wet,t0dry,K,smb_dt,rho_ice,m,this->Sid());
+
+
 		/*Distribution of absorbed short wave radation with depth:*/
-		if(isshortwave)shortwave(&swf, swIdx, aIdx, dsw, a[0], d, dz, re,m,this->Sid());
-		
+		if(isshortwave)shortwave(&swf, swIdx, aIdx, dsw, a[0], d, dz, re,rho_ice,m,this->Sid());
+
 		/*Calculate net shortwave [W m-2]*/
 		netSW = cellsum(swf,m);
 
 		/*Thermal profile computation:*/
-		if(isthermal)thermo(&EC, T, dz, d, swf, dlw, Ta, V, eAir, pAir, W[0], smb_dt, m, Vz, Tz,this->Sid());
+		if(isthermal)thermo(&EC, &T, dz, d, swf, dlw, Ta, V, eAir, pAir, teValue, W[0], smb_dt, m, Vz, Tz, thermo_scaling,rho_ice,this->Sid());
 
 		/*Change in thickness of top cell due to evaporation/condensation  assuming same density as top cell. 
 		 * need to fix this in case all or more of cell evaporates */
 		dz[0] = dz[0] + EC / d[0];
-		
+
 		/*Add snow/rain to top grid cell adjusting cell depth, temperature and density*/
-		if(isaccumulation)accumulation(&T, &dz, &d, &W, &a, &re, &gdn, &gsp, &m, Ta, P, dzMin, aSnow,this->Sid());
+		if(isaccumulation)accumulation(&T, &dz, &d, &W, &a, &re, &gdn, &gsp, &m, aIdx, Ta, P, dzMin, aSnow,rho_ice,this->Sid());
 
 		/*Calculate water production, M [kg m-2] resulting from snow/ice temperature exceeding 273.15 deg K
 		 * (> 0 deg C), runoff R [kg m-2] and resulting changes in density and determine wet compaction [m]*/
-		if(ismelt)melt(&M, &R, &mAdd, &dz_add, &T, &d, &dz, &W, &a, &re, &gdn, &gsp, &m, dzMin, zMax, zMin, zTop,this->Sid());
+		if(ismelt)melt(&M, &R, &mAdd, &dz_add, &T, &d, &dz, &W, &a, &re, &gdn, &gsp, &m, dzMin, zMax, zMin, zTop,rho_ice,this->Sid());
 
 		/*Allow non-melt densification and determine compaction [m]*/
-		if(isdensification)densification(d,dz, T, re, denIdx, C, smb_dt, Tmean,rho_ice,m,this->Sid());
-		
+		if(isdensification)densification(&d,&dz, T, re, denIdx, C, smb_dt, Tmean,rho_ice,m,this->Sid());
+
 		/*Calculate upward longwave radiation flux [W m-2] not used in energy balance. Calculated for every 
 		 * sub-time step in thermo equations*/
-		ulw = 5.67E-8 * pow(T[0],4.0);
+		ulw = 5.67E-8 * pow(T[0],4.0) * teValue;
 
 		/*Calculate net longwave [W m-2]*/
 		netLW = dlw - ulw;
-		
+
 		/*Calculate turbulent heat fluxes [W m-2]*/
-		if(isturbulentflux)turbulentFlux(&shf, &lhf, &dayEC, Ta, T[0], V, eAir, pAir, d[0], W[0], Vz, Tz,this->Sid());
-		
-		/*Verbose some resuls in debug mode: {{{*/
+		if(isturbulentflux)turbulentFlux(&shf, &lhf, &dayEC, Ta, T[0], V, eAir, pAir, d[0], W[0], Vz, Tz,rho_ice,this->Sid());
+
+		/*Verbose some results in debug mode: {{{*/
 		if(VerboseSmb() && 0){ 
 			_printf_("smb log: count[" << count << "] m[" << m << "] " 
-				<< setprecision(16)   << "T[" << cellsum(T,m)  << "] " 
-					                  << "d[" << cellsum(d,m)  << "] "
-					                  << "dz[" << cellsum(dz,m)  << "] "
-					                  << "a[" << cellsum(a,m)  << "] "
-					                  << "W[" << cellsum(W,m)  << "] "
-					                  << "re[" << cellsum(re,m)  << "] "
-					                  << "gdn[" << cellsum(gdn,m)  << "] "
-					                  << "gsp[" << cellsum(gsp,m)  << "] "
-					                  << "swf[" << netSW << "] "
-									  << "\n");
+						<< setprecision(16)   << "T[" << cellsum(T,m)  << "] " 
+						<< "d[" << cellsum(d,m)  << "] "
+						<< "dz[" << cellsum(dz,m)  << "] "
+						<< "a[" << cellsum(a,m)  << "] "
+						<< "W[" << cellsum(W,m)  << "] "
+						<< "re[" << cellsum(re,m)  << "] "
+						<< "gdn[" << cellsum(gdn,m)  << "] "
+						<< "gsp[" << cellsum(gsp,m)  << "] "
+						<< "swf[" << netSW << "] "
+						<< "a[" << a << "] "
+						<< "te[" << teValue << "] "
+						<< "\n");
 		} /*}}}*/
-		
+
 		/*Sum component mass changes [kg m-2]*/
 		sumMassAdd = mAdd + sumMassAdd;
@@ -2652,8 +3149,12 @@
 		sumP = P +  sumP;
 		sumEC = sumEC + EC;  // evap (-)/cond(+)
-		sumdz_add=dz_add+sumdz_add;
 
 		/*Calculate total system mass:*/
-		sumMass=0; for(int i=0;i<m;i++) sumMass += dz[i]*d[i];
+		sumMass=0; 
+		fac=0;
+		for(int i=0;i<m;i++){
+			sumMass += dz[i]*d[i];
+			fac += dz[i]*(rho_ice - fmin(d[i],rho_ice));
+		}
 
 		#ifndef _HAVE_ADOLC_ //we want to avoid the round operation at all cost. Not differentiable.
@@ -2664,8 +3165,8 @@
 		if (dMass != 0.0) _printf_("total system mass not conserved in MB function \n");
 		#endif
-		
+
 		/*Check bottom grid cell T is unchanged:*/
 		if (T[m-1]!=T_bottom) _printf_("T(end)~=T_bottom" << "\n");
-		
+
 		/*Free ressources: */
 		xDelete<IssmDouble>(swf);
@@ -2682,30 +3183,32 @@
 	this->AddInput(new DoubleArrayInput(SmbGspEnum,gsp,m));
 	this->AddInput(new DoubleArrayInput(SmbTEnum,T,m));
-	this->AddInput(new DoubleInput(SmbECEnum,sumEC/yts));
+	this->AddInput(new DoubleInput(SmbECEnum,sumEC/dt/rho_ice));
 	this->AddInput(new DoubleArrayInput(SmbWEnum,W,m));
 	this->AddInput(new DoubleArrayInput(SmbAEnum,a,m));
-	this->AddInput(new DoubleInput(SmbMassBalanceEnum,(sumP + sumEC -sumR)/yts));
-	this->AddInput(new DoubleInput(SmbRunoffEnum,sumR/yts));
-	this->AddInput(new DoubleInput(SmbPrecipitationEnum,sumP/yts));
-	this->AddInput(new DoubleInput(SmbDz_addEnum,sumdz_add/yts));
-	this->AddInput(new DoubleInput(SmbM_addEnum,sumMassAdd/yts));
+	this->AddInput(new DoubleInput(SmbMassBalanceEnum,(sumP + sumEC -sumR)/dt/rho_ice));
+	this->AddInput(new DoubleInput(SmbMeltEnum,sumM/dt/rho_ice));
+	this->AddInput(new DoubleInput(SmbRunoffEnum,sumR/dt/rho_ice));
+	this->AddInput(new DoubleInput(SmbPrecipitationEnum,sumP/dt/rho_ice));
+	this->AddInput(new DoubleInput(SmbDzAddEnum,sumdz_add));
+	this->AddInput(new DoubleInput(SmbMAddEnum,sumMassAdd/dt));
+	this->AddInput(new DoubleInput(SmbFACEnum,fac/1000)); // output in meters
 
 	/*Free allocations:{{{*/
-	xDelete<IssmDouble>(dz);
-	xDelete<IssmDouble>(d);
-	xDelete<IssmDouble>(re);
-	xDelete<IssmDouble>(gdn);
-	xDelete<IssmDouble>(gsp);
-	xDelete<IssmDouble>(W);
-	xDelete<IssmDouble>(a);
-	xDelete<IssmDouble>(T);
-	xDelete<IssmDouble>(dzini);
-	xDelete<IssmDouble>(dini);
-	xDelete<IssmDouble>(reini);
-	xDelete<IssmDouble>(gdnini);
-	xDelete<IssmDouble>(gspini);
-	xDelete<IssmDouble>(Wini);
-	xDelete<IssmDouble>(aini);
-	xDelete<IssmDouble>(Tini);
+	if(dz) xDelete<IssmDouble>(dz);
+	if(d) xDelete<IssmDouble>(d);
+	if(re) xDelete<IssmDouble>(re);
+	if(gdn) xDelete<IssmDouble>(gdn);
+	if(gsp) xDelete<IssmDouble>(gsp);
+	if(W) xDelete<IssmDouble>(W);
+	if(a) xDelete<IssmDouble>(a);
+	if(T) xDelete<IssmDouble>(T);
+	if(dzini) xDelete<IssmDouble>(dzini);
+	if(dini) xDelete<IssmDouble>(dini);
+	if(reini) xDelete<IssmDouble>(reini);
+	if(gdnini) xDelete<IssmDouble>(gdnini);
+	if(gspini) xDelete<IssmDouble>(gspini);
+	if(Wini) xDelete<IssmDouble>(Wini);
+	if(aini) xDelete<IssmDouble>(aini);
+	if(Tini) xDelete<IssmDouble>(Tini);
 
 	delete gauss;
@@ -2943,4 +3446,43 @@
 	return this->matpar->TMeltingPoint(pressure);
 }/*}}}*/
+IssmDouble Element::TotalFloatingBmb(IssmDouble* mask, bool scaled){/*{{{*/
+
+	/*Retrieve values of the mask defining the element: */
+	for(int i=0;i<this->GetNumberOfVertices();i++){
+		if(mask[this->vertices[i]->Sid()]<=0.){
+			return 0.;
+		}
+	}
+
+	/*Return: */
+	return this->TotalFloatingBmb(scaled);
+}
+/*}}}*/
+IssmDouble Element::TotalGroundedBmb(IssmDouble* mask, bool scaled){/*{{{*/
+
+	/*Retrieve values of the mask defining the element: */
+	for(int i=0;i<this->GetNumberOfVertices();i++){
+		if(mask[this->vertices[i]->Sid()]<=0.){
+			return 0.;
+		}
+	}
+
+	/*Return: */
+	return this->TotalGroundedBmb(scaled);
+}
+/*}}}*/
+IssmDouble Element::TotalSmb(IssmDouble* mask, bool scaled){/*{{{*/
+
+	/*Retrieve values of the mask defining the element: */
+	for(int i=0;i<this->GetNumberOfVertices();i++){
+		if(mask[this->vertices[i]->Sid()]<=0.){
+			return 0.;
+		}
+	}
+
+	/*Return: */
+	return this->TotalSmb(scaled);
+}
+/*}}}*/
 void       Element::TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,int transformenum){/*{{{*/
 
@@ -3170,6 +3712,4 @@
 	/*Intermediaries*/
 	IssmDouble phi;
-	IssmDouble viscosity;
-	IssmDouble epsilon[6];
 	IssmDouble thickness;
 	IssmDouble *xyz_list = NULL;
@@ -3180,9 +3720,8 @@
 
 	/*Retrieve all inputs and parameters*/
-	this->GetVerticesCoordinatesBase(&xyz_list);
+	this->GetVerticesCoordinates(&xyz_list);
 	Input* vx_input        = this->GetInput(VxEnum); _assert_(vx_input);
 	Input* vy_input        = this->GetInput(VyEnum); _assert_(vy_input);
 	Input* vz_input        = this->GetInput(VzEnum); _assert_(vz_input);
-	Input* thickness_input = this->GetInput(ThicknessEnum); _assert_(thickness_input);
 
 	/*loop over vertices: */
@@ -3191,11 +3730,7 @@
 		gauss->GaussVertex(iv);
 
-		thickness_input->GetInputValue(&thickness,gauss);
-
-		this->StrainRateFS(&epsilon[0],xyz_list,gauss,vx_input,vy_input,vz_input);
-		this->material->ViscosityFS(&viscosity,3,xyz_list,gauss,vx_input,vy_input,vz_input);
-		this->GetPhi(&phi,&epsilon[0],viscosity);
-
-		viscousheating[iv]=phi*thickness;
+		this->ViscousHeating(&phi,xyz_list,gauss,vx_input,vy_input,vz_input);
+
+		viscousheating[iv]=phi;
 	}
 
Index: /issm/trunk/src/c/classes/Elements/Element.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/Element.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Elements/Element.h	(revision 22758)
@@ -81,4 +81,5 @@
 		void               FindParam(IssmDouble* pvalue,int paramenum);
 		void               FindParam(int** pvalues,int* psize,int paramenum);
+		IssmDouble         FloatingArea(IssmDouble* mask, bool scaled);
 		void	             GetDofList(int** pdoflist,int approximation_enum,int setenum);
 		void	             GetDofListPressure(int** pdoflist,int setenum);
@@ -97,7 +98,9 @@
 		void               GetInputsInterpolations(Vector<IssmDouble>* interps);
 		IssmDouble         GetMaterialParameter(int enum_in);
+		int                GetIntegerMaterialParameter(int enum_in);
 		void               GetNodesLidList(int* lidlist);
 		void               GetNodesSidList(int* sidlist);
 		void               GetPhi(IssmDouble* phi, IssmDouble*  epsilon, IssmDouble viscosity);
+		void               GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution,int solutionenum);
 		void               GetVectorFromInputs(Vector<IssmDouble>* vector, int name_enum, int type);
 		void	             GetVertexPidList(int* pidlist);
@@ -109,9 +112,16 @@
 		IssmDouble         GetZcoord(IssmDouble* xyz_list,Gauss* gauss);
 		void               GradientIndexing(int* indexing,int control_index,bool onsid=false);
+		IssmDouble         GroundedArea(IssmDouble* mask, bool scaled);
 		bool               HasNodeOnBase();
 		bool               HasNodeOnSurface();
+		IssmDouble         IceMass(bool scaled);
+		IssmDouble         IceMass(IssmDouble* mask, bool scaled);
+		IssmDouble         IceVolume(IssmDouble* mask, bool scaled);
+		IssmDouble         IceVolumeAboveFloatation(IssmDouble* mask, bool scaled);
 		int                Id();
 		void               InputChangeName(int enum_type,int enum_type_old);
 		void               InputCreate(IssmDouble* vector,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code);
+		void               ControlInputCreate(IssmDouble* doublearray,IssmDouble* independents_min,IssmDouble* independents_max,IoModel* iomodel,int M,int N,int input_enum,int id);
+		void					 DatasetInputAdd(int enum_type,IssmDouble* vector,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code,int input_enum);
 		void               InputDuplicate(int original_enum,int new_enum);
 		void               InputUpdateFromConstant(IssmDouble constant, int name);
@@ -132,5 +142,5 @@
 		ElementMatrix*     NewElementMatrixCoupling(int number_nodes,int approximation_enum=NoneApproximationEnum);
 		ElementVector*     NewElementVector(int approximation_enum=NoneApproximationEnum);
-		void               PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm,bool ismungsm);
+		void               PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm,bool ismungsm,bool issetpddfac);
 		IssmDouble         PureIceEnthalpy(IssmDouble pressure);
 		void               ResultInterpolation(int* pinterpolation,int*nodesperelement,int* parray_size, int output_enum);
@@ -150,4 +160,7 @@
 		void               ThermalToEnthalpy(IssmDouble* penthalpy,IssmDouble temperature,IssmDouble waterfraction,IssmDouble pressure);
 		IssmDouble         TMeltingPoint(IssmDouble pressure);
+		IssmDouble         TotalFloatingBmb(IssmDouble* mask, bool scaled);
+		IssmDouble         TotalGroundedBmb(IssmDouble* mask, bool scaled);
+		IssmDouble         TotalSmb(IssmDouble* mask, bool scaled);
 		void               TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,int cs_enum);
 		void               TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int cs_enum);
@@ -175,7 +188,10 @@
 		virtual void       AddBasalInput(int input_enum, IssmDouble* values, int interpolation_enum)=0;
 		virtual void       AddInput(int input_enum, IssmDouble* values, int interpolation_enum)=0;
+		virtual void       AddControlInput(int input_enum, IssmDouble* values,IssmDouble* values_min,IssmDouble* values_max, int interpolation_enum,int id){_error_("not supported yet");};
+		virtual void       DatasetInputCreate(IssmDouble* array,int M,int N,int* individual_enums,int num_inputs,IoModel* iomodel,int input_enum){_error_("not supported");};
 		virtual void       AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part)=0;
 		virtual void		 BasalNodeIndices(int* pnumindices,int** pindices,int finiteelement){_error_("not implemented yet");};
-		virtual void       CalvingRateDev(void){_error_("not implemented yet");};
+		virtual void       CalvingRateVonmises(void){_error_("not implemented yet");};
+		virtual void       CalvingCrevasseDepth(void){_error_("not implemented yet");};
 		virtual void	    CalvingRateLevermann(void)=0;
 		virtual IssmDouble CharacteristicLength(void)=0;
@@ -186,13 +202,16 @@
 		virtual void       ComputeEsaStrainAndVorticity(void)=0;
 		virtual void       Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters)=0;
+		virtual void       ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index,int offset,int N,int M)=0;
 		virtual void       ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index)=0;
 		virtual void       ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum)=0;
+		virtual void       CreateDistanceInputFromSegmentlist(IssmDouble* segments,int numsegments,int distanceenum){_error_("not implemented yet");};
 		virtual void       ElementResponse(IssmDouble* presponse,int response_enum)=0;
 		virtual void       ElementSizes(IssmDouble* phx,IssmDouble* phy,IssmDouble* phz)=0;
 		virtual int        FiniteElement(void)=0;
-		virtual IssmDouble FloatingArea(void)=0;
+		virtual IssmDouble FloatingArea(bool scaled)=0;
 		virtual void       FSContactMigration(Vector<IssmDouble>* vertexgrounded,Vector<IssmDouble>* vertexfloating)=0;
 		virtual Element*   GetBasalElement(void)=0;
 		virtual int        GetElementType(void)=0;
+		virtual IssmDouble GetHorizontalSurfaceArea(void){_error_("not implemented");};
 		virtual void       GetGroundedPart(int* point1,IssmDouble* fraction1,IssmDouble* fraction2, bool* mainlyfloating)=0;
 		virtual IssmDouble GetGroundedPortion(IssmDouble* xyz_list)=0;
@@ -206,17 +225,13 @@
 		virtual int        GetNumberOfNodes(int enum_type)=0;
 		virtual int        GetNumberOfVertices(void)=0;
-		virtual void       GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution,int solutionenum)=0;
-		virtual Element*   GetUpperElement(void)=0;
-		virtual void       GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data,bool onsid)=0;
+		virtual void       GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data,int offset, bool onsid)=0;
+		virtual void       GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data, bool onsid)=0;
 		virtual void       GetVerticesCoordinatesBase(IssmDouble** xyz_list)=0;
 		virtual void       GetVerticesCoordinatesTop(IssmDouble** xyz_list)=0;
-		virtual IssmDouble GroundedArea(void)=0;
-		virtual IssmDouble IceMass(void)=0;
-		virtual IssmDouble IceVolume(void)=0;
-		virtual IssmDouble IceVolumeAboveFloatation(void)=0;
-		virtual void       InputControlUpdate(IssmDouble scalar,bool save_parameter)=0;
+		virtual IssmDouble GroundedArea(bool scaled)=0;
+		virtual IssmDouble IceVolume(bool scaled)=0;
+		virtual IssmDouble IceVolumeAboveFloatation(bool scaled)=0;
 		virtual void       InputDepthAverageAtBase(int enum_type,int average_enum_type)=0;
 		virtual void       InputExtrude(int input_enum,int start)=0;
-		virtual void       InputScale(int enum_type,IssmDouble scale_factor)=0;
 		virtual void       InputUpdateFromSolutionOneDofCollapsed(IssmDouble* solution,int inputenum)=0;
 		virtual void       InputUpdateFromSolutionOneDof(IssmDouble* solution,int inputenum)=0;
@@ -244,4 +259,5 @@
       virtual Gauss*     NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order_horiz,int order_vert)=0;
       virtual Gauss*     NewGauss(int point1,IssmDouble fraction1,IssmDouble fraction2,bool mainlyfloating,int order)=0;
+      virtual Gauss*     NewGauss(int point1,IssmDouble fraction1,IssmDouble fraction2,int order)=0;
 		virtual Gauss*     NewGaussBase(int order)=0;
 		virtual Gauss*     NewGaussLine(int vertex1,int vertex2,int order)=0;
@@ -263,4 +279,6 @@
 		virtual int        NumberofNodesPressure(void)=0;
 		virtual int        NumberofNodesVelocity(void)=0;
+		virtual void       PicoUpdateBoxid(int* pmax_boxid_basin)=0;
+		virtual void       PicoUpdateBox(int loopboxid)=0;
 		virtual void       PotentialUngrounding(Vector<IssmDouble>* potential_sheet_ungrounding)=0;
 		virtual int        PressureInterpolation()=0;
@@ -269,4 +287,5 @@
 		virtual void       ResetHooks()=0;
 		virtual void       ResetLevelsetFromSegmentlist(IssmDouble* segments,int numsegments){_error_("not implemented yet");};
+		virtual void       SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index,int offset,int N,int M)=0;
 		virtual void       SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index)=0;
 		virtual void       SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Materials* materials,Parameters* parameters)=0;
@@ -281,7 +300,7 @@
 		virtual int        TensorInterpolation()=0;
 		virtual IssmDouble TimeAdapt()=0;
-		virtual IssmDouble TotalFloatingBmb(void)=0;
-		virtual IssmDouble TotalGroundedBmb(void)=0;
-		virtual IssmDouble TotalSmb(void)=0;
+		virtual IssmDouble TotalFloatingBmb(bool scaled)=0;
+		virtual IssmDouble TotalGroundedBmb(bool scaled)=0;
+		virtual IssmDouble TotalSmb(bool scaled)=0;
 		virtual void       Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finite_element)=0;
 		virtual void       UpdateConstraintsExtrudeFromBase(void)=0;
@@ -295,4 +314,5 @@
 		virtual void       VerticalSegmentIndicesBase(int** pindices,int* pnumseg)=0;
 		virtual void       ViscousHeating(IssmDouble* pphi,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input)=0;
+		virtual void       WriteFieldIsovalueSegment(DataSet* segments,int fieldenum,IssmDouble fieldvalue){_error_("not implemented yet");};
 		virtual void       WriteLevelsetSegment(DataSet* segments){_error_("not implemented yet");};
 		virtual void       ZeroLevelsetCoordinates(IssmDouble** pxyz_zero,IssmDouble* xyz_list,int levelsetenum)=0;
@@ -302,5 +322,5 @@
 		#endif
 		#ifdef _HAVE_ESA_
-		virtual void          EsaGeodetic2D(Vector<IssmDouble>* pUp,Vector<IssmDouble>* pNorth,Vector<IssmDouble>* pEast,IssmDouble* xx,IssmDouble* yy)=0;
+		virtual void          EsaGeodetic2D(Vector<IssmDouble>* pUp,Vector<IssmDouble>* pNorth,Vector<IssmDouble>* pEast, Vector<IssmDouble>* pX, Vector<IssmDouble>* pY,IssmDouble* xx,IssmDouble* yy)=0;
 		virtual void          EsaGeodetic3D(Vector<IssmDouble>* pUp,Vector<IssmDouble>* pNorth,Vector<IssmDouble>* pEast,IssmDouble* latitude,IssmDouble* longitude,IssmDouble* radius,IssmDouble* xx,IssmDouble* yy,IssmDouble* zz,IssmDouble eartharea)=0;
 		#endif
Index: /issm/trunk/src/c/classes/Elements/ElementHook.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/ElementHook.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Elements/ElementHook.cpp	(revision 22758)
@@ -46,5 +46,5 @@
 
 	/*retrieve material_id: */
-	matpar_id = iomodel->numberofelements+1;
+	matpar_id = iomodel->matparcounter;
 
 	/*retrieve material_id*/
Index: /issm/trunk/src/c/classes/Elements/Penta.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/Penta.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Elements/Penta.cpp	(revision 22758)
@@ -24,6 +24,6 @@
 }
 /*}}}*/
-Penta::Penta(int penta_id, int penta_sid, int index, IoModel* iomodel,int nummodels)/*{{{*/
-	:ElementHook(nummodels,index+1,NUMVERTICES,iomodel){
+Penta::Penta(int penta_id, int penta_sid,IoModel* iomodel,int nummodels)/*{{{*/
+	:ElementHook(nummodels,penta_id,NUMVERTICES,iomodel){
 
 	int penta_elements_ids[2];
@@ -38,8 +38,8 @@
 
 	/*Build neighbors list*/
-	if (xIsNan<IssmDouble>(iomodel->Data("md.mesh.upperelements")[index]) || iomodel->Data("md.mesh.upperelements")[index]==-1.) penta_elements_ids[1]=this->id; //upper penta is the same penta
-	else                                    penta_elements_ids[1]=reCast<int,IssmDouble>((iomodel->Data("md.mesh.upperelements")[index]));
-	if (xIsNan<IssmDouble>(iomodel->Data("md.mesh.lowerelements")[index]) || iomodel->Data("md.mesh.lowerelements")[index]==-1.) penta_elements_ids[0]=this->id; //lower penta is the same penta
-	else                                    penta_elements_ids[0]=reCast<int,IssmDouble>((iomodel->Data("md.mesh.lowerelements")[index]));
+	if (xIsNan<IssmDouble>(iomodel->Data("md.mesh.upperelements")[penta_sid]) || iomodel->Data("md.mesh.upperelements")[penta_sid]==-1.) penta_elements_ids[1]=this->id; //upper penta is the same penta
+	else                                    penta_elements_ids[1]=reCast<int,IssmDouble>((iomodel->Data("md.mesh.upperelements")[penta_sid]));
+	if (xIsNan<IssmDouble>(iomodel->Data("md.mesh.lowerelements")[penta_sid]) || iomodel->Data("md.mesh.lowerelements")[penta_sid]==-1.) penta_elements_ids[0]=this->id; //lower penta is the same penta
+	else                                    penta_elements_ids[0]=reCast<int,IssmDouble>((iomodel->Data("md.mesh.lowerelements")[penta_sid]));
 	this->InitHookNeighbors(penta_elements_ids);
 
@@ -172,5 +172,5 @@
 }
 /*}}}*/
-void     Penta::BasalNodeIndices(int* pnumindices,int** pindices,int finiteelement){/*{{{*/
+void       Penta::BasalNodeIndices(int* pnumindices,int** pindices,int finiteelement){/*{{{*/
 
 	PentaRef::BasalNodeIndices(pnumindices,pindices,finiteelement);
@@ -182,5 +182,5 @@
 }
 /*}}}*/
-void       Penta::CalvingRateDev(){/*{{{*/
+void       Penta::CalvingRateVonmises(){/*{{{*/
 
 	if(!this->IsOnBase()) return;
@@ -192,6 +192,6 @@
 	IssmDouble  calvingrate[NUMVERTICES];
 	IssmDouble  lambda1,lambda2,ex,ey,vx,vy,vel;
-	IssmDouble  sigma_vm,sigma_max,sigma_max_floating,sigma_max_grounded;
-	IssmDouble  epse_2,groundedice;
+	IssmDouble  B,sigma_vm,sigma_max,sigma_max_floating,sigma_max_grounded;
+	IssmDouble  epse_2,groundedice,bed;
 
 	/* Get node coordinates and dof list: */
@@ -207,8 +207,9 @@
 	Input* vy_input = inputs->GetInput(VyAverageEnum); _assert_(vy_input);
 	Input* gr_input = inputs->GetInput(MaskGroundediceLevelsetEnum); _assert_(gr_input);
-	IssmDouble  B   = this->GetMaterialParameter(MaterialsRheologyBbarEnum);
+	Input* bs_input = inputs->GetInput(BaseEnum);                    _assert_(bs_input);
+	Input* B_input  = inputs->GetInput(MaterialsRheologyBbarEnum);   _assert_(B_input);
+	Input* smax_fl_input = inputs->GetInput(CalvingStressThresholdFloatingiceEnum); _assert_(smax_fl_input);
+	Input* smax_gr_input = inputs->GetInput(CalvingStressThresholdGroundediceEnum); _assert_(smax_gr_input);
 	IssmDouble  n   = this->GetMaterialParameter(MaterialsRheologyNEnum);
-	this->parameters->FindParam(&sigma_max_floating,CalvingStressThresholdFloatingiceEnum);
-	this->parameters->FindParam(&sigma_max_grounded,CalvingStressThresholdGroundediceEnum);
 
 	/* Start looping on the number of vertices: */
@@ -218,7 +219,11 @@
 
 		/*Get velocity components and thickness*/
+		B_input->GetInputValue(&B,gauss);
 		vx_input->GetInputValue(&vx,gauss);
 		vy_input->GetInputValue(&vy,gauss);
 		gr_input->GetInputValue(&groundedice,gauss);
+		bs_input->GetInputValue(&bed,gauss);
+		smax_fl_input->GetInputValue(&sigma_max_floating,gauss);
+		smax_gr_input->GetInputValue(&sigma_max_grounded,gauss);
 		vel=sqrt(vx*vx+vy*vy)+1.e-14;
 
@@ -246,7 +251,13 @@
 
 		/*Assign values*/
-		calvingratex[iv]=vx*sigma_vm/sigma_max;
-		calvingratey[iv]=vy*sigma_vm/sigma_max;
-		calvingrate[iv]=sqrt(calvingratex[iv]*calvingratex[iv] + calvingratey[iv]*calvingratey[iv]);
+		if(bed>0.){
+			calvingratex[iv]=0.;
+			calvingratey[iv]=0.;
+		}
+		else{
+			calvingratex[iv]=vx*sigma_vm/sigma_max;
+			calvingratey[iv]=vy*sigma_vm/sigma_max;
+		}
+		calvingrate[iv] =sqrt(calvingratex[iv]*calvingratex[iv] + calvingratey[iv]*calvingratey[iv]);
 	}
 
@@ -550,4 +561,30 @@
 }
 /*}}}*/
+void       Penta::ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index,int offset,int N,int M){/*{{{*/
+
+	int    vertexpidlist[NUMVERTICES];
+	IssmDouble grad_list[NUMVERTICES];
+	Input* grad_input=NULL;
+	Input* input=NULL;
+
+	if(enum_type==MaterialsRheologyBbarEnum){
+		input=(Input*)inputs->GetInput(MaterialsRheologyBEnum);
+	}
+	else if(enum_type==DamageDbarEnum){
+		input=(Input*)inputs->GetInput(DamageDEnum);
+	}
+	else{
+		input=inputs->GetInput(enum_type);
+	}
+	if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
+
+	GradientIndexing(&vertexpidlist[0],control_index);
+	for(int i=0;i<NUMVERTICES;i++) grad_list[i]=gradient[vertexpidlist[i]];
+	grad_input=new PentaInput(GradientEnum,grad_list,P1Enum);
+	((ControlInput*)input)->SetGradient(grad_input);
+
+}
+/*}}}*/
 void       Penta::ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index){/*{{{*/
 
@@ -620,8 +657,8 @@
 	switch(response_enum){
 		case MaterialsRheologyBbarEnum:
-			*presponse=this->material->GetBbar();
+			*presponse=this->material->GetBbar(NULL);
 			break;
 		case DamageDbarEnum:
-			*presponse=this->material->GetDbar();
+			*presponse=this->material->GetDbar(NULL);
 			break;
 		case VelEnum:
@@ -675,9 +712,9 @@
 }
 /*}}}*/
-IssmDouble Penta::FloatingArea(void){/*{{{*/
+IssmDouble Penta::FloatingArea(bool scaled){/*{{{*/
 
 	/*Intermediaries*/
 	int         domaintype;
-	IssmDouble  phi,base_area;
+	IssmDouble  phi,base_area,scalefactor,floatingarea;
 	IssmDouble  xyz_list[NUMVERTICES][3];
 
@@ -692,6 +729,14 @@
 	base_area= 1./2.*fabs((xyz_list[0][0]-xyz_list[2][0])*(xyz_list[1][1]-xyz_list[0][1]) - (xyz_list[0][0]-xyz_list[1][0])*(xyz_list[2][1]-xyz_list[0][1]));
 
+	floatingarea=(1-phi)*base_area;
+
+	if(scaled==true){
+		Input* scalefactor_input = inputs->GetInput(MeshScaleFactorEnum); _assert_(scalefactor_input);
+		scalefactor_input->GetInputAverage(&scalefactor);
+		floatingarea=floatingarea*scalefactor;
+	}
+
 	/*Clean up and return*/
-	return (1-phi)*base_area;
+	return floatingarea;
 }
 /*}}}*/
@@ -896,4 +941,5 @@
 			f2=gl[1]/(gl[1]-gl[0]);
 		}
+		else _error_("case not possible");
 	}
 	*point1=point;
@@ -991,4 +1037,5 @@
 			xyz_bis[2][2]=*(xyz_list+3*1+2)+s2*(*(xyz_list+3*2+2)-*(xyz_list+3*1+2));
 		}
+		else _error_("case not possible");
 
 		/*Compute fraction of grounded element*/
@@ -1097,61 +1144,4 @@
 }
 /*}}}*/
-void       Penta::GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution, int enum_type){/*{{{*/
-
-	const int    numdof=NDOF1*NUMVERTICES;
-
-	int          i;
-	int*         doflist=NULL;
-	IssmDouble   values[numdof];
-	IssmDouble   enum_value;
-	GaussPenta   *gauss=NULL;
-
-	/*Get dof list: */
-	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
-	Input* enum_input=inputs->GetInput(enum_type); _assert_(enum_input);
-
-	gauss=new GaussPenta();
-	for(i=0;i<NUMVERTICES;i++){
-		/*Recover temperature*/
-		gauss->GaussVertex(i);
-		enum_input->GetInputValue(&enum_value,gauss);
-		values[i]=enum_value;
-	}
-
-	/*Add value to global vector*/
-	solution->SetValues(numdof,doflist,values,INS_VAL);
-
-	/*Free ressources:*/
-	delete gauss;
-	xDelete<int>(doflist);
-}
-/*}}}*/
-Penta*     Penta::GetSurfacePenta(void){/*{{{*/
-
-	/*Output*/
-	Penta* penta=NULL;
-
-	/*Go through all pentas till the surface is reached*/
-	penta=this;
-	for(;;){
-		/*Stop if we have reached the surface, else, take upper penta*/
-		if (penta->IsOnSurface()) break;
-
-		/* get upper Penta*/
-		penta=penta->GetUpperPenta();
-		_assert_(penta->Id()!=this->id);
-	}
-
-	/*return output*/
-	return penta;
-}
-/*}}}*/
-Element*   Penta::GetUpperElement(void){/*{{{*/
-
-	/*Output*/
-	Element* upper_element=this->GetUpperPenta();
-	return upper_element;
-}
-/*}}}*/
 Penta*     Penta::GetUpperPenta(void){/*{{{*/
 
@@ -1186,4 +1176,82 @@
 }
 /*}}}*/
+void       Penta::GetVectorFromControlInputs(Vector<IssmDouble>* vector,int control_enum,int control_index,const char* data,int offset,bool onsid){/*{{{*/
+
+	int* idlist = NULL;
+	IssmDouble* values = NULL;
+	int* M = NULL;
+
+	/*Get out if this is not an element input*/
+	if(!IsInput(control_enum)) _error_("Enum "<<EnumToStringx(control_enum)<<" is not in IsInput");
+	Input* input=(Input*)this->inputs->GetInput(control_enum);   _assert_(input);
+
+
+	/*Cast to Controlinput*/
+	if(input->ObjectEnum()!=ControlInputEnum) _error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
+	ControlInput* controlinput = xDynamicCast<ControlInput*>(input);
+
+	if(strcmp(data,"value")==0){
+		input  = controlinput->values;
+	}
+	else if (strcmp(data,"lowerbound")==0){
+		input = controlinput->minvalues;
+	}
+	else if (strcmp(data,"upperbound")==0){
+		input = controlinput->maxvalues;
+	}
+	else if (strcmp(data,"gradient")==0){
+		input = controlinput->gradient;
+	}
+	else{
+		_error_("Data " << data << " not supported yet");
+	}
+	/*Check what input we are dealing with*/
+
+	switch(input->ObjectEnum()){
+		case PentaInputEnum:
+				  {
+					PentaInput* pentainput = xDynamicCast<PentaInput*>(input);
+					if(pentainput->interpolation_type!=P1Enum) _error_("not supported yet");
+
+					/*Create list of indices and values for global vector*/
+					idlist = xNew<int>(NUMVERTICES);
+					values = xNew<IssmDouble>(NUMVERTICES);
+					GradientIndexing(&idlist[0],control_index,true);
+					for(int i=0;i<NUMVERTICES;i++){
+						values[i] = pentainput->values[i];
+					}
+					vector->SetValues(NUMVERTICES,idlist,values,INS_VAL);
+					break;
+				  }
+
+				case TransientInputEnum:
+				  {
+					parameters->FindParam(&M,NULL,ControlInputSizeMEnum);
+					TransientInput* transientinput = xDynamicCast<TransientInput*>(input);
+					int N = transientinput->numtimesteps;
+					idlist = xNew<int>(NUMVERTICES*N);
+					values = xNew<IssmDouble>(NUMVERTICES*N);
+					for(int t=0;t<transientinput->numtimesteps;t++) {
+						IssmDouble time = transientinput->GetTimeByOffset(t);
+						input = transientinput->GetTimeInput(time);
+						TriaInput* timeinput = xDynamicCast<TriaInput*>(input);
+						if(timeinput->interpolation_type!=P1Enum) _error_("not supported yet");
+						/*Create list of indices and values for global vector*/
+						for(int i=0;i<NUMVERTICES;i++){
+							idlist[N*i+t] = offset + this->vertices[i]->Sid()+t*M[control_index];
+							values[N*i+t] = timeinput->values[i];
+						}
+					}
+
+					vector->SetValues(NUMVERTICES*transientinput->numtimesteps,idlist,values,INS_VAL);
+					break;
+				  }
+				default: _error_("input "<<input->ObjectEnum()<<" not supported yet");
+
+		}
+			xDelete<int>(idlist);
+			xDelete<IssmDouble>(values);
+	}
+/*}}}*/
 void       Penta::GetVerticesCoordinatesBase(IssmDouble** pxyz_list){/*{{{*/
 
@@ -1204,9 +1272,9 @@
 
 }/*}}}*/
-IssmDouble Penta::GroundedArea(void){/*{{{*/
+IssmDouble Penta::GroundedArea(bool scaled){/*{{{*/
 
 	/*Intermediaries*/
 	int         domaintype;
-	IssmDouble  phi,base_area;
+	IssmDouble  phi,base_area,scalefactor,groundedarea;
 	IssmDouble  xyz_list[NUMVERTICES][3];
 
@@ -1221,24 +1289,19 @@
 	base_area= 1./2.*fabs((xyz_list[0][0]-xyz_list[2][0])*(xyz_list[1][1]-xyz_list[0][1]) - (xyz_list[0][0]-xyz_list[1][0])*(xyz_list[2][1]-xyz_list[0][1]));
 
+	groundedarea=phi*base_area;
+
+	if(scaled==true){
+		Input* scalefactor_input = inputs->GetInput(MeshScaleFactorEnum); _assert_(scalefactor_input);
+		scalefactor_input->GetInputAverage(&scalefactor);
+		groundedarea=groundedarea*scalefactor;
+	}
 	/*Clean up and return*/
-	return phi*base_area;
-}
-/*}}}*/
-IssmDouble Penta::IceMass(void){/*{{{*/
-
-	IssmDouble rho_ice; 
-	
-	if(!IsIceInElement())return 0.; //do not contribute to the volume of the ice!
-
-	/*recover ice density: */
-	rho_ice=matpar->GetMaterialParameter(MaterialsRhoIceEnum);
-
-	return rho_ice*this->IceVolume();
-}
-/*}}}*/
-IssmDouble Penta::IceVolume(void){/*{{{*/
+	return groundedarea;
+}
+/*}}}*/
+IssmDouble Penta::IceVolume(bool scaled){/*{{{*/
 
 	/*The volume of a troncated prism is base * 1/3 sum(length of edges)*/
-	IssmDouble base,height;
+	IssmDouble base,height,scalefactor;
 	IssmDouble xyz_list[NUMVERTICES][3];
 
@@ -1252,4 +1315,10 @@
 	base = 1./2.*fabs((xyz_list[0][0]-xyz_list[2][0])*(xyz_list[1][1]-xyz_list[0][1]) - (xyz_list[0][0]-xyz_list[1][0])*(xyz_list[2][1]-xyz_list[0][1]));
 
+	if(scaled==true){ //scale for area projection correction
+		Input* scalefactor_input = inputs->GetInput(MeshScaleFactorEnum); _assert_(scalefactor_input);
+		scalefactor_input->GetInputAverage(&scalefactor);
+		base=base*scalefactor;
+	}
+
 	/*Now get the average height*/
 	height = 1./3.*((xyz_list[3][2]-xyz_list[0][2])+(xyz_list[4][2]-xyz_list[1][2])+(xyz_list[5][2]-xyz_list[2][2]));
@@ -1259,9 +1328,9 @@
 }
 /*}}}*/
-IssmDouble Penta::IceVolumeAboveFloatation(void){/*{{{*/
+IssmDouble Penta::IceVolumeAboveFloatation(bool scaled){/*{{{*/
 
 	/*Volume above floatation: H + rho_water/rho_ice*bathymetry for nodes on the bed*/
 	IssmDouble rho_ice,rho_water;
-	IssmDouble base,bed,surface,bathymetry;
+	IssmDouble base,bed,surface,bathymetry,scalefactor;
 	IssmDouble xyz_list[NUMVERTICES][3];
 
@@ -1276,4 +1345,9 @@
 	 * base = 1/2 abs((xA-xC)(yB-yA)-(xA-xB)(yC-yA))*/
 	base = 1./2.*fabs((xyz_list[0][0]-xyz_list[2][0])*(xyz_list[1][1]-xyz_list[0][1]) - (xyz_list[0][0]-xyz_list[1][0])*(xyz_list[2][1]-xyz_list[0][1]));
+	if(scaled==true){
+		Input* scalefactor_input = inputs->GetInput(MeshScaleFactorEnum); _assert_(scalefactor_input);
+		scalefactor_input->GetInputAverage(&scalefactor);
+		base=base*scalefactor;
+	}
 
 	/*Now get the average height above floatation*/
@@ -1289,143 +1363,67 @@
 }
 /*}}}*/
-void       Penta::InputControlUpdate(IssmDouble scalar,bool save_parameter){/*{{{*/
-
-	/*Intermediary*/
-	int    num_controls;
-	int*   control_type=NULL;
-	Input* input=NULL;
-
-	/*retrieve some parameters: */
-	this->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
-	this->parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
-
-	for(int i=0;i<num_controls;i++){
-
-		if(control_type[i]==MaterialsRheologyBbarEnum){
-			if (!IsOnBase()) goto cleanup_and_return;
-			input=(Input*)this->inputs->GetInput(MaterialsRheologyBEnum); _assert_(input);
-		}
-		else if(control_type[i]==DamageDbarEnum){
-			if (!IsOnBase()) goto cleanup_and_return;
-			input=(Input*)this->inputs->GetInput(DamageDEnum); _assert_(input);
-		}
-		else{
-			input=(Input*)this->inputs->GetInput(control_type[i]); _assert_(input);
-		}
-		if(input->ObjectEnum()!=ControlInputEnum) _error_("input " << EnumToStringx(control_type[i]) << " is not a ControlInput");
-
-		((ControlInput*)input)->UpdateValue(scalar);
-		((ControlInput*)input)->Constrain();
-		if (save_parameter) ((ControlInput*)input)->SaveValue();
-
-		if(control_type[i]==MaterialsRheologyBbarEnum){
-			this->InputExtrude(MaterialsRheologyBEnum,-1);
-		}
-		else if(control_type[i]==DamageDbarEnum){
-			this->InputExtrude(DamageDEnum,-1);
-		}
-	}
-
-	/*Clean up and return*/
-cleanup_and_return:
-	xDelete<int>(control_type);
-}
-/*}}}*/
-void       Penta::InputDepthAverageAtBase(int enum_type,int average_enum_type){/*{{{*/
-
-	int  step,i;
+void       Penta::InputDepthAverageAtBase(int original_enum,int average_enum){/*{{{*/
+
+	IssmDouble  Jdet,value;
 	IssmDouble  xyz_list[NUMVERTICES][3];
-	IssmDouble  Helem_list[NUMVERTICES];
-	IssmDouble  zeros_list[NUMVERTICES]={0.0};
-	IssmDouble  p0top1_list[NUMVERTICES];
-	Penta* penta=NULL;
-	Input* original_input=NULL;
-	Input* element_integrated_input=NULL;
-	Input* total_integrated_input=NULL;
-	Input* element_thickness_input=NULL;
-	Input* total_thickness_input=NULL;
-	Input* depth_averaged_input=NULL;
-
-	/*recover parameters: */
+	IssmDouble  xyz_list_line[2][3];
+	IssmDouble  total[NUMVERTICES]       = {0.};
+	IssmDouble  intz[NUMVERTICES]        = {0.};
+	Input      *original_input           = NULL;
+	Input      *depth_averaged_input     = NULL;
 
 	/*Are we on the base? If not, return*/
 	if(!IsOnBase()) return;
 
-	/*OK, we are on bed. Initialize global inputs as 0*/
-	total_thickness_input =new PentaInput(ThicknessEnum,zeros_list,P1Enum);
-
 	/*Now follow all the upper element from the base to the surface to integrate the input*/
-	penta=this;
-	step =0;
+	Penta* penta = this;
+	int    step  = 0;
 	for(;;){
 
-		/*Step1: Get original input (to be depth avegaged): */
-		original_input=(Input*)penta->inputs->GetInput(enum_type);
-		if(!original_input) _error_("could not find input with enum " << EnumToStringx(enum_type));
-
-		/*If first time, initialize total_integrated_input*/
-		if (step==0){
-			if (original_input->ObjectEnum()==PentaInputEnum)
-			 total_integrated_input=new PentaInput(average_enum_type,zeros_list,P1Enum);
-			else if (original_input->ObjectEnum()==ControlInputEnum)
-			 total_integrated_input=new PentaInput(average_enum_type,zeros_list,P1Enum);
-			else if (original_input->ObjectEnum()==DoubleInputEnum)
-			 total_integrated_input=new DoubleInput(average_enum_type,0.0);
-			else{
-			 _error_("object " << EnumToStringx(original_input->ObjectEnum()) << " not supported yet");
-			}
-		}
+		/*Step1: Get original input (to be depth-avegaged): */
+		original_input=(Input*)penta->inputs->GetInput(original_enum);
+		if(!original_input) _error_("could not find input with enum " << EnumToStringx(original_enum));
 
 		/*Step2: Create element thickness input*/
 		::GetVerticesCoordinates(&xyz_list[0][0],penta->vertices,NUMVERTICES);
-		for(i=0;i<3;i++){
-			Helem_list[i]=xyz_list[i+3][2]-xyz_list[i][2];
-			Helem_list[i+3]=Helem_list[i];
-		}
-		element_thickness_input=new PentaInput(ThicknessEnum,Helem_list,P1Enum);
-
-		/*Step3: Vertically integrate A COPY of the original*/
-		if(original_input->ObjectEnum()==PentaInputEnum){
-			if(((PentaInput*)original_input)->interpolation_type==P0Enum){
-				original_input->GetInputValue(&p0top1_list[i]);
-				element_integrated_input= new  PentaInput(original_input->InstanceEnum(),p0top1_list,P1Enum);
-				element_integrated_input->VerticallyIntegrate(element_thickness_input);
+		for(int iv=0;iv<3;iv++){
+			/*Get segment length*/
+			for(int i=0;i<3;i++){
+				xyz_list_line[0][i]=xyz_list[iv][i];
+				xyz_list_line[1][i]=xyz_list[iv+3][i];
 			}
-			else{
-				element_integrated_input= (Input*)original_input->copy();
-				element_integrated_input->VerticallyIntegrate(element_thickness_input);
+			/*Integrate over edge*/
+			Gauss* gauss=penta->NewGaussLine(iv,iv+3,3);
+			for(int ig=gauss->begin();ig<gauss->end();ig++){
+				gauss->GaussPoint(ig);
+				penta->JacobianDeterminantLine(&Jdet,&xyz_list_line[0][0],gauss);
+				original_input->GetInputValue(&value,gauss);
+				total[iv] += value*Jdet*gauss->weight;
+				intz[iv]  += Jdet*gauss->weight;
 			}
-		}
-		else{
-			element_integrated_input= (Input*)original_input->copy();
-			element_integrated_input->VerticallyIntegrate(element_thickness_input);
-		}
-
-		/*Add contributions to global inputs*/
-		total_integrated_input->AXPY(element_integrated_input,1.0);
-		total_thickness_input ->AXPY(element_thickness_input,1.0);
-
-		/*Clean up*/
-		delete element_thickness_input;
-		delete element_integrated_input;
+			delete gauss;
+		}
 
 		/*Stop if we have reached the surface, else, take upper penta*/
-		if (penta->IsOnSurface()) break;
+		if(penta->IsOnSurface()) break;
 
 		/* get upper Penta*/
-		penta=penta->GetUpperPenta();
-		_assert_(penta->Id()!=this->id);
-
-		/*increase couter*/
+		penta=penta->GetUpperPenta(); _assert_(penta->Id()!=this->id);
 		step++;
 	}
 
-	/*OK, now we only need to divide the depth integrated input by the total thickness!*/
-	depth_averaged_input=total_integrated_input->PointwiseDivide(total_thickness_input);
-	depth_averaged_input->ChangeEnum(average_enum_type);
-
-	/*Clean up*/
-	delete total_thickness_input;
-	delete total_integrated_input;
+	/*Now we only need to divide the depth integrated input by the total thickness!*/
+	for(int iv=0;iv<3;iv++){
+		total[iv  ] = total[iv]/intz[iv];
+		total[iv+3] = total[iv];
+	}
+	switch(original_input->ObjectEnum()){
+		case PentaInputEnum:
+		case ControlInputEnum:
+			depth_averaged_input=new PentaInput(average_enum,&total[0],P1Enum); 
+			break;
+		default:
+			_error_("Interpolation " << EnumToStringx(original_input->ObjectEnum()) << " not supported yet");
+	}
 
 	/*Finally, add to inputs*/
@@ -1466,16 +1464,4 @@
 		if(start==+1 && penta->IsOnBase())    break;
 	}
-}
-/*}}}*/
-void       Penta::InputScale(int enum_type,IssmDouble scale_factor){/*{{{*/
-
-	Input* input=NULL;
-
-	/*Make a copy of the original input: */
-	input=(Input*)this->inputs->GetInput(enum_type);
-	if(!input)_error_("could not find old input with enum: " << EnumToStringx(enum_type));
-
-	/*Scale: */
-	input->Scale(scale_factor);
 }
 /*}}}*/
@@ -1518,5 +1504,5 @@
 						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data("md.inversion.min_parameters")[(penta_vertex_ids[j]-1)*num_control_type+i]/yts;
 						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data("md.inversion.max_parameters")[(penta_vertex_ids[j]-1)*num_control_type+i]/yts;
-						this->inputs->AddInput(new ControlInput(BalancethicknessThickeningRateEnum,PentaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						this->inputs->AddInput(new ControlInput(BalancethicknessThickeningRateEnum,PentaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,P1Enum,i+1));
 					}
 					break;
@@ -1526,5 +1512,5 @@
 						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data("md.inversion.min_parameters")[(penta_vertex_ids[j]-1)*num_control_type+i]/yts;
 						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data("md.inversion.max_parameters")[(penta_vertex_ids[j]-1)*num_control_type+i]/yts;
-						this->inputs->AddInput(new ControlInput(VxEnum,PentaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						this->inputs->AddInput(new ControlInput(VxEnum,PentaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,P1Enum,i+1));
 					}
 					break;
@@ -1534,5 +1520,5 @@
 						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data("md.inversion.min_parameters")[(penta_vertex_ids[j]-1)*num_control_type+i]/yts;
 						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data("md.inversion.max_parameters")[(penta_vertex_ids[j]-1)*num_control_type+i]/yts;
-						this->inputs->AddInput(new ControlInput(VyEnum,PentaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						this->inputs->AddInput(new ControlInput(VyEnum,PentaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,P1Enum,i+1));
 					}
 					break;
@@ -1542,5 +1528,5 @@
 						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data("md.inversion.min_parameters")[(penta_vertex_ids[j]-1)*num_control_type+i];
 						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data("md.inversion.max_parameters")[(penta_vertex_ids[j]-1)*num_control_type+i];
-						this->inputs->AddInput(new ControlInput(FrictionCoefficientEnum,PentaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						this->inputs->AddInput(new ControlInput(FrictionCoefficientEnum,PentaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,P1Enum,i+1));
 					}
 					break;
@@ -1550,5 +1536,5 @@
 						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data("md.inversion.min_parameters")[(penta_vertex_ids[j]-1)*num_control_type+i];
 						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data("md.inversion.max_parameters")[(penta_vertex_ids[j]-1)*num_control_type+i];
-						this->inputs->AddInput(new ControlInput(MaterialsRheologyBEnum,PentaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						this->inputs->AddInput(new ControlInput(MaterialsRheologyBEnum,PentaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,P1Enum,i+1));
 					}
 					break;
@@ -1558,5 +1544,5 @@
 						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data("md.inversion.min_parameters")[(penta_vertex_ids[j]-1)*num_control_type+i];
 						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data("md.inversion.max_parameters")[(penta_vertex_ids[j]-1)*num_control_type+i];
-						this->inputs->AddInput(new ControlInput(DamageDEnum,PentaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						this->inputs->AddInput(new ControlInput(DamageDEnum,PentaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,P1Enum,i+1));
 					}
 					break;
@@ -2285,4 +2271,5 @@
 void       Penta::ResetHooks(){/*{{{*/
 
+	if(this->nodes) xDelete<Node*>(this->nodes);
 	this->nodes=NULL;
 	this->vertices=NULL;
@@ -2311,5 +2298,4 @@
 	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
 	GetInputListOnVertices(&ls[0],MaskIceLevelsetEnum);
-	InputDuplicate(MaskIceLevelsetEnum,PressureEnum);
 
 	/*Get distance from list of segments and reset ls*/
@@ -2370,4 +2356,46 @@
 }
 
+/*}}}*/
+void       Penta::SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index,int offset, int N, int M){/*{{{*/
+
+	IssmDouble  values[NUMVERTICES];
+	int         vertexpidlist[NUMVERTICES],control_init;
+
+	/*Specific case for depth averaged quantities*/
+	control_init=control_enum;
+	if(control_enum==MaterialsRheologyBbarEnum){
+		control_enum=MaterialsRheologyBEnum;
+		if(!IsOnBase()) return;
+	}
+	if(control_enum==DamageDbarEnum){
+		control_enum=DamageDEnum;
+		if(!IsOnBase()) return;
+	}
+
+	/*Get out if this is not an element input*/
+	if(!IsInput(control_enum)) return;
+
+	/*Prepare index list*/
+	GradientIndexing(&vertexpidlist[0],control_index);
+
+	/*Get values on vertices*/
+	for(int i=0;i<NUMVERTICES;i++){
+		values[i]=vector[vertexpidlist[i]];
+	}
+	Input* new_input = new PentaInput(control_enum,values,P1Enum);
+	Input* input=(Input*)this->inputs->GetInput(control_enum);   _assert_(input);
+	if(input->ObjectEnum()!=ControlInputEnum){
+		_error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
+	}
+
+	((ControlInput*)input)->SetInput(new_input);
+
+	if(control_init==MaterialsRheologyBbarEnum){
+		this->InputExtrude(control_enum,-1);
+	}
+	if(control_init==DamageDbarEnum){
+		this->InputExtrude(control_enum,-1);
+	}
+}
 /*}}}*/
 void       Penta::SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index){/*{{{*/
@@ -2776,5 +2804,5 @@
 	return dt;
 }/*}}}*/
-IssmDouble Penta::TotalFloatingBmb(void){/*{{{*/
+IssmDouble Penta::TotalFloatingBmb(bool scaled){/*{{{*/
 
 	/*The fbmb[kg yr-1] of one element is area[m2] * melting_rate [kg m^-2 yr^-1]*/
@@ -2782,5 +2810,5 @@
 	bool       mainlyfloating;
 	IssmDouble fbmb=0;
-	IssmDouble rho_ice,fraction1,fraction2,floatingmelt,Jdet;
+	IssmDouble rho_ice,fraction1,fraction2,floatingmelt,Jdet,scalefactor;
 	IssmDouble Total_Fbmb=0;
 	IssmDouble xyz_list[NUMVERTICES][3];
@@ -2793,4 +2821,8 @@
 	Input* floatingmelt_input = this->GetInput(BasalforcingsFloatingiceMeltingRateEnum); _assert_(floatingmelt_input); 
 	Input* gllevelset_input = this->GetInput(MaskGroundediceLevelsetEnum); _assert_(gllevelset_input);
+	Input* scalefactor_input = NULL;
+	if(scaled==true){
+		scalefactor_input = this->GetInput(MeshScaleFactorEnum); _assert_(scalefactor_input); 
+	}
 	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
 
@@ -2803,5 +2835,9 @@
 		this->JacobianDeterminantBase(&Jdet,&xyz_list[0][0],gauss);
 		floatingmelt_input->GetInputValue(&floatingmelt,gauss);
-		fbmb+=floatingmelt*Jdet*gauss->weight;
+		if(scaled==true){
+			scalefactor_input->GetInputValue(&scalefactor,gauss);
+		}
+		else scalefactor=1;
+		fbmb+=floatingmelt*Jdet*gauss->weight*scalefactor;
 	}
 
@@ -2813,5 +2849,5 @@
 }
 /*}}}*/
-IssmDouble Penta::TotalGroundedBmb(void){/*{{{*/
+IssmDouble Penta::TotalGroundedBmb(bool scaled){/*{{{*/
 
 	/*The gbmb[kg yr-1] of one element is area[m2] * gounded melting rate [kg m^-2 yr^-1]*/
@@ -2819,5 +2855,5 @@
 	bool       mainlyfloating;
 	IssmDouble gbmb=0;
-	IssmDouble rho_ice,fraction1,fraction2,groundedmelt,Jdet;
+	IssmDouble rho_ice,fraction1,fraction2,groundedmelt,Jdet,scalefactor;
 	IssmDouble Total_Gbmb=0;
 	IssmDouble xyz_list[NUMVERTICES][3];
@@ -2830,4 +2866,8 @@
 	Input* groundedmelt_input = this->GetInput(BasalforcingsGroundediceMeltingRateEnum); _assert_(groundedmelt_input); 
 	Input* gllevelset_input = this->GetInput(MaskGroundediceLevelsetEnum); _assert_(gllevelset_input);
+	Input* scalefactor_input = NULL;
+	if(scaled==true){
+		scalefactor_input = this->GetInput(MeshScaleFactorEnum); _assert_(scalefactor_input); 
+	}
 	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
 
@@ -2840,5 +2880,9 @@
 		this->JacobianDeterminantBase(&Jdet,&xyz_list[0][0],gauss);
 		groundedmelt_input->GetInputValue(&groundedmelt,gauss);
-		gbmb+=groundedmelt*Jdet*gauss->weight;
+		if(scaled==true){
+			scalefactor_input->GetInputValue(&scalefactor,gauss);
+		}
+		else scalefactor=1;
+		gbmb+=groundedmelt*Jdet*gauss->weight*scalefactor;
 	}
 
@@ -2850,8 +2894,8 @@
 }
 /*}}}*/
-IssmDouble Penta::TotalSmb(void){/*{{{*/
+IssmDouble Penta::TotalSmb(bool scaled){/*{{{*/
 
 	/*The smb[Gt yr-1] of one element is area[m2] * smb [ m ice yr^-1] * rho_ice [kg m-3] / 1e+10^12 */
-	IssmDouble base,smb,rho_ice;
+	IssmDouble base,smb,rho_ice,scalefactor;
 	IssmDouble Total_Smb=0;
 	IssmDouble xyz_list[NUMVERTICES][3];
@@ -2873,5 +2917,12 @@
 
 	smb_input->GetInputAverage(&smb);
-	Total_Smb=rho_ice*base*smb;// smb on element in kg s-1
+	if(scaled==true){
+		Input* scalefactor_input = inputs->GetInput(MeshScaleFactorEnum); _assert_(scalefactor_input);
+		scalefactor_input->GetInputAverage(&scalefactor);// average scalefactor on element 
+	}
+	else{
+		scalefactor=1.;
+	}
+	Total_Smb=rho_ice*base*smb*scalefactor;// smb on element in kg s-1
 
 	/*Return: */
@@ -2896,4 +2947,5 @@
 	/*Checks if debuging*/
 	_assert_(iomodel->elements);
+	_assert_(index==this->sid); 
 
 	/*Recover element type*/
@@ -2971,4 +3023,23 @@
 			penta_node_ids[11]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+8]+1;
 			break;
+		case P1xP4Enum:
+			numnodes         = 15;
+			penta_node_ids   = xNew<int>(numnodes);
+			penta_node_ids[ 0]=iomodel->nodecounter+iomodel->elements[6*index+0]; /*Vertex 1*/
+			penta_node_ids[ 1]=iomodel->nodecounter+iomodel->elements[6*index+1]; /*Vertex 2*/
+			penta_node_ids[ 2]=iomodel->nodecounter+iomodel->elements[6*index+2]; /*Vertex 3*/
+			penta_node_ids[ 3]=iomodel->nodecounter+iomodel->elements[6*index+3]; /*Vertex 4*/
+			penta_node_ids[ 4]=iomodel->nodecounter+iomodel->elements[6*index+4]; /*Vertex 5*/
+			penta_node_ids[ 5]=iomodel->nodecounter+iomodel->elements[6*index+5]; /*Vertex 6*/
+			penta_node_ids[ 6]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+0]+1; /*mid vertical edge 1*/
+			penta_node_ids[ 7]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+1]+1; /*mid vertical edge 2*/
+			penta_node_ids[ 8]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+2]+1; /*mid vertical edge 3*/
+			penta_node_ids[ 9]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+0]+2; /* 1/4 vertical edge 1*/
+			penta_node_ids[10]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+1]+2; /* 1/4 vertical edge 2*/
+			penta_node_ids[11]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+2]+2; /* 1/4 vertical edge 3*/
+			penta_node_ids[12]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+0]+3; /* 3/4 vertical edge 1*/
+			penta_node_ids[13]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+1]+3; /* 3/4 vertical edge 2*/
+			penta_node_ids[14]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+2]+3; /* 3/4 vertical edge 3*/
+			break;
 		case P2xP4Enum:
 			numnodes         = 30;
@@ -2992,7 +3063,7 @@
 			penta_node_ids[16]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+1]+2; /* 1/4 vertical edge 2*/
 			penta_node_ids[17]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+2]+2; /* 1/4 vertical edge 3*/
-			penta_node_ids[18]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+0]+3; /* 2/4 vertical edge 1*/
-			penta_node_ids[19]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+1]+3; /* 2/4 vertical edge 2*/
-			penta_node_ids[20]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+2]+3; /* 2/4 vertical edge 3*/
+			penta_node_ids[18]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+0]+3; /* 3/4 vertical edge 1*/
+			penta_node_ids[19]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+1]+3; /* 3/4 vertical edge 2*/
+			penta_node_ids[20]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->elementtoedgeconnectivity[9*index+2]+3; /* 3/4 vertical edge 3*/
 			penta_node_ids[21]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->numberofedges+3*iomodel->elementtofaceconnectivity[5*index+2]+1; /* 1/4 vertical face 1*/
 			penta_node_ids[22]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->numberofedges+3*iomodel->elementtofaceconnectivity[5*index+3]+1; /* 1/4 vertical face 2*/
Index: /issm/trunk/src/c/classes/Elements/Penta.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/Penta.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Elements/Penta.h	(revision 22758)
@@ -36,5 +36,5 @@
 		/*Penta constructors and destructor: {{{*/
 		Penta(){};
-		Penta(int penta_id,int penta_sid,int i, IoModel* iomodel,int nummodels);
+		Penta(int penta_id,int penta_sid,IoModel* iomodel,int nummodels);
 		~Penta();
 		/*}}}*/
@@ -49,5 +49,5 @@
 		void           AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part);
 		void           BasalNodeIndices(int* pnumindices,int** pindices,int finiteelement);
-		void           CalvingRateDev();
+		void           CalvingRateVonmises();
 		void           CalvingRateLevermann();
 		IssmDouble     CharacteristicLength(void){_error_("not implemented yet");};
@@ -58,4 +58,5 @@
 		void           ComputeStressTensor();
 		void           Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
+		void           ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index,int offset,int N,int M);
 		void           ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index);
 		void           ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum);
@@ -64,5 +65,5 @@
 		void           ElementSizes(IssmDouble* hx,IssmDouble* hy,IssmDouble* hz);
 		int            FiniteElement(void);
-		IssmDouble     FloatingArea(void);
+		IssmDouble     FloatingArea(bool scaled);
 		void           FSContactMigration(Vector<IssmDouble>* vertexgrounded,Vector<IssmDouble>* vertexfloating);
 		IssmDouble     GetArea3D(void){_error_("not implemented yet!");};
@@ -84,19 +85,14 @@
 		int            GetNumberOfVertices(void);
 		Penta*         GetLowerPenta(void);
-		void           GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution,int enum_type);
-		Penta*         GetSurfacePenta(void);
-		Element*       GetUpperElement(void);
 		Penta*         GetUpperPenta(void);
 		void           GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data,bool onsid);
+		void           GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data,int offset,bool onsid);
 		void           GetVerticesCoordinatesBase(IssmDouble** pxyz_list);
 		void           GetVerticesCoordinatesTop(IssmDouble** pxyz_list);
-		IssmDouble     GroundedArea(void);
-		IssmDouble     IceMass(void);
-		IssmDouble     IceVolume(void);
-		IssmDouble     IceVolumeAboveFloatation(void);
-		void           InputControlUpdate(IssmDouble scalar,bool save_parameter);
+		IssmDouble     GroundedArea(bool scaled);
+		IssmDouble     IceVolume(bool scaled);
+		IssmDouble     IceVolumeAboveFloatation(bool scaled);
 		void           InputDepthAverageAtBase(int enum_type,int average_enum_type);
 		void	         InputExtrude(int enum_type,int start);
-		void           InputScale(int enum_type,IssmDouble scale_factor);
 		void           InputUpdateFromIoModel(int index, IoModel* iomodel);
 		void           InputUpdateFromSolutionOneDof(IssmDouble* solutiong,int enum_type);
@@ -125,4 +121,5 @@
 		Gauss*         NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order_horiz,int order_vert);
 		Gauss*         NewGauss(int point1,IssmDouble fraction1,IssmDouble fraction2,bool mainlyfloating,int order);
+		Gauss*         NewGauss(int point1,IssmDouble fraction1,IssmDouble fraction2,int order){_error_("not implemented yet");};
 		Gauss*         NewGaussBase(int order);
 		Gauss*         NewGaussLine(int vertex1,int vertex2,int order);
@@ -144,4 +141,6 @@
 		int            NumberofNodesPressure(void);
 		int            NumberofNodesVelocity(void);
+		void				PicoUpdateBoxid(int* pmax_boxid_basin){_error_("not implemented yet");};
+		void				PicoUpdateBox(int loopboxid){_error_("not implemented yet");};
 		void           PotentialUngrounding(Vector<IssmDouble>* potential_sheet_ungrounding);
 		int            PressureInterpolation();
@@ -151,4 +150,5 @@
 		void           ResetLevelsetFromSegmentlist(IssmDouble* segments,int numsegments);
 		void	         SetClone(int* minranks);
+		void           SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index,int offset, int N,int M);
 		void           SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index);
 		void           SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Materials* materials,Parameters* parameters);
@@ -164,7 +164,7 @@
 		int            TensorInterpolation(){_error_("not implemented yet");};
 		IssmDouble     TimeAdapt();
-		IssmDouble     TotalFloatingBmb(void);
-		IssmDouble     TotalGroundedBmb(void);
-		IssmDouble     TotalSmb(void);
+		IssmDouble     TotalFloatingBmb(bool scaled);
+		IssmDouble     TotalGroundedBmb(bool scaled);
+		IssmDouble     TotalSmb(bool scaled);
 		void           Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finitelement);
 		void           UpdateConstraintsExtrudeFromBase(void);
@@ -189,5 +189,5 @@
 		#endif
 		#ifdef _HAVE_ESA_
-		void    EsaGeodetic2D(Vector<IssmDouble>* pUp,Vector<IssmDouble>* pNorth,Vector<IssmDouble>* pEast,IssmDouble* xx,IssmDouble* yy){_error_("not implemented yet!");};
+		void    EsaGeodetic2D(Vector<IssmDouble>* pUp,Vector<IssmDouble>* pNorth,Vector<IssmDouble>* pEast,Vector<IssmDouble>* pX,Vector<IssmDouble>* pY,IssmDouble* xx,IssmDouble* yy){_error_("not implemented yet!");};
 		void    EsaGeodetic3D(Vector<IssmDouble>* pUp,Vector<IssmDouble>* pNorth,Vector<IssmDouble>* pEast,IssmDouble* latitude,IssmDouble* longitude,IssmDouble* radius,IssmDouble* xx,IssmDouble* yy,IssmDouble* zz,IssmDouble eartharea){_error_("not implemented yet!");};
 		#endif
Index: /issm/trunk/src/c/classes/Elements/PentaRef.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/PentaRef.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Elements/PentaRef.cpp	(revision 22758)
@@ -22,4 +22,5 @@
 #define NUMNODESP1xP2 9
 #define NUMNODESP1xP3 12
+#define NUMNODESP1xP4 15
 #define NUMNODESP2xP1 12
 #define NUMNODESP2    18
@@ -76,4 +77,11 @@
 			break;
 		case P1xP3Enum:
+			numindices = 3;
+			indices    = xNew<int>(numindices);
+			indices[0] = 0;
+			indices[1] = 1;
+			indices[2] = 2;
+			break;
+		case P1xP4Enum:
 			numindices = 3;
 			indices    = xNew<int>(numindices);
@@ -423,5 +431,5 @@
 			basis[ 4]=(9.)/(16.)*gauss->coord2*(zeta-1./3.)*(zeta+1./3.)*(zeta+1.);
 			basis[ 5]=(9.)/(16.)*gauss->coord3*(zeta-1./3.)*(zeta+1./3.)*(zeta+1.);
-			/*quarter-sides of quads*/
+			/*third-sides of quads*/
 			basis[ 6]=(27.)/(16.)*gauss->coord1*(zeta-1)*(zeta-1./3.)*(zeta+1.);
 			basis[ 7]=(27.)/(16.)*gauss->coord2*(zeta-1)*(zeta-1./3.)*(zeta+1.);
@@ -430,4 +438,24 @@
 			basis[10]=-(27.)/(16.)*gauss->coord2*(zeta-1)*(zeta+1./3.)*(zeta+1.);
 			basis[11]=-(27.)/(16.)*gauss->coord3*(zeta-1)*(zeta+1./3.)*(zeta+1.);
+			return;
+		case P1xP4Enum :
+			/*Corner nodes*/
+			basis[ 0]=gauss->coord1*(2./3.)*(zeta-1.)*(zeta-0.5 )*(zeta)*(zeta+0.5);
+			basis[ 1]=gauss->coord2*(2./3.)*(zeta-1.)*(zeta-0.5 )*(zeta)*(zeta+0.5);
+			basis[ 2]=gauss->coord3*(2./3.)*(zeta-1.)*(zeta-0.5 )*(zeta)*(zeta+0.5);
+			basis[ 3]=gauss->coord1*(2./3.)*(zeta-0.5)*(zeta)*(zeta+0.5)*(zeta +1.);
+			basis[ 4]=gauss->coord2*(2./3.)*(zeta-0.5)*(zeta)*(zeta+0.5)*(zeta +1.);
+			basis[ 5]=gauss->coord3*(2./3.)*(zeta-0.5)*(zeta)*(zeta+0.5)*(zeta +1.);
+			/*mid-sides of quads (center of vertical edges)*/
+			basis[ 6]=gauss->coord1*4.*(zeta-1.)*(zeta-0.5)*(zeta+0.5)*(zeta+1.);
+			basis[ 7]=gauss->coord2*4.*(zeta-1.)*(zeta-0.5)*(zeta+0.5)*(zeta+1.);
+			basis[ 8]=gauss->coord3*4.*(zeta-1.)*(zeta-0.5)*(zeta+0.5)*(zeta+1.);
+			/*quarter-sides of quads (-0.5 and +0.5 of vertical edges)*/
+			basis[ 9]=gauss->coord1*(-8./3.)*(zeta-1.0)*(zeta-0.5)*zeta*(zeta+1.);
+			basis[10]=gauss->coord2*(-8./3.)*(zeta-1.0)*(zeta-0.5)*zeta*(zeta+1.);
+			basis[11]=gauss->coord3*(-8./3.)*(zeta-1.0)*(zeta-0.5)*zeta*(zeta+1.);
+			basis[12]=gauss->coord1*(-8./3.)*(zeta-1.0)*zeta*(zeta+0.5)*(zeta+1.);
+			basis[13]=gauss->coord2*(-8./3.)*(zeta-1.0)*zeta*(zeta+0.5)*(zeta+1.);
+			basis[14]=gauss->coord3*(-8./3.)*(zeta-1.0)*zeta*(zeta+0.5)*(zeta+1.);
 			return;
 		default:
@@ -964,4 +992,69 @@
 			dbasis[NUMNODESP1xP3*2+11] = -gauss->coord3 *(27./16.)*( 2.* zeta *( zeta + (1./3.)) + ( zeta - 1. )*( zeta + 1. ));
 			return;
+		case P1xP4Enum :
+			/*Nodal function 1*/
+			dbasis[NUMNODESP1xP4*0+0 ] = -0.5*(2./3.)     *(zeta - 1.)*(zeta - 0.5)*(zeta)*(zeta+0.5);
+			dbasis[NUMNODESP1xP4*1+0 ] = -SQRT3/6.*(2./3.)*(zeta - 1.)*(zeta - 0.5)*(zeta)*(zeta+0.5); 
+			dbasis[NUMNODESP1xP4*2+0 ] =  gauss->coord1 * 2./3.*( (2.*zeta-1)*(zeta -0.5)*(zeta +0.5) + 2.* zeta *zeta *(zeta -1.)); 
+			/*Nodal function 2*/
+			dbasis[NUMNODESP1xP4*0+1 ] = +0.5*(2./3.)     *(zeta - 1.)*(zeta - 0.5)*(zeta)*(zeta+0.5);
+			dbasis[NUMNODESP1xP4*1+1 ] = -SQRT3/6.*(2./3.)*(zeta - 1.)*(zeta - 0.5)*(zeta)*(zeta+0.5);
+			dbasis[NUMNODESP1xP4*2+1 ] = gauss->coord2* 2./3.* ((2.*zeta-1.)*(zeta -0.5)*(zeta +0.5) + 2. * zeta *zeta*(zeta -1.)); 
+			/*Nodal function 3*/
+			dbasis[NUMNODESP1xP4*0+2 ] = 0. ; 
+			dbasis[NUMNODESP1xP4*1+2 ] = SQRT3/3.*(2./3.)*(zeta -1.)*(zeta-0.5)*(zeta)*(zeta+0.5); 
+			dbasis[NUMNODESP1xP4*2+2 ] = gauss->coord3* 2./3.*( (2.*zeta-1.)*(zeta -0.5)*(zeta +0.5) + 2.*zeta *zeta*(zeta -1.)); 
+			/*Nodal function 4*/
+			dbasis[NUMNODESP1xP4*0+3 ] = -0.5 *(2./3.) *(zeta - 0.5)*(zeta)*(zeta+0.5)*(zeta +1. ); 
+			dbasis[NUMNODESP1xP4*1+3 ] = -SQRT3/6.*(2./3.) *(zeta - 0.5)*(zeta)*(zeta+0.5)*(zeta +1. ); 
+			dbasis[NUMNODESP1xP4*2+3 ] = gauss->coord1* 2./3.*( (2.*zeta+1.)*(zeta -0.5)*(zeta +0.5) + 2.*zeta *zeta*(zeta +1.)); 
+			/*Nodal function 5*/
+			dbasis[NUMNODESP1xP4*0+4 ] = +0.5 *    (2./3.) *(zeta - 0.5)*(zeta)*(zeta+0.5)*(zeta +1. ); 
+			dbasis[NUMNODESP1xP4*1+4 ] = -SQRT3/6.*(2./3.)*(zeta - 0.5)*(zeta)*(zeta+0.5)*(zeta +1. );
+			dbasis[NUMNODESP1xP4*2+4 ] = gauss->coord2 * 2./3.*( (2.*zeta+1.)*(zeta -0.5)*(zeta +0.5) + 2.*zeta *zeta*(zeta +1.)); 
+			/*Nodal function 6*/
+			dbasis[NUMNODESP1xP4*0+5 ] = 0. ; 
+			dbasis[NUMNODESP1xP4*1+5 ] = SQRT3/3.*(2./3.) *(zeta - 0.5)*(zeta)*(zeta+0.5)*(zeta +1. ); 
+			dbasis[NUMNODESP1xP4*2+5 ] = gauss->coord3 * 2./3.*( (2.*zeta+1.)*(zeta -0.5)*(zeta +0.5) + 2.*zeta *zeta*(zeta +1)); 
+
+			/*Nodal function 7*/
+			dbasis[NUMNODESP1xP4*0+6 ] = -0.5 * 4.*(zeta - 1.)*(zeta - 0.5)*(zeta+0.5)*(zeta +1. ) ; 
+			dbasis[NUMNODESP1xP4*1+6 ] = -SQRT3/6.* 4.*(zeta - 1.)*(zeta - 0.5)*(zeta+0.5)*(zeta +1.)  ; 
+			dbasis[NUMNODESP1xP4*2+6 ] = gauss->coord1* 4.*( 4.*zeta *zeta*zeta - (5./2.)*zeta ); 
+			/*Nodal function 8*/
+			dbasis[NUMNODESP1xP4*0+7 ] = +0.5* 4.*(zeta - 1.)*(zeta - 0.5)*(zeta+0.5)*(zeta +1. ) ; 
+			dbasis[NUMNODESP1xP4*1+7 ] = -SQRT3/6.* 4.*(zeta - 1.)*(zeta - 0.5)*(zeta+0.5)*(zeta +1. )  ; 
+			dbasis[NUMNODESP1xP4*2+7 ] = gauss->coord2* 4.*( 4.*zeta *zeta*zeta - (5./2.)*zeta ); 
+			/*Nodal function 9*/
+			dbasis[NUMNODESP1xP4*0+8 ] = 0. ; 
+			dbasis[NUMNODESP1xP4*1+8 ] = SQRT3/3. * 4.*(zeta - 1.)*(zeta - 0.5)*(zeta+0.5)*(zeta +1. )  ; 
+			dbasis[NUMNODESP1xP4*2+8 ] = gauss->coord3* 4.*( 4.*zeta *zeta*zeta - (5./2.)*zeta ); 
+
+			/*Nodal function 10*/
+			dbasis[NUMNODESP1xP4*0+9 ] = -0.5* (-8./3.)*(zeta - 1.)*(zeta - 0.5)*(zeta)*(zeta +1. ) ; 
+			dbasis[NUMNODESP1xP4*1+9 ] = -SQRT3/6.* (-8./3.)*(zeta - 1.)*(zeta - 0.5)*(zeta)*(zeta +1. ) ; 
+			dbasis[NUMNODESP1xP4*2+9 ] = gauss->coord1* (-8./3.)*((2.*zeta -1.)*(zeta-0.5)*(zeta +1.) +zeta*(zeta -1.)*( 2.*zeta + 0.5)); 
+			/*Nodal function 11*/
+			dbasis[NUMNODESP1xP4*0+10] = +0.5* (-8./3.)*(zeta - 1.)*(zeta - 0.5)*(zeta)*(zeta +1. ) ; 
+			dbasis[NUMNODESP1xP4*1+10] = -SQRT3/6.* (-8./3.)*(zeta - 1.)*(zeta - 0.5)*(zeta)*(zeta +1. ) ; 
+			dbasis[NUMNODESP1xP4*2+10] = gauss->coord2* (-8./3.)*((2.*zeta -1.)*(zeta-0.5)*(zeta +1.) +zeta *(zeta -1.)*( 2.*zeta + 0.5)); 
+			/*Nodal function 12*/
+			dbasis[NUMNODESP1xP4*0+11] = 0. ; 
+			dbasis[NUMNODESP1xP4*1+11] = SQRT3/3.* (-8./3.)*(zeta - 1.)*(zeta - 0.5)*(zeta)*(zeta +1. ) ; 
+			dbasis[NUMNODESP1xP4*2+11] = gauss->coord3* (-8./3.)*((2.*zeta-1.)*(zeta-0.5)*(zeta +1.) +zeta *(zeta -1.)*( 2.*zeta + 0.5));
+			/*Nodal function 13*/
+			dbasis[NUMNODESP1xP4*0+12] = -0.5* (-8./3.)*(zeta - 1.)*(zeta)*(zeta+0.5)*(zeta +1. ) ; 
+			dbasis[NUMNODESP1xP4*1+12] = -SQRT3/6.* (-8./3.)*(zeta - 1.)*(zeta)*(zeta+0.5)*(zeta +1. ) ; 
+			dbasis[NUMNODESP1xP4*2+12] = gauss->coord1* (-8./3.)*((2.*zeta -1. ) *(zeta+0.5)* (zeta +1.) +  zeta* (zeta -1.)*( 2.*zeta + 3./2.));
+			/*Nodal function 14*/
+			dbasis[NUMNODESP1xP4*0+13] = +0.5* (-8./3.)*(zeta - 1.)*(zeta)*(zeta+0.5)*(zeta +1. ) ; 
+			dbasis[NUMNODESP1xP4*1+13] = -SQRT3/6.* (-8./3.)*(zeta - 1.)*(zeta)*(zeta+0.5)*(zeta +1. ) ; 
+			dbasis[NUMNODESP1xP4*2+13] = gauss->coord2* (-8./3.)*((2.*zeta -1. )*(zeta+0.5)*(zeta +1.) +  zeta*(zeta -1.)*( 2.*zeta + 3./2.)); 
+			/*Nodal function 15*/
+			dbasis[NUMNODESP1xP4*0+14] = 0 ; 
+			dbasis[NUMNODESP1xP4*1+14] = SQRT3/3.* (-8./3.)*(zeta - 1.)*(zeta + 0.5)*(zeta)*(zeta +1. ) ; 
+			dbasis[NUMNODESP1xP4*2+14] = gauss->coord3* (-8./3.)*((2. *zeta -1. )*(zeta+0.5)*(zeta +1.) +  zeta*(zeta -1.)*( 2.*zeta + 3./2.));
+
+			return;
 		default:
 			_error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
@@ -1069,4 +1162,11 @@
 			break;
 		case P1xP3Enum:
+			numseg = 3;
+			indices = xNew<int>(numseg*2);
+			indices[0*2 + 0] = 0; indices[0*2 + 1] = 6;
+			indices[1*2 + 0] = 1; indices[1*2 + 1] = 7;
+			indices[2*2 + 0] = 2; indices[2*2 + 1] = 8;
+			break;
+		case P1xP4Enum:
 			numseg = 3;
 			indices = xNew<int>(numseg*2);
@@ -1130,4 +1230,5 @@
 		case P2xP4Enum:             return NUMNODESP2xP4;
 		case P1xP3Enum:             return NUMNODESP1xP3;
+		case P1xP4Enum:             return NUMNODESP1xP4;
 		case P1P1Enum:              return NUMNODESP1*2;
 		case P1P1GLSEnum:           return NUMNODESP1*2;
@@ -1196,4 +1297,5 @@
 		case P1xP2Enum:
 		case P1xP3Enum:
+		case P1xP4Enum:
 			numindices = 3;
 			indices    = xNew<int>(numindices);
Index: /issm/trunk/src/c/classes/Elements/Seg.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/Seg.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Elements/Seg.cpp	(revision 22758)
@@ -19,6 +19,6 @@
 #define NUMVERTICES 2
 /*Constructors/destructor/copy*/
-Seg::Seg(int seg_id, int seg_sid, int index, IoModel* iomodel,int nummodels)/*{{{*/
-		:ElementHook(nummodels,index+1,NUMVERTICES,iomodel){
+Seg::Seg(int seg_id, int seg_sid,IoModel* iomodel,int nummodels)/*{{{*/
+		:ElementHook(nummodels,seg_id,NUMVERTICES,iomodel){
 
 			/*id: */
@@ -168,4 +168,33 @@
 	*pxyz_front=xyz_front;
 }/*}}}*/
+IssmDouble Seg::GetGroundedPortion(IssmDouble* xyz_list){/*{{{*/
+	/*Computeportion of the element that is grounded*/ 
+
+	bool              mainlyfloating = true;
+	const IssmPDouble epsilon        = 1.e-15;
+	IssmDouble        phi;
+	IssmDouble        gl[NUMVERTICES];
+
+	/*Recover parameters and values*/
+	GetInputListOnVertices(&gl[0],MaskGroundediceLevelsetEnum);
+
+	/*Be sure that values are not zero*/
+	if(gl[0]==0.) gl[0]=gl[0]+epsilon;
+	if(gl[1]==0.) gl[1]=gl[1]+epsilon;
+
+	if(gl[0]>0 && gl[1]>0) phi=1; // All grounded
+	else if(gl[0]<0 && gl[1]<0) phi=0; // All floating
+	else if(gl[0]<0 && gl[1]>0){ //1 grounded
+		phi=1./(1.-gl[0]/gl[1]);
+	}
+	else if(gl[1]<0 && gl[0]>0){ //0 grounded
+		phi=1./(1.-gl[1]/gl[0]);
+	}
+
+	if(phi>1 || phi<0) _error_("Error. Problem with portion of grounded element: value should be between 0 and 1");
+
+	return phi;
+}
+/*}}}*/
 int        Seg::GetNumberOfNodes(void){/*{{{*/
 	return this->NumberofNodes(this->element_type);
Index: /issm/trunk/src/c/classes/Elements/Seg.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/Seg.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Elements/Seg.h	(revision 22758)
@@ -32,5 +32,5 @@
 		/*Seg constructors, destructors {{{*/
 		Seg(){};
-		Seg(int seg_id,int seg_sid,int i, IoModel* iomodel,int nummodels);
+		Seg(int seg_id,int seg_sid,IoModel* iomodel,int nummodels);
 		~Seg();
 		/*}}}*/
@@ -52,4 +52,5 @@
 		void        ComputeStressTensor(){_error_("not implemented yet");};
 		void        Configure(Elements* elements,Loads* loads,Nodes* nodesin,Vertices* verticesin,Materials* materials,Parameters* parameters){_error_("not implemented yet");};
+		void        ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index,int offset,int N,int M){_error_("not implemented yet");};
 		void        ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index){_error_("not implemented yet");};
 		void        ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum){_error_("not implemented yet");};
@@ -57,10 +58,10 @@
 		void        ElementSizes(IssmDouble* hx,IssmDouble* hy,IssmDouble* hz){_error_("not implemented yet");};
 		int         FiniteElement(void);
-		IssmDouble  FloatingArea(void){_error_("not implemented yet");};
+		IssmDouble  FloatingArea(bool scaled){_error_("not implemented yet");};
 		void        FSContactMigration(Vector<IssmDouble>* vertexgrounded,Vector<IssmDouble>* vertexfloating){_error_("not implemented yet");};
 		Element*    GetBasalElement(void){_error_("not implemented yet");};
 		int         GetElementType(void){_error_("not implemented yet");};
 		void        GetGroundedPart(int* point1,IssmDouble* fraction1, IssmDouble* fraction2,bool* mainlyfloating){_error_("not implemented yet");};
-		IssmDouble  GetGroundedPortion(IssmDouble* xyz_list){_error_("not implemented yet");};
+		IssmDouble  GetGroundedPortion(IssmDouble* xyz_list);
 		void		   GetIcefrontCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum);
 		void        GetInputValue(IssmDouble* pvalue,Node* node,int enumtype){_error_("not implemented yet");};
@@ -72,18 +73,14 @@
 		int         GetNumberOfNodes(int enum_type){_error_("not implemented yet");};
 		int         GetNumberOfVertices(void);
-		void        GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution,int enum_type){_error_("not implemented yet");};
-		Element*    GetUpperElement(void){_error_("not implemented yet");};
+		void        GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data,int offset,bool onsid){_error_("not implemented yet");};
 		void        GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data,bool onsid){_error_("not implemented yet");};
 		void        GetVerticesCoordinates(IssmDouble** pxyz_list);
 		void        GetVerticesCoordinatesBase(IssmDouble** pxyz_list){_error_("not implemented yet");};
 		void        GetVerticesCoordinatesTop(IssmDouble** pxyz_list){_error_("not implemented yet");};
-		IssmDouble  GroundedArea(void){_error_("not implemented yet");};
-		IssmDouble  IceMass(void){_error_("not implemented yet");};
-		IssmDouble  IceVolume(void){_error_("not implemented yet");};
-		IssmDouble  IceVolumeAboveFloatation(void){_error_("not implemented yet");};
-		void        InputControlUpdate(IssmDouble scalar,bool save_parameter){_error_("not implemented yet");};
+		IssmDouble  GroundedArea(bool scaled){_error_("not implemented yet");};
+		IssmDouble  IceVolume(bool scaled){_error_("not implemented yet");};
+		IssmDouble  IceVolumeAboveFloatation(bool scaled){_error_("not implemented yet");};
 		void        InputDepthAverageAtBase(int enum_type,int average_enum_type){_error_("not implemented yet");};
 		void        InputExtrude(int enum_type,int start){_error_("not implemented"); /*For penta only*/};
-		void        InputScale(int enum_type,IssmDouble scale_factor){_error_("not implemented yet");};
 		void        InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented yet");};
 		void        InputUpdateFromSolutionOneDof(IssmDouble* solution,int inputenum){_error_("not implemented yet");};
@@ -113,4 +110,5 @@
       Gauss*      NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order_horiz,int order_vert){_error_("not implemented yet");};
       Gauss*      NewGauss(int point1,IssmDouble fraction1,IssmDouble fraction2,bool mainlyfloating,int order){_error_("not implemented yet");};
+      Gauss*      NewGauss(int point1,IssmDouble fraction1,IssmDouble fraction2,int order){_error_("not implemented yet");};
 		Gauss*      NewGaussBase(int order){_error_("not implemented yet");};
 		Gauss*      NewGaussLine(int vertex1,int vertex2,int order){_error_("not implemented yet");};
@@ -132,4 +130,6 @@
 		int         NumberofNodesPressure(void){_error_("not implemented yet");};
 		int         NumberofNodesVelocity(void){_error_("not implemented yet");};
+		void        PicoUpdateBoxid(int* pmax_boxid_basin){_error_("not implemented yet");};
+		void			PicoUpdateBox(int loopboxid){_error_("not implemented yet");};
 		void        PotentialUngrounding(Vector<IssmDouble>* potential_sheet_ungrounding){_error_("not implemented yet");};
 		int         PressureInterpolation(void){_error_("not implemented yet");};
@@ -137,4 +137,5 @@
 		void        ResetFSBasalBoundaryCondition(void){_error_("not implemented yet");};
 		void        ResetHooks(){_error_("not implemented yet");};
+		void        SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index,int offset,int N,int M){_error_("not implemented yet");};
 		void        SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index){_error_("not implemented yet");};
 		void        SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Materials* materials,Parameters* parameters){_error_("not implemented yet");};
@@ -149,7 +150,7 @@
 		int         TensorInterpolation(void){_error_("not implemented yet");};
 		IssmDouble  TimeAdapt(){_error_("not implemented yet");};
-		IssmDouble  TotalFloatingBmb(void){_error_("not implemented yet");};
-		IssmDouble  TotalGroundedBmb(void){_error_("not implemented yet");};
-		IssmDouble  TotalSmb(void){_error_("not implemented yet");};
+		IssmDouble  TotalFloatingBmb(bool scaled){_error_("not implemented yet");};
+		IssmDouble  TotalGroundedBmb(bool scaled){_error_("not implemented yet");};
+		IssmDouble  TotalSmb(bool scaled){_error_("not implemented yet");};
 		void        Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finitelement){_error_("not implemented yet");};
 		void        UpdateConstraintsExtrudeFromBase(){_error_("not implemented");};
@@ -171,5 +172,5 @@
 #endif
 #ifdef _HAVE_ESA_
-		void    EsaGeodetic2D(Vector<IssmDouble>* pUp,Vector<IssmDouble>* pNorth,Vector<IssmDouble>* pEast,IssmDouble* xx,IssmDouble* yy){_error_("not implemented yet!");};
+		void    EsaGeodetic2D(Vector<IssmDouble>* pUp,Vector<IssmDouble>* pNorth,Vector<IssmDouble>* pEast,Vector<IssmDouble>* pX,Vector<IssmDouble>* pY,IssmDouble* xx,IssmDouble* yy){_error_("not implemented yet!");};
 		void    EsaGeodetic3D(Vector<IssmDouble>* pUp,Vector<IssmDouble>* pNorth,Vector<IssmDouble>* pEast,IssmDouble* latitude,IssmDouble* longitude,IssmDouble* radius,IssmDouble* xx,IssmDouble* yy,IssmDouble* zz,IssmDouble eartharea){_error_("not implemented yet!");};
 #endif
Index: /issm/trunk/src/c/classes/Elements/Tetra.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/Tetra.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Elements/Tetra.cpp	(revision 22758)
@@ -20,10 +20,10 @@
 
 /*Constructors/destructor/copy*/
-Tetra::Tetra(int seg_id, int seg_sid, int index, IoModel* iomodel,int nummodels)/*{{{*/
-		:ElementHook(nummodels,index+1,NUMVERTICES,iomodel){
+Tetra::Tetra(int tet_id, int tet_sid,IoModel* iomodel,int nummodels)/*{{{*/
+		:ElementHook(nummodels,tet_id,NUMVERTICES,iomodel){
 
 			/*id: */
-			this->id  = seg_id;
-			this->sid = seg_sid;
+			this->id  = tet_id;
+			this->sid = tet_sid;
 
 			//this->parameters: we still can't point to it, it may not even exist. Configure will handle this.
@@ -394,5 +394,5 @@
 						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data("md.inversion.min_parameters")[(tetra_vertex_ids[j]-1)*num_control_type+i]/yts;
 						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data("md.inversion.max_parameters")[(tetra_vertex_ids[j]-1)*num_control_type+i]/yts;
-						this->inputs->AddInput(new ControlInput(BalancethicknessThickeningRateEnum,TetraInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						this->inputs->AddInput(new ControlInput(BalancethicknessThickeningRateEnum,TetraInputEnum,nodeinputs,cmmininputs,cmmaxinputs,P1Enum,i+1));
 					}
 					break;
@@ -402,5 +402,5 @@
 						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data("md.inversion.min_parameters")[(tetra_vertex_ids[j]-1)*num_control_type+i]/yts;
 						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data("md.inversion.max_parameters")[(tetra_vertex_ids[j]-1)*num_control_type+i]/yts;
-						this->inputs->AddInput(new ControlInput(VxEnum,TetraInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						this->inputs->AddInput(new ControlInput(VxEnum,TetraInputEnum,nodeinputs,cmmininputs,cmmaxinputs,P1Enum,i+1));
 					}
 					break;
@@ -410,5 +410,5 @@
 						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data("md.inversion.min_parameters")[(tetra_vertex_ids[j]-1)*num_control_type+i]/yts;
 						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data("md.inversion.max_parameters")[(tetra_vertex_ids[j]-1)*num_control_type+i]/yts;
-						this->inputs->AddInput(new ControlInput(VyEnum,TetraInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						this->inputs->AddInput(new ControlInput(VyEnum,TetraInputEnum,nodeinputs,cmmininputs,cmmaxinputs,P1Enum,i+1));
 					}
 					break;
@@ -418,5 +418,5 @@
 						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data("md.inversion.min_parameters")[(tetra_vertex_ids[j]-1)*num_control_type+i];
 						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data("md.inversion.max_parameters")[(tetra_vertex_ids[j]-1)*num_control_type+i];
-						this->inputs->AddInput(new ControlInput(FrictionCoefficientEnum,TetraInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						this->inputs->AddInput(new ControlInput(FrictionCoefficientEnum,TetraInputEnum,nodeinputs,cmmininputs,cmmaxinputs,P1Enum,i+1));
 					}
 					break;
@@ -426,5 +426,5 @@
 						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data("md.inversion.min_parameters")[(tetra_vertex_ids[j]-1)*num_control_type+i];
 						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data("md.inversion.max_parameters")[(tetra_vertex_ids[j]-1)*num_control_type+i];
-						this->inputs->AddInput(new ControlInput(MaterialsRheologyBEnum,TetraInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						this->inputs->AddInput(new ControlInput(MaterialsRheologyBEnum,TetraInputEnum,nodeinputs,cmmininputs,cmmaxinputs,P1Enum,i+1));
 					}
 					break;
@@ -434,5 +434,5 @@
 						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data("md.inversion.min_parameters")[(tetra_vertex_ids[j]-1)*num_control_type+i];
 						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data("md.inversion.max_parameters")[(tetra_vertex_ids[j]-1)*num_control_type+i];
-						this->inputs->AddInput(new ControlInput(DamageDEnum,TetraInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						this->inputs->AddInput(new ControlInput(DamageDEnum,TetraInputEnum,nodeinputs,cmmininputs,cmmaxinputs,P1Enum,i+1));
 					}
 					break;
@@ -808,4 +808,5 @@
 void     Tetra::ResetHooks(){/*{{{*/
 
+	if(this->nodes) xDelete<Node*>(this->nodes);
 	this->nodes=NULL;
 	this->vertices=NULL;
@@ -903,4 +904,5 @@
 	/*Checks if debuging*/
 	_assert_(iomodel->elements);
+	_assert_(index==this->sid); 
 
 	/*Recover element type*/
Index: /issm/trunk/src/c/classes/Elements/Tetra.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/Tetra.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Elements/Tetra.h	(revision 22758)
@@ -32,5 +32,5 @@
 		/*Tetra constructors, destructors {{{*/
 		Tetra(){};
-		Tetra(int seg_id,int seg_sid,int i, IoModel* iomodel,int nummodels);
+		Tetra(int tet_id,int tet_sid,IoModel* iomodel,int nummodels);
 		~Tetra();
 		/*}}}*/
@@ -52,4 +52,5 @@
 		void        ComputeEsaStrainAndVorticity(){_error_("not implemented yet!");};
 		void        Configure(Elements* elements,Loads* loads,Nodes* nodesin,Vertices* verticesin,Materials* materials,Parameters* parameters);
+		void        ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index,int offset,int N,int M){_error_("not implemented yet");};
 		void        ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index){_error_("not implemented yet");};
 		void        ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum){_error_("not implemented yet");};
@@ -61,5 +62,5 @@
 		void        FaceOnSurfaceIndices(int* pindex1,int* pindex2,int* pindex3);
 		int         FiniteElement(void);
-		IssmDouble  FloatingArea(void){_error_("not implemented yet");};
+		IssmDouble  FloatingArea(bool scaled){_error_("not implemented yet");};
 		void        FSContactMigration(Vector<IssmDouble>* vertexgrounded,Vector<IssmDouble>* vertexfloating){_error_("not implemented yet");};
 		IssmDouble     GetArea3D(void){_error_("not implemented yet!");};
@@ -78,16 +79,14 @@
 		int         GetNumberOfNodes(int enum_type){_error_("not implemented yet");};
 		int         GetNumberOfVertices(void);
-		void        GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution,int enum_type){_error_("not implemented yet");};
-		Element*    GetUpperElement(void){_error_("not implemented yet");};
+		void        GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data,int offset,bool onsid){_error_("not implemented yet");};
 		void        GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data,bool onsid){_error_("not implemented yet");};
 		void        GetVerticesCoordinatesBase(IssmDouble** pxyz_list);
 		void        GetVerticesCoordinatesTop(IssmDouble** pxyz_list);
 		void        GradientIndexing(int* indexing,int control_index){_error_("not implemented yet");};
-		IssmDouble  GroundedArea(void){_error_("not implemented yet");};
+		IssmDouble  GroundedArea(bool scaled){_error_("not implemented yet");};
 		bool        HasFaceOnBase();
 		bool        HasFaceOnSurface();
-		IssmDouble  IceMass(void){_error_("not implemented yet");};
-		IssmDouble  IceVolume(void){_error_("not implemented yet");};
-		IssmDouble  IceVolumeAboveFloatation(void){_error_("not implemented yet");};
+		IssmDouble  IceVolume(bool scaled){_error_("not implemented yet");};
+		IssmDouble  IceVolumeAboveFloatation(bool scaled){_error_("not implemented yet");};
 		bool        IsFaceOnBoundary(void){_error_("not implemented yet");};
 		bool		   IsIcefront(void);
@@ -96,8 +95,6 @@
 		bool        IsOnSurface();
 		bool        IsZeroLevelset(int levelset_enum){_error_("not implemented");};
-		void        InputControlUpdate(IssmDouble scalar,bool save_parameter){_error_("not implemented yet");};
 		void        InputDepthAverageAtBase(int enum_type,int average_enum_type){_error_("not implemented yet");};
 		void        InputExtrude(int enum_type,int start){_error_("not implemented"); /*For penta only*/};
-		void        InputScale(int enum_type,IssmDouble scale_factor){_error_("not implemented yet");};
 		void        InputUpdateFromIoModel(int index, IoModel* iomodel);
 		void        InputUpdateFromSolutionOneDof(IssmDouble* solution,int inputenum);
@@ -121,4 +118,5 @@
       Gauss*      NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order_horiz,int order_vert);
       Gauss*      NewGauss(int point1,IssmDouble fraction1,IssmDouble fraction2,bool mainlyfloating,int order){_error_("not implemented yet");};
+      Gauss*      NewGauss(int point1,IssmDouble fraction1,IssmDouble fraction2,int order){_error_("not implemented yet");};
 		Gauss*      NewGaussBase(int order);
 		Gauss*      NewGaussLine(int vertex1,int vertex2,int order){_error_("not implemented yet");};
@@ -140,4 +138,6 @@
 		int         NumberofNodesPressure(void);
 		int         NumberofNodesVelocity(void);
+		void			PicoUpdateBoxid(int* pmax_boxid_basin){_error_("not implemented yet");};	
+		void			PicoUpdateBox(int loopboxid){_error_("not implemented yet");};
 		void        PotentialUngrounding(Vector<IssmDouble>* potential_sheet_ungrounding){_error_("not implemented yet");};
 		int         PressureInterpolation(void);
@@ -145,4 +145,5 @@
 		void        ResetHooks();
 		void        ReduceMatrices(ElementMatrix* Ke,ElementVector* pe);
+		void        SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index,int offset,int N, int M){_error_("not implemented yet");};
 		void        SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index){_error_("not implemented yet");};
 		void        SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Materials* materials,Parameters* parameters);
@@ -158,7 +159,7 @@
 		int         TensorInterpolation(void);
 		IssmDouble  TimeAdapt(){_error_("not implemented yet");};
-		IssmDouble  TotalFloatingBmb(void){_error_("not implemented yet");};
-		IssmDouble  TotalGroundedBmb(void){_error_("not implemented yet");};
-		IssmDouble  TotalSmb(void){_error_("not implemented yet");};
+		IssmDouble  TotalFloatingBmb(bool scaled){_error_("not implemented yet");};
+		IssmDouble  TotalGroundedBmb(bool scaled){_error_("not implemented yet");};
+		IssmDouble  TotalSmb(bool scaled){_error_("not implemented yet");};
 		void        Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finitelement);
 		void        UpdateConstraintsExtrudeFromBase(){_error_("not implemented");};
@@ -178,5 +179,5 @@
 #endif
 #ifdef _HAVE_ESA_
-		void    EsaGeodetic2D(Vector<IssmDouble>* pUp,Vector<IssmDouble>* pNorth,Vector<IssmDouble>* pEast,IssmDouble* xx,IssmDouble* yy){_error_("not implemented yet!");};
+		void    EsaGeodetic2D(Vector<IssmDouble>* pUp,Vector<IssmDouble>* pNorth,Vector<IssmDouble>* pEast,Vector<IssmDouble>* pX,Vector<IssmDouble>* pY,IssmDouble* xx,IssmDouble* yy){_error_("not implemented yet!");};
 		void    EsaGeodetic3D(Vector<IssmDouble>* pUp,Vector<IssmDouble>* pNorth,Vector<IssmDouble>* pEast,IssmDouble* latitude,IssmDouble* longitude,IssmDouble* radius,IssmDouble* xx,IssmDouble* yy,IssmDouble* zz,IssmDouble eartharea){_error_("not implemented yet!");};
 #endif
Index: /issm/trunk/src/c/classes/Elements/Tria.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/Tria.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Elements/Tria.cpp	(revision 22758)
@@ -25,6 +25,6 @@
 
 /*Constructors/destructor/copy*/
-Tria::Tria(int tria_id, int tria_sid, int index, IoModel* iomodel,int nummodels)/*{{{*/
-	:ElementHook(nummodels,index+1,NUMVERTICES,iomodel){
+Tria::Tria(int tria_id, int tria_sid, IoModel* iomodel,int nummodels)/*{{{*/
+	:ElementHook(nummodels,tria_id,NUMVERTICES,iomodel){
 
 		/*id: */
@@ -170,4 +170,34 @@
 }
 /*}}}*/
+void       Tria::AddControlInput(int input_enum,IssmDouble* values,IssmDouble* values_min,IssmDouble* values_max, int interpolation_enum,int id){/*{{{*/
+
+	/*Call inputs method*/
+	_assert_(this->inputs);
+	this->inputs->AddInput(new ControlInput(input_enum,TriaInputEnum,values,values_min,values_max,interpolation_enum,id));
+}
+/*}}}*/
+void       Tria::DatasetInputCreate(IssmDouble* array,int M,int N,int* individual_enums,int num_inputs,IoModel* iomodel,int input_enum){/*{{{*/
+
+	IssmDouble nodeinputs[NUMVERTICES];
+	if(num_inputs<1) _error_("Cannot create a DatasetInput of size <1");
+	if(M!=iomodel->numberofvertices) _error_("not supported yet");
+	if(N!=num_inputs) _error_("sizes are not consistent");
+
+	int        tria_vertex_ids[3];
+	
+	for(int k=0;k<3;k++){
+		tria_vertex_ids[k]=reCast<int>(iomodel->elements[3*this->Sid()+k]); //ids for vertices are in the elements array from Matlab
+	}
+	/*Create inputs and add to DataSetInput*/
+	DatasetInput* datasetinput=new DatasetInput(input_enum);
+	for(int i=0;i<num_inputs;i++){
+		for(int j=0;j<NUMVERTICES;j++)nodeinputs[j]=array[(tria_vertex_ids[j]-1)*N+i];
+		datasetinput->AddInput(new TriaInput(input_enum,nodeinputs,P1Enum),individual_enums[i]);
+	}
+
+	/*Add datasetinput to element inputs*/
+	this->inputs->AddInput(datasetinput);
+}
+/*}}}*/
 void       Tria::AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part){/*{{{*/
 
@@ -208,5 +238,5 @@
 }
 /*}}}*/
-void       Tria::CalvingRateDev(){/*{{{*/
+void       Tria::CalvingRateVonmises(){/*{{{*/
 
 	IssmDouble  xyz_list[NUMVERTICES][3];
@@ -216,6 +246,7 @@
 	IssmDouble  calvingrate[NUMVERTICES];
 	IssmDouble  lambda1,lambda2,ex,ey,vx,vy,vel;
-	IssmDouble  sigma_vm,sigma_max,sigma_max_floating,sigma_max_grounded;
-	IssmDouble  epse_2,groundedice;
+	IssmDouble  sigma_vm[NUMVERTICES];
+	IssmDouble  B,sigma_max,sigma_max_floating,sigma_max_grounded;
+	IssmDouble  epse_2,groundedice,bed;
 
 	/* Get node coordinates and dof list: */
@@ -225,9 +256,10 @@
 	Input* vx_input = inputs->GetInput(VxEnum); _assert_(vx_input);
 	Input* vy_input = inputs->GetInput(VyEnum); _assert_(vy_input);
+	Input* B_input  = inputs->GetInput(MaterialsRheologyBbarEnum);   _assert_(B_input);
 	Input* gr_input = inputs->GetInput(MaskGroundediceLevelsetEnum); _assert_(gr_input);
-	IssmDouble  B   = this->GetMaterialParameter(MaterialsRheologyBbarEnum);
+	Input* bs_input = inputs->GetInput(BaseEnum);                    _assert_(bs_input);
+	Input* smax_fl_input = inputs->GetInput(CalvingStressThresholdFloatingiceEnum); _assert_(smax_fl_input);
+	Input* smax_gr_input = inputs->GetInput(CalvingStressThresholdGroundediceEnum); _assert_(smax_gr_input);
 	IssmDouble  n   = this->GetMaterialParameter(MaterialsRheologyNEnum);
-	this->parameters->FindParam(&sigma_max_floating,CalvingStressThresholdFloatingiceEnum);
-	this->parameters->FindParam(&sigma_max_grounded,CalvingStressThresholdGroundediceEnum);
 
 	/* Start looping on the number of vertices: */
@@ -237,7 +269,11 @@
 
 		/*Get velocity components and thickness*/
+		B_input->GetInputValue(&B,gauss);
 		vx_input->GetInputValue(&vx,gauss);
 		vy_input->GetInputValue(&vy,gauss);
 		gr_input->GetInputValue(&groundedice,gauss);
+		bs_input->GetInputValue(&bed,gauss);
+		smax_fl_input->GetInputValue(&sigma_max_floating,gauss);
+		smax_gr_input->GetInputValue(&sigma_max_grounded,gauss);
 		vel=sqrt(vx*vx+vy*vy)+1.e-14;
 
@@ -256,5 +292,5 @@
 		/*Calculate sigma_vm*/
 		epse_2    = 1./2. *(lambda1*lambda1 + lambda2*lambda2);
-		sigma_vm  = sqrt(3.) * B * pow(epse_2,1./(2.*n));
+		sigma_vm[iv]  = sqrt(3.) * B * pow(epse_2,1./(2.*n));
 
 		/*OLD (keep for a little bit)*/
@@ -270,7 +306,13 @@
 
 		/*Assign values*/
-		calvingratex[iv]=vx*sigma_vm/sigma_max;
-		calvingratey[iv]=vy*sigma_vm/sigma_max;
-		calvingrate[iv]=sqrt(calvingratex[iv]*calvingratex[iv] + calvingratey[iv]*calvingratey[iv]);
+		if(bed>0.){
+			calvingratex[iv]=0.;
+			calvingratey[iv]=0.;
+		}
+		else{
+			calvingratex[iv]=vx*sigma_vm[iv]/sigma_max;
+			calvingratey[iv]=vy*sigma_vm[iv]/sigma_max;
+		}
+		calvingrate[iv] =sqrt(calvingratex[iv]*calvingratex[iv] + calvingratey[iv]*calvingratey[iv]);
 	}
 
@@ -279,4 +321,5 @@
 	this->inputs->AddInput(new TriaInput(CalvingrateyEnum,&calvingratey[0],P1Enum));
 	this->inputs->AddInput(new TriaInput(CalvingCalvingrateEnum,&calvingrate[0],P1Enum));
+	this->inputs->AddInput(new TriaInput(SigmaVMEnum,&sigma_vm[0],P1Enum));
 
 	/*Clean up and return*/
@@ -284,11 +327,102 @@
 }
 /*}}}*/
+void       Tria::CalvingCrevasseDepth(){/*{{{*/
+	
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  calvingrate[NUMVERTICES];
+	IssmDouble  vx,vy,vel;
+	IssmDouble  critical_fraction,water_height;
+	IssmDouble  bed,Ho,thickness,float_depth;
+	IssmDouble  surface_crevasse[NUMVERTICES], basal_crevasse[NUMVERTICES], crevasse_depth[NUMVERTICES], H_surf, H_surfbasal;
+	IssmDouble  strainparallel, straineffective;
+	IssmDouble  s_xx,s_xy,s_yy,s1,s2,stmp;
+
+	/* Get node coordinates and dof list: */
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+		
+	/*Get the critical fraction of thickness surface and basal crevasses penetrate for calving onset*/
+	this->parameters->FindParam(&critical_fraction,CalvingCrevasseDepthEnum);
+		
+	IssmDouble rho_ice        = this->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble rho_seawater   = this->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	IssmDouble rho_freshwater = this->GetMaterialParameter(MaterialsRhoFreshwaterEnum);
+	IssmDouble constant_g     = this->GetMaterialParameter(ConstantsGEnum);
+	IssmDouble rheology_n     = this->GetMaterialParameter(MaterialsRheologyNEnum);
+
+	Input*   H_input                 = inputs->GetInput(ThicknessEnum); _assert_(H_input);
+	Input*   bed_input               = inputs->GetInput(BedEnum); _assert_(bed_input);
+	Input*   surface_input           = inputs->GetInput(SurfaceEnum); _assert_(surface_input);
+	Input*	strainrateparallel_input  = inputs->GetInput(StrainRateparallelEnum);  _assert_(strainrateparallel_input);
+	Input*	strainrateeffective_input = inputs->GetInput(StrainRateeffectiveEnum); _assert_(strainrateeffective_input);
+	Input*	vx_input                  = inputs->GetInput(VxEnum); _assert_(vx_input);
+	Input*	vy_input                  = inputs->GetInput(VxEnum); _assert_(vy_input);
+	Input*   waterheight_input       = inputs->GetInput(WaterheightEnum); _assert_(waterheight_input);
+	Input*   s_xx_input              = inputs->GetInput(DeviatoricStressxxEnum);     _assert_(s_xx_input);
+	Input*   s_xy_input              = inputs->GetInput(DeviatoricStressxyEnum);     _assert_(s_xy_input);
+	Input*   s_yy_input              = inputs->GetInput(DeviatoricStressyyEnum);     _assert_(s_yy_input);
+	
+	/*Loop over all elements of this partition*/
+	GaussTria* gauss=new GaussTria();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+	
+		H_input->GetInputValue(&thickness,gauss);
+		bed_input->GetInputValue(&bed,gauss);
+		surface_input->GetInputValue(&float_depth,gauss);
+		strainrateparallel_input->GetInputValue(&strainparallel,gauss);
+		strainrateeffective_input->GetInputValue(&straineffective,gauss);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		waterheight_input->GetInputValue(&water_height,gauss);
+		s_xx_input->GetInputValue(&s_xx,gauss);
+		s_xy_input->GetInputValue(&s_xy,gauss);
+		s_yy_input->GetInputValue(&s_yy,gauss);
+		
+		vel=sqrt(vx*vx+vy*vy)+1.e-14;
+
+		s1=(s_xx+s_yy)/2.+sqrt(pow((s_xx-s_yy)/2.,2)+pow(s_xy,2));
+		s2=(s_xx+s_yy)/2.-sqrt(pow((s_xx-s_yy)/2.,2)+pow(s_xy,2));
+		if(fabs(s2)>fabs(s1)){stmp=s2; s2=s1; s1=stmp;}
+		
+		Ho = thickness - (rho_seawater/rho_ice) * (-bed);
+		if(Ho<0.)  Ho=0.;
+
+		/*Otero2010: balance between the tensile deviatoric stress and ice overburden pressure*/
+		/*surface crevasse*/
+		//surface_crevasse[iv] = rheology_B * strainparallel * pow(straineffective, ((1 / rheology_n)-1)) / (rho_ice * constant_g);
+		surface_crevasse[iv] = s1 / (rho_ice*constant_g);
+		if (surface_crevasse[iv]<0.) {
+			surface_crevasse[iv]=0.;
+			water_height = 0.;
+		}
+		//if (surface_crevasse[iv]<water_height){
+		//	water_height = surface_crevasse[iv];
+		//}
+		
+		/*basal crevasse*/
+		//basal_crevasse[iv] = (rho_ice/(rho_seawater-rho_ice)) * (rheology_B * strainparallel * pow(straineffective,((1/rheology_n)-1)) / (rho_ice*constant_g) - Ho);
+		basal_crevasse[iv] = (rho_ice/(rho_seawater-rho_ice))* (s1/ (rho_ice*constant_g)-Ho);
+		if (basal_crevasse[iv]<0.) basal_crevasse[iv]=0.;
+		if (bed>0.) basal_crevasse[iv] = 0.; 
+	
+		H_surf = surface_crevasse[iv] + (rho_freshwater/rho_ice)*water_height - critical_fraction*float_depth;
+		H_surfbasal = (surface_crevasse[iv] + (rho_freshwater/rho_ice)*water_height + basal_crevasse[iv])-(critical_fraction*thickness);
+		
+		crevasse_depth[iv] = max(H_surf,H_surfbasal);
+	}
+	
+	this->inputs->AddInput(new TriaInput(SurfaceCrevasseEnum,&surface_crevasse[0],P1Enum));
+	this->inputs->AddInput(new TriaInput(BasalCrevasseEnum,&basal_crevasse[0],P1Enum));
+	this->inputs->AddInput(new TriaInput(CrevasseDepthEnum,&crevasse_depth[0],P1Enum));
+
+	delete gauss;
+}
+/*}}}*/
 void       Tria::CalvingRateLevermann(){/*{{{*/
 
 	IssmDouble  xyz_list[NUMVERTICES][3];
-	GaussTria* gauss=NULL;
 	IssmDouble  vx,vy,vel;
 	IssmDouble  strainparallel;
-	IssmDouble  propcoeff;
+	IssmDouble  propcoeff,bed;
 	IssmDouble  strainperpendicular;
 	IssmDouble  calvingratex[NUMVERTICES];
@@ -300,12 +434,13 @@
 
 	/*Retrieve all inputs and parameters we will need*/
-	Input* vx_input=inputs->GetInput(VxEnum);																		_assert_(vx_input);
-	Input* vy_input=inputs->GetInput(VyEnum);																		_assert_(vy_input);
-	Input* strainparallel_input=inputs->GetInput(StrainRateparallelEnum);								_assert_(strainparallel_input);
-	Input* strainperpendicular_input=inputs->GetInput(StrainRateperpendicularEnum);					_assert_(strainperpendicular_input);
-	Input* levermanncoeff_input=inputs->GetInput(CalvinglevermannCoeffEnum);                     _assert_(levermanncoeff_input);
+	Input* vx_input=inputs->GetInput(VxEnum);													_assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);													_assert_(vy_input);
+	Input* bs_input = inputs->GetInput(BaseEnum);                                 _assert_(bs_input);
+	Input* strainparallel_input=inputs->GetInput(StrainRateparallelEnum);			_assert_(strainparallel_input);
+	Input* strainperpendicular_input=inputs->GetInput(StrainRateperpendicularEnum);_assert_(strainperpendicular_input);
+	Input* levermanncoeff_input=inputs->GetInput(CalvinglevermannCoeffEnum);      _assert_(levermanncoeff_input);
 
 	/* Start looping on the number of vertices: */
-	gauss=new GaussTria();
+	GaussTria* gauss=new GaussTria();
 	for (int iv=0;iv<NUMVERTICES;iv++){
 		gauss->GaussVertex(iv);
@@ -318,10 +453,13 @@
 		strainperpendicular_input->GetInputValue(&strainperpendicular,gauss);
 		levermanncoeff_input->GetInputValue(&propcoeff,gauss);
+		bs_input->GetInputValue(&bed,gauss);
 
 		/*Calving rate proportionnal to the positive product of the strain rate along the ice flow direction and the strain rate perpendicular to the ice flow */
-		calvingrate[iv]=propcoeff*strainparallel*strainperpendicular;
-		if(calvingrate[iv]<0){
-			calvingrate[iv]=0;
-		}
+		if(strainparallel>0. && strainperpendicular>0. && bed<=0.){
+			calvingrate[iv]=propcoeff*strainparallel*strainperpendicular;
+		}
+		else
+			calvingrate[iv]=0.;
+		
 		calvingratex[iv]=calvingrate[iv]*vx/(sqrt(vel)+1.e-14);
 		calvingratey[iv]=calvingrate[iv]*vy/(sqrt(vel)+1.e-14);
@@ -415,5 +553,5 @@
 }
 /*}}}*/
-void			Tria::ComputeEsaStrainAndVorticity(){ /*{{{*/
+void			    Tria::ComputeEsaStrainAndVorticity(){ /*{{{*/
 
 	IssmDouble  xyz_list[NUMVERTICES][3];
@@ -429,6 +567,6 @@
 
 	/*Retrieve all inputs we will be needing: */
-	Input* vx_input=this->GetInput(EsaEmotionEnum); _assert_(vx_input);
-	Input* vy_input=this->GetInput(EsaNmotionEnum); _assert_(vy_input);
+	Input* vx_input=this->GetInput(EsaXmotionEnum); _assert_(vx_input);
+	Input* vy_input=this->GetInput(EsaYmotionEnum); _assert_(vy_input);
 	
 	/* Start looping on the number of vertices: */
@@ -604,4 +742,37 @@
 }
 /*}}}*/
+void       Tria::ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index,int offset,int N, int M){/*{{{*/
+
+	int    idlist[NUMVERTICES];
+	int	gradidlist[NUMVERTICES];
+	IssmDouble grad_list[NUMVERTICES];
+	Input* grad_input=NULL;
+
+	Input* input=inputs->GetInput(enum_type);
+	if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
+
+	GradientIndexing(&gradidlist[0],control_index,true);
+
+	for(int n=0;n<N;n++){
+		for(int i=0;i<NUMVERTICES;i++){
+			idlist[i] = offset + this->vertices[i]->Sid()+n*M;
+			grad_list[i]=gradient[idlist[i]];
+		}
+
+		ControlInput* controlinput = xDynamicCast<ControlInput*>(input);
+		if(controlinput->layout_enum!=TransientInputEnum){
+			grad_input=new TriaInput(GradientEnum,grad_list,P1Enum);
+			controlinput->SetGradient(grad_input);
+		}
+		else{
+			grad_input = new TriaInput(GradientEnum,grad_list,P1Enum);
+			controlinput->SetGradient(grad_input,n);
+			controlinput->Configure(parameters);
+		}
+	}
+
+		
+}/*}}}*/
 void       Tria::ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index){/*{{{*/
 
@@ -652,4 +823,67 @@
 
 }/*}}}*/
+void       Tria::CreateDistanceInputFromSegmentlist(IssmDouble* segments,int numsegments,int distanceenum){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble d,xn,yn;
+
+	/*Get current field and vertex coordinates*/
+	IssmDouble ls[NUMVERTICES];
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	GetInputListOnVertices(&ls[0],distanceenum);
+
+	/*Get distance from list of segments and reset ls*/
+	for(int j=0;j<NUMVERTICES;j++){
+		IssmDouble dmin = 1.e+50;
+		for(int i=0;i<numsegments;i++){
+			IssmDouble x = xyz_list[j][0];
+			IssmDouble y = xyz_list[j][1];
+			IssmDouble l2 = (segments[4*i+2]-segments[4*i+0])*(segments[4*i+2]-segments[4*i+0]) + (segments[4*i+3]-segments[4*i+1])*(segments[4*i+3]-segments[4*i+1]);
+
+			/*Segment has a length of 0*/
+			if(l2==0.){
+				d = (x-segments[4*i+0])*(x-segments[4*i+0])+(y-segments[4*i+1])*(y-segments[4*i+1]);
+				if(d<dmin) dmin = d;
+				continue;
+			}
+
+			/*Consider the line extending the segment, parameterized as v + t (w - v).
+			 *We find projection of point p onto the line.
+			 *It falls where t = [(p-v) . (w-v)] / |w-v|^2*/
+			IssmDouble t = ((x-segments[4*i+0])*(segments[4*i+2]-segments[4*i+0]) + (y-segments[4*i+1])*(segments[4*i+3]-segments[4*i+1]))/l2;
+			if(t < 0.0){
+				// Beyond the 'v' end of the segment
+				d = (x-segments[4*i+0])*(x-segments[4*i+0])+(y-segments[4*i+1])*(y-segments[4*i+1]);
+			}
+			else if (t > 1.0){
+				// Beyond the 'w' end of the segment
+				d = (x-segments[4*i+2])*(x-segments[4*i+2])+(y-segments[4*i+3])*(y-segments[4*i+3]);
+			}
+			else{
+				// Projection falls on the segment
+				xn = segments[4*i+0] + t * (segments[4*i+2] - segments[4*i+0]);
+				yn = segments[4*i+1] + t * (segments[4*i+3] - segments[4*i+1]);
+				d = (x-xn)*(x-xn)+(y-yn)*(y-yn);
+			}
+
+			if(d<dmin) dmin = d;
+		}
+
+		/*Update signed distance*/
+		dmin = sqrt(dmin);
+		// if(dmin>10000) dmin=10000;
+		if(ls[j]>0){
+			ls[j] = dmin;
+		}
+		else{
+			ls[j] = - dmin;
+		}
+	}
+
+	/*Update Levelset*/
+	this->inputs->AddInput(new TriaInput(distanceenum,&ls[0],P1Enum));
+}
+/*}}}*/
 int        Tria::EdgeOnBaseIndex(void){/*{{{*/
 
@@ -732,5 +966,5 @@
 	switch(response_enum){
 		case MaterialsRheologyBbarEnum:
-			*presponse=this->material->GetBbar();
+			*presponse=this->material->GetBbar(NULL);
 			break;
 
@@ -780,9 +1014,9 @@
 }
 /*}}}*/
-IssmDouble Tria::FloatingArea(void){/*{{{*/
+IssmDouble Tria::FloatingArea(bool scaled){/*{{{*/
 
 	/*Intermediaries*/
 	int         domaintype;
-	IssmDouble  phi;
+	IssmDouble  phi,scalefactor,floatingarea;
 	IssmDouble *xyz_list  = NULL;
 
@@ -795,8 +1029,14 @@
 	this->GetVerticesCoordinates(&xyz_list);
 	phi=this->GetGroundedPortion(xyz_list);
+	floatingarea=(1-phi)*this->GetArea();
+	if(scaled==true){
+		Input* scalefactor_input = inputs->GetInput(MeshScaleFactorEnum); _assert_(scalefactor_input);
+		scalefactor_input->GetInputAverage(&scalefactor);
+		floatingarea=floatingarea*scalefactor;
+	}
 
 	/*Clean up and return*/
 	xDelete<IssmDouble>(xyz_list);
-	return (1-phi)*this->GetArea();
+	return floatingarea;
 }
 /*}}}*/
@@ -900,4 +1140,9 @@
 	_assert_(x2*y3 - y2*x3 + x1*y2 - y1*x2 + x3*y1 - y3*x1>0);
 	return (x2*y3 - y2*x3 + x1*y2 - y1*x2 + x3*y1 - y3*x1)/2;
+}
+/*}}}*/
+IssmDouble Tria::GetHorizontalSurfaceArea(void){/*{{{*/
+
+	return this->GetArea();
 }
 /*}}}*/
@@ -1070,4 +1315,5 @@
 			f2=gl[1]/(gl[1]-gl[0]);
 		}
+		else _error_("case not possible");
 	}
 	*point1=point;
@@ -1180,4 +1426,5 @@
 				xyz_bis[2][2]=*(xyz_list+3*1+2)+s2*(*(xyz_list+3*2+2)-*(xyz_list+3*1+2));
 			}
+			else _error_("case not possible");
 
 			/*Compute fraction of grounded element*/
@@ -1284,5 +1531,5 @@
 
 }/*}}}*/
-void			Tria::GetLevelsetIntersection(int** pindices, int* pnumiceverts, IssmDouble* fraction, int levelset_enum, IssmDouble level){/*{{{*/
+void       Tria::GetLevelsetIntersection(int** pindices, int* pnumiceverts, IssmDouble* fraction, int levelset_enum, IssmDouble level){/*{{{*/
 	
 	/* GetLevelsetIntersection computes: 
@@ -1365,5 +1612,5 @@
 
 	bool               negative=true;
-	int                point;
+	int                point=0;
 	const IssmPDouble  epsilon= 1.e-15;
 	IssmDouble         f1,f2;
@@ -1403,4 +1650,7 @@
 			f2=gl[1]/(gl[1]-gl[0]);
 		}
+		else{
+			_error_("This case should NOT be happening");
+		}
 	}
 	*point1=point;
@@ -1439,36 +1689,4 @@
 }
 /*}}}*/
-void       Tria::GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution, int enum_type){/*{{{*/
-
-	int        *doflist = NULL;
-	IssmDouble  value;
-
-	/*Fetch number of nodes for this finite element*/
-	int numnodes = this->NumberofNodes(this->element_type);
-
-	/*Fetch dof list and allocate solution vector*/
-	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
-	IssmDouble* values = xNew<IssmDouble>(numnodes);
-
-	/*Get inputs*/
-	Input* enum_input=inputs->GetInput(enum_type); _assert_(enum_input);
-
-	/*Ok, we have the values, fill in the array: */
-	GaussTria* gauss=new GaussTria();
-	for(int i=0;i<numnodes;i++){
-		gauss->GaussNode(this->element_type,i);
-
-		enum_input->GetInputValue(&value,gauss);
-		values[i]=value;
-	}
-
-	solution->SetValues(numnodes,doflist,values,INS_VAL);
-
-	/*Free ressources:*/
-	xDelete<int>(doflist);
-	xDelete<IssmDouble>(values);
-	delete gauss;
-}
-/*}}}*/
 void       Tria::GetVectorFromControlInputs(Vector<IssmDouble>* vector,int control_enum,int control_index,const char* data,bool onsid){/*{{{*/
 
@@ -1491,4 +1709,80 @@
 
 	((ControlInput*)input)->GetVectorFromInputs(vector,&vertexidlist[0],data);
+}
+/*}}}*/
+void       Tria::GetVectorFromControlInputs(Vector<IssmDouble>* vector,int control_enum,int control_index,const char* data,int offset, bool onsid){/*{{{*/
+
+	int* idlist = NULL;
+	IssmDouble* values = NULL;
+	int* M = NULL;
+
+	/*Get out if this is not an element input*/
+	if(!IsInput(control_enum)) _error_("Enum "<<EnumToStringx(control_enum)<<" is not in IsInput");
+	Input* input=(Input*)this->inputs->GetInput(control_enum);   _assert_(input);
+
+	parameters->FindParam(&M,NULL,ControlInputSizeMEnum);
+	
+	/*Cast to Controlinput*/
+	if(input->ObjectEnum()!=ControlInputEnum) _error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
+	ControlInput* controlinput = xDynamicCast<ControlInput*>(input);
+	
+	if(strcmp(data,"value")==0){
+		input  = controlinput->values;
+	}
+	else if (strcmp(data,"lowerbound")==0){
+		input = controlinput->minvalues;
+	}
+	else if (strcmp(data,"upperbound")==0){
+		input = controlinput->maxvalues;
+	}
+	else if (strcmp(data,"gradient")==0){
+		input = controlinput->gradient;
+	}
+	else{
+		_error_("Data " << data << " not supported yet");
+	}
+	/*Check what input we are dealing with*/
+	
+	switch(input->ObjectEnum()){
+		case TriaInputEnum:
+			  {
+				TriaInput* triainput = xDynamicCast<TriaInput*>(input);
+				if(triainput->interpolation_type!=P1Enum) _error_("not supported yet");
+
+				/*Create list of indices and values for global vector*/
+				idlist = xNew<int>(NUMVERTICES);
+				values = xNew<IssmDouble>(NUMVERTICES);
+				GradientIndexing(&idlist[0],control_index,true);
+				for(int i=0;i<NUMVERTICES;i++){
+					values[i] = triainput->values[i];
+				}
+				vector->SetValues(NUMVERTICES,idlist,values,INS_VAL);
+				break;
+			  }
+			
+		case TransientInputEnum:
+				{
+					TransientInput* transientinput = xDynamicCast<TransientInput*>(input);
+					int N = transientinput->numtimesteps;
+					idlist = xNew<int>(NUMVERTICES*N);
+					values = xNew<IssmDouble>(NUMVERTICES*N);
+					for(int t=0;t<transientinput->numtimesteps;t++) {
+						IssmDouble time = transientinput->GetTimeByOffset(t);
+						input = transientinput->GetTimeInput(time);
+						TriaInput* timeinput = xDynamicCast<TriaInput*>(input);
+						if(timeinput->interpolation_type!=P1Enum) _error_("not supported yet");
+						/*Create list of indices and values for global vector*/
+						for(int i=0;i<NUMVERTICES;i++){
+								idlist[N*i+t] = offset + this->vertices[i]->Sid()+t*M[control_index];
+								values[N*i+t] = timeinput->values[i];
+						}
+					}
+					vector->SetValues(NUMVERTICES*transientinput->numtimesteps,idlist,values,INS_VAL);
+					break;
+				}
+		default: _error_("input "<<input->ObjectEnum()<<" not supported yet");
+	}
+	xDelete<int>(idlist);
+	xDelete<IssmDouble>(values);
 }
 /*}}}*/
@@ -1527,9 +1821,9 @@
 
 }/*}}}*/
-IssmDouble Tria::GroundedArea(void){/*{{{*/
+IssmDouble Tria::GroundedArea(bool scaled){/*{{{*/
 
 	/*Intermediaries*/
 	int         domaintype;
-	IssmDouble  phi;
+	IssmDouble  phi,scalefactor,groundedarea;
 	IssmDouble *xyz_list  = NULL;
 
@@ -1542,8 +1836,14 @@
 	this->GetVerticesCoordinates(&xyz_list);
 	phi=this->GetGroundedPortion(xyz_list);
+	groundedarea=phi*this->GetArea();
+	if(scaled==true){
+		Input* scalefactor_input = inputs->GetInput(MeshScaleFactorEnum); _assert_(scalefactor_input);
+		scalefactor_input->GetInputAverage(&scalefactor);
+		groundedarea=groundedarea*scalefactor;
+	}
 
 	/*Clean up and return*/
 	xDelete<IssmDouble>(xyz_list);
-	return phi*this->GetArea();
+	return groundedarea;
 }
 /*}}}*/
@@ -1590,17 +1890,5 @@
 }
 /*}}}*/
-IssmDouble Tria::IceMass(void){/*{{{*/
-
-	IssmDouble rho_ice; 
-	
-	if(!IsIceInElement())return 0.; //do not contribute to the volume of the ice!
-
-	/*recover ice density: */
-	rho_ice=matpar->GetMaterialParameter(MaterialsRhoIceEnum);
-
-	return rho_ice*this->IceVolume();
-}
-/*}}}*/
-IssmDouble Tria::IceVolume(void){/*{{{*/
+IssmDouble Tria::IceVolume(bool scaled){/*{{{*/
 
 	/*The volume of a truncated prism is area_base * 1/numedges sum(length of edges)*/
@@ -1608,9 +1896,11 @@
 	/*Intermediaries*/
 	int i, numiceverts;
-	IssmDouble area_base,surface,base,Haverage;
+	IssmDouble area_base,surface,base,Haverage,scalefactor;
 	IssmDouble Haux[NUMVERTICES], surfaces[NUMVERTICES], bases[NUMVERTICES];
+	IssmDouble SFaux[NUMVERTICES], scalefactors[NUMVERTICES];
 	IssmDouble s[2]; // s:fraction of intersected triangle edges, that lies inside ice
 	int* indices=NULL;
 	IssmDouble* H=NULL;
+	IssmDouble* SF=NULL;
 
 	if(!IsIceInElement())return 0.;
@@ -1620,13 +1910,38 @@
 
 	if(false && IsIcefront()){
-		area_base=this->GetAreaIce();
 		//Assumption: linear ice thickness profile on element. 
 		//Hence ice thickness at intersection of levelset function with triangle edge is linear interpolation of ice thickness at vertices.
 		this->GetLevelsetIntersection(&indices, &numiceverts, s, MaskIceLevelsetEnum, 0.);
+		int numthk=numiceverts+2;
+		H=xNew<IssmDouble>(numthk);
+		//Correct area distortion caused by projection if requestion
+		area_base=this->GetAreaIce();
+		if(scaled==true){
+			GetInputListOnVertices(&scalefactors[0],MeshScaleFactorEnum);
+			for(i=0;i<NUMVERTICES;i++) SFaux[i]= scalefactors[indices[i]]; //sort thicknesses in ice/noice
+			switch(numiceverts){
+				case 1: // average over triangle 
+					SF[0]=SFaux[0];
+					SF[1]=SFaux[0]+s[0]*(SFaux[1]-SFaux[0]);
+					SF[2]=SFaux[0]+s[1]*(SFaux[2]-SFaux[0]);
+					break;
+				case 2: // average over quadrangle
+					SF[0]=SFaux[0];
+					SF[1]=SFaux[1];
+					SF[2]=SFaux[0]+s[0]*(SFaux[2]-SFaux[0]);
+					SF[3]=SFaux[1]+s[1]*(SFaux[2]-SFaux[1]);
+					break;
+				default:
+					_error_("Number of ice covered vertices wrong in Tria::IceVolume()");
+					break;
+			}
+			scalefactor=0.;
+			for(i=0;i<numthk;i++)	scalefactor+=SF[i];
+			scalefactor/=IssmDouble(numthk);
+			area_base=area_base*scalefactor;
+		}
 		GetInputListOnVertices(&surfaces[0],SurfaceEnum);
 		GetInputListOnVertices(&bases[0],BaseEnum);
 		for(i=0;i<NUMVERTICES;i++) Haux[i]= surfaces[indices[i]]-bases[indices[i]]; //sort thicknesses in ice/noice
-		int numthk=numiceverts+2;
-		H=xNew<IssmDouble>(numthk);
 		switch(numiceverts){
 			case 1: // average over triangle 
@@ -1652,4 +1967,9 @@
 		/*First get back the area of the base*/
 		area_base=this->GetArea();
+		if(scaled==true){
+			Input* scalefactor_input = inputs->GetInput(MeshScaleFactorEnum); _assert_(scalefactor_input);
+			scalefactor_input->GetInputAverage(&scalefactor);
+			area_base=area_base*scalefactor;
+		}
 
 		/*Now get the average height*/
@@ -1664,4 +1984,5 @@
 	xDelete<int>(indices);
 	xDelete<IssmDouble>(H);
+	xDelete<IssmDouble>(SF);
 
 	if(domaintype==Domain2DverticalEnum){
@@ -1673,9 +1994,9 @@
 }
 /*}}}*/
-IssmDouble Tria::IceVolumeAboveFloatation(void){/*{{{*/
+IssmDouble Tria::IceVolumeAboveFloatation(bool scaled){/*{{{*/
 
 	/*The volume above floatation: H + rho_water/rho_ice * bathymetry */
 	IssmDouble rho_ice,rho_water;
-	IssmDouble base,surface,bed,bathymetry;
+	IssmDouble base,surface,bed,bathymetry,scalefactor;
 	IssmDouble xyz_list[NUMVERTICES][3];
 
@@ -1690,4 +2011,9 @@
 	 * base = 1/2 abs((xA-xC)(yB-yA)-(xA-xB)(yC-yA))*/
 	base = 1./2. * fabs((xyz_list[0][0]-xyz_list[2][0])*(xyz_list[1][1]-xyz_list[0][1]) - (xyz_list[0][0]-xyz_list[1][0])*(xyz_list[2][1]-xyz_list[0][1]));
+	if(scaled==true){
+		Input* scalefactor_input = inputs->GetInput(MeshScaleFactorEnum); _assert_(scalefactor_input);
+		scalefactor_input->GetInputAverage(&scalefactor);
+		base=base*scalefactor;
+	}
 
 	/*Now get the average height and bathymetry*/
@@ -1703,31 +2029,4 @@
 }
 /*}}}*/
-void       Tria::InputControlUpdate(IssmDouble scalar,bool save_parameter){/*{{{*/
-
-	/*Intermediary*/
-	int    num_controls;
-	int*   control_type=NULL;
-	Input* input=NULL;
-
-	/*retrieve some parameters: */
-	this->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
-	this->parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
-
-	for(int i=0;i<num_controls;i++){
-		input=(Input*)this->inputs->GetInput(control_type[i]);   _assert_(input);
-		if (input->ObjectEnum()!=ControlInputEnum){
-			_error_("input " << EnumToStringx(control_type[i]) << " is not a ControlInput");
-		}
-
-		((ControlInput*)input)->UpdateValue(scalar);
-		((ControlInput*)input)->Constrain();
-		if (save_parameter) ((ControlInput*)input)->SaveValue();
-
-	}
-
-	/*Clean up and return*/
-	xDelete<int>(control_type);
-}
-/*}}}*/
 void       Tria::InputDepthAverageAtBase(int enum_type,int average_enum_type){/*{{{*/
 
@@ -1746,16 +2045,4 @@
 	/*Add new input to current element*/
 	this->inputs->AddInput((Input*)newinput);
-}
-/*}}}*/
-void       Tria::InputScale(int enum_type,IssmDouble scale_factor){/*{{{*/
-
-	Input* input=NULL;
-
-	/*Make a copy of the original input: */
-	input=(Input*)this->inputs->GetInput(enum_type);
-	if(!input)_error_("could not find old input with enum: " << EnumToStringx(enum_type));
-
-	/*Scale: */
-	input->Scale(scale_factor);
 }
 /*}}}*/
@@ -1768,5 +2055,5 @@
 	IssmDouble cmmininputs[3];
 	IssmDouble cmmaxinputs[3];
-	bool       control_analysis   = false;
+	bool       control_analysis,ad_analysis   = false;
 	int        num_control_type,num_responses;
 	char**     controls = NULL;
@@ -1774,11 +2061,16 @@
 
 	/*Get parameters: */
-	iomodel->FindConstant(&yts,"md.constants.yts"); 
+	iomodel->FindConstant(&yts,"md.constants.yts");
 	iomodel->FindConstant(&control_analysis,"md.inversion.iscontrol");
-	if(control_analysis) iomodel->FindConstant(&num_control_type,"md.inversion.num_control_parameters");
-	if(control_analysis) iomodel->FindConstant(&num_responses,"md.inversion.num_cost_functions");
+	iomodel->FindConstant(&ad_analysis, "md.autodiff.isautodiff");
+	if(control_analysis && !ad_analysis) iomodel->FindConstant(&num_control_type,"md.inversion.num_control_parameters");
+	if(control_analysis && !ad_analysis) iomodel->FindConstant(&num_responses,"md.inversion.num_cost_functions");
+	if(control_analysis && ad_analysis) iomodel->FindConstant(&num_control_type,"md.autodiff.num_independent_objects");
+	if(control_analysis && ad_analysis) iomodel->FindConstant(&num_responses,"md.autodiff.num_dependent_objects");
+
+
 
 	/*Recover vertices ids needed to initialize inputs*/
-	for(i=0;i<3;i++){ 
+	for(i=0;i<3;i++){
 		tria_vertex_ids[i]=reCast<int>(iomodel->elements[3*index+i]); //ids for vertices are in the elements array from Matlab
 	}
@@ -1791,5 +2083,7 @@
 	/*Control Inputs*/
 	if (control_analysis){
-		iomodel->FindConstant(&controls,NULL,"md.inversion.control_parameters");
+		if(!ad_analysis)iomodel->FindConstant(&controls,NULL,"md.inversion.control_parameters");
+		if(ad_analysis)iomodel->FindConstant(&controls,NULL,"md.autodiff.independent_object_names");
+
 		for(i=0;i<num_control_type;i++){
 			_assert_(controls[i]);
@@ -1801,5 +2095,5 @@
 						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data("md.inversion.min_parameters")[(tria_vertex_ids[j]-1)*num_control_type+i]/yts;
 						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data("md.inversion.max_parameters")[(tria_vertex_ids[j]-1)*num_control_type+i]/yts;
-						this->inputs->AddInput(new ControlInput(BalancethicknessThickeningRateEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						this->inputs->AddInput(new ControlInput(BalancethicknessThickeningRateEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,P1Enum,i+1));
 					}
 					break;
@@ -1809,5 +2103,5 @@
 						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data("md.inversion.min_parameters")[(tria_vertex_ids[j]-1)*num_control_type+i]/yts;
 						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data("md.inversion.max_parameters")[(tria_vertex_ids[j]-1)*num_control_type+i]/yts;
-						this->inputs->AddInput(new ControlInput(VxEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						this->inputs->AddInput(new ControlInput(VxEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,P1Enum,i+1));
 					}
 					break;
@@ -1817,5 +2111,5 @@
 						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data("md.inversion.min_parameters")[(tria_vertex_ids[j]-1)*num_control_type+i]/yts;
 						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data("md.inversion.max_parameters")[(tria_vertex_ids[j]-1)*num_control_type+i]/yts;
-						this->inputs->AddInput(new ControlInput(VyEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						this->inputs->AddInput(new ControlInput(VyEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,P1Enum,i+1));
 					}
 					break;
@@ -1825,5 +2119,21 @@
 						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data("md.inversion.min_parameters")[(tria_vertex_ids[j]-1)*num_control_type+i];
 						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data("md.inversion.max_parameters")[(tria_vertex_ids[j]-1)*num_control_type+i];
-						this->inputs->AddInput(new ControlInput(ThicknessEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						this->inputs->AddInput(new ControlInput(ThicknessEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,P1Enum,i+1));
+					}
+					break;
+				case BalancethicknessSpcthicknessEnum:
+					if(iomodel->Data("md.balancethickness.spcthickness")){
+						for(j=0;j<NUMVERTICES;j++) nodeinputs[j]=iomodel->Data("md.balancethickness.spcthickness")[tria_vertex_ids[j]-1];
+						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data("md.inversion.min_parameters")[(tria_vertex_ids[j]-1)*num_control_type+i];
+						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data("md.inversion.max_parameters")[(tria_vertex_ids[j]-1)*num_control_type+i];
+						this->inputs->AddInput(new ControlInput(BalancethicknessSpcthicknessEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,P1Enum,i+1));
+					}
+					break;
+				case BalancethicknessOmegaEnum:
+					if(iomodel->Data("md.balancethickness.omega")){
+						for(j=0;j<NUMVERTICES;j++) nodeinputs[j]=iomodel->Data("md.balancethickness.omega")[tria_vertex_ids[j]-1];
+						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data("md.inversion.min_parameters")[(tria_vertex_ids[j]-1)*num_control_type+i];
+						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data("md.inversion.max_parameters")[(tria_vertex_ids[j]-1)*num_control_type+i];
+						this->inputs->AddInput(new ControlInput(BalancethicknessOmegaEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,P1Enum,i+1));
 					}
 					break;
@@ -1833,5 +2143,5 @@
 						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data("md.inversion.min_parameters")[(tria_vertex_ids[j]-1)*num_control_type+i];
 						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data("md.inversion.max_parameters")[(tria_vertex_ids[j]-1)*num_control_type+i];
-						this->inputs->AddInput(new ControlInput(FrictionCoefficientEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						this->inputs->AddInput(new ControlInput(FrictionCoefficientEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,P1Enum,i+1));
 					}
 					break;
@@ -1841,5 +2151,5 @@
 						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data("md.inversion.min_parameters")[(tria_vertex_ids[j]-1)*num_control_type+i];
 						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data("md.inversion.max_parameters")[(tria_vertex_ids[j]-1)*num_control_type+i];
-						this->inputs->AddInput(new ControlInput(MaterialsRheologyBbarEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						this->inputs->AddInput(new ControlInput(MaterialsRheologyBbarEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,P1Enum,i+1));
 					}
 					break;
@@ -1849,5 +2159,5 @@
 						for(j=0;j<NUMVERTICES;j++)cmmininputs[j]=iomodel->Data("md.inversion.min_parameters")[(tria_vertex_ids[j]-1)*num_control_type+i];
 						for(j=0;j<NUMVERTICES;j++)cmmaxinputs[j]=iomodel->Data("md.inversion.max_parameters")[(tria_vertex_ids[j]-1)*num_control_type+i];
-						this->inputs->AddInput(new ControlInput(DamageDbarEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						this->inputs->AddInput(new ControlInput(DamageDbarEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,P1Enum,i+1));
 					}
 					break;
@@ -1862,9 +2172,9 @@
 	/*DatasetInputs*/
 	if (control_analysis && iomodel->Data("md.inversion.cost_functions_coefficients")){
-	
+
 		/*Generate cost functions associated with the iomodel*/
-		char**	cost_functions			= NULL;
-		int*		cost_functions_enums = NULL;
-		int		num_cost_functions;
+		char**   cost_functions       = NULL;
+		int*     cost_functions_enums = NULL;
+		int      num_cost_functions;
 
 		iomodel->FindConstant(&num_cost_functions,"md.inversion.num_cost_functions");
@@ -2392,4 +2702,9 @@
 }
 /*}}}*/
+Gauss*     Tria::NewGauss(int point1,IssmDouble fraction1,IssmDouble fraction2,int order){/*{{{*/
+
+	return new GaussTria(point1,fraction1,fraction2,order);
+}
+/*}}}*/
 Gauss*     Tria::NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order_horiz,int order_vert){/*{{{*/
 
@@ -2571,4 +2886,174 @@
 }
 /*}}}*/
+void       Tria::PicoUpdateBoxid(int* max_boxid_basin_list){/*{{{*/
+
+	if(!this->IsIceInElement() || !this->IsFloating()) return;
+
+	int        basin_id;
+	IssmDouble dist_gl,dist_cf;
+
+	inputs->GetInputValue(&basin_id,BasalforcingsPicoBasinIdEnum);
+	IssmDouble boxid_max=reCast<IssmDouble>(max_boxid_basin_list[basin_id])+1.;
+
+	Input* dist_gl_input=inputs->GetInput(DistanceToGroundinglineEnum); _assert_(dist_gl_input);
+	Input* dist_cf_input=inputs->GetInput(DistanceToCalvingfrontEnum);  _assert_(dist_cf_input);
+
+	/*Get dist_gl and dist_cf at center of element*/
+	Gauss* gauss=this->NewGauss(1); gauss->GaussPoint(0);
+	dist_gl_input->GetInputValue(&dist_gl,gauss);
+	dist_cf_input->GetInputValue(&dist_cf,gauss);
+	delete gauss;
+	
+	/*Ensure values are positive for floating ice*/
+	dist_gl = fabs(dist_gl);
+	dist_cf = fabs(dist_cf);
+
+	/*Compute relative distance to grounding line*/
+	IssmDouble rel_dist_gl=dist_gl/(dist_gl+dist_cf);
+
+	/*Assign box numbers based on rel_dist_gl*/
+	int boxid = -1;
+	for(IssmDouble i=0.;i<boxid_max;i++){
+		IssmDouble lowbound  = 1. -sqrt((boxid_max-i   )/boxid_max);
+		IssmDouble highbound = 1. -sqrt((boxid_max-i-1.)/boxid_max);
+		if(rel_dist_gl>=lowbound && rel_dist_gl<=highbound){
+			boxid=reCast<int>(i);
+			break;
+		}
+	}
+	if(boxid==-1){_error_("No boxid found for element " << this->Sid() << "!");}
+
+	this->inputs->AddInput(new IntInput(BasalforcingsPicoBoxIdEnum, boxid));	
+}/*}}}*/
+void       Tria::PicoUpdateBox(int loopboxid){/*{{{*/
+
+	if(!this->IsIceInElement() || !this->IsFloating()) return;
+
+	int boxid;
+	this->inputs->GetInputValue(&boxid,BasalforcingsPicoBoxIdEnum);
+	if(loopboxid!=boxid) return;
+
+	int        basinid, maxbox, num_basins, numnodes, M;
+	IssmDouble gamma_T, overturning_coeff, thickness;
+	IssmDouble pressure, T_star,p_coeff, q_coeff;
+
+	/*Get variables*/
+	IssmDouble rhoi       = this->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble rhow       = this->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	IssmDouble earth_grav = this->GetMaterialParameter(ConstantsGEnum);
+	IssmDouble rho_star   = 1033.;             // kg/m^3
+	IssmDouble nu         = rhoi/rhow;
+	IssmDouble latentheat = this->GetMaterialParameter(MaterialsLatentheatEnum);
+	IssmDouble c_p_ocean  = this->GetMaterialParameter(MaterialsMixedLayerCapacityEnum);
+	IssmDouble lambda     = latentheat/c_p_ocean;
+	IssmDouble a          = -0.0572;          // K/psu
+	IssmDouble b          = 0.0788 + this->GetMaterialParameter(MaterialsMeltingpointEnum);  //K
+	IssmDouble c          = 7.77e-4;
+	IssmDouble alpha      = 7.5e-5;           // 1/K
+	IssmDouble Beta       = 7.7e-4;           // K
+
+	/* Get non-box-specific parameters and inputs */
+	this->parameters->FindParam(&num_basins, BasalforcingsPicoNumBasinsEnum);
+	this->parameters->FindParam(&gamma_T,BasalforcingsPicoGammaTEnum);
+	this->parameters->FindParam(&overturning_coeff,BasalforcingsPicoOverturningCoeffEnum);
+	this->parameters->FindParam(&maxbox,BasalforcingsPicoMaxboxcountEnum);
+	this->inputs->GetInputValue(&basinid,BasalforcingsPicoBasinIdEnum);
+	Input* thickness_input=this->GetInput(ThicknessEnum); _assert_(thickness_input);
+	_assert_(basinid<=num_basins);
+
+   IssmDouble* boxareas = xNew<IssmDouble>(num_basins*maxbox);
+	this->parameters->FindParam(&boxareas,&M,BasalforcingsPicoBoxAreaEnum);
+
+	IssmDouble area_boxi        = boxareas[basinid*maxbox+boxid];
+	IssmDouble g1               = area_boxi*gamma_T;
+
+	IssmDouble basalmeltrates_shelf[NUMVERTICES];
+	IssmDouble potential_pressure_melting_point[NUMVERTICES];
+	IssmDouble Tocs[NUMVERTICES];
+	IssmDouble Socs[NUMVERTICES];
+
+	/* First box calculations */
+	if(boxid==0){
+		/* Get box1 parameters and inputs */
+		IssmDouble time, toc_farocean, soc_farocean;
+		this->parameters->FindParam(&time,TimeEnum);
+		this->parameters->FindParam(&toc_farocean, basinid, time, BasalforcingsPicoFarOceantemperatureEnum);
+		this->parameters->FindParam(&soc_farocean, basinid, time, BasalforcingsPicoFarOceansalinityEnum);
+		IssmDouble s1 = soc_farocean/(nu*lambda);
+		IssmDouble overturnings[NUMVERTICES];
+
+		/* Start looping on the number of verticies and calculate ocean vars */
+		Gauss* gauss=this->NewGauss();
+		for(int i=0;i<NUMVERTICES;i++){
+			gauss->GaussVertex(i);
+			thickness_input->GetInputValue(&thickness,gauss);
+			pressure = (rhoi*earth_grav*1e-4)*thickness;
+			T_star   = a*soc_farocean+b-c*pressure-toc_farocean;
+			p_coeff  = g1/(overturning_coeff*rho_star*(Beta*s1-alpha));
+			q_coeff  = T_star*(g1/(overturning_coeff*rho_star*(Beta*s1-alpha)));
+
+			/* To avoid negatives under the square root */
+			if((0.25*pow(p_coeff,2)-q_coeff)<0){
+				q_coeff = 0.25*p_coeff*p_coeff;
+			}
+
+			Tocs[i] = toc_farocean-(-0.5*p_coeff+sqrt(0.25*pow(p_coeff,2)-q_coeff));
+			Socs[i] = soc_farocean-(soc_farocean/(nu*lambda))*(toc_farocean-Tocs[i]);
+			potential_pressure_melting_point[i] = a*Socs[i]+b-c*pressure;
+			basalmeltrates_shelf[i] = (-gamma_T/(nu*lambda))*(potential_pressure_melting_point[i]-Tocs[i]);
+			overturnings[i] = overturning_coeff*rho_star*(Beta*(soc_farocean-Socs[i])-alpha*(toc_farocean-Tocs[i]));
+		}
+
+		this->AddInput(BasalforcingsFloatingiceMeltingRateEnum,basalmeltrates_shelf,P1Enum);
+		this->AddInput(BasalforcingsPicoSubShelfOceanTempEnum,Tocs,P1Enum);
+		this->AddInput(BasalforcingsPicoSubShelfOceanSalinityEnum,Socs,P1Enum);
+		this->AddInput(BasalforcingsPicoSubShelfOceanOverturningEnum,overturnings,P1Enum);
+
+		/*Cleanup and return*/
+		delete gauss;
+	}
+
+	/* Subsequent box calculations */
+	else {
+		/* Get subsequent box parameters and inputs */
+		IssmDouble* toc_weighted_avg         = NULL;
+		IssmDouble* soc_weighted_avg         = NULL;
+		IssmDouble* overturning_weighted_avg = NULL;
+		this->parameters->FindParam(&toc_weighted_avg,&num_basins,BasalforcingsPicoAverageTemperatureEnum);
+		this->parameters->FindParam(&soc_weighted_avg,&num_basins,BasalforcingsPicoAverageSalinityEnum);
+		this->parameters->FindParam(&overturning_weighted_avg,&num_basins,BasalforcingsPicoAverageOverturningEnum);
+		IssmDouble mean_toc                  = toc_weighted_avg[basinid];
+		IssmDouble mean_soc                  = soc_weighted_avg[basinid];
+		IssmDouble mean_overturning          = overturning_weighted_avg[basinid];
+		IssmDouble g2                        = g1/(nu*lambda);
+
+		/* Start looping on the number of verticies and calculate ocean vars */
+		Gauss* gauss=this->NewGauss();
+		for(int i=0;i<NUMVERTICES;i++){
+			gauss->GaussVertex(i);
+			thickness_input->GetInputValue(&thickness,gauss);
+			pressure = (rhoi*earth_grav*1.e-4)*thickness;
+			T_star   = a*mean_soc+b-c*pressure-mean_toc;
+			Tocs[i]  = mean_toc+T_star*(g1/(mean_overturning+g1-g2*a*mean_soc));
+			Socs[i]  = mean_soc-mean_soc*((mean_toc-Tocs[i])/(nu*lambda));
+			potential_pressure_melting_point[i] = a*Socs[i]+b-c*pressure;
+			basalmeltrates_shelf[i] = (-gamma_T/(nu*lambda))*(potential_pressure_melting_point[i]-Tocs[i]);
+		}
+
+		this->AddInput(BasalforcingsFloatingiceMeltingRateEnum,basalmeltrates_shelf,P1Enum);
+		this->AddInput(BasalforcingsPicoSubShelfOceanTempEnum,Tocs,P1Enum);
+		this->AddInput(BasalforcingsPicoSubShelfOceanSalinityEnum,Socs,P1Enum);
+
+		/*Cleanup and return*/
+		xDelete<IssmDouble>(toc_weighted_avg);
+		xDelete<IssmDouble>(soc_weighted_avg);
+		xDelete<IssmDouble>(overturning_weighted_avg);
+		delete gauss;
+	}
+
+	/*Cleanup and return*/
+	xDelete<IssmDouble>(boxareas);
+}
+/*}}}*/
 void       Tria::PotentialUngrounding(Vector<IssmDouble>* potential_ungrounding){/*{{{*/
 
@@ -2692,4 +3177,5 @@
 void       Tria::ResetHooks(){/*{{{*/
 
+	if(this->nodes) xDelete<Node*>(this->nodes);
 	this->nodes=NULL;
 	this->vertices=NULL;
@@ -2717,5 +3203,4 @@
 	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
 	GetInputListOnVertices(&ls[0],MaskIceLevelsetEnum);
-	InputDuplicate(MaskIceLevelsetEnum,PressureEnum);
 
 	/*Get distance from list of segments and reset ls*/
@@ -2776,8 +3261,8 @@
 }
 /*}}}*/
-void       Tria::SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index){/*{{{*/
+void       Tria::SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index,int offset,int N, int M){/*{{{*/
 
 	IssmDouble  values[NUMVERTICES];
-	int         vertexpidlist[NUMVERTICES],control_init;
+	int         idlist[NUMVERTICES],control_init;
 
 
@@ -2801,6 +3286,59 @@
 	/*Get out if this is not an element input*/
 	if(!IsInput(control_enum)) return;
-
-	/*Prepare index list*/
+	
+	Input* input     = (Input*)this->inputs->GetInput(control_enum);   _assert_(input);
+	if(input->ObjectEnum()!=ControlInputEnum){
+		_error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
+	}
+
+	ControlInput* controlinput = xDynamicCast<ControlInput*>(input);
+	input = controlinput->values;
+
+	/*Get values on vertices*/
+	for(int n=0;n<N;n++){
+		for(int i=0;i<NUMVERTICES;i++){
+			idlist[i]=offset + this->vertices[i]->Sid()+n*M;
+			values[i]=vector[idlist[i]];
+		}
+		if(input->ObjectEnum()==TriaInputEnum){
+			Input* new_input = new TriaInput(control_enum,values,P1Enum);
+			controlinput->SetInput(new_input);
+		}
+		else if(input->ObjectEnum()==TransientInputEnum){
+			Input* new_input = new TriaInput(control_enum,values,P1Enum);
+			controlinput->SetInput(new_input,n);
+			controlinput->Configure(parameters);
+		}
+		else _error_("Type not supported");
+	}
+}
+/*}}}*/
+void       Tria::SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index){/*{{{*/
+
+	IssmDouble  values[NUMVERTICES];
+	int         vertexpidlist[NUMVERTICES],control_init;
+
+
+	/*Get Domain type*/
+	int domaintype;
+	parameters->FindParam(&domaintype,DomainTypeEnum);
+
+	/*Specific case for depth averaged quantities*/
+	control_init=control_enum;
+	if(domaintype==Domain2DverticalEnum){
+		if(control_enum==MaterialsRheologyBbarEnum){
+			control_enum=MaterialsRheologyBEnum;
+			if(!IsOnBase()) return;
+		}
+		if(control_enum==DamageDbarEnum){
+			control_enum=DamageDEnum;
+			if(!IsOnBase()) return;
+		}
+	}
+
+	/*Get out if this is not an element input*/
+	if(!IsInput(control_enum)) return;
+
+	/*hrepare index list*/
 	GradientIndexing(&vertexpidlist[0],control_index);
 
@@ -3061,5 +3599,5 @@
 }
 /*}}}*/
-IssmDouble Tria::TotalFloatingBmb(void){/*{{{*/
+IssmDouble Tria::TotalFloatingBmb(bool scaled){/*{{{*/
 
 	/*The fbmb[kg yr-1] of one element is area[m2] * melting_rate [kg m^-2 yr^-1]*/
@@ -3067,5 +3605,5 @@
 	bool       mainlyfloating;
 	IssmDouble fbmb=0;
-	IssmDouble rho_ice,fraction1,fraction2,floatingmelt,Jdet;
+	IssmDouble rho_ice,fraction1,fraction2,floatingmelt,Jdet,scalefactor;
 	IssmDouble Total_Fbmb=0;
 	IssmDouble xyz_list[NUMVERTICES][3];
@@ -3078,4 +3616,8 @@
 	Input* floatingmelt_input = this->GetInput(BasalforcingsFloatingiceMeltingRateEnum); _assert_(floatingmelt_input); 
 	Input* gllevelset_input = this->GetInput(MaskGroundediceLevelsetEnum); _assert_(gllevelset_input);
+	Input* scalefactor_input = NULL;
+	if(scaled==true){
+		scalefactor_input = this->GetInput(MeshScaleFactorEnum); _assert_(scalefactor_input); 
+	}
 	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
 
@@ -3088,5 +3630,9 @@
 		this->JacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
 		floatingmelt_input->GetInputValue(&floatingmelt,gauss);
-		fbmb+=floatingmelt*Jdet*gauss->weight;
+		if(scaled==true){
+			scalefactor_input->GetInputValue(&scalefactor,gauss);
+		}
+		else scalefactor=1;
+		fbmb+=floatingmelt*Jdet*gauss->weight*scalefactor;
 	}
 
@@ -3098,5 +3644,5 @@
 }
 /*}}}*/
-IssmDouble Tria::TotalGroundedBmb(void){/*{{{*/
+IssmDouble Tria::TotalGroundedBmb(bool scaled){/*{{{*/
 
 	/*The gbmb[kg yr-1] of one element is area[m2] * gounded melting rate [kg m^-2 yr^-1]*/
@@ -3104,5 +3650,5 @@
 	bool       mainlyfloating;
 	IssmDouble gbmb=0;
-	IssmDouble rho_ice,fraction1,fraction2,groundedmelt,Jdet;
+	IssmDouble rho_ice,fraction1,fraction2,groundedmelt,Jdet,scalefactor;
 	IssmDouble Total_Gbmb=0;
 	IssmDouble xyz_list[NUMVERTICES][3];
@@ -3115,4 +3661,8 @@
 	Input* groundedmelt_input = this->GetInput(BasalforcingsGroundediceMeltingRateEnum); _assert_(groundedmelt_input); 
 	Input* gllevelset_input = this->GetInput(MaskGroundediceLevelsetEnum); _assert_(gllevelset_input);
+	Input* scalefactor_input = NULL;
+	if(scaled==true){
+		scalefactor_input = this->GetInput(MeshScaleFactorEnum); _assert_(scalefactor_input); 
+	}
 	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
 
@@ -3125,5 +3675,9 @@
 		this->JacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
 		groundedmelt_input->GetInputValue(&groundedmelt,gauss);
-		gbmb+=groundedmelt*Jdet*gauss->weight;
+		if(scaled==true){
+			scalefactor_input->GetInputValue(&scalefactor,gauss);
+		}
+		else scalefactor=1;
+		gbmb+=groundedmelt*Jdet*gauss->weight*scalefactor;
 	}
 
@@ -3135,8 +3689,8 @@
 }
 /*}}}*/
-IssmDouble Tria::TotalSmb(void){/*{{{*/
+IssmDouble Tria::TotalSmb(bool scaled){/*{{{*/
 
 	/*The smb[kg yr-1] of one element is area[m2] * smb [kg m^-2 yr^-1]*/
-	IssmDouble base,smb,rho_ice;
+	IssmDouble base,smb,rho_ice,scalefactor;
 	IssmDouble Total_Smb=0;
 	IssmDouble xyz_list[NUMVERTICES][3];
@@ -3156,6 +3710,13 @@
 	/*Now get the average SMB over the element*/
 	Input* smb_input = inputs->GetInput(SmbMassBalanceEnum); _assert_(smb_input);
-	smb_input->GetInputAverage(&smb);																								// average smb on element in m ice s-1
-   Total_Smb=rho_ice*base*smb;																											// smb on element in kg s-1
+	smb_input->GetInputAverage(&smb);	// average smb on element in m ice s-1
+	if(scaled==true){
+		Input* scalefactor_input = inputs->GetInput(MeshScaleFactorEnum); _assert_(scalefactor_input);
+		scalefactor_input->GetInputAverage(&scalefactor);// average scalefactor on element 
+	}
+	else{
+		scalefactor=1.;
+	}
+   Total_Smb=rho_ice*base*smb*scalefactor;	// smb on element in kg s-1
 
 	/*Return: */
@@ -3171,4 +3732,5 @@
 	/*Checks if debuging*/
 	_assert_(iomodel->elements);
+	_assert_(index==this->sid); 
 
 	/*Recover element type*/
@@ -3388,4 +3950,36 @@
 }
 /*}}}*/
+void       Tria::WriteFieldIsovalueSegment(DataSet* segments,int fieldenum,IssmDouble fieldvalue){/*{{{*/
+
+	_assert_(fieldvalue==0.); //field value != 0 not implemented yet
+
+	/*1. check that we do cross fieldvalue in this element*/
+	Input* input = inputs->GetInput(fieldenum);
+	if(!input) _error_("Cannot calculate distance to "<<EnumToStringx(fieldenum)<<", input not found");
+	IssmDouble minvalue = input->Min();
+	IssmDouble maxvalue = input->Max();
+	if(minvalue>fieldvalue || maxvalue<fieldvalue) return;
+
+	/* check #2: If only one vertex is on fieldvalue, there is no segment here */
+	IssmDouble lsf[NUMVERTICES];
+	this->GetInputListOnVertices(&lsf[0],fieldenum);
+	int nrice=0;       
+	for(int i=0;i<NUMVERTICES;i++) if(lsf[i]==fieldvalue) nrice++;
+	if(nrice==1) return;
+
+	/*2. Write segments*/
+	IssmDouble* xyz_list_zero = NULL;
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	::GetVerticesCoordinates(&xyz_list[0][0],this->vertices,NUMVERTICES);
+	this->ZeroLevelsetCoordinates(&xyz_list_zero,&xyz_list[0][0],fieldenum);
+	if(xyz_list_zero){
+		IssmDouble x[2],y[2];
+		x[0] = xyz_list_zero[0*3 + 0]; x[1] = xyz_list_zero[1*3 + 0];
+		y[0] = xyz_list_zero[0*3 + 1]; y[1] = xyz_list_zero[1*3 + 1];
+		segments->AddObject(new Contour<IssmDouble>(segments->Size()+1,2,&x[0],&y[0],false));
+	}
+	xDelete<IssmDouble>(xyz_list_zero);
+}
+/*}}}*/
 void       Tria::WriteLevelsetSegment(DataSet* segments){/*{{{*/
 
@@ -3623,5 +4217,5 @@
 #endif
 #ifdef _HAVE_ESA_
-void    Tria::EsaGeodetic2D(Vector<IssmDouble>* pUp,Vector<IssmDouble>* pNorth,Vector<IssmDouble>* pEast,IssmDouble* xx,IssmDouble* yy){ /*{{{*/
+void    Tria::EsaGeodetic2D(Vector<IssmDouble>* pUp,Vector<IssmDouble>* pNorth,Vector<IssmDouble>* pEast,Vector<IssmDouble>* pX,Vector<IssmDouble>* pY,IssmDouble* xx,IssmDouble* yy){ /*{{{*/
 
 	/*diverse:*/
@@ -3632,4 +4226,144 @@
 	IssmDouble I;		//ice/water loading 
 	IssmDouble rho_ice, rho_earth;
+
+	/*precomputed elastic green functions:*/
+	IssmDouble* U_elastic_precomputed = NULL;
+	IssmDouble* H_elastic_precomputed = NULL;
+	int         M, hemi; 
+	
+	/*computation of Green functions:*/
+	IssmDouble* U_elastic= NULL;
+	IssmDouble* N_elastic= NULL;
+	IssmDouble* E_elastic= NULL;
+	IssmDouble* X_elastic= NULL;
+	IssmDouble* Y_elastic= NULL;
+	
+	/*optimization:*/
+	bool store_green_functions=false;
+
+	/*Compute ice thickness change: */
+	Input*	deltathickness_input=inputs->GetInput(EsaDeltathicknessEnum); 
+	if (!deltathickness_input)_error_("delta thickness input needed to compute elastic adjustment!");
+	deltathickness_input->GetInputAverage(&I);
+		
+	/*early return if we are not on the (ice) loading point: */ 
+	if(I==0) return; 
+
+	/*recover material parameters: */
+	rho_ice=matpar->GetMaterialParameter(MaterialsRhoIceEnum);
+	rho_earth=matpar->GetMaterialParameter(MaterialsEarthDensityEnum);
+
+	/*how many dofs are we working with here? */
+	this->parameters->FindParam(&gsize,MeshNumberofverticesEnum);
+
+	/*which hemisphere? for north-south, east-west components*/
+	this->parameters->FindParam(&hemi,EsaHemisphereEnum); 
+	
+	/*compute area of element:*/
+	area=GetArea();
+
+	/*figure out gravity center of our element (Cartesian): */
+	IssmDouble x_element, y_element; 
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	x_element=(xyz_list[0][0]+xyz_list[1][0]+xyz_list[2][0])/3.0;
+	y_element=(xyz_list[0][1]+xyz_list[1][1]+xyz_list[2][1])/3.0;
+
+	/*recover elastic Green's functions for displacement:*/
+	DoubleVecParam* U_parameter = static_cast<DoubleVecParam*>(this->parameters->FindParamObject(EsaUElasticEnum)); _assert_(U_parameter);
+	DoubleVecParam* H_parameter = static_cast<DoubleVecParam*>(this->parameters->FindParamObject(EsaHElasticEnum)); _assert_(H_parameter);
+	U_parameter->GetParameterValueByPointer(&U_elastic_precomputed,&M);
+	H_parameter->GetParameterValueByPointer(&H_elastic_precomputed,&M);
+
+	/*initialize: */
+	U_elastic=xNewZeroInit<IssmDouble>(gsize);
+	N_elastic=xNewZeroInit<IssmDouble>(gsize);
+	E_elastic=xNewZeroInit<IssmDouble>(gsize);
+	X_elastic=xNewZeroInit<IssmDouble>(gsize);
+	Y_elastic=xNewZeroInit<IssmDouble>(gsize);
+
+	int* indices=xNew<int>(gsize);
+	IssmDouble* U_values=xNewZeroInit<IssmDouble>(gsize);
+	IssmDouble* N_values=xNewZeroInit<IssmDouble>(gsize);
+	IssmDouble* E_values=xNewZeroInit<IssmDouble>(gsize);
+	IssmDouble* X_values=xNewZeroInit<IssmDouble>(gsize);
+	IssmDouble* Y_values=xNewZeroInit<IssmDouble>(gsize);
+	IssmDouble dx, dy, dist, alpha, ang, ang2;
+	IssmDouble N_azim, E_azim, X_azim, Y_azim; 
+
+	for(int i=0;i<gsize;i++){
+
+		indices[i]=i; 
+
+		IssmDouble N_azim=0; 
+		IssmDouble E_azim=0;
+
+		/*Compute alpha angle between centroid and current vertex: */
+		dx = x_element - xx[i];		dy = y_element - yy[i]; 
+		dist = sqrt(pow(dx,2)+pow(dy,2));						// distance between vertex and elemental centroid [m] 
+		alpha = dist*360.0/(2*PI*earth_radius) * PI/180.0;	// [in radians] 360 degree = 2*pi*earth_radius 
+
+		/*Compute azimuths, both north and east components: */
+		ang = PI/2 - atan2(dy,dx);		// this is bearing angle! 
+		Y_azim = cos(ang); 
+		X_azim = sin(ang); 
+
+		/*Elastic component  (from Eq 17 in Adhikari et al, GMD 2015): */
+		int index=reCast<int,IssmDouble>(alpha/PI*(M-1));
+		U_elastic[i] += U_elastic_precomputed[index];
+		Y_elastic[i] += H_elastic_precomputed[index]*Y_azim;
+		X_elastic[i] += H_elastic_precomputed[index]*X_azim;
+
+		/*Add all components to the pUp solution vectors:*/
+		U_values[i]+=3*rho_ice/rho_earth*area/(4*PI*pow(earth_radius,2))*I*U_elastic[i];
+		Y_values[i]+=3*rho_ice/rho_earth*area/(4*PI*pow(earth_radius,2))*I*Y_elastic[i];
+		X_values[i]+=3*rho_ice/rho_earth*area/(4*PI*pow(earth_radius,2))*I*X_elastic[i];
+		
+		/*North-south, East-west components */ 
+		if (hemi == -1) {
+			ang2 = PI/2 - atan2(yy[i],xx[i]); 
+		} 
+		else if (hemi == 1) {
+			ang2 = PI/2 - atan2(-yy[i],-xx[i]); 
+		}
+		if (hemi != 0){
+			N_azim = Y_azim*cos(ang2) + X_azim*sin(ang2);
+			E_azim = X_azim*cos(ang2) - Y_azim*sin(ang2);
+			N_elastic[i] += H_elastic_precomputed[index]*N_azim;
+			E_elastic[i] += H_elastic_precomputed[index]*E_azim;
+			N_values[i]+=3*rho_ice/rho_earth*area/(4*PI*pow(earth_radius,2))*I*N_elastic[i];
+			E_values[i]+=3*rho_ice/rho_earth*area/(4*PI*pow(earth_radius,2))*I*E_elastic[i];
+		}
+	}
+
+	pUp->SetValues(gsize,indices,U_values,ADD_VAL);
+	pNorth->SetValues(gsize,indices,N_values,ADD_VAL);
+	pEast->SetValues(gsize,indices,E_values,ADD_VAL);
+	pX->SetValues(gsize,indices,X_values,ADD_VAL);
+	pY->SetValues(gsize,indices,Y_values,ADD_VAL);
+	
+	/*free ressources:*/
+	xDelete<int>(indices); 
+	xDelete<IssmDouble>(U_values); xDelete<IssmDouble>(N_values); xDelete<IssmDouble>(E_values);
+	xDelete<IssmDouble>(U_elastic); xDelete<IssmDouble>(N_elastic); xDelete<IssmDouble>(E_elastic);
+	xDelete<IssmDouble>(X_values); xDelete<IssmDouble>(Y_values);
+	xDelete<IssmDouble>(X_elastic); xDelete<IssmDouble>(Y_elastic);
+
+	return;
+}
+/*}}}*/
+void    Tria::EsaGeodetic3D(Vector<IssmDouble>* pUp,Vector<IssmDouble>* pNorth,Vector<IssmDouble>* pEast,IssmDouble* latitude,IssmDouble* longitude,IssmDouble* radius,IssmDouble* xx,IssmDouble* yy,IssmDouble* zz,IssmDouble eartharea){ /*{{{*/
+
+	/*diverse:*/
+	int gsize;
+	bool spherical=true;
+	IssmDouble llr_list[NUMVERTICES][3];
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble area;
+	IssmDouble I;		//ice/water loading 
+	IssmDouble late,longe,re;
+	IssmDouble lati,longi,ri;
+	IssmDouble rho_ice,rho_earth;
+	IssmDouble minlong=400;
+	IssmDouble maxlong=-20;
 
 	/*precomputed elastic green functions:*/
@@ -3662,115 +4396,4 @@
 
 	/*compute area of element:*/
-	area=GetArea();
-
-	/*figure out gravity center of our element (Cartesian): */
-	IssmDouble x_element, y_element; 
-	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	x_element=(xyz_list[0][0]+xyz_list[1][0]+xyz_list[2][0])/3.0;
-	y_element=(xyz_list[0][1]+xyz_list[1][1]+xyz_list[2][1])/3.0;
-
-	/*recover elastic Green's functions for displacement:*/
-	DoubleVecParam* U_parameter = static_cast<DoubleVecParam*>(this->parameters->FindParamObject(EsaUElasticEnum)); _assert_(U_parameter);
-	DoubleVecParam* H_parameter = static_cast<DoubleVecParam*>(this->parameters->FindParamObject(EsaHElasticEnum)); _assert_(H_parameter);
-	U_parameter->GetParameterValueByPointer(&U_elastic_precomputed,&M);
-	H_parameter->GetParameterValueByPointer(&H_elastic_precomputed,&M);
-
-	/*initialize: */
-	U_elastic=xNewZeroInit<IssmDouble>(gsize);
-	N_elastic=xNewZeroInit<IssmDouble>(gsize);
-	E_elastic=xNewZeroInit<IssmDouble>(gsize);
-
-	int* indices=xNew<int>(gsize);
-	IssmDouble* U_values=xNewZeroInit<IssmDouble>(gsize);
-	IssmDouble* N_values=xNewZeroInit<IssmDouble>(gsize);
-	IssmDouble* E_values=xNewZeroInit<IssmDouble>(gsize);
-	IssmDouble dx, dy; 
-	IssmDouble dist, alpha, ang;
-	IssmDouble N_azim, E_azim;
-
-	for(int i=0;i<gsize;i++){
-
-		indices[i]=i; 
-		IssmDouble N_azim=0; 
-		IssmDouble E_azim=0;
-
-		/*Compute alpha angle between centroid and current vertex: */
-		dx = x_element - xx[i];		dy = y_element - yy[i]; 
-		dist = sqrt(pow(dx,2)+pow(dy,2));						// distance between vertex and elemental centroid [m] 
-		alpha = dist*360.0/(2*PI*earth_radius) * PI/180.0;	// [in radians] 360 degree = 2*pi*earth_radius 
-
-		/*Compute azimuths, both north and east components: */
-		ang = PI/2 - atan2(dy,dx);		// this is bearing angle! 
-		N_azim = cos(ang); 
-		E_azim = sin(ang); 
-
-		/*Elastic component  (from Eq 17 in Adhikari et al, GMD 2015): */
-		int index=reCast<int,IssmDouble>(alpha/PI*(M-1));
-		U_elastic[i] += U_elastic_precomputed[index];
-		N_elastic[i] += H_elastic_precomputed[index]*N_azim;
-		E_elastic[i] += H_elastic_precomputed[index]*E_azim;
-
-		/*Add all components to the pUp solution vectors:*/
-		U_values[i]+=3*rho_ice/rho_earth*area/(4*PI*pow(earth_radius,2))*I*U_elastic[i];
-		N_values[i]+=3*rho_ice/rho_earth*area/(4*PI*pow(earth_radius,2))*I*N_elastic[i];
-		E_values[i]+=3*rho_ice/rho_earth*area/(4*PI*pow(earth_radius,2))*I*E_elastic[i];
-	}
-
-	pUp->SetValues(gsize,indices,U_values,ADD_VAL);
-	pNorth->SetValues(gsize,indices,N_values,ADD_VAL);
-	pEast->SetValues(gsize,indices,E_values,ADD_VAL);
-	
-	/*free ressources:*/
-	xDelete<int>(indices); 
-	xDelete<IssmDouble>(U_values); xDelete<IssmDouble>(N_values); xDelete<IssmDouble>(E_values);
-	xDelete<IssmDouble>(U_elastic); xDelete<IssmDouble>(N_elastic); xDelete<IssmDouble>(E_elastic);
-
-	return;
-}
-/*}}}*/
-void    Tria::EsaGeodetic3D(Vector<IssmDouble>* pUp,Vector<IssmDouble>* pNorth,Vector<IssmDouble>* pEast,IssmDouble* latitude,IssmDouble* longitude,IssmDouble* radius,IssmDouble* xx,IssmDouble* yy,IssmDouble* zz,IssmDouble eartharea){ /*{{{*/
-
-	/*diverse:*/
-	int gsize;
-	bool spherical=true;
-	IssmDouble llr_list[NUMVERTICES][3];
-	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble area;
-	IssmDouble I;		//ice/water loading 
-	IssmDouble late,longe,re;
-	IssmDouble lati,longi,ri;
-	IssmDouble rho_ice,rho_earth;
-	IssmDouble minlong=400;
-	IssmDouble maxlong=-20;
-
-	/*precomputed elastic green functions:*/
-	IssmDouble* U_elastic_precomputed = NULL;
-	IssmDouble* H_elastic_precomputed = NULL;
-	int         M;
-	
-	/*computation of Green functions:*/
-	IssmDouble* U_elastic= NULL;
-	IssmDouble* N_elastic= NULL;
-	IssmDouble* E_elastic= NULL;
-	
-	/*optimization:*/
-	bool store_green_functions=false;
-
-	/*Compute ice thickness change: */
-	Input*	deltathickness_input=inputs->GetInput(EsaDeltathicknessEnum); 
-	if (!deltathickness_input)_error_("delta thickness input needed to compute elastic adjustment!");
-	deltathickness_input->GetInputAverage(&I);
-		
-	/*early return if we are not on the (ice) loading point: */ 
-	if(I==0) return; 
-
-	/*recover material parameters: */
-	rho_ice=matpar->GetMaterialParameter(MaterialsRhoIceEnum);
-	rho_earth=matpar->GetMaterialParameter(MaterialsEarthDensityEnum);
-
-	/*how many dofs are we working with here? */
-	this->parameters->FindParam(&gsize,MeshNumberofverticesEnum);
-
-	/*compute area of element:*/
 	area=GetAreaSpherical();
 
@@ -3915,5 +4538,10 @@
 
 	/*early return if we are not on an ice cap OR ocean:*/
-	if(!(this->inputs->Max(MaskIceLevelsetEnum)<0) && !IsWaterInElement()) return; 
+	if(!(this->inputs->Max(MaskIceLevelsetEnum)<0) && !IsWaterInElement()){
+		dI_list[0] = 0.0; // this is important!!! 
+		dI_list[1] = 0.0; // this is important!!! 
+		dI_list[2] = 0.0; // this is important!!! 
+		return; 
+	}
 
 	/*Compute area of element:*/
Index: /issm/trunk/src/c/classes/Elements/Tria.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/Tria.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Elements/Tria.h	(revision 22758)
@@ -34,5 +34,5 @@
 		/*Tria constructors, destructors {{{*/
 		Tria(){};
-		Tria(int tria_id,int tria_sid,int i, IoModel* iomodel,int nummodels);
+		Tria(int tria_id,int tria_sid,IoModel* iomodel,int nummodels);
 		~Tria();
 		/*}}}*/
@@ -52,5 +52,6 @@
 		/*Element virtual functions definitions: {{{*/
 		void        AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part);
-		void			CalvingRateDev();
+		void			CalvingRateVonmises();
+		void        CalvingCrevasseDepth();
 		void			CalvingRateLevermann();
 		IssmDouble  CharacteristicLength(void);
@@ -62,6 +63,8 @@
 		void        ComputeSurfaceNormalVelocity();
 		void        Configure(Elements* elements,Loads* loads,Nodes* nodesin,Vertices* verticesin,Materials* materials,Parameters* parameters);
+		void        ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index,int offset,int N, int M);
 		void        ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index);
 		void        ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum);
+		void        CreateDistanceInputFromSegmentlist(IssmDouble* segments,int numsegments,int distanceenum);
 		int         EdgeOnBaseIndex();
 		void        EdgeOnBaseIndices(int* pindex1,int* pindex);
@@ -71,5 +74,5 @@
 		void        ElementSizes(IssmDouble* hx,IssmDouble* hy,IssmDouble* hz);
 		int         FiniteElement(void);
-		IssmDouble  FloatingArea(void);
+		IssmDouble  FloatingArea(bool scaled);
 		void        FSContactMigration(Vector<IssmDouble>* vertexgrounded,Vector<IssmDouble>* vertexfloating);
 		Element*    GetBasalElement(void){_error_("not implemented yet");};
@@ -83,19 +86,15 @@
 		int         GetNumberOfNodes(int enum_type);
 		int         GetNumberOfVertices(void);
-		void        GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution,int enum_type);
-		Element*    GetUpperElement(void){_error_("not implemented yet");};
+		void        GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data,int offset,bool onsid);
 		void        GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data,bool onsid);
 		void        GetVerticesCoordinatesBase(IssmDouble** pxyz_list);
 		void        GetVerticesCoordinatesTop(IssmDouble** pxyz_list);
-		IssmDouble  GroundedArea(void);
+		IssmDouble  GroundedArea(bool scaled);
 		bool        HasEdgeOnBase();
 		bool        HasEdgeOnSurface();
-		IssmDouble  IceMass(void);
-		IssmDouble  IceVolume(void);
-		IssmDouble  IceVolumeAboveFloatation(void);
-		void        InputControlUpdate(IssmDouble scalar,bool save_parameter);
+		IssmDouble  IceVolume(bool scaled);
+		IssmDouble  IceVolumeAboveFloatation(bool scaled);
 		void        InputDepthAverageAtBase(int enum_type,int average_enum_type);
 		void        InputExtrude(int enum_type,int start){_error_("not implemented"); /*For penta only*/};
-		void        InputScale(int enum_type,IssmDouble scale_factor);
 		bool	   	IsFaceOnBoundary(void);
 		bool	   	IsIcefront(void);
@@ -113,4 +112,6 @@
 		int         NumberofNodesPressure(void);
 		int         NumberofNodesVelocity(void);
+		void        PicoUpdateBoxid(int* pmax_boxid_basin);
+		void        PicoUpdateBox(int loopboxid);
 		void        PotentialUngrounding(Vector<IssmDouble>* potential_sheet_ungrounding);
 		int         PressureInterpolation();
@@ -119,4 +120,5 @@
 		void        ResetHooks();
 		void        ResetLevelsetFromSegmentlist(IssmDouble* segments,int numsegments);
+		void        SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index,int offset,int N,int M);
 		void        SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index);
 		void        SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Materials* materials,Parameters* parameters);
@@ -129,7 +131,7 @@
 		int         TensorInterpolation();
 		IssmDouble  TimeAdapt();
-		IssmDouble  TotalFloatingBmb(void);
-		IssmDouble  TotalGroundedBmb(void);
-		IssmDouble  TotalSmb(void);
+		IssmDouble  TotalFloatingBmb(bool scaled);
+		IssmDouble  TotalGroundedBmb(bool scaled);
+		IssmDouble  TotalSmb(bool scaled);
 		void        Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finitelement);
 		int         UpdatePotentialUngrounding(IssmDouble* vertices_potentially_ungrounding,Vector<IssmDouble>* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf);
@@ -140,4 +142,5 @@
 		void        VerticalSegmentIndices(int** pindices,int* pnumseg){_error_("not implemented yet");};
 		void        VerticalSegmentIndicesBase(int** pindices,int* pnumseg){_error_("not implemented yet");};
+		void			WriteFieldIsovalueSegment(DataSet* segments,int fieldenum,IssmDouble fieldvalue);
 		void			WriteLevelsetSegment(DataSet* segments);
 		void        ZeroLevelsetCoordinates(IssmDouble** pxyz_zero,IssmDouble* xyz_list,int levelsetenum);
@@ -147,5 +150,5 @@
 		#endif
 		#ifdef _HAVE_ESA_
-		void    EsaGeodetic2D(Vector<IssmDouble>* pUp,Vector<IssmDouble>* pNorth,Vector<IssmDouble>* pEast,IssmDouble* xx,IssmDouble* yy);
+		void    EsaGeodetic2D(Vector<IssmDouble>* pUp,Vector<IssmDouble>* pNorth,Vector<IssmDouble>* pEast,  Vector<IssmDouble>* pX,Vector<IssmDouble>* pY,IssmDouble* xx,IssmDouble* yy);
 		void    EsaGeodetic3D(Vector<IssmDouble>* pUp,Vector<IssmDouble>* pNorth,Vector<IssmDouble>* pEast,IssmDouble* latitude,IssmDouble* longitude,IssmDouble* radius,IssmDouble* xx,IssmDouble* yy,IssmDouble* zz,IssmDouble eartharea);
 		#endif
@@ -162,5 +165,8 @@
 		void           AddBasalInput(int input_enum, IssmDouble* values, int interpolation_enum);
 		void           AddInput(int input_enum, IssmDouble* values, int interpolation_enum);
+		void           AddControlInput(int input_enum, IssmDouble* values,IssmDouble* values_min,IssmDouble* values_max, int interpolation_enum,int id);
+		void           DatasetInputCreate(IssmDouble* array,int M,int N,int* individual_enums,int num_inputs,IoModel* iomodel,int input_enum);
 		IssmDouble     GetArea(void);
+		IssmDouble     GetHorizontalSurfaceArea(void);
 		IssmDouble 	   GetArea3D(void);
 		IssmDouble 	   GetAreaIce(void);
@@ -184,4 +190,5 @@
       Gauss*         NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order);
       Gauss*         NewGauss(int point1,IssmDouble fraction1,IssmDouble fraction2,bool mainlyfloating,int order);
+      Gauss*         NewGauss(int point1,IssmDouble fraction1,IssmDouble fraction2,int order);
       Gauss*         NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order_horiz,int order_vert);
 		Gauss*         NewGaussBase(int order);
Index: /issm/trunk/src/c/classes/ExternalResults/GenericExternalResult.h
===================================================================
--- /issm/trunk/src/c/classes/ExternalResults/GenericExternalResult.h	(revision 22757)
+++ /issm/trunk/src/c/classes/ExternalResults/GenericExternalResult.h	(revision 22758)
@@ -321,5 +321,5 @@
 template <> inline void GenericExternalResult<char*>::Marshall(char** pmarshalled_data,int* pmarshalled_data_size, int marshall_direction){/*{{{*/
 
-	int size;
+	int size = 0;
 
 	if(marshall_direction==MARSHALLING_FORWARD || marshall_direction == MARSHALLING_SIZE)size=strlen(value)+1;
@@ -462,50 +462,4 @@
 
 }  /*}}}*/
-/*Specific instantiations for int*: */
-#if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)  //We hook off this specific specialization when not running ADOLC, otherwise we get a redeclaration with the next specialization. 
-template <> inline void GenericExternalResult<int*>::WriteData(FILE* fid,bool io_gather){ /*{{{*/
-
-	int     i;
-	int     my_rank;
-	int     type;
-	int     rows,cols;
-	char   *name    = NULL;
-	IssmPDouble passiveDouble;
-	int* passiveInts;
-
-	/*recover my_rank:*/
-	my_rank=IssmComm::GetRank();
-
-	if(io_gather){
-		/*we are gathering the data on cpu 0, don't write on other cpus: */
-		if(my_rank) return;
-	}
-
-	/*First write enum: */
-	int length=(strlen(this->result_name)+1)*sizeof(char);
-	fwrite(&length,sizeof(int),1,fid);
-	fwrite(this->result_name,length,1,fid);
-
-	/*Now write time and step: */
-	passiveDouble=reCast<IssmPDouble>(time);
-	fwrite(&passiveDouble,sizeof(IssmPDouble),1,fid);
-	fwrite(&step,sizeof(int),1,fid);
-
-	/*writing a int array, type is 4 (see parseresultsfromdisk.m):*/
-	type=4;
-	fwrite(&type,sizeof(int),1,fid);
-	rows=this->M;
-	fwrite(&rows,sizeof(int),1,fid);
-	cols=this->N;
-	fwrite(&cols,sizeof(int),1,fid);
-
-	passiveInts=xNew<int>(this->M*this->N);
-	for (i=0;i<this->M*this->N;i++)passiveInts[i]=reCast<int>(value[i]);
-	fwrite(passiveInts,cols*rows*sizeof(int),1,fid);
-	xDelete<int>(int);
-
-}
-/*}}}*/
-#endif
 
 /*Specific instantiations for IssmPDouble*: */
Index: /issm/trunk/src/c/classes/FemModel.cpp
===================================================================
--- /issm/trunk/src/c/classes/FemModel.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/FemModel.cpp	(revision 22758)
@@ -10,4 +10,5 @@
 
 #include <stdio.h>
+#include <math.h>
 #include "../cores/cores.h"
 #include "../shared/io/io.h"
@@ -45,5 +46,5 @@
 
 	/*configuration: */
-	int  solution_type;
+	int  solution_type,amrtype,amr_frequency;
 	int  ierr;
 
@@ -67,5 +68,5 @@
 	/*Start profiler: */
 	this->profiler=new Profiler();
-	profiler->Tag(START);
+	profiler->Start(TOTAL);
 
 	/*From command line arguments, retrieve different filenames needed to create the FemModel: */
@@ -73,13 +74,50 @@
 
 	/*Create femmodel from input files: */
-	profiler->Tag(STARTINIT);
+	profiler->Start(MPROCESSOR);
 	this->InitFromFiles(rootpath,binfilename,outbinfilename,petscfilename,lockfilename,restartfilename, solution_type,trace,NULL);
-	profiler->Tag(FINISHINIT);
+	profiler->Stop(MPROCESSOR);
 
 	/*Save communicator in the parameters dataset: */
 	this->parameters->AddObject(new GenericParam<ISSM_MPI_Comm>(incomm,FemModelCommEnum));
 
-	#ifdef _HAVE_NEOPZ_
-	this->InitializeAdaptiveRefinement();
+   /*AMR stuff*/
+	this->parameters->FindParam(&amr_frequency,TransientAmrFrequencyEnum);
+	#if defined(_HAVE_NEOPZ_) && !defined(_HAVE_ADOLC_)
+	this->amr = NULL;
+	#endif
+	#if defined(_HAVE_BAMG_) && !defined(_HAVE_ADOLC_)
+	this->amrbamg = NULL;
+	#endif
+	#if !defined(_HAVE_ADOLC_)
+	if(amr_frequency){
+		/*Verifications. AMR supports SSA, P1 and horizontal 2D domain*/
+		bool isSSA;
+		int domaintype,element_type,analysis_counter=-1;
+		this->parameters->FindParam(&isSSA,FlowequationIsSSAEnum);
+		this->parameters->FindParam(&domaintype,DomainTypeEnum);
+		for(int i=0;i<this->nummodels;i++) if(this->analysis_type_list[i]==StressbalanceAnalysisEnum){analysis_counter=i;break;}
+		if(analysis_counter==-1) _error_("Could not find alias for analysis_type StressbalanceAnalysisEnum in list of FemModel analyses\n");
+		for(int i=0;i<this->elements->Size();i++){
+			Element* element	= xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
+			element_type		= element->element_type_list[analysis_counter];
+			if(element_type!=P1Enum) _error_("Element type "<<EnumToStringx(element_type)<<" not supported with AMR yet!\n");
+		}
+		if(!isSSA) _error_("Flow equation not supported with AMR yet!\n ");
+		if(domaintype!=Domain2DhorizontalEnum) _error_("Domain "<<EnumToStringx(domaintype)<<" not supported with AMR yet!\n");
+
+		this->parameters->FindParam(&amrtype,AmrTypeEnum);
+		switch(amrtype){
+
+			#if defined(_HAVE_NEOPZ_)
+			case AmrNeopzEnum: this->InitializeAdaptiveRefinementNeopz(); break;
+			#endif
+
+			#if defined(_HAVE_BAMG_)
+			case AmrBamgEnum: this->InitializeAdaptiveRefinementBamg(); break;
+			#endif
+
+			default: _error_("not implemented yet");
+		}
+	}
 	#endif
 
@@ -104,7 +142,14 @@
 
 	/*Create femmodel from input files, with trace activated: */
-	profiler->Tag(STARTINIT);
+	profiler->Start(MPROCESSOR);
 	this->InitFromFiles(rootpath,inputfilename,outputfilename,toolkitsfilename,lockfilename,restartfilename, solution_type,traceon,X);
-	profiler->Tag(FINISHINIT);
+	profiler->Stop(MPROCESSOR);
+
+	#if defined(_HAVE_NEOPZ_) && !defined(_HAVE_ADOLC_)
+	this->amr = NULL;
+	#endif
+	#if defined(_HAVE_BAMG_) && !defined(_HAVE_ADOLC_)
+	this->amrbamg = NULL;
+	#endif
 	
 	/*Save communicator in the parameters dataset: */
@@ -122,5 +167,5 @@
 	#ifndef _HAVE_JAVASCRIPT_
 	if(this->parameters->Exist(OutputFileNameEnum)) this->parameters->FindParam(&outbinfilename,OutputFileNameEnum);
-	if(this-parameters->Exist(LockFileNameEnum)) this->parameters->FindParam(&lockfilename,LockFileNameEnum);
+	if(this->parameters->Exist(LockFileNameEnum)) this->parameters->FindParam(&lockfilename,LockFileNameEnum);
 	#endif
 
@@ -138,14 +183,15 @@
 	if(results)delete results;
 	
-	#ifdef _HAVE_NEOPZ_
+	#if defined(_HAVE_NEOPZ_) && !defined(_HAVE_ADOLC_)
 	if(amr)delete amr;
 	#endif
 
+	#if defined(_HAVE_BAMG_) && !defined(_HAVE_ADOLC_)
+	if(amrbamg)delete amrbamg;
+	#endif
+
 	/*Now delete: */
 	if(profiler)delete profiler;
-	
-	
-}
-/*}}}*/
+}/*}}}*/
 
 /*Object management*/
@@ -207,13 +253,14 @@
 
 	/*Before we delete the profiler, report statistics for this run: */
-	profiler->Tag(FINISH);  //final tagging
+	profiler->Stop(TOTAL);  //final tagging
 	_printf0_("\n");
-	_printf0_("   "<<setw(40)<<left<<"FemModel initialization elapsed time:"<<profiler->DeltaTime(STARTINIT,FINISHINIT) << "\n");
-	_printf0_("   "<<setw(40)<<left<<"Core solution elapsed time:"<<profiler->DeltaTime(STARTCORE,FINISHCORE) << "\n");
+	_printf0_("   "<<setw(40)<<left<<"FemModel initialization elapsed time:"<<profiler->TotalTime(MPROCESSOR) << "\n");
+	_printf0_("   "<<setw(40)<<left<<"Core solution elapsed time:"<<profiler->TotalTime(CORE) << "\n");
+	_printf0_("   "<<setw(40)<<left<<"Solver elapsed time:"<<profiler->TotalTime(SOLVER) << "\n");
 	_printf0_("\n");
 	_printf0_("   Total elapsed time: "
-				<<profiler->DeltaTimeModHour(START,FINISH)<<" hrs "
-				<<profiler->DeltaTimeModMin(START,FINISH)<<" min "
-				<<profiler->DeltaTimeModSec(START,FINISH)<<" sec"
+				<<profiler->TotalTimeModHour(TOTAL)<<" hrs "
+				<<profiler->TotalTimeModMin(TOTAL)<<" min "
+				<<profiler->TotalTimeModSec(TOTAL)<<" sec"
 				);
 	_printf0_("\n");
@@ -270,4 +317,12 @@
 		ConfigureObjectsx(output->elements,output->loads,output->nodes,output->vertices,output->materials,output->parameters);
 	}
+
+	/*AMR, no copy for now*/
+	#if defined(_HAVE_NEOPZ_) && !defined(_HAVE_ADOLC_)
+	this->amr = NULL;
+	#endif
+	#if defined(_HAVE_BAMG_) && !defined(_HAVE_ADOLC_)
+	this->amrbamg = NULL;
+	#endif
 
 	/*Reset current configuration: */
@@ -490,5 +545,4 @@
 	int found=-1;
 	for(int i=0;i<nummodels;i++){
-	
 		if (analysis_type_list[i]==configuration_type){
 			found=i;
@@ -511,9 +565,8 @@
 	if(this->parameters->Exist(ToolkitsOptionsStringsEnum)){
 		ToolkitsOptionsFromAnalysis(this->parameters,analysis_type);
-		if(VerboseSolver()) _printf0_("      toolkits Options set for analysis type: " << EnumToStringx(analysis_type) << "\n");
-	}
-
-}
-/*}}}*/
+		if(VerboseSolver()) _printf0_("      toolkits Options set for analysis: " << EnumToStringx(analysis_type) << "\n");
+	}
+
+}/*}}}*/
 void FemModel::SetCurrentConfiguration(int configuration_type){/*{{{*/
 	this->SetCurrentConfiguration(configuration_type,configuration_type);
@@ -639,5 +692,9 @@
 			analyses_temp[numanalyses++]=GiaIvinsAnalysisEnum;
 			break;
-		
+
+		case LoveSolutionEnum:
+			analyses_temp[numanalyses++]=LoveAnalysisEnum;
+			break;
+
 		case EsaSolutionEnum:
 			analyses_temp[numanalyses++]=EsaAnalysisEnum;
@@ -768,12 +825,12 @@
 
 	/*run solution core: */
-	profiler->Tag(STARTCORE);   
+	profiler->Start(CORE);   
 	solutioncore(this); 
-	profiler->Tag(FINISHCORE);
+	profiler->Stop(CORE);
 
 	/*run AD core if needed: */
-	profiler->Tag(STARTADCORE); 
+	profiler->Start(ADCORE); 
 	ad_core(this);      
-	profiler->Tag(FINISHADCORE);
+	profiler->Stop(ADCORE);
 
 	/*some profiling results for the core: */
@@ -781,7 +838,7 @@
 	if(profiling){
 
-		solution_time=profiler->DeltaTime(STARTCORE,FINISHCORE);
-		solution_flops=profiler->DeltaFlops(STARTCORE,FINISHCORE);
-		solution_memory=profiler->Memory(FINISHCORE);
+		solution_time=profiler->TotalTime(CORE);
+		solution_flops=profiler->TotalFlops(CORE);
+		solution_memory=profiler->Memory(CORE);
 
 		_printf0_("Core solution elapsed time    : " << solution_time   << " Seconds\n");
@@ -795,7 +852,7 @@
 
 		#ifdef _HAVE_ADOLC_
-		solution_time=profiler->DeltaTime(STARTADCORE,FINISHADCORE);
-		solution_flops=profiler->DeltaFlops(STARTADCORE,FINISHADCORE);
-		solution_memory=profiler->Memory(FINISHADCORE);
+		solution_time=profiler->TotalTime(ADCORE);
+		solution_flops=profiler->TotalFlops(ADCORE);
+		solution_memory=profiler->Memory(ADCORE);
 
 		_printf0_("AD Solution elapsed time    : " << solution_time   << " Seconds\n");
@@ -877,9 +934,9 @@
 
 }/*}}}*/
-void FemModel::CalvingRateDevx(){/*{{{*/
+void FemModel::CalvingRateVonmisesx(){/*{{{*/
 
 	for(int i=0;i<elements->Size();i++){
 		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
-		element->CalvingRateDev();
+		element->CalvingRateVonmises();
 	}
 }
@@ -934,4 +991,75 @@
 }
 /*}}}*/
+void FemModel::DistanceToFieldValue(int fieldenum,IssmDouble fieldvalue,int distanceenum){/*{{{*/
+
+	/*recover my_rank:*/
+	int my_rank   = IssmComm::GetRank();
+	int num_procs = IssmComm::GetSize();
+
+	/*Get domain type (2d or 3d)*/
+	int domaintype;
+	this->parameters->FindParam(&domaintype,DomainTypeEnum);
+
+	/*1: go throug all elements of this partition and figure out how many
+	 * segments we have (corresopnding to field = value)*/
+	DataSet* segments=new DataSet();
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		if(!element->IsOnBase()) continue;
+		Element* basalelement = element->SpawnBasalElement();
+		basalelement->WriteFieldIsovalueSegment(segments,fieldenum,fieldvalue);
+		if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+	}
+
+	/*2: now get the segments from all partitions*/
+	int  segcount=segments->Size();
+	int* allsegcount=xNew<int>(num_procs);
+	ISSM_MPI_Gather(&segcount,1,ISSM_MPI_INT,allsegcount,1,ISSM_MPI_INT,0,IssmComm::GetComm());
+	ISSM_MPI_Bcast(allsegcount,num_procs,ISSM_MPI_INT,0,IssmComm::GetComm());
+
+	/* Every cpu should start its own dof count at the end of the dofcount from cpu-1*/
+	int numseg_offset=0;
+	int numseg=0;
+	for(int i=0;i<my_rank;  i++) numseg_offset+=allsegcount[i];
+	for(int i=0;i<num_procs;i++) numseg+=allsegcount[i];
+	IssmDouble* segmentlist    = xNewZeroInit<IssmDouble>(4*numseg);
+	IssmDouble* allsegmentlist = xNewZeroInit<IssmDouble>(4*numseg);
+	for(int i=0;i<segments->Size();i++){
+		Contour<IssmDouble>* segment=(Contour<IssmDouble>*)segments->GetObjectByOffset(i);
+		_assert_(segment->nods == 2);
+		segmentlist[(numseg_offset+i)*4 + 0] = segment->x[0];
+		segmentlist[(numseg_offset+i)*4 + 1] = segment->y[0];
+		segmentlist[(numseg_offset+i)*4 + 2] = segment->x[1];
+		segmentlist[(numseg_offset+i)*4 + 3] = segment->y[1];
+	}
+	ISSM_MPI_Allreduce((void*)segmentlist,(void*)allsegmentlist,4*numseg,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
+	delete segments;
+	xDelete<IssmDouble>(segmentlist);
+	xDelete<int>(allsegcount);
+
+	/*3: Add distance input to all elements*/
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		if(!element->IsOnBase()) continue;
+		element->CreateDistanceInputFromSegmentlist(allsegmentlist,numseg,distanceenum);
+	}
+
+
+	/*Extrude if necessary*/
+	int elementtype;
+	this->parameters->FindParam(&elementtype,MeshElementtypeEnum);
+	if(elementtype==PentaEnum){
+		InputExtrudex(this,distanceenum,-1);
+	}
+	else if(elementtype==TriaEnum){
+		/*no need to extrude*/
+	}
+	else{
+		_error_("not implemented yet");
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(allsegmentlist);
+}/*}}}*/
 void FemModel::Divergencex(IssmDouble* pdiv){/*{{{*/
 
@@ -999,5 +1127,5 @@
 
 }/*}}}*/
-void FemModel::FloatingAreax(IssmDouble* pV){/*{{{*/
+void FemModel::FloatingAreax(IssmDouble* pV, bool scaled){/*{{{*/
 
 	IssmDouble local_floating_area= 0;
@@ -1006,5 +1134,5 @@
 	for(int i=0;i<this->elements->Size();i++){
 		Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
-		local_floating_area+=element->FloatingArea();
+		local_floating_area+=element->FloatingArea(scaled);
 	}
 	ISSM_MPI_Reduce(&local_floating_area,&total_floating_area,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
@@ -1048,5 +1176,5 @@
 
 }/*}}}*/
-void FemModel::GroundedAreax(IssmDouble* pV){/*{{{*/
+void FemModel::GroundedAreax(IssmDouble* pV, bool scaled){/*{{{*/
 
 	IssmDouble local_grounded_area= 0;
@@ -1055,5 +1183,5 @@
 	for(int i=0;i<this->elements->Size();i++){
 		Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
-		local_grounded_area+=element->GroundedArea();
+		local_grounded_area+=element->GroundedArea(scaled);
 	}
 	ISSM_MPI_Reduce(&local_grounded_area,&total_grounded_area,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
@@ -1064,5 +1192,5 @@
 
 }/*}}}*/
-void FemModel::IceMassx(IssmDouble* pM){/*{{{*/
+void FemModel::IceMassx(IssmDouble* pM, bool scaled){/*{{{*/
 
 	IssmDouble local_ice_mass = 0;
@@ -1071,5 +1199,5 @@
 	for(int i=0;i<this->elements->Size();i++){
 		Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
-		local_ice_mass+=element->IceMass();
+		local_ice_mass+=element->IceMass(scaled);
 	}
 	ISSM_MPI_Reduce(&local_ice_mass,&total_ice_mass,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
@@ -1080,5 +1208,5 @@
 
 }/*}}}*/
-void FemModel::IceVolumeAboveFloatationx(IssmDouble* pV){/*{{{*/
+void FemModel::IceVolumeAboveFloatationx(IssmDouble* pV, bool scaled){/*{{{*/
 
 	IssmDouble local_ice_volume_af = 0;
@@ -1087,5 +1215,5 @@
 	for(int i=0;i<this->elements->Size();i++){
 		Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
-		local_ice_volume_af+=element->IceVolumeAboveFloatation();
+		local_ice_volume_af+=element->IceVolumeAboveFloatation(scaled);
 	}
 	ISSM_MPI_Reduce(&local_ice_volume_af,&total_ice_volume_af,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
@@ -1096,5 +1224,5 @@
 
 }/*}}}*/
-void FemModel::IceVolumex(IssmDouble* pV){/*{{{*/
+void FemModel::IceVolumex(IssmDouble* pV, bool scaled){/*{{{*/
 
 	IssmDouble local_ice_volume = 0;
@@ -1103,5 +1231,5 @@
 	for(int i=0;i<this->elements->Size();i++){
 		Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
-		local_ice_volume+=element->IceVolume();
+		local_ice_volume+=element->IceVolume(scaled);
 	}
 	ISSM_MPI_Reduce(&local_ice_volume,&total_ice_volume,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
@@ -1453,4 +1581,120 @@
 
 }/*}}}*/
+void FemModel::OmegaAbsGradientx( IssmDouble* pJ){/*{{{*/
+
+	/*output: */
+	IssmDouble J=0.;
+	IssmDouble J_sum;
+
+	IssmDouble  omega,weight;
+	IssmDouble  Jdet;
+	IssmDouble* xyz_list = NULL;
+	IssmDouble  dp[3];
+
+	/*Compute Misfit: */
+	for(int i=0;i<elements->Size();i++){
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
+
+		/*If on water, return 0: */
+		if(!element->IsIceInElement()) continue;
+
+		/* Get node coordinates*/
+		element->GetVerticesCoordinates(&xyz_list);
+
+		/*Retrieve all inputs we will be needing: */
+		Input* weights_input   =element->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+		Input* omega_input =element->GetInput(BalancethicknessOmegaEnum);                   _assert_(omega_input);
+
+		/* Start  looping on the number of gaussian points: */
+		Gauss* gauss=element->NewGauss(2);
+		for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+			gauss->GaussPoint(ig);
+
+			/* Get Jacobian determinant: */
+			element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+
+			/*Get all parameters at gaussian point*/
+			weights_input->GetInputValue(&weight,gauss,OmegaAbsGradientEnum);
+			omega_input->GetInputDerivativeValue(&dp[0],xyz_list,gauss);
+
+			/*Tikhonov regularization: J = 1/2 ((dp/dx)^2 + (dp/dy)^2) */ 
+			//J+=weight*1/2*(dp[0]*dp[0]+dp[1]*dp[1])*Jdet*gauss->weight;
+			J+=weight*1/2*pow(dp[0]*dp[0]+dp[1]*dp[1],2)*Jdet*gauss->weight;
+		}
+
+		/*clean up and Return: */
+		xDelete<IssmDouble>(xyz_list);
+		delete gauss;
+	}
+
+	/*Sum all J from all cpus of the cluster:*/
+	ISSM_MPI_Reduce (&J,&J_sum,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&J_sum,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+	J=J_sum;
+
+	/*Assign output pointers: */
+	*pJ=J;
+}
+/*}}}*/
+void FemModel::EtaDiffx( IssmDouble* pJ){/*{{{*/
+
+	/*output: */
+	IssmDouble J=0.;
+	IssmDouble J_sum;
+
+	IssmDouble  omega,weight;
+	IssmDouble  Jdet;
+	IssmDouble* xyz_list = NULL;
+	IssmDouble  p,p0;
+
+	/*Compute Misfit: */
+	for(int i=0;i<elements->Size();i++){
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
+
+		/*If on water, return 0: */
+		if(!element->IsIceInElement()) continue;
+
+		/* Get node coordinates*/
+		element->GetVerticesCoordinates(&xyz_list);
+
+		/*Retrieve all inputs we will be needing: */
+		Input* weights_input =element->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+		Input* omega_input   =element->GetInput(BalancethicknessOmegaEnum);              _assert_(omega_input);
+		Input* omega0_input  =element->GetInput(BalancethicknessOmega0Enum);             _assert_(omega0_input);
+
+		/* Start  looping on the number of gaussian points: */
+		Gauss* gauss=element->NewGauss(2);
+		for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+			gauss->GaussPoint(ig);
+
+			/* Get Jacobian determinant: */
+			element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+
+			/*Get all parameters at gaussian point*/
+			weights_input->GetInputValue(&weight,gauss,EtaDiffEnum);
+			omega_input->GetInputValue(&p,gauss);
+			omega0_input->GetInputValue(&p0,gauss);
+
+			/*Tikhonov regularization: J = 1/2 ((dp/dx)^2 + (dp/dy)^2) */ 
+			//J+=weight*1/2*(dp[0]*dp[0]+dp[1]*dp[1])*Jdet*gauss->weight;
+			J+=weight*1/2*pow(p - p0,2)*Jdet*gauss->weight;
+		}
+
+		/*clean up and Return: */
+		xDelete<IssmDouble>(xyz_list);
+		delete gauss;
+	}
+
+	/*Sum all J from all cpus of the cluster:*/
+	ISSM_MPI_Reduce (&J,&J_sum,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&J_sum,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+	J=J_sum;
+
+	/*Assign output pointers: */
+	*pJ=J;
+}
+/*}}}*/
 void FemModel::OutputControlsx(Results **presults){/*{{{*/
 
@@ -1574,5 +1818,5 @@
 		else{
 			/*last chance for the output definition, if the enum is one of Outputdefinition[1-10]Enum:*/
-			if(output_enum>=Outputdefinition1Enum && output_enum <=Outputdefinition10Enum){
+			if(output_enum>=Outputdefinition1Enum && output_enum <=Outputdefinition100Enum){
 				double_result = OutputDefinitionsResponsex(this,output_enum);
 				if(save_results){
@@ -1585,26 +1829,34 @@
 
 					/*Scalar output*/
-					case DivergenceEnum:               this->Divergencex(&double_result);               break;
-					case MaxDivergenceEnum:            this->MaxDivergencex(&double_result);            break;
-					case IceMassEnum:                  this->IceMassx(&double_result);                  break;
-					case IceVolumeEnum:                this->IceVolumex(&double_result);                break;
-					case IceVolumeAboveFloatationEnum: this->IceVolumeAboveFloatationx(&double_result); break;
-					case GroundedAreaEnum:             this->GroundedAreax(&double_result);             break;
-					case FloatingAreaEnum:             this->FloatingAreax(&double_result);             break;
-					case MinVelEnum:                   this->MinVelx(&double_result);                   break;
-					case MaxVelEnum:                   this->MaxVelx(&double_result);                   break;
-					case MinVxEnum:                    this->MinVxx(&double_result);                    break;
-					case MaxVxEnum:                    this->MaxVxx(&double_result);                    break;
-					case MaxAbsVxEnum:                 this->MaxAbsVxx(&double_result);                 break;
-					case MinVyEnum:                    this->MinVyx(&double_result);                    break;
-					case MaxVyEnum:                    this->MaxVyx(&double_result);                    break;
-					case MaxAbsVyEnum:                 this->MaxAbsVyx(&double_result);                 break;
-					case MinVzEnum:                    this->MinVzx(&double_result);                    break;
-					case MaxVzEnum:                    this->MaxVzx(&double_result);                    break;
-					case MaxAbsVzEnum:                 this->MaxAbsVzx(&double_result);                 break;
-					case MassFluxEnum:                 this->MassFluxx(&double_result);                 break;
-					case TotalFloatingBmbEnum:         this->TotalFloatingBmbx(&double_result);         break;
-					case TotalGroundedBmbEnum:         this->TotalGroundedBmbx(&double_result);         break;
-					case TotalSmbEnum:                 this->TotalSmbx(&double_result);                 break;
+					case DivergenceEnum:                     this->Divergencex(&double_result);                     break;
+					case MaxDivergenceEnum:                  this->MaxDivergencex(&double_result);                  break;
+					case IceMassEnum:                        this->IceMassx(&double_result,false);                  break;
+					case IceMassScaledEnum:                  this->IceMassx(&double_result,true);                   break;
+					case IceVolumeEnum:                      this->IceVolumex(&double_result,false);                break;
+					case IceVolumeScaledEnum:                this->IceVolumex(&double_result,true);                 break;
+					case IceVolumeAboveFloatationEnum:       this->IceVolumeAboveFloatationx(&double_result,false); break;
+					case IceVolumeAboveFloatationScaledEnum: this->IceVolumeAboveFloatationx(&double_result,true);  break;
+					case GroundedAreaEnum:                   this->GroundedAreax(&double_result,false);             break;
+					case GroundedAreaScaledEnum:             this->GroundedAreax(&double_result,true);              break;
+					case FloatingAreaEnum:                   this->FloatingAreax(&double_result,false);             break;
+					case FloatingAreaScaledEnum:             this->FloatingAreax(&double_result,true);              break;
+					case MinVelEnum:                         this->MinVelx(&double_result);                         break;
+					case MaxVelEnum:                         this->MaxVelx(&double_result);                         break;
+					case MinVxEnum:                          this->MinVxx(&double_result);                          break;
+					case MaxVxEnum:                          this->MaxVxx(&double_result);                          break;
+					case MaxAbsVxEnum:                       this->MaxAbsVxx(&double_result);                       break;
+					case MinVyEnum:                          this->MinVyx(&double_result);                          break;
+					case MaxVyEnum:                          this->MaxVyx(&double_result);                          break;
+					case MaxAbsVyEnum:                       this->MaxAbsVyx(&double_result);                       break;
+					case MinVzEnum:                          this->MinVzx(&double_result);                          break;
+					case MaxVzEnum:                          this->MaxVzx(&double_result);                          break;
+					case MaxAbsVzEnum:                       this->MaxAbsVzx(&double_result);                       break;
+					case MassFluxEnum:                       this->MassFluxx(&double_result);                       break;
+					case TotalFloatingBmbEnum:               this->TotalFloatingBmbx(&double_result,false);         break;
+					case TotalFloatingBmbScaledEnum:         this->TotalFloatingBmbx(&double_result,true);          break;
+					case TotalGroundedBmbEnum:               this->TotalGroundedBmbx(&double_result,false);         break;
+					case TotalGroundedBmbScaledEnum:         this->TotalGroundedBmbx(&double_result,true);          break;
+					case TotalSmbEnum:                       this->TotalSmbx(&double_result,false);                 break;
+					case TotalSmbScaledEnum:                 this->TotalSmbx(&double_result,true);                  break;
 
 			   /*Scalar control output*/
@@ -1624,4 +1876,6 @@
 				case BalancethicknessMisfitEnum:    BalancethicknessMisfitx(&double_result);                                                        break;
 				case SurfaceAbsMisfitEnum:          SurfaceAbsMisfitx(&double_result); break;
+				case OmegaAbsGradientEnum:          OmegaAbsGradientx(&double_result); break;
+				case EtaDiffEnum:                   EtaDiffx(&double_result); break;
 
 				   /*Vector */
@@ -1690,5 +1944,11 @@
 								vector_result->Assemble();
 
-								if(save_results)results->AddResult(new GenericExternalResult<Vector<IssmDouble>*>(results->Size()+1,output_enum,vector_result,step,time));
+								if(save_results){
+									results->AddResult(new GenericExternalResult<Vector<IssmDouble>*>(results->Size()+1,output_enum,vector_result,step,time));
+									/*We do not do a copy for Vectors, so don't delete*/
+								}
+								else{
+									delete vector_result;
+								}
 							}
 							else{
@@ -1827,42 +2087,56 @@
 	switch (response_descriptor_enum){
 
-		case DivergenceEnum:               this->Divergencex(responses); break;
-		case MaxDivergenceEnum:            this->MaxDivergencex(responses); break;
-		case IceMassEnum:                  this->IceMassx(responses); break;
-		case IceVolumeEnum:                this->IceVolumex(responses); break;
-		case IceVolumeAboveFloatationEnum: this->IceVolumeAboveFloatationx(responses); break;
-		case GroundedAreaEnum:             this->GroundedAreax(responses); break;
-		case FloatingAreaEnum:             this->FloatingAreax(responses); break;
-		case MinVelEnum:                   this->MinVelx(responses); break;
-		case MaxVelEnum:                   this->MaxVelx(responses); break;
-		case MinVxEnum:                    this->MinVxx(responses); break;
-		case MaxVxEnum:                    this->MaxVxx(responses); break;
-		case MaxAbsVxEnum:                 this->MaxAbsVxx(responses); break;
-		case MinVyEnum:                    this->MinVyx(responses); break;
-		case MaxVyEnum:                    this->MaxVyx(responses); break;
-		case MaxAbsVyEnum:                 this->MaxAbsVyx(responses); break;
-		case MinVzEnum:                    this->MinVzx(responses); break;
-		case MaxVzEnum:                    this->MaxVzx(responses); break;
-		case MaxAbsVzEnum:                 this->MaxAbsVzx(responses); break;
-		case MassFluxEnum:                 this->MassFluxx(responses); break;
-		case SurfaceAbsVelMisfitEnum:      SurfaceAbsVelMisfitx(responses, elements,nodes, vertices, loads, materials,parameters); break;
-		case SurfaceRelVelMisfitEnum:      SurfaceRelVelMisfitx(responses, elements,nodes, vertices, loads, materials,parameters); break;
-		case SurfaceLogVelMisfitEnum:      SurfaceLogVelMisfitx(responses, elements,nodes, vertices, loads, materials,parameters); break;
-		case SurfaceLogVxVyMisfitEnum:     SurfaceLogVxVyMisfitx(responses, elements,nodes, vertices, loads, materials,parameters); break;
-		case SurfaceAverageVelMisfitEnum:  SurfaceAverageVelMisfitx(responses,this); break;
-		case ThicknessAbsMisfitEnum:       ThicknessAbsMisfitx(responses, elements,nodes, vertices, loads, materials, parameters); break;
-		case ThicknessAbsGradientEnum:     this->ThicknessAbsGradientx(responses); break;
-		case ThicknessAlongGradientEnum:   ThicknessAlongGradientx(responses, elements,nodes, vertices, loads, materials, parameters); break;
-		case ThicknessAcrossGradientEnum:  ThicknessAcrossGradientx(responses, elements,nodes, vertices, loads, materials, parameters); break;
-		case RheologyBbarAbsGradientEnum:  RheologyBbarAbsGradientx(responses, elements,nodes, vertices, loads, materials, parameters); break;
-		case DragCoefficientAbsGradientEnum:DragCoefficientAbsGradientx(responses, elements,nodes, vertices, loads, materials, parameters); break;
-		case BalancethicknessMisfitEnum:   BalancethicknessMisfitx(responses); break;
-		case TotalFloatingBmbEnum:			  this->TotalFloatingBmbx(responses); break;
-		case TotalGroundedBmbEnum:			  this->TotalGroundedBmbx(responses); break;
-		case TotalSmbEnum:					  this->TotalSmbx(responses); break;
-		case MaterialsRheologyBbarEnum:    this->ElementResponsex(responses,MaterialsRheologyBbarEnum); break;
-		case VelEnum:                      this->ElementResponsex(responses,VelEnum); break;
-		case FrictionCoefficientEnum:      NodalValuex(responses, FrictionCoefficientEnum,elements,nodes, vertices, loads, materials, parameters); break;
-		default: _error_("response descriptor \"" << EnumToStringx(response_descriptor_enum) << "\" not supported yet!"); break; 
+		case DivergenceEnum:                     this->Divergencex(responses); break;
+		case MaxDivergenceEnum:                  this->MaxDivergencex(responses); break;
+		case IceMassEnum:                        this->IceMassx(responses, false); break;
+		case IceMassScaledEnum:                  this->IceMassx(responses, true); break;
+		case IceVolumeEnum:                      this->IceVolumex(responses, false); break;
+		case IceVolumeScaledEnum:                this->IceVolumex(responses, true); break;
+		case IceVolumeAboveFloatationEnum:       this->IceVolumeAboveFloatationx(responses, false); break;
+		case IceVolumeAboveFloatationScaledEnum: this->IceVolumeAboveFloatationx(responses, true); break;
+		case GroundedAreaEnum:                   this->GroundedAreax(responses, false); break;
+		case GroundedAreaScaledEnum:             this->GroundedAreax(responses, true); break;
+		case FloatingAreaEnum:                   this->FloatingAreax(responses, false); break;
+		case FloatingAreaScaledEnum:             this->FloatingAreax(responses, true); break;
+		case MinVelEnum:                         this->MinVelx(responses); break;
+		case MaxVelEnum:                         this->MaxVelx(responses); break;
+		case MinVxEnum:                          this->MinVxx(responses); break;
+		case MaxVxEnum:                          this->MaxVxx(responses); break;
+		case MaxAbsVxEnum:                       this->MaxAbsVxx(responses); break;
+		case MinVyEnum:                          this->MinVyx(responses); break;
+		case MaxVyEnum:                          this->MaxVyx(responses); break;
+		case MaxAbsVyEnum:                       this->MaxAbsVyx(responses); break;
+		case MinVzEnum:                          this->MinVzx(responses); break;
+		case MaxVzEnum:                          this->MaxVzx(responses); break;
+		case MaxAbsVzEnum:                       this->MaxAbsVzx(responses); break;
+		case MassFluxEnum:                       this->MassFluxx(responses); break;
+		case SurfaceAbsVelMisfitEnum:            SurfaceAbsVelMisfitx(responses, elements,nodes, vertices, loads, materials,parameters); break;
+		case SurfaceRelVelMisfitEnum:            SurfaceRelVelMisfitx(responses, elements,nodes, vertices, loads, materials,parameters); break;
+		case SurfaceLogVelMisfitEnum:            SurfaceLogVelMisfitx(responses, elements,nodes, vertices, loads, materials,parameters); break;
+		case SurfaceLogVxVyMisfitEnum:           SurfaceLogVxVyMisfitx(responses, elements,nodes, vertices, loads, materials,parameters); break;
+		case SurfaceAverageVelMisfitEnum:        SurfaceAverageVelMisfitx(responses,this); break;
+		case ThicknessAbsMisfitEnum:             ThicknessAbsMisfitx(responses, elements,nodes, vertices, loads, materials, parameters); break;
+		case ThicknessAbsGradientEnum:           this->ThicknessAbsGradientx(responses); break;
+		case ThicknessAlongGradientEnum:         ThicknessAlongGradientx(responses, elements,nodes, vertices, loads, materials, parameters); break;
+		case ThicknessAcrossGradientEnum:        ThicknessAcrossGradientx(responses, elements,nodes, vertices, loads, materials, parameters); break;
+		case RheologyBbarAbsGradientEnum:        RheologyBbarAbsGradientx(responses, elements,nodes, vertices, loads, materials, parameters); break;
+		case DragCoefficientAbsGradientEnum:     DragCoefficientAbsGradientx(responses, elements,nodes, vertices, loads, materials, parameters); break;
+		case BalancethicknessMisfitEnum:         BalancethicknessMisfitx(responses); break;
+		case TotalFloatingBmbEnum:			        this->TotalFloatingBmbx(responses, false); break;
+		case TotalFloatingBmbScaledEnum:			  this->TotalFloatingBmbx(responses, true); break;
+		case TotalGroundedBmbEnum:			        this->TotalGroundedBmbx(responses, false); break;
+		case TotalGroundedBmbScaledEnum:			  this->TotalGroundedBmbx(responses, true); break;
+		case TotalSmbEnum:					        this->TotalSmbx(responses, false); break;
+		case TotalSmbScaledEnum:					  this->TotalSmbx(responses, true); break;
+		case MaterialsRheologyBbarEnum:          this->ElementResponsex(responses,MaterialsRheologyBbarEnum); break;
+		case VelEnum:                            this->ElementResponsex(responses,VelEnum); break;
+		case FrictionCoefficientEnum:            NodalValuex(responses, FrictionCoefficientEnum,elements,nodes, vertices, loads, materials, parameters); break;
+		default: 
+			if(response_descriptor_enum>=Outputdefinition1Enum && response_descriptor_enum <=Outputdefinition100Enum){
+				IssmDouble double_result = OutputDefinitionsResponsex(this,response_descriptor_enum);
+				*responses=double_result;
+			}
+			else _error_("response descriptor \"" << EnumToStringx(response_descriptor_enum) << "\" not supported yet!"); 
+			break; 
 	}
 
@@ -1882,4 +2156,12 @@
 		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
 		element->StrainRateperpendicular();
+	}
+}
+/*}}}*/
+void FemModel::StrainRateeffectivex(){/*{{{*/
+
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element->ComputeStrainRate();
 	}
 }
@@ -1955,5 +2237,5 @@
 	IssmDouble J_sum;
 
-	IssmDouble  thickness,thicknessobs,weight;
+	IssmDouble  thickness,weight;
 	IssmDouble  Jdet;
 	IssmDouble* xyz_list = NULL;
@@ -2065,18 +2347,15 @@
 void FemModel::TimeAdaptx(IssmDouble* pdt){/*{{{*/
 
-	int      i;
-
 	/*output: */
 	IssmDouble   dt;
 
 	/*intermediary: */
-	Element *element     = NULL;
 	IssmDouble   min_dt      = 0;
 	IssmDouble   node_min_dt = 0;
 
 	/*Go through elements, and figure out the minimum of the time steps for each element (using CFL criterion): */
-	element=(Element*)elements->GetObjectByOffset(0); min_dt=element->TimeAdapt();
-
-	for (i=1;i<elements->Size();i++){
+	Element* element=(Element*)elements->GetObjectByOffset(0); min_dt=element->TimeAdapt();
+
+	for(int i=1;i<elements->Size();i++){
 		element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 		dt=element->TimeAdapt();
@@ -2089,9 +2368,16 @@
 	min_dt=node_min_dt;
 
+	/*Constrain dt */
+	IssmDouble dt_low,dt_high;
+	parameters->FindParam(&dt_low,TimesteppingTimeStepMinEnum);
+	parameters->FindParam(&dt_high,TimesteppingTimeStepMaxEnum);
+	if(min_dt<dt_low)  min_dt = dt_low;
+	if(min_dt>dt_high) min_dt = dt_high;
+
 	/*Assign output pointers:*/
 	*pdt=min_dt;
 }
 /*}}}*/
-void FemModel::TotalFloatingBmbx(IssmDouble* pFbmb){/*{{{*/
+void FemModel::TotalFloatingBmbx(IssmDouble* pFbmb, bool scaled){/*{{{*/
 
 	IssmDouble local_fbmb = 0;
@@ -2100,5 +2386,5 @@
 	for(int i=0;i<this->elements->Size();i++){
 		Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
-		local_fbmb+=element->TotalFloatingBmb();
+		local_fbmb+=element->TotalFloatingBmb(scaled);
 	}
 	ISSM_MPI_Reduce(&local_fbmb,&total_fbmb,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
@@ -2109,5 +2395,5 @@
 
 }/*}}}*/
-void FemModel::TotalGroundedBmbx(IssmDouble* pGbmb){/*{{{*/
+void FemModel::TotalGroundedBmbx(IssmDouble* pGbmb, bool scaled){/*{{{*/
 
 	IssmDouble local_gbmb = 0;
@@ -2116,5 +2402,5 @@
 	for(int i=0;i<this->elements->Size();i++){
 		Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
-		local_gbmb+=element->TotalGroundedBmb();
+		local_gbmb+=element->TotalGroundedBmb(scaled);
 	}
 	ISSM_MPI_Reduce(&local_gbmb,&total_gbmb,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
@@ -2125,5 +2411,5 @@
 
 }/*}}}*/
-void FemModel::TotalSmbx(IssmDouble* pSmb){/*{{{*/
+void FemModel::TotalSmbx(IssmDouble* pSmb, bool scaled){/*{{{*/
 
 	IssmDouble local_smb = 0;
@@ -2132,5 +2418,5 @@
 	for(int i=0;i<this->elements->Size();i++){
 		Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
-		local_smb+=element->TotalSmb();
+		local_smb+=element->TotalSmb(scaled);
 	}
 	ISSM_MPI_Reduce(&local_smb,&total_smb,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
@@ -2224,803 +2510,10 @@
 }
 /*}}}*/
-#ifdef  _HAVE_DAKOTA_
-void FemModel::DakotaResponsesx(double* d_responses,char** responses_descriptors,int numresponsedescriptors,int d_numresponses){/*{{{*/
-
-	int        i,j;
-	int        my_rank;
-
-	/*intermediary: */
-	char   root[50];
-	int    index;
-	int    npart;
-	double femmodel_response;
-	int    flag;
-	double *vertex_response   = NULL;
-	double *qmu_response      = NULL;
-	double *responses_pointer = NULL;
-
-	/*retrieve npart: */
-	parameters->FindParam(&npart,QmuNumberofpartitionsEnum);
-	my_rank=IssmComm::GetRank();
-
-	/*save the d_responses pointer: */
-	responses_pointer=d_responses;
-
-	//watch out, we have more d_numresponses than numresponsedescriptors, because the responses have been expanded if they were scaled. 
-	//because we don't know the d_responses descriptors (the scaled ones) we can't key off them, so we will key off the responses_descriptors: */
-
-	for(i=0;i<numresponsedescriptors;i++){
-
-		flag=DescriptorIndex(root,&index,responses_descriptors[i]);
-
-		if(flag==ScaledEnum){
-
-			/*this response was scaled. pick up the response from the inputs: */
-			GetVectorFromInputsx(&vertex_response,this, StringToEnumx(root),VertexPIdEnum);
-
-			/*Now, average it onto the partition nodes: */
-			AverageOntoPartitionx(&qmu_response,elements,nodes,vertices,loads,materials,parameters,vertex_response);
-
-			/*Copy onto our dakota responses: */
-			if(my_rank==0){
-				/*plug response: */
-				for(j=0;j<npart;j++)responses_pointer[j]=qmu_response[j];
-
-				/*increment response_pointer :*/
-				responses_pointer+=npart;
-			}
-
-			/*Free ressources:*/
-			xDelete<double>(vertex_response);
-			xDelete<double>(qmu_response);
-
-		}
-		else if (flag==IndexedEnum){
-
-			/*indexed response: plug index into parameters and call response module: */
-			parameters->SetParam(index,IndexEnum);
-
-			this->Responsex(&femmodel_response,root);
-
-			if(my_rank==0){
-				/*plug response: */
-				responses_pointer[0]=femmodel_response;
-
-				/*increment response_pointer :*/
-				responses_pointer++;
-			}
-		}
-		else if (flag==NodalEnum){
-			_error_("nodal response functions not supported yet!");
-
-			/*increment response_pointer :*/
-			responses_pointer++;
-		}
-		else if (flag==RegularEnum){
-
-			/*perfectly normal response function: */
-			this->Responsex(&femmodel_response,root);
-
-			if(my_rank==0){
-				/*plug response: */
-				responses_pointer[0]=femmodel_response;
-
-				/*increment response_pointer :*/
-				responses_pointer++;
-			}
-		}
-		else _error_("flag type " << flag << " not supported yet for response analysis");
-	}
-
-	/*Synthesize echo: {{{*/
-	if(my_rank==0){
-		_printf_("   responses: " << d_numresponses << ": ");
-		for(i=0;i<d_numresponses-1;i++)_printf_(d_responses[i] << "|");
-		_printf_(d_responses[d_numresponses-1]);
-		_printf_("\n");
-	}
-	/*}}}*/
-
-}
-/*}}}*/
-#endif
-#ifdef _HAVE_GIAIVINS_
-void FemModel::Deflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt, IssmDouble* x, IssmDouble* y){ /*{{{*/
-
-	/*Go through elements, and add contribution from each element to the deflection vector wg:*/
-	for(int i=0;i<elements->Size();i++){
-		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
-		element->GiaDeflection(wg,dwgdt, x,y);
-	}
-}
-/*}}}*/
-#endif
-#ifdef _HAVE_ESA_
-void FemModel::EsaGeodetic2D(Vector<IssmDouble>* pUp, Vector<IssmDouble>* pNorth, Vector<IssmDouble>* pEast, IssmDouble* xx, IssmDouble* yy){/*{{{*/
-
-	int         ns,nsmax;
-	
-	/*Go through elements, and add contribution from each element to the deflection vector wg:*/
-	ns = elements->Size();
-	
-	/*Figure out max of ns: */
-	ISSM_MPI_Reduce(&ns,&nsmax,1,ISSM_MPI_INT,ISSM_MPI_MAX,0,IssmComm::GetComm());
-	ISSM_MPI_Bcast(&nsmax,1,ISSM_MPI_INT,0,IssmComm::GetComm());
-
-	/*Call the esa geodetic core: */
-	for(int i=0;i<nsmax;i++){
-		if(i<ns){
-			Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
-			element->EsaGeodetic2D(pUp,pNorth,pEast,xx,yy);
-		}
-		if(i%100==0){
-			pUp->Assemble();
-			pNorth->Assemble();
-			pEast->Assemble();
-		}
-	}
-	
-	/*One last time: */
-	pUp->Assemble();
-	pNorth->Assemble();
-	pEast->Assemble();
-
-	/*Free ressources:*/
-	xDelete<IssmDouble>(xx);
-	xDelete<IssmDouble>(yy);
-}
-/*}}}*/
-void FemModel::EsaGeodetic3D(Vector<IssmDouble>* pUp, Vector<IssmDouble>* pNorth, Vector<IssmDouble>* pEast, IssmDouble* latitude, IssmDouble* longitude, IssmDouble* radius, IssmDouble* xx, IssmDouble* yy, IssmDouble* zz){/*{{{*/
-
-	IssmDouble  eartharea=0;
-	IssmDouble  eartharea_cpu=0;
-
-	int         ns,nsmax;
-	
-	/*Go through elements, and add contribution from each element to the deflection vector wg:*/
-	ns = elements->Size();
-	
-	/*First, figure out the surface area of Earth: */ 
-	for(int i=0;i<ns;i++){
-		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
-		eartharea_cpu += element->GetAreaSpherical();
-	}
-	ISSM_MPI_Reduce (&eartharea_cpu,&eartharea,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
-	ISSM_MPI_Bcast(&eartharea,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
-
-	/*Figure out max of ns: */
-	ISSM_MPI_Reduce(&ns,&nsmax,1,ISSM_MPI_INT,ISSM_MPI_MAX,0,IssmComm::GetComm());
-	ISSM_MPI_Bcast(&nsmax,1,ISSM_MPI_INT,0,IssmComm::GetComm());
-
-	/*Call the esa geodetic core: */
-	for(int i=0;i<nsmax;i++){
-		if(i<ns){
-			Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
-			element->EsaGeodetic3D(pUp,pNorth,pEast,latitude,longitude,radius,xx,yy,zz,eartharea);
-		}
-		if(i%100==0){
-			pUp->Assemble();
-			pNorth->Assemble();
-			pEast->Assemble();
-		}
-	}
-	
-	/*One last time: */
-	pUp->Assemble();
-	pNorth->Assemble();
-	pEast->Assemble();
-
-	/*Free ressources:*/
-	xDelete<IssmDouble>(latitude);
-	xDelete<IssmDouble>(longitude);
-	xDelete<IssmDouble>(radius);
-	xDelete<IssmDouble>(xx);
-	xDelete<IssmDouble>(yy);
-	xDelete<IssmDouble>(zz);
-}
-/*}}}*/
-#endif
-#ifdef _HAVE_SEALEVELRISE_
-void FemModel::SealevelriseEustatic(Vector<IssmDouble>* pSgi, IssmDouble* peustatic, IssmDouble* latitude, IssmDouble* longitude, IssmDouble* radius) { /*{{{*/
-
-	/*serialized vectors:*/
-	IssmDouble  eustatic       = 0.;
-	IssmDouble  eustatic_cpu   = 0.;
-	IssmDouble  eustatic_cpu_e = 0.;
-	IssmDouble  oceanarea      = 0.;
-	IssmDouble  oceanarea_cpu  = 0.;
-	IssmDouble  eartharea      = 0.;
-	IssmDouble  eartharea_cpu  = 0.;
-	int         ns,nsmax;
-	
-	/*Go through elements, and add contribution from each element to the deflection vector wg:*/
-	ns = elements->Size();
-
-	/*First, figure out the area of the ocean, which is needed to compute the eustatic component: */
-	for(int i=0;i<ns;i++){
-		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
-		oceanarea_cpu += element->OceanArea();
-		eartharea_cpu += element->GetAreaSpherical();
-	}
-	ISSM_MPI_Reduce (&oceanarea_cpu,&oceanarea,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
-	ISSM_MPI_Bcast(&oceanarea,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
-	_assert_(oceanarea>0.);
-
-	ISSM_MPI_Reduce (&eartharea_cpu,&eartharea,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
-	ISSM_MPI_Bcast(&eartharea,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
-
-	/*Figure out max of ns: */
-	ISSM_MPI_Reduce(&ns,&nsmax,1,ISSM_MPI_INT,ISSM_MPI_MAX,0,IssmComm::GetComm());
-	ISSM_MPI_Bcast(&nsmax,1,ISSM_MPI_INT,0,IssmComm::GetComm());
-
-	/*Call the sea level rise core: */
-	for(int i=0;i<nsmax;i++){
-		if(i<ns){
-		
-			if(VerboseConvergence())if(i%100==0)_printf0_("\r" << "      convolution progress: " << (double)i/(double)ns*100 << "%  ");
-		
-			Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
-			element->SealevelriseEustatic(pSgi,&eustatic_cpu_e,latitude,longitude,radius,oceanarea,eartharea);
-			eustatic_cpu+=eustatic_cpu_e;
-		}
-		if(i%100==0)pSgi->Assemble();
-	}
-	if(VerboseConvergence())_printf0_("\n");
-		
-	/*One last time: */
-	pSgi->Assemble();
-
-	/*Sum all eustatic components from all cpus:*/
-	ISSM_MPI_Reduce (&eustatic_cpu,&eustatic,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
-	ISSM_MPI_Bcast(&eustatic,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
-	_assert_(!xIsNan<IssmDouble>(eustatic));
-
-	/*Assign output pointers:*/
-	*peustatic=eustatic;
-
-}
-/*}}}*/
-void FemModel::SealevelriseNonEustatic(Vector<IssmDouble>* pSgo, Vector<IssmDouble>* pSg_old, IssmDouble* latitude, IssmDouble* longitude, IssmDouble* radius, bool verboseconvolution){/*{{{*/
-
-	/*serialized vectors:*/
-	IssmDouble* Sg_old=NULL;
-	
-	IssmDouble  eartharea=0;
-	IssmDouble  eartharea_cpu=0;
-
-	int         ns,nsmax;
-	
-	/*Serialize vectors from previous iteration:*/
-	Sg_old=pSg_old->ToMPISerial();
-
-	/*Go through elements, and add contribution from each element to the deflection vector wg:*/
-	ns = elements->Size();
-
-	/*First, figure out the area of the ocean, which is needed to compute the eustatic component: */
-	for(int i=0;i<ns;i++){
-		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
-		eartharea_cpu += element->GetAreaSpherical();
-	}
-	
-	ISSM_MPI_Reduce (&eartharea_cpu,&eartharea,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
-	ISSM_MPI_Bcast(&eartharea,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
-
-	/*Figure out max of ns: */
-	ISSM_MPI_Reduce(&ns,&nsmax,1,ISSM_MPI_INT,ISSM_MPI_MAX,0,IssmComm::GetComm());
-	ISSM_MPI_Bcast(&nsmax,1,ISSM_MPI_INT,0,IssmComm::GetComm());
-
-	/*Call the sea level rise core: */
-	for(int i=0;i<nsmax;i++){
-		if(i<ns){
-			if(verboseconvolution)if(VerboseConvergence())if(i%100==0)_printf_("\r" << "      convolution progress: " << (double)i/(double)ns*100 << "%   ");
-			Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
-			element->SealevelriseNonEustatic(pSgo,Sg_old,latitude,longitude,radius,eartharea);
-		}
-		if(i%100==0)pSgo->Assemble();
-	}
-	if(verboseconvolution)if(VerboseConvergence())_printf_("\n");
-	
-	/*Free ressources:*/
-	xDelete<IssmDouble>(Sg_old);
-}
-/*}}}*/
-void FemModel::SealevelriseRotationalFeedback(Vector<IssmDouble>* pSgo_rot, Vector<IssmDouble>* pSg_old, IssmDouble* latitude, IssmDouble* longitude, IssmDouble* radius){/*{{{*/
-
-	/*serialized vectors:*/
-	IssmDouble* Sg_old=NULL;
-	IssmDouble  eartharea=0;
-	IssmDouble  eartharea_cpu=0;
-	IssmDouble	tide_love_h, tide_love_k, fluid_love, moi_e, moi_p, omega, g;
-	IssmDouble	load_love_k2 = -0.30922675; //degree 2 load Love number 
-	IssmDouble	m1, m2, m3; 
-	IssmDouble	lati, longi, radi, value; 
-
-	/*Serialize vectors from previous iteration:*/
-	Sg_old=pSg_old->ToMPISerial();
-
-	/*First, figure out the area of the ocean, which is needed to compute the eustatic component: */
-	for(int i=0;i<elements->Size();i++){
-		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
-		eartharea_cpu += element->GetAreaSpherical();
-	}
-	ISSM_MPI_Reduce (&eartharea_cpu,&eartharea,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
-	ISSM_MPI_Bcast(&eartharea,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
-
-	IssmDouble moi_list[3]={0,0,0}; 
-	IssmDouble moi_list_cpu[3]={0,0,0}; 
-	for(int i=0;i<elements->Size();i++){
-		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
-		element->SealevelriseMomentOfInertia(&moi_list[0],Sg_old,eartharea);
-		moi_list_cpu[0] += moi_list[0]; 
-		moi_list_cpu[1] += moi_list[1]; 
-		moi_list_cpu[2] += moi_list[2]; 
-	}
-	ISSM_MPI_Reduce (&moi_list_cpu[0],&moi_list[0],1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
-	ISSM_MPI_Bcast(&moi_list[0],1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
-	// 	
-	ISSM_MPI_Reduce (&moi_list_cpu[1],&moi_list[1],1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
-	ISSM_MPI_Bcast(&moi_list[1],1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
-	// 	
-	ISSM_MPI_Reduce (&moi_list_cpu[2],&moi_list[2],1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
-	ISSM_MPI_Bcast(&moi_list[2],1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
-	
-	/*pull out some useful parameters: */
-	parameters->FindParam(&tide_love_h,SealevelriseTidalLoveHEnum);
-	parameters->FindParam(&tide_love_k,SealevelriseTidalLoveKEnum);
-	parameters->FindParam(&fluid_love,SealevelriseFluidLoveEnum);
-	parameters->FindParam(&moi_e,SealevelriseEquatorialMoiEnum);
-	parameters->FindParam(&moi_p,SealevelrisePolarMoiEnum);
-	parameters->FindParam(&omega,SealevelriseAngularVelocityEnum);
-
-	/*compute perturbation terms for angular velocity vector: */
-	m1 = 1/(1-tide_love_k/fluid_love) * (1+load_love_k2)/(moi_p-moi_e) * moi_list[0]; 
-	m2 = 1/(1-tide_love_k/fluid_love) * (1+load_love_k2)/(moi_p-moi_e) * moi_list[1]; 
-	m3 = -(1+load_love_k2)/moi_p * moi_list[2];	// term associated with fluid number (3-order-of-magnitude smaller) is negelected  
-
-	/* Green's function (1+k_2-h_2/g): checked against Glenn Milne's thesis Chapter 3 (eqs: 3.3-4, 3.10-11)
-	 * Perturbation terms for angular velocity vector (m1, m2, m3): checked against Mitrovica (2005 Appendix) & Jensen et al (2013 Appendix A3) 
-	 * Sea level rotational feedback: checked against GMD eqs 8-9 (only first order terms, i.e., degree 2 order 0 & 1 considered) 
-	 * all DONE in Geographic coordinates: theta \in [-90,90], lambda \in [-180 180] 
-	 */
-	for(int i=0;i<vertices->Size();i++){
-		int sid;
-		//Vertex* vertex=(Vertex*)vertices->GetObjectByOffset(i);
-		Vertex* vertex=xDynamicCast<Vertex*>(vertices->GetObjectByOffset(i));
-		sid=vertex->Sid();
-
-		lati=latitude[sid]/180*PI;	longi=longitude[sid]/180*PI; radi=radius[sid];
-
-		/*only first order terms are considered now: */ 
-		value=((1.0+tide_love_k-tide_love_h)/9.81)*pow(omega*radi,2.0)*
-						(-m3/6.0 + 0.5*m3*cos(2.0*lati) - 0.5*sin(2.*lati)*(m1*cos(longi)+m2*sin(longi))); 
-	
-		pSgo_rot->SetValue(sid,value,INS_VAL); //INS_VAL ensures that you don't add several times
-	}
-
-	/*Assemble mesh velocity*/
-	pSgo_rot->Assemble();
-	
-	/*Free ressources:*/
-	xDelete<IssmDouble>(Sg_old);
-	
-}
-/*}}}*/
-void FemModel::SealevelriseGeodetic(Vector<IssmDouble>* pUp, Vector<IssmDouble>* pNorth, Vector<IssmDouble>* pEast, Vector<IssmDouble>* pSg, IssmDouble* latitude, IssmDouble* longitude, IssmDouble* radius, IssmDouble* xx, IssmDouble* yy, IssmDouble* zz){/*{{{*/
-
-	/*serialized vectors:*/
-	IssmDouble* Sg=NULL;
-	
-	IssmDouble  eartharea=0;
-	IssmDouble  eartharea_cpu=0;
-
-	int         ns,nsmax;
-	
-	/*Serialize vectors from previous iteration:*/
-	Sg=pSg->ToMPISerial();
-
-	/*Go through elements, and add contribution from each element to the deflection vector wg:*/
-	ns = elements->Size();
-	
-	/*First, figure out the area of the ocean, which is needed to compute the eustatic component: */
-	for(int i=0;i<ns;i++){
-		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
-		eartharea_cpu += element->GetAreaSpherical();
-	}
-	ISSM_MPI_Reduce (&eartharea_cpu,&eartharea,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
-	ISSM_MPI_Bcast(&eartharea,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
-
-	/*Figure out max of ns: */
-	ISSM_MPI_Reduce(&ns,&nsmax,1,ISSM_MPI_INT,ISSM_MPI_MAX,0,IssmComm::GetComm());
-	ISSM_MPI_Bcast(&nsmax,1,ISSM_MPI_INT,0,IssmComm::GetComm());
-
-	/*Call the sea level rise core: */
-	for(int i=0;i<nsmax;i++){
-		if(i<ns){
-			Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
-			element->SealevelriseGeodetic(pUp,pNorth,pEast,Sg,latitude,longitude,radius,xx,yy,zz,eartharea);
-		}
-		if(i%100==0){
-			pUp->Assemble();
-			pNorth->Assemble();
-			pEast->Assemble();
-		}
-	}
-	
-	/*One last time: */
-	pUp->Assemble();
-	pNorth->Assemble();
-	pEast->Assemble();
-
-	/*Free ressources:*/
-	xDelete<IssmDouble>(Sg);
-	xDelete<IssmDouble>(latitude);
-	xDelete<IssmDouble>(longitude);
-	xDelete<IssmDouble>(radius);
-	xDelete<IssmDouble>(xx);
-	xDelete<IssmDouble>(yy);
-	xDelete<IssmDouble>(zz);
-}
-/*}}}*/
-IssmDouble FemModel::SealevelriseOceanAverage(Vector<IssmDouble>* Sg) { /*{{{*/
-
-	IssmDouble* Sg_serial=NULL;
-	IssmDouble  oceanvalue,oceanvalue_cpu;
-	IssmDouble  oceanarea,oceanarea_cpu;
-
-	/*Serialize vectors from previous iteration:*/
-	Sg_serial=Sg->ToMPISerial();
-
-	/*Initialize:*/
-	oceanvalue_cpu=0;
-	oceanarea_cpu=0;
-
-	/*Go through elements, and add contribution from each element and divide by overall ocean area:*/
-	for(int i=0;i<elements->Size();i++){
-		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
-		oceanarea_cpu += element->OceanArea();
-		oceanvalue_cpu += element->OceanAverage(Sg_serial);
-	}
-	ISSM_MPI_Reduce (&oceanarea_cpu,&oceanarea,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
-	ISSM_MPI_Bcast(&oceanarea,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
-	
-	ISSM_MPI_Reduce (&oceanvalue_cpu,&oceanvalue,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
-	ISSM_MPI_Bcast(&oceanvalue,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
-
-	/*Free ressources:*/
-	xDelete<IssmDouble>(Sg_serial);
-	
-	return oceanvalue/oceanarea;
-}
-/*}}}*/
-#endif
-void FemModel::HydrologyEPLupdateDomainx(IssmDouble* pEplcount){ /*{{{*/
-
-	Vector<IssmDouble>* mask							= NULL;
-	Vector<IssmDouble>* recurence  				= NULL;
-	Vector<IssmDouble>* active						= NULL;
-	IssmDouble*         serial_mask				= NULL;
-	IssmDouble*         serial_rec  			= NULL;
-	IssmDouble*         serial_active			= NULL;
-	IssmDouble*         old_active        = NULL;
-	int*                eplzigzag_counter =	NULL;
-	int                 eplflip_lock;
-	
-	HydrologyDCEfficientAnalysis* effanalysis =  new HydrologyDCEfficientAnalysis();
-	HydrologyDCInefficientAnalysis* inefanalysis =  new HydrologyDCInefficientAnalysis();
-
-	/*Step 1: update mask, the mask might be extended by residual and/or using downstream sediment head*/
-	mask=new Vector<IssmDouble>(this->nodes->NumberOfNodes(HydrologyDCEfficientAnalysisEnum));
-	recurence=new Vector<IssmDouble>(this->nodes->NumberOfNodes(HydrologyDCEfficientAnalysisEnum));
-	this->parameters->FindParam(&eplzigzag_counter,NULL,EplZigZagCounterEnum); 
-	this->parameters->FindParam(&eplflip_lock,HydrologydcEplflipLockEnum); 
-	GetVectorFromInputsx(&old_active,this,HydrologydcMaskEplactiveNodeEnum,NodeSIdEnum);
-	
-	for (int i=0;i<elements->Size();i++){
-		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
-		effanalysis->HydrologyEPLGetMask(mask,recurence,eplzigzag_counter,element);
-	}
-	/*check for changes and increment zigzag counter, change the mask if necessary*/
-	recurence->Assemble();
-	serial_rec=recurence->ToMPISerial();
-	for (int i=0;i<nodes->Size();i++){
-		Node* node=xDynamicCast<Node*>(nodes->GetObjectByOffset(i));
-		if(serial_rec[node->Sid()]==1.)eplzigzag_counter[node->Lid()] ++;
-		if(eplzigzag_counter[node->Lid()]>eplflip_lock & eplflip_lock!=0){
-			mask->SetValue(node->Sid(),old_active[node->Sid()],INS_VAL);
-		}
-	}
-	this->parameters->SetParam(eplzigzag_counter,this->nodes->Size(),EplZigZagCounterEnum);
-	/*Assemble and serialize*/
-	mask->Assemble();
-	serial_mask=mask->ToMPISerial();	
-	
-	xDelete<int>(eplzigzag_counter);
-	xDelete<IssmDouble>(serial_rec);
-	xDelete<IssmDouble>(old_active);
-	delete mask;
-	delete recurence;
-
-	/*Update Mask*/
-	InputUpdateFromVectorx(this,serial_mask,HydrologydcMaskEplactiveNodeEnum,NodeSIdEnum);
-	xDelete<IssmDouble>(serial_mask);
-	inefanalysis->ElementizeEplMask(this);
-	/*Step 2: update node activity. If one element is connected to mask=1, all nodes are active*/
-	active=new Vector<IssmDouble>(nodes->NumberOfNodes(HydrologyDCEfficientAnalysisEnum));
-	for (int i=0;i<elements->Size();i++){
-		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
-		effanalysis->HydrologyEPLGetActive(active,element);
-	}
-
-	/*Assemble and serialize*/
-	active->Assemble();
-	serial_active=active->ToMPISerial();
-	delete active;
-
-	/*Update node activation accordingly*/
-	int counter =0;
-	for (int i=0;i<nodes->Size();i++){
-		Node* node=xDynamicCast<Node*>(nodes->GetObjectByOffset(i));
-		if(node->InAnalysis(HydrologyDCEfficientAnalysisEnum)){
-			if(serial_active[node->Sid()]==1.){
-				node->Activate();
-				if(!node->IsClone()) counter++;
-			}
-			else{
-				node->Deactivate();
-			}
-		}
-	}
-	xDelete<IssmDouble>(serial_active);
-	delete effanalysis;
-	delete inefanalysis;
-	int sum_counter;
-	ISSM_MPI_Reduce(&counter,&sum_counter,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
-	ISSM_MPI_Bcast(&sum_counter,1,ISSM_MPI_INT,0,IssmComm::GetComm());                
-	counter=sum_counter;
-	*pEplcount = counter;
-	if(VerboseSolution()) _printf0_("   Number of active nodes in EPL layer: "<< counter <<"\n");
-
-	/*Update dof indexings*/
-	this->UpdateConstraintsx();
-
-}
-/*}}}*/
-void FemModel::UpdateConstraintsL2ProjectionEPLx(IssmDouble* pL2count){ /*{{{*/
-
-	Vector<IssmDouble>* active        = NULL;
-	IssmDouble*         serial_active = NULL;
-	HydrologyDCEfficientAnalysis* effanalysis = new HydrologyDCEfficientAnalysis();
-
-	/*update node activity. If one element is connected to mask=1, all nodes are active*/
-	active=new Vector<IssmDouble>(nodes->NumberOfNodes(HydrologyDCEfficientAnalysisEnum));
-	for (int i=0;i<elements->Size();i++){
-		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
-		effanalysis->HydrologyEPLGetActive(active,element);
-	}
-
-	/*Assemble and serialize*/
-	active->Assemble();
-	serial_active=active->ToMPISerial();
-	delete active;
-	delete effanalysis;
-
-	/*Update node activation accordingly*/
-	int counter =0;
-	for (int i=0;i<nodes->Size();i++){
-		Node* node=xDynamicCast<Node*>(nodes->GetObjectByOffset(i));
-		if(node->InAnalysis(L2ProjectionEPLAnalysisEnum)){
-			if(serial_active[node->Sid()]==1.){
-				node->Activate();
-				if(!node->IsClone()) counter++;
-			}
-			else{
-				node->Deactivate();
-			}
-		}
-	}
-	xDelete<IssmDouble>(serial_active);
-	int sum_counter;
-	ISSM_MPI_Reduce(&counter,&sum_counter,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
-	ISSM_MPI_Bcast(&sum_counter,1,ISSM_MPI_INT,0,IssmComm::GetComm());                
-	counter=sum_counter;
-	*pL2count = counter;
-	if(VerboseSolution()) _printf0_("   Number of active nodes L2 Projection: "<< counter <<"\n");
-}
-/*}}}*/
-#ifdef _HAVE_JAVASCRIPT_ 
-FemModel::FemModel(IssmDouble* buffer, int buffersize, char* toolkits, char* solution, char* modelname,ISSM_MPI_Comm incomm, bool trace){ /*{{{*/
-	/*configuration: */
-	int  solution_type;
-	int  ierr;
-
-	/*First things first, store the communicator, and set it as a global variable: */
-	IssmComm::SetComm(incomm);
-
-	/*Start profiler: */
-	this->profiler=new Profiler();
-	profiler->Tag(START);
-
-	/*From command line arguments, retrieve different filenames needed to create the FemModel: */
-	solution_type=StringToEnumx(solution);
-	
-	/*Create femmodel from input files: */
-	profiler->Tag(STARTINIT);
-	this->InitFromBuffers((char*)buffer,buffersize,toolkits, solution_type,trace,NULL);
-	profiler->Tag(FINISHINIT);
-	
-	/*Save communicator in the parameters dataset: */
-	this->parameters->AddObject(new GenericParam<ISSM_MPI_Comm>(incomm,FemModelCommEnum));
-
-}
-/*}}}*/
-void FemModel::CleanUpJs(char** poutput, size_t* psize){/*{{{*/
-
-	/*Intermediary*/
-	FILE *output_fid;
-	GenericParam<char**>* outputbufferparam=NULL;
-	GenericParam<size_t*>* outputbuffersizeparam=NULL;
-	char** poutputbuffer;
-	size_t* poutputbuffersize;
-
-	
-	/*Before we delete the profiler, report statistics for this run: */
-	profiler->Tag(FINISH);  //final tagging
-	_printf0_("\n");
-	_printf0_("   "<<setw(40)<<left<<"FemModel initialization elapsed time:"<<profiler->DeltaTime(STARTINIT,FINISHINIT) << "\n");
-	_printf0_("   "<<setw(40)<<left<<"Core solution elapsed time:"<<profiler->DeltaTime(STARTCORE,FINISHCORE) << "\n");
-	_printf0_("\n");
-	_printf0_("   Total elapsed time: "
-				<<profiler->DeltaTimeModHour(START,FINISH)<<" hrs "
-				<<profiler->DeltaTimeModMin(START,FINISH)<<" min "
-				<<profiler->DeltaTimeModSec(START,FINISH)<<" sec"
-				);
-	_printf0_("\n");
-	
-	/*Before we close the output file, recover the buffer and size:*/
-	outputbufferparam = xDynamicCast<GenericParam<char**>*>(this->parameters->FindParamObject(OutputBufferPointerEnum));
-	poutputbuffer=outputbufferparam->GetParameterValue();
-	outputbuffersizeparam = xDynamicCast<GenericParam<size_t*>*>(this->parameters->FindParamObject(OutputBufferSizePointerEnum));
-	poutputbuffersize=outputbuffersizeparam->GetParameterValue();
-
-	/*Assign output values: */
-	*poutput=*poutputbuffer;
-	*psize=*poutputbuffersize;
-}
-/*}}}*/
-void FemModel::InitFromBuffers(char* buffer, int buffersize, char* toolkits, int in_solution_type, bool trace, IssmPDouble* X){/*{{{*/
-
-	/*intermediary*/
-	FILE       *IOMODEL = NULL;
-	FILE       *toolkitsoptionsfid = NULL;
-	FILE       *output_fid = NULL;
-	int         my_rank;
-	size_t      outputsize;
-	char       *outputbuffer;
-	const char *rootpath = "";   //needed for Dakota runs only, which we won't do here.
-
-	/*recover my_rank:*/
-	my_rank=IssmComm::GetRank();
-
-	/*Open input file descriptor on cpu 0: */
-	if(my_rank==0) IOMODEL = fmemopen((void*)buffer, buffersize, "rb");
-
-	/*Open toolkits file descriptor: */
-	toolkitsoptionsfid=fmemopen((void*)toolkits, strlen(toolkits)+1, "r");
-
-	/*Now, go create FemModel:*/
-	this->InitFromFids((char*)rootpath,IOMODEL,toolkitsoptionsfid,in_solution_type,trace,X);
-
-	/*Close input file and toolkits file descriptors: */
-	if(my_rank==0) fclose(IOMODEL);
-	fclose(toolkitsoptionsfid);
-
-	/*Open output file once for all and add output file descriptor to parameters*/
-	output_fid=open_memstream(&outputbuffer,&outputsize); 
-	if(output_fid==NULL)_error_("could not initialize output stream");
-	this->parameters->SetParam(output_fid,OutputFilePointerEnum);
-	this->parameters->AddObject(new GenericParam<char**>(&outputbuffer,OutputBufferPointerEnum));
-	this->parameters->AddObject(new GenericParam<size_t*>(&outputsize,OutputBufferSizePointerEnum));
-
-}/*}}}*/
-#endif
-
-#ifdef _HAVE_NEOPZ_
-void FemModel::InitializeAdaptiveRefinement(void){/*{{{*/
-	
-	/*Define variables*/
-	int my_rank						= IssmComm::GetRank();
-	this->amr						= NULL;//initialize amr as NULL
-	int numberofvertices			= this->vertices->NumberOfVertices();
-	int numberofelements			= this->elements->NumberOfElements();
-	int numberofsegments			= 0; //used on matlab
-	IssmDouble* x					= NULL;
-	IssmDouble* y					= NULL;
-	IssmDouble* z					= NULL;
-	int* elements					= NULL;
-	int elementswidth				= this->GetElementsWidth(); //just tria elements in this version. Itapopo:
-	int levelmax					= 0;
-	IssmDouble regionlevel1		= 0.;
-	IssmDouble regionlevelmax	= 0.;
-
-	/*Get vertices coordinates of the coarse mesh (father mesh)*/
-	/*elements comes in Matlab indexing*/
-	this->GetMesh(this->vertices,this->elements,&x,&y,&z,&elements);
-	
-	/*Get amr parameters*/
-	this->parameters->FindParam(&levelmax,AmrLevelMaxEnum);
-	this->parameters->FindParam(&regionlevel1,AmrRegionLevel1Enum);
-	this->parameters->FindParam(&regionlevelmax,AmrRegionLevelMaxEnum);
-
-	/*Create initial mesh (coarse mesh) in neopz data structure*/ 
-	/*Just CPU #0 should keep AMR object*/
-   this->SetRefPatterns();
-	if(my_rank==0){ 
-	   bool ismisomip	= true;
-		if(ismisomip){//itapopo
-			TPZFileStream fstr;
-			std::stringstream ss;
-
-			ss							<< levelmax;
-			std::string AMRfile  = "/home/santos/Misomip2/L" + ss.str() + "_tsai/amr.txt";
-			fstr.OpenRead(AMRfile.c_str());
-			
-			TPZSaveable *sv		= TPZSaveable::Restore(fstr,0);
-			this->amr				= dynamic_cast<AdaptiveMeshRefinement*>(sv);
-		}
-		else{
-			this->amr = new AdaptiveMeshRefinement();
-			//this->amr->SetLevelMax(levelmax); //Set max level of refinement
-			//this->amr->SetRegions(regionlevel1,regionlevelmax);
-			this->amr->CreateInitialMesh(numberofvertices,numberofelements,numberofsegments,elementswidth,x,y,z,elements,NULL);
-		}
-		this->amr->SetLevelMax(levelmax); //Set max level of refinement
-		this->amr->SetRegions(regionlevel1,regionlevelmax);
-	}
-
-	/*Free the vectors*/
-	xDelete<IssmDouble>(x);
-	xDelete<IssmDouble>(y);
-	xDelete<IssmDouble>(z);
-	xDelete<int>(elements);
-
-}
-/*}}}*/
-void FemModel::SetRefPatterns(){/*{{{*/
-
-   /*Initialize the global variable of refinement patterns*/
-   gRefDBase.InitializeUniformRefPattern(EOned);
-   gRefDBase.InitializeUniformRefPattern(ETriangle);
-
-    //gRefDBase.InitializeRefPatterns();
-   /*Insert specifics patterns to ISSM core*/
-   std::string filepath  = REFPATTERNDIR;
-   std::string filename1 = filepath + "/2D_Triang_Rib_3.rpt";
-   std::string filename2 = filepath + "/2D_Triang_Rib_4.rpt";
-   std::string filename3 = filepath + "/2D_Triang_Rib_OnlyTriang_Side_3_4.rpt";
-   std::string filename4 = filepath + "/2D_Triang_Rib_OnlyTriang_Side_3_4_permuted.rpt";
-   std::string filename5 = filepath + "/2D_Triang_Rib_OnlyTriang_Side_3_5.rpt";
-   std::string filename6 = filepath + "/2D_Triang_Rib_OnlyTriang_Side_3_5_permuted.rpt";
-   std::string filename7 = filepath + "/2D_Triang_Rib_5.rpt";
-
-   TPZAutoPointer<TPZRefPattern> refpat1 = new TPZRefPattern(filename1);
-   TPZAutoPointer<TPZRefPattern> refpat2 = new TPZRefPattern(filename2);
-   TPZAutoPointer<TPZRefPattern> refpat3 = new TPZRefPattern(filename3);
-   TPZAutoPointer<TPZRefPattern> refpat4 = new TPZRefPattern(filename4);
-   TPZAutoPointer<TPZRefPattern> refpat5 = new TPZRefPattern(filename5);
-   TPZAutoPointer<TPZRefPattern> refpat6 = new TPZRefPattern(filename6);
-   TPZAutoPointer<TPZRefPattern> refpat7 = new TPZRefPattern(filename7);
-
-   if(!gRefDBase.FindRefPattern(refpat1)) gRefDBase.InsertRefPattern(refpat1);
-   if(!gRefDBase.FindRefPattern(refpat2)) gRefDBase.InsertRefPattern(refpat2);
-   if(!gRefDBase.FindRefPattern(refpat3)) gRefDBase.InsertRefPattern(refpat3);
-   if(!gRefDBase.FindRefPattern(refpat4)) gRefDBase.InsertRefPattern(refpat4);
-   if(!gRefDBase.FindRefPattern(refpat5)) gRefDBase.InsertRefPattern(refpat5);
-   if(!gRefDBase.FindRefPattern(refpat6)) gRefDBase.InsertRefPattern(refpat6);
-   if(!gRefDBase.FindRefPattern(refpat7)) gRefDBase.InsertRefPattern(refpat7);
-}
-/*}}}*/
+
+/*AMR*/
+#if !defined(_HAVE_ADOLC_) 
 void FemModel::ReMesh(void){/*{{{*/
 
-	/*Variables*/
+	/*Intermediaries*/
 	IssmDouble *newx			= NULL;
 	IssmDouble *newy			= NULL;
@@ -3031,10 +2524,22 @@
 	bool* my_elements			= NULL; 
 	int* my_vertices			= NULL;
-	int elementswidth			= this->GetElementsWidth();//just tria elements in this version
-
-	/*Execute refinement and get the new mesh*/
-	/*newelementslist come in Matlab indexing*/
-	this->ExecuteRefinement(newnumberofvertices,newnumberofelements,&newx,&newy,&newz,&newelementslist);
-
+	int elementswidth       = this->GetElementsWidth();//just tria elements in this version
+	int amrtype,basalforcing_model;
+	bool isgroundingline;
+
+	/*Branch to specific amr depending on requested method*/	
+	this->parameters->FindParam(&amrtype,AmrTypeEnum);
+	switch(amrtype){
+		#if defined(_HAVE_NEOPZ_) && !defined(_HAVE_ADOLC_)
+		case AmrNeopzEnum: this->ReMeshNeopz(&newnumberofvertices,&newnumberofelements,&newx,&newy,&newz,&newelementslist); break;
+								 #endif
+
+		#if defined(_HAVE_BAMG_) && !defined(_HAVE_ADOLC_)
+		case AmrBamgEnum: this->ReMeshBamg(&newnumberofvertices,&newnumberofelements,&newx,&newy,&newz,&newelementslist); break;
+		#endif
+
+		default: _error_("not implemented yet");
+	}
+	
 	/*Partitioning the new mesh. Maybe ElementsAndVerticesPartitioning.cpp could be modified to set this without iomodel.*/
 	this->ElementsAndVerticesPartitioning(newnumberofvertices,newnumberofelements,elementswidth,newelementslist,&my_elements,&my_vertices);
@@ -3045,5 +2550,5 @@
 	Vertices* new_vertices=new Vertices();
 	this->CreateVertices(newnumberofvertices,newnumberofelements,elementswidth,newelementslist,my_vertices,newx,newy,newz,new_vertices);
- 
+
 	/*Creating elements*/
 	/*Just Tria in this version*/
@@ -3054,22 +2559,21 @@
 	Materials* new_materials=new Materials();
 	this->CreateMaterials(newnumberofelements,my_elements,new_materials);
-	
+
 	/*Creating nodes and constraints*/
 	/*Just SSA (2D) and P1 in this version*/
-	Nodes* new_nodes=new Nodes();
-	Constraints* new_constraints=new Constraints();
-
-	int nodecounter=0;
+	Nodes* new_nodes					= new Nodes();
+	Constraints* new_constraints	= new Constraints();
+
+	int nodecounter		=0;
 	int constraintcounter=0;
 	for(int i=0;i<this->nummodels;i++){//create nodes for each analysis in analysis_type_list
-	
+
 		int analysis_enum = this->analysis_type_list[i];
-		
+
 		/*As the domain is 2D, it is not necessary to create nodes for this analysis*/
-		/*itapopo must verify if domain is not 3D. Only 2D in this version!*/
-		if(analysis_enum==StressbalanceVerticalAnalysisEnum) continue;	    
-		
+		if(analysis_enum==StressbalanceVerticalAnalysisEnum) continue;    
+
 		this->CreateNodes(newnumberofvertices,my_vertices,nodecounter,analysis_enum,new_nodes);
-		if(analysis_enum==StressbalanceAnalysisEnum) this->CreateConstraints(newnumberofvertices,newnumberofelements,nodecounter,constraintcounter,newx,newy,my_vertices,new_constraints);
+		this->CreateConstraints(new_vertices,nodecounter,constraintcounter,analysis_enum,new_constraints);
 		this->UpdateElements(newnumberofelements,newelementslist,my_elements,nodecounter,i,new_elements);
 
@@ -3113,5 +2617,5 @@
 			if(VerboseSolver()) _printf0_("      toolkits Options set for analysis type: " << EnumToStringx(analysis_type) << "\n");
 		}
-		
+
 		ConfigureObjectsx(new_elements,this->loads,new_nodes,new_vertices,new_materials,this->parameters);
 		if(i==0){ 
@@ -3131,12 +2635,14 @@
 	delete this->constraints;	this->constraints	= new_constraints;
 	delete this->materials;		this->materials	= new_materials;
-	
+
 	GetMaskOfIceVerticesLSMx(this);
 
-	/*Insert MISMIP+ bed topography*/
-	if(true) this->BedrockFromMismipPlus();
-	
+	/*Insert MISMIP+ bed topography FIXME it could be stay in another place*/
+	this->parameters->FindParam(&basalforcing_model,BasalforcingsEnum);
+	if(basalforcing_model==MismipFloatingMeltRateEnum) this->BedrockFromMismipPlus();
+
 	/*Adjust base, thickness and mask grounded ice leve set*/
-	if(true) this->AdjustBaseThicknessAndMask();
+	this->parameters->FindParam(&isgroundingline,TransientIsgroundinglineEnum);
+	if(isgroundingline) this->AdjustBaseThicknessAndMask();
 
 	/*Reset current configuration: */
@@ -3151,7 +2657,4 @@
 	xDelete<int>(my_vertices);
 	xDelete<bool>(my_elements);
-
-	return;
-
 }
 /*}}}*/
@@ -3161,4 +2664,6 @@
 	/*This was used to Misomip project/simulations*/
 	
+	if(VerboseSolution())_printf0_("	call Mismip bedrock adjust module\n");
+
 	IssmDouble x,y,bx,by;
 	int numvertices 		= this->GetElementsWidth();
@@ -3168,31 +2673,25 @@
 	for(int el=0;el<this->elements->Size();el++){
       Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(el));
- 		
 		element->GetVerticesCoordinates(&xyz_list);
 		for(int i=0;i<numvertices;i++){
-			x = *(xyz_list+3*i+0);
-			y = *(xyz_list+3*i+1);
-			
-			bx=-150.-728.8*std::pow(x/300000.,2)+343.91*std::pow(x/300000.,4)-50.57*std::pow(x/300000.,6);
-			by=500./(1.+std::exp((-2./4000.)*(y-80000./2.-24000.)))+500./(1.+std::exp((2./4000.)*(y-80000./2.+24000.)));
-			
-			r[i]=std::max(bx+by,-720.);
+			x		= xyz_list[3*i+0];
+			y		= xyz_list[3*i+1];
+			bx		= -150.-728.8*pow(x/300000.,2)+343.91*pow(x/300000.,4)-50.57*pow(x/300000.,6);
+			by		= 500./(1.+exp((-2./4000.)*(y-80000./2.-24000.)))+500./(1.+exp((2./4000.)*(y-80000./2.+24000.)));
+			r[i]	= max(bx+by,-720.);
 		}	
-
 		/*insert new bedrock*/
 		element->AddInput(BedEnum,&r[0],P1Enum);
-		
 		/*Cleanup*/
 		xDelete<IssmDouble>(xyz_list);
 	}
-
    /*Delete*/
    xDelete<IssmDouble>(r);
-	
-	return;
 }
 /*}}}*/
 void FemModel::AdjustBaseThicknessAndMask(void){/*{{{*/
 
+	if(VerboseSolution())_printf0_("	call adjust base and thickness module\n");
+	
 	int     numvertices = this->GetElementsWidth();
    IssmDouble rho_water,rho_ice,density,base_float;
@@ -3224,5 +2723,5 @@
 			} 
 
-			if(abs(sl[i])>0) _error_("Sea level value not supported!");
+			if(fabs(sl[i])>0) _error_("Sea level value "<<sl[i]<<" not supported!");
 			/*update thickness and mask grounded ice level set*/
 			h[i]	  = s[i]-b[i];
@@ -3234,5 +2733,4 @@
 		element->AddInput(ThicknessEnum,&h[0],P1Enum);
 		element->AddInput(BaseEnum,&b[0],P1Enum);
-
 	}
 	
@@ -3244,76 +2742,44 @@
    xDelete<IssmDouble>(r);
    xDelete<IssmDouble>(sl);
-
-	return;
-}
-/*}}}*/
-void FemModel::WriteMeshInResults(void){/*{{{*/
-
-	int step					= -1;
-	int numberofelements = -1;
-	int numberofvertices = -1;
-	IssmDouble time		= -1;
-	IssmDouble* x			= NULL;
-	IssmDouble* y			= NULL;
-	IssmDouble* z			= NULL;
-	int* elementslist		= NULL;
-
-	if(!this->elements || !this->vertices || !this->results || !this->parameters) return;
-	 
-	parameters->FindParam(&step,StepEnum);
-	parameters->FindParam(&time,TimeEnum);
-	numberofelements=this->elements->NumberOfElements();
-	numberofvertices=this->vertices->NumberOfVertices();
-
-	/*Get mesh. Elementslist comes in Matlab indexing*/
-	this->GetMesh(this->vertices,this->elements,&x,&y,&z,&elementslist);
-
-	/*Write mesh in Results*/
-	this->results->AddResult(new GenericExternalResult<int*>(this->results->Size()+1,MeshElementsEnum,
-																					elementslist,numberofelements,this->GetElementsWidth(),step,time));
-
-	this->results->AddResult(new GenericExternalResult<IssmDouble*>(this->results->Size()+1,MeshXEnum,
-																					x,numberofvertices,1,step,time));
-
-	this->results->AddResult(new GenericExternalResult<IssmDouble*>(this->results->Size()+1,MeshYEnum,
-																					y,numberofvertices,1,step,time));
-	
-	/*Cleanup*/
-	xDelete<IssmDouble>(x);
-	xDelete<IssmDouble>(y);
-	xDelete<IssmDouble>(z);
-	xDelete<int>(elementslist);
-
-	return;
-}
-/*}}}*/
-void FemModel::InterpolateInputs(Vertices* newfemmodel_vertices,Elements* newfemmodel_elements){/*{{{*/
-
-	int maxinputs = MaximumNumberOfDefinitionsEnum;
+}
+/*}}}*/
+void FemModel::GetInputs(int* pnumP0inputs,IssmDouble** pP0inputs,int** pP0input_enums,int** pP0input_interp,int* pnumP1inputs,IssmDouble** pP1inputs,int** pP1input_enums,int** pP1input_interp){/*{{{*/
+
+	int maxinputs										= MaximumNumberOfDefinitionsEnum;
+	int numberofvertices								= this->vertices->NumberOfVertices();
+	int numberofelements								= this->elements->NumberOfElements();
+	int elementswidth									= this->GetElementsWidth();
+	int numP0inputs									= -1;
+	IssmDouble* P0inputs								= NULL;
+	Vector<IssmDouble>* vP0inputs					= NULL;
+	int* P0input_enums								= NULL;
+	int* P0input_interp 								= NULL;
+	int numP1inputs									= -1;
+	IssmDouble* P1inputs								= NULL;
+	Vector<IssmDouble>* vP1inputs					= NULL;
+	int* P1input_enums  								= NULL;
+	int* P1input_interp 								= NULL;
+	Vector<IssmDouble>* input_interpolations	= NULL;
+	IssmDouble* input_interpolations_serial	= NULL;
+   int* pos												= NULL; 
+	IssmDouble value									= 0;
 
 	/*Figure out how many inputs we have and their respective interpolation*/
-	Vector<IssmDouble>* input_interpolations=new Vector<IssmDouble>(maxinputs);
+	input_interpolations=new Vector<IssmDouble>(maxinputs);
 	if(this->elements->Size()){
 		Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(0));
 		element->GetInputsInterpolations(input_interpolations);
 	}
+
+	/*Assemble and serialize*/
 	input_interpolations->Assemble();
-	
-	/*Serialize and set output*/
-	IssmDouble* input_interpolations_serial = input_interpolations->ToMPISerial();
-	delete input_interpolations;
+	input_interpolations_serial = input_interpolations->ToMPISerial();
 
 	/*Count and get enums of all inputs in old mesh*/
-	int  numP0inputs;
-	int  numP1inputs;
-	int *P0input_enums  = NULL;
-	int *P1input_enums  = NULL;
-	int *P0input_interp = NULL;
-	int *P1input_interp = NULL;
 	for(int step=0;step<2;step++){
 		if(step){
 			P0input_enums  = xNew<int>(numP0inputs);
+			P0input_interp = xNew<int>(numP0inputs);
 			P1input_enums  = xNew<int>(numP1inputs);
-			P0input_interp = xNew<int>(numP0inputs);
 			P1input_interp = xNew<int>(numP1inputs);	
 		}
@@ -3331,5 +2797,5 @@
 						P1input_interp[numP1inputs] = inputinterp;
 					}
-					 numP1inputs++;
+					numP1inputs++;
 					break;
 				case P0Enum:
@@ -3348,199 +2814,242 @@
 		}
 	}
-
-	/*========== Deal with P0 inputs ==========*/
-	int numelementsold = this->elements->NumberOfElements();
-	int numelementsnew = newfemmodel_elements->NumberOfElements();
-	int numverticesold = this->vertices->NumberOfVertices();
-	int numverticesnew = newfemmodel_vertices->NumberOfVertices();
-	IssmDouble* P0inputsold = xNew<IssmDouble>(numelementsold*numP0inputs);
-	IssmDouble* P0inputsnew = NULL;
-	IssmDouble* vector      = NULL;
-
-	for(int i=0;i<numP0inputs;i++){
-		GetVectorFromInputsx(&vector,this,P0input_enums[i],ElementSIdEnum);
-
-		/*Copy vector in matrix*/
-		for(int j=0;j<numelementsold;j++) P0inputsold[j*numP0inputs+i] = vector[j];
-		xDelete<IssmDouble>(vector);
-	}
-
-	/*========== Deal with P1 inputs ==========*/
-	IssmDouble* P1inputsold = xNew<IssmDouble>(numverticesold*numP1inputs);
-	IssmDouble* P1inputsnew = NULL;
-	vector      = NULL;
-
-	for(int i=0;i<numP1inputs;i++){
-		GetVectorFromInputsx(&vector,this,P1input_enums[i],VertexSIdEnum);
-
-		/*Copy vector in matrix*/
-		for(int j=0;j<numverticesold;j++) P1inputsold[j*numP1inputs+i] = vector[j];
-		xDelete<IssmDouble>(vector);
-	}
-	
-	/*Old mesh coordinates*/
-	IssmDouble *Xold     = NULL;
-	IssmDouble *Yold     = NULL;
-	IssmDouble *Zold		= NULL;
-	int        *Indexold = NULL;
-	IssmDouble *Xnew     = NULL;
-	IssmDouble *Ynew     = NULL;
-	IssmDouble *Znew		= NULL;
-	IssmDouble* XC_new   = NULL;
-	IssmDouble* YC_new   = NULL;
-	int        *Indexnew = NULL;
-	
-	/*Get the old mesh*/
-	this->GetMesh(this->vertices,this->elements,&Xold,&Yold,&Zold,&Indexold);
-
-	/*Get the new mesh*/
-	this->GetMesh(newfemmodel_vertices,newfemmodel_elements,&Xnew,&Ynew,&Znew,&Indexnew);
-
-	/*Calculate the center points xc and xy*/
-	int elementswidth = this->GetElementsWidth(); //just tria in this version
-	/*new mesh*/
-	XC_new=xNewZeroInit<IssmDouble>(numelementsnew);
-	YC_new=xNewZeroInit<IssmDouble>(numelementsnew);
-	for(int i=0;i<numelementsnew;i++){
+	
+	/*Get P0 and P1 inputs over the elements*/	
+	pos		= xNew<int>(elementswidth);
+	vP0inputs= new Vector<IssmDouble>(numberofelements*numP0inputs);
+	vP1inputs= new Vector<IssmDouble>(numberofvertices*numP1inputs);
+	for(int i=0;i<this->elements->Size();i++){
+		Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
+		
+		/*Get P0 inputs*/
+		for(int j=0;j<numP0inputs;j++){
+			TriaInput* input=xDynamicCast<TriaInput*>(element->GetInput(P0input_enums[j]));		
+			input->GetInputAverage(&value);
+			pos[0]=element->Sid()*numP0inputs+j;
+			/*Insert input in the vector*/	
+			vP0inputs->SetValues(1,pos,&value,INS_VAL);
+		}
+		
+		/*Get P1 inputs*/
+		for(int j=0;j<numP1inputs;j++){
+			TriaInput* input=xDynamicCast<TriaInput*>(element->GetInput(P1input_enums[j]));
+			pos[0]=element->vertices[0]->Sid()*numP1inputs+j;
+			pos[1]=element->vertices[1]->Sid()*numP1inputs+j;
+			pos[2]=element->vertices[2]->Sid()*numP1inputs+j;
+			/*Insert input in the vector*/	
+			vP1inputs->SetValues(elementswidth,pos,input->values,INS_VAL);	
+		}
+	}
+
+	/*Assemble and serialize*/
+	vP0inputs->Assemble();
+	vP1inputs->Assemble();
+	P0inputs=vP0inputs->ToMPISerial();
+	P1inputs=vP1inputs->ToMPISerial();
+	
+	/*Assign pointers*/
+	*pnumP0inputs		= numP0inputs; 
+	*pP0inputs			= P0inputs; 
+	*pP0input_enums	= P0input_enums;
+	*pP0input_interp	= P0input_interp;
+	*pnumP1inputs		= numP1inputs; 
+	*pP1inputs			= P1inputs; 
+	*pP1input_enums	= P1input_enums;
+	*pP1input_interp	= P1input_interp;	
+
+	/*Cleanup*/
+	delete input_interpolations;
+	delete vP0inputs;
+	delete vP1inputs;
+	xDelete<IssmDouble>(input_interpolations_serial);
+	xDelete<int>(pos);
+}
+/*}}}*/
+void FemModel::InterpolateInputs(Vertices* newfemmodel_vertices,Elements* newfemmodel_elements){/*{{{*/
+	
+	int numberofelements			= this->elements->NumberOfElements();	//global, entire old mesh
+	int newnumberofelements		= newfemmodel_elements->Size();			//just on the new partition
+	int numberofvertices			= this->vertices->NumberOfVertices();	//global, entire old mesh
+	int newnumberofvertices 	= newfemmodel_vertices->Size();			//just on the new partition
+	int elementswidth				= this->GetElementsWidth(); //just tria in this version
+	int numP0inputs				= -1;
+	IssmDouble* P0inputs			= NULL; //global, entire old mesh
+	IssmDouble* newP0inputs		= NULL; //just on the new partition
+	int* P0input_enums			= NULL;
+	int* P0input_interp 			= NULL;
+	int numP1inputs				= -1;
+	IssmDouble* P1inputs			= NULL; //global, entire old mesh
+	IssmDouble* newP1inputs 	= NULL; //just on the new partition
+	int* P1input_enums  			= NULL;
+	int* P1input_interp 			= NULL;
+	IssmDouble* values			= NULL;	
+   IssmDouble* vector      	= NULL;
+	IssmDouble* x					= NULL;//global, entire old mesh
+	IssmDouble* y					= NULL;//global, entire old mesh
+	IssmDouble* z					= NULL;//global, entire old mesh
+	int* elementslist				= NULL;//global, entire old mesh
+	IssmDouble* newx				= NULL;//just on the new partition
+	IssmDouble* newy				= NULL;//just on the new partition
+	IssmDouble* newz				= NULL;//just on the new partition
+	IssmDouble* newxc				= NULL;//just on the new partition
+	IssmDouble* newyc				= NULL;//just on the new partition
+	int* newelementslist			= NULL;//just on the new partition
+	int* sidtoindex				= NULL;//global vertices sid to partition index 
+
+	/*Get old P0 and P1  inputs (entire mesh)*/
+	this->GetInputs(&numP0inputs,&P0inputs,&P0input_enums,&P0input_interp,&numP1inputs,&P1inputs,&P1input_enums,&P1input_interp);
+
+	/*Get the old mesh (global, entire mesh)*/
+	this->GetMesh(this->vertices,this->elements,&x,&y,&z,&elementslist);
+
+	/*Get the new mesh (just on the new partition)*/
+	this->GetMeshOnPartition(newfemmodel_vertices,newfemmodel_elements,&newx,&newy,&newz,&newelementslist,&sidtoindex);
+
+	/*Calculate the center points xc and xy (new mesh, new partition)*/
+	newxc=xNewZeroInit<IssmDouble>(newnumberofelements);
+	newyc=xNewZeroInit<IssmDouble>(newnumberofelements);
+	for(int i=0;i<newnumberofelements;i++){
 		for(int j=0;j<elementswidth;j++){
-			int vid = Indexnew[i*elementswidth+j]-1;//Transform to C indexing
-			XC_new[i]+=Xnew[vid];
-			YC_new[i]+=Ynew[vid];
-		}
-		XC_new[i]=XC_new[i]/3;
-		YC_new[i]=YC_new[i]/3;
-	}
-
-	/*Interplate P0 inputs in the new mesh*/
-	InterpFromMeshToMesh2dx(&P0inputsnew,Indexold,Xold,Yold,numverticesold,numelementsold,
-				P0inputsold,numelementsold,numP0inputs,
-				XC_new,YC_new,numelementsnew,NULL);
-	
-	/*Interpolate P1 inputs in the new mesh*/
-	InterpFromMeshToMesh2dx(&P1inputsnew,Indexold,Xold,Yold,numverticesold,numelementsold,
-				P1inputsold,numverticesold,numP1inputs,
-				Xnew,Ynew,numverticesnew,NULL);
-	
-	/*Insert P0 inputs into the new elements.*/
-	vector=NULL;
-	for(int i=0;i<numP0inputs;i++){
-		
-		/*Get P0 input vector from the interpolated matrix*/
-		vector=xNew<IssmDouble>(numelementsnew);
-		for(int j=0;j<numelementsnew;j++) vector[j]=P0inputsnew[j*numP0inputs+i];//vector has values for all elements (serial)
-
-		/*Update elements from inputs: */
-		for(int j=0;j<newfemmodel_elements->Size();j++){
-			Element* element=xDynamicCast<Element*>(newfemmodel_elements->GetObjectByOffset(j));
-			switch(P0input_interp[i]){	
+			int vid = newelementslist[i*elementswidth+j]-1;//Transform to C indexing
+			newxc[i]+=newx[vid]/elementswidth;
+			newyc[i]+=newy[vid]/elementswidth;
+		}
+	}
+
+	/*Interplate P0 inputs in the new mesh (just on the new partition)*/
+	InterpFromMeshToMesh2dx(&newP0inputs,elementslist,x,y,numberofvertices,numberofelements,
+				P0inputs,numberofelements,numP0inputs,
+				newxc,newyc,newnumberofelements,NULL);
+
+	/*Interpolate P1 inputs in the new mesh (just on the new partition)*/
+	InterpFromMeshToMesh2dx(&newP1inputs,elementslist,x,y,numberofvertices,numberofelements,
+				P1inputs,numberofvertices,numP1inputs,
+				newx,newy,newnumberofvertices,NULL);
+
+	/*Insert P0 and P1 inputs into the new elements (just on the new partition)*/
+	values=xNew<IssmDouble>(elementswidth);	
+	for(int i=0;i<newfemmodel_elements->Size();i++){//just on the new partition
+		Element* element=xDynamicCast<Element*>(newfemmodel_elements->GetObjectByOffset(i));
+		/*newP0inputs is just on the new partition*/
+		for(int j=0;j<numP0inputs;j++){
+			switch(P0input_interp[j]){	
 				case P0Enum:
 				case DoubleInputEnum:
-					element->AddInput(new DoubleInput(P0input_enums[i],vector[element->sid]));//sid because newfemmodel has just a partitioning 
+					element->AddInput(new DoubleInput(P0input_enums[j],newP0inputs[i*numP0inputs+j]));
 					break;
 				case IntInputEnum: 
-					element->AddInput(new IntInput(P0input_enums[i],vector[element->sid]));//sid because newfemmodel has just a partitioning
+					element->AddInput(new IntInput(P0input_enums[j],reCast<int>(newP0inputs[i*numP0inputs+j])));
 					break;
 				case BoolInputEnum:
-					element->AddInput(new BoolInput(P0input_enums[i],vector[element->sid]));//sid because newfemmodel has just a partitioning
+					element->AddInput(new BoolInput(P0input_enums[j],reCast<bool>(newP0inputs[i*numP0inputs+j])));
 					break;
 				default:
-					_error_(EnumToStringx(P0input_enums[i])<<" Not supported yet");
+					_error_(EnumToStringx(P0input_enums[j])<<" Not supported yet");
 			}
 		}
-
-		xDelete<IssmDouble>(vector);
-	}
-
-	/*Insert P1 inputs into the new elements.*/
-	vector=NULL;
-	for(int i=0;i<numP1inputs;i++){
-
-		/*Get P1 input vector from the interpolated matrix*/
-		vector=xNew<IssmDouble>(numverticesnew);
-		for(int j=0;j<numverticesnew;j++) vector[j]=P1inputsnew[j*numP1inputs+i];//vector has all vertices	(serial)
-
-		/*Update elements from inputs: */
-		//InputUpdateFromVectorx(newfemmodel,vector,P1input_enums[i],VertexSIdEnum);//VertexSId because vector is serial in SId indexing
-		for(int j=0;j<newfemmodel_elements->Size();j++){
-			Element* element=xDynamicCast<Element*>(newfemmodel_elements->GetObjectByOffset(j));
-			element->InputUpdateFromVector(vector,P1input_enums[i],VertexSIdEnum);
-		}
-
-		xDelete<IssmDouble>(vector);
-	}
-
+		/*newP1inputs is just on the new partition*/
+		for(int j=0;j<numP1inputs;j++){
+			values[0]=newP1inputs[sidtoindex[element->vertices[0]->Sid()]*numP1inputs+j];
+			values[1]=newP1inputs[sidtoindex[element->vertices[1]->Sid()]*numP1inputs+j];
+			values[2]=newP1inputs[sidtoindex[element->vertices[2]->Sid()]*numP1inputs+j];
+			element->inputs->AddInput(new TriaInput(P1input_enums[j],values,P1Enum));
+		}
+	}
+	
 	/*Cleanup*/
-	xDelete<IssmDouble>(input_interpolations_serial);
-	xDelete<IssmDouble>(P0inputsold);
-	xDelete<IssmDouble>(P0inputsnew);
+	xDelete<IssmDouble>(P0inputs);
+	xDelete<IssmDouble>(newP0inputs);
 	xDelete<int>(P0input_enums);
 	xDelete<int>(P0input_interp);
-	xDelete<IssmDouble>(P1inputsold);
-	xDelete<IssmDouble>(P1inputsnew);
+	xDelete<IssmDouble>(P1inputs);
+	xDelete<IssmDouble>(newP1inputs);
 	xDelete<int>(P1input_enums);
 	xDelete<int>(P1input_interp);
-	xDelete<IssmDouble>(Xold);
-	xDelete<IssmDouble>(Yold);
-	xDelete<IssmDouble>(Zold);
-	xDelete<int>(Indexold);
-	xDelete<IssmDouble>(Xnew);
-	xDelete<IssmDouble>(Ynew);
-	xDelete<IssmDouble>(Znew);
-	xDelete<IssmDouble>(XC_new);
-	xDelete<IssmDouble>(YC_new);
-	xDelete<int>(Indexnew);
-
-}
-/*}}}*/
-void FemModel::ExecuteRefinement(int &numberofvertices,int &numberofelements,IssmDouble** px,IssmDouble** py,IssmDouble** pz,int** pelementslist){/*{{{*/
-	
-	/*elements is in Matlab indexing*/
-	
-	int my_rank					 = IssmComm::GetRank();
-	int numberofsegments		 = -1;
-	IssmDouble* vx				 = NULL; //itapopo this is not being used
-	IssmDouble* vy				 = NULL; //itapopo this is not being used
-	IssmDouble* x				 = NULL;
-	IssmDouble* y				 = NULL;
-	IssmDouble* z				 = NULL;
-	int* elementslist			 = NULL;
-	int* segments				 = NULL;
-	IssmDouble* masklevelset = NULL;
-   const int elementswidth  = this->GetElementsWidth();//just 2D mesh, tria elements
-	
-	/*Solutions which will be used to refine the elements*/
-	this->GetGroundediceLevelSet(&masklevelset);//itapopo verificar se já existe um método igual a esse
-
-	if(my_rank==0){
-		int type_process=1; //1: it refines father mesh. See AdaptiveMeshRefinement.h (.cpp)
-		this->amr->ExecuteRefinement(type_process,vx,vy,masklevelset,
-												numberofvertices,numberofelements,numberofsegments,&x,&y,&z,&elementslist,&segments);
-		if(numberofvertices<=0 || numberofelements<=0 /*|| newnumberofsegments<=0*/) _error_("Error in the refinement process.");
-	}
-	else{
-		x=xNew<IssmDouble>(numberofvertices);
-		y=xNew<IssmDouble>(numberofvertices);
-		z=xNew<IssmDouble>(numberofvertices);
-		elementslist=xNew<int>(numberofelements*this->GetElementsWidth());
-	}
-
-	/*Send new mesh to others CPU*/
-	ISSM_MPI_Bcast(&numberofvertices,1,ISSM_MPI_INT,0,IssmComm::GetComm());
-	ISSM_MPI_Bcast(&numberofelements,1,ISSM_MPI_INT,0,IssmComm::GetComm());
-	ISSM_MPI_Bcast(x,numberofvertices,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm());	
-	ISSM_MPI_Bcast(y,numberofvertices,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm());	
-	ISSM_MPI_Bcast(z,numberofvertices,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm());	
-	ISSM_MPI_Bcast(elementslist,numberofelements*this->GetElementsWidth(),ISSM_MPI_INT,0,IssmComm::GetComm());	
-
-	/*Assign the pointers*/	
-	(*pelementslist) = elementslist; //Matlab indexing
-	(*px)				  = x;
-	(*py)				  = y;
-	(*pz)				  = z;
-
+	xDelete<IssmDouble>(x);
+	xDelete<IssmDouble>(y);
+	xDelete<IssmDouble>(z);
+	xDelete<int>(elementslist);
+	xDelete<IssmDouble>(newx);
+	xDelete<IssmDouble>(newy);
+	xDelete<IssmDouble>(newz);
+	xDelete<IssmDouble>(newxc);
+	xDelete<IssmDouble>(newyc);
+	xDelete<int>(newelementslist);
+	xDelete<int>(sidtoindex);
+	xDelete<IssmDouble>(values);
+}
+/*}}}*/
+void FemModel::WriteMeshInResults(void){/*{{{*/
+
+	/*Write the erros estimators*/
+	this->WriteErrorEstimatorsInResults();
+
+	int step					= -1;
+	int numberofelements = -1;
+	int numberofvertices = -1;
+	IssmDouble time		= -1;
+	IssmDouble* x			= NULL;
+	IssmDouble* y			= NULL;
+	IssmDouble* z			= NULL;
+	int* elementslist		= NULL;
+
+	if(!this->elements || !this->vertices || !this->results || !this->parameters) return;
+	 
+	parameters->FindParam(&step,StepEnum);
+	parameters->FindParam(&time,TimeEnum);
+	numberofelements=this->elements->NumberOfElements();
+	numberofvertices=this->vertices->NumberOfVertices();
+
+	/*Get mesh. Elementslist comes in Matlab indexing*/
+	this->GetMesh(this->vertices,this->elements,&x,&y,&z,&elementslist);
+
+	/*Write mesh in Results*/
+	this->results->AddResult(new GenericExternalResult<int*>(this->results->Size()+1,MeshElementsEnum,
+					elementslist,numberofelements,this->GetElementsWidth(),step,time));
+
+	this->results->AddResult(new GenericExternalResult<IssmDouble*>(this->results->Size()+1,MeshXEnum,
+					x,numberofvertices,1,step,time));
+
+	this->results->AddResult(new GenericExternalResult<IssmDouble*>(this->results->Size()+1,MeshYEnum,
+					y,numberofvertices,1,step,time));
+	
 	/*Cleanup*/
-	if(segments) xDelete<int>(segments);
-	xDelete<IssmDouble>(masklevelset);
-
+	xDelete<IssmDouble>(x);
+	xDelete<IssmDouble>(y);
+	xDelete<IssmDouble>(z);
+	xDelete<int>(elementslist);
+}
+/*}}}*/
+void FemModel::WriteErrorEstimatorsInResults(void){/*{{{*/
+
+   int step                   = -1;
+   int numberofelements       = -1;
+   IssmDouble time            = -1;
+   IssmDouble* stresserror    = NULL;
+   IssmDouble* thicknesserror = NULL;
+
+   if(!this->elements || !this->vertices || !this->results || !this->parameters) return;
+
+   parameters->FindParam(&step,StepEnum);
+   parameters->FindParam(&time,TimeEnum);
+   numberofelements=this->elements->NumberOfElements();
+
+   /*Compute the deviatoric stress tensor*/
+   this->ZZErrorEstimator(&stresserror);
+
+   /*Compute the thickness error*/
+   this->ThicknessZZErrorEstimator(&thicknesserror);
+
+   /*Write error estimators in Results*/
+   this->results->AddResult(new GenericExternalResult<IssmDouble*>(this->results->Size()+1,DeviatoricStressErrorEstimatorEnum,
+                                                                  stresserror,numberofelements,1,step,time));
+
+   this->results->AddResult(new GenericExternalResult<IssmDouble*>(this->results->Size()+1,ThicknessErrorEstimatorEnum,
+                                                                  thicknesserror,numberofelements,1,step,time));
+   /*Cleanup*/
+   xDelete<IssmDouble>(stresserror);
+   xDelete<IssmDouble>(thicknesserror);
+
+   return;
 }
 /*}}}*/
@@ -3548,5 +3057,4 @@
 
 	int elementswidth		= this->GetElementsWidth();//just 2D mesh, tria elements
-	int numberofelements = this->elements->NumberOfElements();
 	int numberofvertices = this->vertices->NumberOfVertices();
 
@@ -3585,6 +3093,6 @@
 	connectivity=xNewZeroInit<int>(newnumberofvertices);
 
-	for (int i=0;i<newnumberofelements;i++){
-		for (int j=0;j<elementswidth;j++){
+	for(int i=0;i<newnumberofelements;i++){
+		for(int j=0;j<elementswidth;j++){
 			int vertexid = newelementslist[elementswidth*i+j];
 			_assert_(vertexid>0 && vertexid-1<newnumberofvertices);//Matlab indexing
@@ -3672,5 +3180,4 @@
 	newmatpar->SetMid(newnumberofelements+1);
 	materials->AddObject(newmatpar);//put it at the end of the materials	    
-
 }
 /*}}}*/
@@ -3718,5 +3225,4 @@
 		}
 	}
-	return;
 }
 /*}}}*/
@@ -3726,19 +3232,21 @@
 	if(!femmodel_elements) _error_("GetMesh: elements are NULL.");
 	
-	int numberofvertices, numberofelements;
-	int elementswidth = this->GetElementsWidth(); // just 2D mesh in this version (just tria elements)
-	IssmDouble *x		= NULL;
-	IssmDouble *y		= NULL;
-	IssmDouble *z		= NULL;	
-	int* elementslist = NULL;
-	
+	int numberofvertices = femmodel_vertices->NumberOfVertices();
+	int numberofelements = femmodel_elements->NumberOfElements();
+	int elementswidth		= this->GetElementsWidth(); // just 2D mesh in this version (just tria elements)
+	IssmDouble* x			= NULL;
+	IssmDouble* y			= NULL;
+	IssmDouble* z			= NULL;	
+	int* elementslist 	= NULL;
+	int* elem_vertices	= NULL;
+	IssmDouble *id1		= NULL;
+   IssmDouble *id2 		= NULL;
+	IssmDouble *id3 		= NULL;
+
 	/*Get vertices coordinates*/
-	VertexCoordinatesx(&x, &y, &z, femmodel_vertices,false) ;
-
-	numberofvertices = femmodel_vertices->NumberOfVertices();
-	numberofelements = femmodel_elements->NumberOfElements();
+	VertexCoordinatesx(&x,&y,&z,femmodel_vertices,false) ;
 	
 	/*Get element vertices*/
-	int* elem_vertices=xNew<int>(elementswidth);
+	elem_vertices				= xNew<int>(elementswidth);
 	Vector<IssmDouble>* vid1= new Vector<IssmDouble>(numberofelements);
 	Vector<IssmDouble>* vid2= new Vector<IssmDouble>(numberofelements);
@@ -3760,7 +3268,7 @@
 
    /*Serialize*/
-	IssmDouble *id1 = vid1->ToMPISerial();
-   IssmDouble *id2 = vid2->ToMPISerial();
-	IssmDouble *id3 = vid3->ToMPISerial();
+	id1 = vid1->ToMPISerial();
+   id2 = vid2->ToMPISerial();
+	id3 = vid3->ToMPISerial();
 	
 	/*Construct elements list*/
@@ -3768,7 +3276,7 @@
 	if(numberofelements*elementswidth<0) _error_("numberofelements negative.");
 	for(int i=0;i<numberofelements;i++){
-		elementslist[elementswidth*i+0] = (int)id1[i]+1; //InterpMesh wants Matlab indexing
-		elementslist[elementswidth*i+1] = (int)id2[i]+1; //InterpMesh wants Matlab indexing
-		elementslist[elementswidth*i+2] = (int)id3[i]+1; //InterpMesh wants Matlab indexinf
+		elementslist[elementswidth*i+0] = reCast<int>(id1[i])+1; //InterpMesh wants Matlab indexing
+		elementslist[elementswidth*i+1] = reCast<int>(id2[i])+1; //InterpMesh wants Matlab indexing
+		elementslist[elementswidth*i+2] = reCast<int>(id3[i])+1; //InterpMesh wants Matlab indexing
 	}
 	
@@ -3789,99 +3297,150 @@
 }
 /*}}}*/
-void FemModel::CreateConstraints(int newnumberofvertices,int newnumberofelements,int nodecounter,int constraintcounter,IssmDouble* newx,IssmDouble* newy,int* my_vertices,Constraints* constraints){/*{{{*/
-
-	/*itapopo ATTENTION: JUST SPCVX AND SPCVY TO TEST!!!*/
-	/*OTHERS CONSTRAINTS MUST BE IMPLEMENTED!!!*/
-	
-	/*Get x and y of the mesh i-1*/
-	int numberofvertices			= this->vertices->NumberOfVertices();
-	int numberofelements			= this->elements->NumberOfElements();
-	IssmDouble *x					= NULL;
-	IssmDouble *y					= NULL;
-	IssmDouble *z					= NULL;
-	int        *elementslist	= NULL;
-
-	/*elementslist is in Matlab indexing*/
+void FemModel::GetMeshOnPartition(Vertices* femmodel_vertices,Elements* femmodel_elements,IssmDouble** px,IssmDouble** py,IssmDouble** pz,int** pelementslist,int** psidtoindex){/*{{{*/
+
+	if(!femmodel_vertices) _error_("GetMesh: vertices are NULL.");
+	if(!femmodel_elements) _error_("GetMesh: elements are NULL.");
+	
+	int numberofvertices			= femmodel_vertices->Size();	//number of vertices of this partition
+	int numbertotalofvertices	= femmodel_vertices->NumberOfVertices();	//number total of vertices (entire mesh)
+	int numberofelements			= femmodel_elements->Size();  //number of elements of this partition
+	int elementswidth				= this->GetElementsWidth();	//just 2D mesh in this version (just tria elements)
+	IssmDouble* x					= NULL;
+	IssmDouble* y					= NULL;
+	IssmDouble* z					= NULL;	
+	int* elementslist				= NULL;
+	int* sidtoindex				= NULL;
+	int* elem_vertices			= NULL;
+	
+	/*Get vertices coordinates of this partition*/
+	sidtoindex	= xNewZeroInit<int>(numbertotalofvertices);//entire mesh, all vertices
+	x				= xNew<IssmDouble>(numberofvertices);//just this partition
+	y				= xNew<IssmDouble>(numberofvertices);//just this partitio;
+	z				= xNew<IssmDouble>(numberofvertices);//just this partitio;
+	
+	/*Go through in this partition (vertices)*/
+	for(int i=0;i<numberofvertices;i++){//just this partition
+		Vertex* vertex=(Vertex*)femmodel_vertices->GetObjectByOffset(i);	
+		/*Attention: no spherical coordinates*/
+		x[i]=vertex->GetX();
+		y[i]=vertex->GetY();
+		z[i]=vertex->GetZ();
+		/*Keep the index and sid pair*/
+		sidtoindex[vertex->Sid()]=i;
+	}
+
+	/*Go through in this partition (elements) and build the element list*/
+	elem_vertices= xNew<int>(elementswidth);
+	elementslist = xNew<int>(numberofelements*elementswidth);
+	if(numberofelements*elementswidth<0) _error_("numberofelements negative.");
+	
+	for(int i=0;i<numberofelements;i++){//just this partition
+    	Element* element=xDynamicCast<Element*>(femmodel_elements->GetObjectByOffset(i));
+    	element->GetVerticesSidList(elem_vertices);
+		elementslist[elementswidth*i+0] = sidtoindex[elem_vertices[0]]+1; //InterpMesh wants Matlab indexing
+		elementslist[elementswidth*i+1] = sidtoindex[elem_vertices[1]]+1; //InterpMesh wants Matlab indexing
+		elementslist[elementswidth*i+2] = sidtoindex[elem_vertices[2]]+1; //InterpMesh wants Matlab indexing
+	}	
+		
+	/*Assign pointers*/
+	*px				= x;
+	*py				= y;
+	*pz				= z;
+	*pelementslist = elementslist; //Matlab indexing. InterMesh uses this type.
+	*psidtoindex	= sidtoindex;  //it is ncessary to insert inputs 
+
+	/*Cleanup*/
+	xDelete<int>(elem_vertices);
+}
+/*}}}*/
+void FemModel::CreateConstraints(Vertices* newfemmodel_vertices,int nodecounter,int constraintcounter,int analysis_enum,Constraints* newfemmodel_constraints){/*{{{*/
+
+	/*ATTENTION: JUST SPCVX AND SPCVY*/
+	/*OTHERS CONSTRAINTS MUST BE IMPLEMENTED*/
+	if(analysis_enum!=StressbalanceAnalysisEnum) return;
+	
+	int numberofnodes_analysistype= this->nodes->NumberOfNodes(analysis_enum);
+	int dofpernode						= 2;														//vx and vy 
+	int numberofcols					= dofpernode*2;										//to keep dofs and flags in the vspc vector
+	int numberofvertices				= this->vertices->NumberOfVertices();			//global, entire old mesh
+	int numberofelements				= this->elements->NumberOfElements();			//global, entire old mesh
+	int newnumberofvertices			= newfemmodel_vertices->Size();					//local, just the new partition
+	int count							= 0;
+	IssmDouble* x						= NULL;													//global, entire old mesh
+	IssmDouble* y						= NULL;													//global, entire old mesh
+	IssmDouble* z						= NULL;													//global, entire old mesh
+	int*			elementslist		= NULL;													//global, entire old mesh
+	IssmDouble* spc					= NULL;													//global, entire old mesh
+	IssmDouble* newx					= NULL;													//local, just new partition
+	IssmDouble* newy					= NULL;													//local, just new partition
+	IssmDouble* newspc				= NULL;													//local, just new partition
+	IssmDouble eps						= 1.e-8;
+	Vector<IssmDouble>* vspc		= new Vector<IssmDouble>(numberofnodes_analysistype*numberofcols);
+
+	/*Get old mesh (global, entire mesh). Elementslist comes in Matlab indexing*/
 	this->GetMesh(this->vertices,this->elements,&x,&y,&z,&elementslist);
-	
-	/*Get spcvx and spcvy for mesh i-1*/
-	IssmDouble *spcvx						= NULL;
-	IssmDouble *spcvy						= NULL;
-	IssmDouble *spcvxflag				= NULL;
-	IssmDouble *spcvyflag				= NULL;
-	int numberofnodes_analysistype	= this->nodes->NumberOfNodes(StressbalanceAnalysisEnum);
-	Vector<IssmDouble>* vspcvx			= new Vector<IssmDouble>(numberofnodes_analysistype);
-	Vector<IssmDouble>* vspcvy			= new Vector<IssmDouble>(numberofnodes_analysistype);
-	Vector<IssmDouble>* vspcvxflag	= new Vector<IssmDouble>(numberofnodes_analysistype);
-	Vector<IssmDouble>* vspcvyflag	= new Vector<IssmDouble>(numberofnodes_analysistype);
-	
+
+	/*Get vertices coordinates of the new partition*/
+	newx=xNew<IssmDouble>(newnumberofvertices);//just the new partition
+	newy=xNew<IssmDouble>(newnumberofvertices);//just the new partition
+	for(int i=0;i<newnumberofvertices;i++){//just the new partition
+		Vertex* vertex=(Vertex*)newfemmodel_vertices->GetObjectByOffset(i);	
+		/*Attention: no spherical coordinates*/
+		newx[i]=vertex->GetX();
+		newy[i]=vertex->GetY();
+	}
+
+	/*Get spcvx and spcvy of old mesh*/
 	for(int i=0;i<this->constraints->Size();i++){
-		SpcStatic* spc			= xDynamicCast<SpcStatic*>(this->constraints->GetObjectByOffset(i));
-		int dof					= spc->GetDof();
-		int node					= spc->GetNodeId();
-		IssmDouble spcvalue	= spc->GetValue(); 
+		
+		Constraint* constraint=(Constraint*)constraints->GetObjectByOffset(i);
+		if(!constraint->InAnalysis(analysis_enum)) _error_("AMR create constraints for "<<EnumToStringx(analysis_enum)<<" not supported yet!\n");
+
+		SpcStatic* spcstatic = xDynamicCast<SpcStatic*>(constraint);
+		int dof					= spcstatic->GetDof();
+		int node					= spcstatic->GetNodeId();
+		IssmDouble spcvalue	= spcstatic->GetValue(); 
 		int nodeindex			= node-1;
 		
+		/*vx and vx flag insertion*/
 		if(dof==0) {//vx
-			vspcvx->SetValue(nodeindex,spcvalue,INS_VAL);
-			vspcvxflag->SetValue(nodeindex,1,INS_VAL);
+			vspc->SetValue(nodeindex*numberofcols,spcvalue,INS_VAL);    //vx
+			vspc->SetValue(nodeindex*numberofcols+dofpernode,1,INS_VAL);//vxflag
 		} 
+		/*vy and vy flag insertion*/
 		if(dof==1){//vy
-			vspcvy->SetValue(nodeindex,spcvalue,INS_VAL);
-			vspcvyflag->SetValue(nodeindex,1,INS_VAL);
-		}
-	}
-
-	/*Assemble*/
-	vspcvx->Assemble();
-	vspcvy->Assemble();
-	vspcvxflag->Assemble();
-	vspcvyflag->Assemble();
-
-	/*Serialize*/
-	spcvx		 = vspcvx->ToMPISerial();
-	spcvy		 = vspcvy->ToMPISerial();
-	spcvxflag = vspcvxflag->ToMPISerial();
-	spcvyflag = vspcvyflag->ToMPISerial();
-	
-	IssmDouble *newspcvx		 = NULL;
-	IssmDouble *newspcvy		 = NULL;
-	IssmDouble *newspcvxflag = NULL;
-	IssmDouble *newspcvyflag = NULL;
-	int nods_data				 = numberofvertices;
-	int nels_data				 = numberofelements;
-	int M_data					 = numberofvertices;
-	int N_data					 = 1;
-	int N_interp				 = newnumberofvertices;
-
-  /*Interpolate spcvx and spcvy in the new mesh*/
-	InterpFromMeshToMesh2dx(&newspcvx,elementslist,x,y,nods_data,nels_data,spcvx,M_data,N_data,newx,newy,N_interp,NULL);
-	InterpFromMeshToMesh2dx(&newspcvy,elementslist,x,y,nods_data,nels_data,spcvy,M_data,N_data,newx,newy,N_interp,NULL);
-	InterpFromMeshToMesh2dx(&newspcvxflag,elementslist,x,y,nods_data,nels_data,spcvxflag,M_data,N_data,newx,newy,N_interp,NULL);
-	InterpFromMeshToMesh2dx(&newspcvyflag,elementslist,x,y,nods_data,nels_data,spcvyflag,M_data,N_data,newx,newy,N_interp,NULL);
-
-	int count					= 0;
-	IssmDouble eps				= 1.e-8;
-
+			vspc->SetValue(nodeindex*numberofcols+1,spcvalue,INS_VAL);	//vy
+			vspc->SetValue(nodeindex*numberofcols+dofpernode+1,1,INS_VAL);//vyflag
+		}
+	}
+
+	/*Assemble and serialize*/
+	vspc->Assemble();
+	spc=vspc->ToMPISerial();
+
+	/*Interpolate spc values and flags in the new partition*/
+	InterpFromMeshToMesh2dx(&newspc,elementslist,x,y,numberofvertices,numberofelements,
+								spc,numberofvertices,numberofcols,
+								newx,newy,newnumberofvertices,NULL);
+	
 	/*Now, insert the interpolated constraints in the data set (constraints)*/
-	for(int i=0;i<newnumberofvertices;i++){
-		if(my_vertices[i]){ 
-			/*spcvx*/
-			if(!xIsNan<IssmDouble>(newspcvx[i]) && newspcvxflag[i]>(1-eps)){
-				constraints->AddObject(new SpcStatic(constraintcounter+count+1,nodecounter+i+1,0,newspcvx[i],StressbalanceAnalysisEnum));
-				//add count'th spc, on node i+1, setting dof 1 to vx.
-				count++;
-			}
-		}
-	}
 	count=0;
-	for(int i=0;i<newnumberofvertices;i++){
-		if(my_vertices[i]){
-			/*spcvy*/
-			if(!xIsNan<IssmDouble>(newspcvy[i]) && newspcvyflag[i]>(1-eps) ){
-				constraints->AddObject(new SpcStatic(constraintcounter+count+1,nodecounter+i+1,1,newspcvy[i],StressbalanceAnalysisEnum)); 
-				//add count'th spc, on node i+1, setting dof 1 to vx.
-				count++;
-			}
+	for(int i=0;i<newnumberofvertices;i++){//just in the new partition
+		Vertex* vertex=(Vertex*)newfemmodel_vertices->GetObjectByOffset(i);
+		/*spcvx*/
+		if(!xIsNan<IssmDouble>(newspc[i*numberofcols]) && newspc[i*numberofcols+dofpernode]>(1-eps)){
+			newfemmodel_constraints->AddObject(new SpcStatic(constraintcounter+count+1,nodecounter+vertex->Sid()+1,0,newspc[i*numberofcols],analysis_enum));
+			//add count'th spc, on node i+1, setting dof 1 to vx.
+			count++;
+		}
+	}
+	count=0;
+	for(int i=0;i<newnumberofvertices;i++){//just in the new partition
+		Vertex* vertex=(Vertex*)newfemmodel_vertices->GetObjectByOffset(i);
+		/*spcvy*/
+		if(!xIsNan<IssmDouble>(newspc[i*numberofcols+1]) && newspc[i*numberofcols+dofpernode+1]>(1-eps) ){
+			newfemmodel_constraints->AddObject(new SpcStatic(constraintcounter+count+1,nodecounter+vertex->Sid()+1,1,newspc[i*numberofcols+1],analysis_enum)); 
+			//add count'th spc, on node i+1, setting dof 1 to vx.
+			count++;
 		}
 	}
@@ -3892,17 +3451,9 @@
 	xDelete<IssmDouble>(z);
 	xDelete<int>(elementslist);
-	xDelete<IssmDouble>(spcvx);
-	xDelete<IssmDouble>(spcvy);
-	xDelete<IssmDouble>(spcvxflag);
-	xDelete<IssmDouble>(spcvyflag);
-	xDelete<IssmDouble>(newspcvx);
-	xDelete<IssmDouble>(newspcvy);
-	xDelete<IssmDouble>(newspcvxflag);
-	xDelete<IssmDouble>(newspcvyflag);
-	delete vspcvx;
-	delete vspcvy;	
-	delete vspcvxflag;
-	delete vspcvyflag;
-
+	xDelete<IssmDouble>(spc);
+	xDelete<IssmDouble>(newspc);
+	xDelete<IssmDouble>(newx);
+	xDelete<IssmDouble>(newy);
+	delete vspc;
 }
 /*}}}*/
@@ -4003,6 +3554,1775 @@
 	xDelete<int>(npart);	    
 	xDelete<int>(index);
-
+}
+/*}}}*/
+void FemModel::SmoothedDeviatoricStressTensor(IssmDouble** ptauxx,IssmDouble** ptauyy,IssmDouble** ptauxy){/*{{{*/
+	
+	int elementswidth							= this->GetElementsWidth();//just 2D mesh, tria elements
+   int numberofvertices						= this->vertices->NumberOfVertices();
+   IssmDouble weight 						= 0.;
+	IssmDouble*	tauxx							= NULL; 
+	IssmDouble*	tauyy							= NULL; 
+	IssmDouble*	tauxy							= NULL; 
+   IssmDouble* totalweight 				= NULL;
+	IssmDouble* deviatoricstressxx 		= xNew<IssmDouble>(elementswidth);
+   IssmDouble* deviatoricstressyy 		= xNew<IssmDouble>(elementswidth);
+   IssmDouble* deviatoricstressxy 		= xNew<IssmDouble>(elementswidth);
+   int* elem_vertices 						= xNew<int>(elementswidth);
+   Vector<IssmDouble>* vectauxx			= new Vector<IssmDouble>(numberofvertices);
+   Vector<IssmDouble>* vectauyy			= new Vector<IssmDouble>(numberofvertices);
+   Vector<IssmDouble>* vectauxy			= new Vector<IssmDouble>(numberofvertices);
+   Vector<IssmDouble>* vectotalweight	= new Vector<IssmDouble>(numberofvertices);
+	
+	/*Update the Deviatoric Stress tensor over the elements*/
+	this->DeviatoricStressx();
+	
+   /*Calculate the Smoothed Deviatoric Stress tensor*/
+	for(int i=0;i<this->elements->Size();i++){
+      Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
+      element->GetInputListOnVertices(deviatoricstressxx,DeviatoricStressxxEnum);
+      element->GetInputListOnVertices(deviatoricstressyy,DeviatoricStressyyEnum);
+      element->GetInputListOnVertices(deviatoricstressxy,DeviatoricStressxyEnum);
+      element->GetVerticesSidList(elem_vertices);
+
+		/*weight to calculate the smoothed deviatoric stress*/
+		Tria* triaelement = xDynamicCast<Tria*>(element);
+		weight				= triaelement->GetArea();//the tria area is a choice for the weight
+
+      /*taux xx*/
+		vectauxx->SetValue(elem_vertices[0],weight*deviatoricstressxx[0],ADD_VAL);
+      vectauxx->SetValue(elem_vertices[1],weight*deviatoricstressxx[1],ADD_VAL);
+      vectauxx->SetValue(elem_vertices[2],weight*deviatoricstressxx[2],ADD_VAL);
+      /*tau yy*/
+		vectauyy->SetValue(elem_vertices[0],weight*deviatoricstressyy[0],ADD_VAL);
+	   vectauyy->SetValue(elem_vertices[1],weight*deviatoricstressyy[1],ADD_VAL);
+      vectauyy->SetValue(elem_vertices[2],weight*deviatoricstressyy[2],ADD_VAL);
+      /*tau xy*/
+		vectauxy->SetValue(elem_vertices[0],weight*deviatoricstressxy[0],ADD_VAL);
+      vectauxy->SetValue(elem_vertices[1],weight*deviatoricstressxy[1],ADD_VAL);
+      vectauxy->SetValue(elem_vertices[2],weight*deviatoricstressxy[2],ADD_VAL);
+		/*total weight*/
+		vectotalweight->SetValue(elem_vertices[0],weight,ADD_VAL);
+      vectotalweight->SetValue(elem_vertices[1],weight,ADD_VAL);
+      vectotalweight->SetValue(elem_vertices[2],weight,ADD_VAL);
+   }
+
+   /*Assemble*/
+   vectauxx->Assemble();
+   vectauyy->Assemble();
+   vectauxy->Assemble();
+   vectotalweight->Assemble();
+
+   /*Serialize*/
+   tauxx			= vectauxx->ToMPISerial();
+   tauyy			= vectauyy->ToMPISerial();
+   tauxy			= vectauxy->ToMPISerial();
+   totalweight	= vectotalweight->ToMPISerial();
+
+	/*Divide for the total weight*/
+	for(int i=0;i<numberofvertices;i++){
+		_assert_(totalweight[i]>0);	
+		tauxx[i] = tauxx[i]/totalweight[i];
+		tauyy[i] = tauyy[i]/totalweight[i];
+		tauxy[i] = tauxy[i]/totalweight[i];
+	}
+
+	/*Set output*/
+	(*ptauxx) = tauxx;
+	(*ptauyy) = tauyy;
+	(*ptauxy) = tauxy;
+
+   /*Cleanup*/
+   delete vectauxx;
+   delete vectauyy;
+   delete vectauxy;
+	delete vectotalweight;
+   xDelete<IssmDouble>(deviatoricstressxx);
+   xDelete<IssmDouble>(deviatoricstressyy);
+   xDelete<IssmDouble>(deviatoricstressxy);
+   xDelete<IssmDouble>(totalweight);
+   xDelete<int>(elem_vertices);
+}
+/*}}}*/
+void FemModel::ZZErrorEstimator(IssmDouble** pelementerror){/*{{{*/
+
+	/*Compute the Zienkiewicz and Zhu (ZZ) error estimator for the deviatoric stress tensor. 
+	 * Ref.: Zienkiewicz and Zhu, A Simple Error Estimator and Adaptive Procedure for Practical Engineering Analysis, Int. J. Numer. Meth. Eng, 1987*/
+
+	IssmDouble Jdet,error,ftxx,ftyy,ftxy;
+	int sid;
+	int numnodes							= this->GetElementsWidth();//just 2D mesh, tria elements, P1
+	int numberofelements 				= this->elements->NumberOfElements();
+	IssmDouble* xyz_list 				= NULL;
+	IssmDouble* smoothedtauxx			= NULL;
+	IssmDouble* smoothedtauyy			= NULL;
+	IssmDouble* smoothedtauxy			= NULL;
+	IssmDouble* tauxx						= xNew<IssmDouble>(numnodes);
+   IssmDouble* tauyy						= xNew<IssmDouble>(numnodes);
+   IssmDouble* tauxy						= xNew<IssmDouble>(numnodes);
+	IssmDouble* basis 					= xNew<IssmDouble>(numnodes);
+	int* elem_vertices 					= xNew<int>(numnodes);
+   Vector<IssmDouble>* velementerror= new Vector<IssmDouble>(numberofelements);
+
+	/*Get smoothed deviatoric stress tensor*/
+	this->SmoothedDeviatoricStressTensor(&smoothedtauxx,&smoothedtauyy,&smoothedtauxy);
+	
+	/*Integrate the error over elements*/
+   for(int i=0;i<this->elements->Size();i++){
+      Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
+		element->GetInputListOnVertices(tauxx,DeviatoricStressxxEnum);
+      element->GetInputListOnVertices(tauyy,DeviatoricStressyyEnum);
+      element->GetInputListOnVertices(tauxy,DeviatoricStressxyEnum);
+      element->GetVerticesSidList(elem_vertices);
+		
+		/*Integrate*/
+		element->GetVerticesCoordinates(&xyz_list);
+		Gauss* gauss=element->NewGauss(2);
+   	error=0.;
+		for(int ig=gauss->begin();ig<gauss->end();ig++){
+      	gauss->GaussPoint(ig);
+			element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+			element->NodalFunctions(basis,gauss);
+			ftxx=0;ftyy=0;ftxy=0;
+			for(int n=0;n<numnodes;n++) {
+				ftxx+=(tauxx[n]-smoothedtauxx[elem_vertices[n]])*basis[n];
+				ftyy+=(tauyy[n]-smoothedtauyy[elem_vertices[n]])*basis[n];
+				ftxy+=(tauxy[n]-smoothedtauxy[elem_vertices[n]])*basis[n];
+			}
+			error+=Jdet*gauss->weight*( pow(ftxx,2)+pow(ftyy,2)+pow(ftxy,2) ); //e^2 
+		}
+		/*Set the error in the global vector*/	
+      sid=element->Sid();
+		error = sqrt(error);//sqrt(e^2)
+		velementerror->SetValue(sid,error,INS_VAL);
+		/*Cleanup intermediaries*/
+		xDelete<IssmDouble>(xyz_list);
+		delete gauss;
+	}
+
+	/*Assemble*/
+   velementerror->Assemble();
+
+   /*Serialize and set output*/
+   (*pelementerror)=velementerror->ToMPISerial();
+	
+	/*Cleanup*/
+	xDelete<IssmDouble>(smoothedtauxx);
+	xDelete<IssmDouble>(smoothedtauyy);
+	xDelete<IssmDouble>(smoothedtauxy);
+	xDelete<IssmDouble>(tauxx);
+	xDelete<IssmDouble>(tauyy);
+	xDelete<IssmDouble>(tauxy);
+	xDelete<IssmDouble>(basis);
+	xDelete<int>(elem_vertices);
+	delete velementerror;
+}
+/*}}}*/
+void FemModel::SmoothedGradThickness(IssmDouble** pdHdx,IssmDouble** pdHdy){/*{{{*/
+
+   int elementswidth                   = this->GetElementsWidth();//just 2D mesh, tria elements
+   int numberofvertices                = this->vertices->NumberOfVertices();
+
+   IssmDouble weight                   = 0.;
+   IssmDouble* dHdx                    = NULL;
+   IssmDouble* dHdy                    = NULL;
+   IssmDouble* totalweight             = NULL;
+   IssmDouble* xyz_list                = NULL;
+   IssmDouble* H                       = xNew<IssmDouble>(elementswidth);
+   IssmDouble* GradH                   = xNew<IssmDouble>(2);
+   int* elem_vertices                  = xNew<int>(elementswidth);
+   Vector<IssmDouble>* vecdHdx         = new Vector<IssmDouble>(numberofvertices);
+   Vector<IssmDouble>* vecdHdy         = new Vector<IssmDouble>(numberofvertices);
+   Vector<IssmDouble>* vectotalweight  = new Vector<IssmDouble>(numberofvertices);
+
+   for(int i=0;i<this->elements->Size();i++){
+      Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
+      element->GetInputListOnVertices(H,ThicknessEnum);
+      element->GetVerticesSidList(elem_vertices);
+      element->GetVerticesCoordinates(&xyz_list);
+
+      /*Get the gradient of thickness at the center point (in fact, GradH is constante over the element)*/
+      Gauss* gauss=element->NewGauss(1);
+      gauss->GaussPoint(gauss->begin());
+      element->ValueP1DerivativesOnGauss(GradH,H,xyz_list,gauss);
+
+      /*weight to calculate the smoothed grad H*/
+      Tria* triaelement = xDynamicCast<Tria*>(element);
+      weight            = triaelement->GetArea();//the tria area is a choice for the weight
+      
+		/*dH/dx*/
+      vecdHdx->SetValue(elem_vertices[0],weight*GradH[0],ADD_VAL);
+      vecdHdx->SetValue(elem_vertices[1],weight*GradH[0],ADD_VAL);
+      vecdHdx->SetValue(elem_vertices[2],weight*GradH[0],ADD_VAL);
+      /*dH/dy*/
+      vecdHdy->SetValue(elem_vertices[0],weight*GradH[1],ADD_VAL);
+      vecdHdy->SetValue(elem_vertices[1],weight*GradH[1],ADD_VAL);
+      vecdHdy->SetValue(elem_vertices[2],weight*GradH[1],ADD_VAL);
+      /*total weight*/
+      vectotalweight->SetValue(elem_vertices[0],weight,ADD_VAL);
+      vectotalweight->SetValue(elem_vertices[1],weight,ADD_VAL);
+      vectotalweight->SetValue(elem_vertices[2],weight,ADD_VAL);
+      /*Cleanup intermediaries*/
+      xDelete<IssmDouble>(xyz_list);
+      delete gauss;
+   }
+
+   /*Assemble*/
+   vecdHdx->Assemble();
+   vecdHdy->Assemble();
+   vectotalweight->Assemble();
+
+   /*Serialize*/
+   dHdx        = vecdHdx->ToMPISerial();
+   dHdy        = vecdHdy->ToMPISerial();
+   totalweight = vectotalweight->ToMPISerial();
+
+   /*Divide for the total weight*/
+   for(int i=0;i<numberofvertices;i++){
+      _assert_(totalweight[i]>0);
+      dHdx[i] = dHdx[i]/totalweight[i];
+      dHdy[i] = dHdy[i]/totalweight[i];
+   }
+
+   /*Set output*/
+   (*pdHdx) = dHdx;
+   (*pdHdy) = dHdy;
+
+ 	/*Cleanup*/
+   delete vecdHdx;
+   delete vecdHdy;
+   delete vectotalweight;
+   xDelete<IssmDouble>(H);
+   xDelete<IssmDouble>(GradH);
+   xDelete<IssmDouble>(totalweight);
+   xDelete<int>(elem_vertices);
+}
+/*}}}*/
+void FemModel::ThicknessZZErrorEstimator(IssmDouble** pelementerror){/*{{{*/
+   /*Compute the Zienkiewicz and Zhu (ZZ) error estimator for the thickness
+    * Ref.: Zienkiewicz and Zhu, A Simple Error Estimator and Adaptive Procedure for Practical Engineering Analysis, Int. J. Numer. Meth. Eng, 1987*/
+
+   IssmDouble Jdet,error,fdHdx,fdHdy;
+   int sid;
+   int numnodes                     = this->GetElementsWidth();//just 2D mesh, tria elements, P1
+   int numberofelements             = this->elements->NumberOfElements();
+   IssmDouble* xyz_list             = NULL;
+   IssmDouble* smoothed_dHdx        = NULL;
+   IssmDouble* smoothed_dHdy        = NULL;
+   IssmDouble* H                    = xNew<IssmDouble>(numnodes);
+   IssmDouble* GradH                = xNew<IssmDouble>(2);
+   IssmDouble* basis                = xNew<IssmDouble>(numnodes);
+   int* elem_vertices               = xNew<int>(numnodes);
+   Vector<IssmDouble>* velementerror= new Vector<IssmDouble>(numberofelements);
+
+   /*Get smoothed deviatoric stress tensor*/
+   this->SmoothedGradThickness(&smoothed_dHdx,&smoothed_dHdy);
+   
+	/*Integrate the error over elements*/
+   for(int i=0;i<this->elements->Size();i++){
+      Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
+      element->GetInputListOnVertices(H,ThicknessEnum);
+      element->GetVerticesSidList(elem_vertices);
+      element->GetVerticesCoordinates(&xyz_list);
+      /*Get the gradient of thickness*/
+      Gauss* gaussH=element->NewGauss(1);
+      gaussH->GaussPoint(gaussH->begin());
+      element->ValueP1DerivativesOnGauss(GradH,H,xyz_list,gaussH);
+      /*Integrate*/
+      Gauss* gauss=element->NewGauss(2);
+      error=0.;
+      for(int ig=gauss->begin();ig<gauss->end();ig++){
+         gauss->GaussPoint(ig);
+         element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+         element->NodalFunctions(basis,gauss);
+         fdHdx=0;fdHdy=0;
+         for(int n=0;n<numnodes;n++) {
+            fdHdx+=(GradH[0]-smoothed_dHdx[elem_vertices[n]])*basis[n];
+            fdHdy+=(GradH[1]-smoothed_dHdy[elem_vertices[n]])*basis[n];
+         }
+         error+=Jdet*gauss->weight*(pow(fdHdx,2)+pow(fdHdy,2) ); //e^2
+      }
+      /*Set the error in the global vector*/
+      sid=element->Sid();
+		error = sqrt(error); //sqrt( e^2 )
+      velementerror->SetValue(sid,error,INS_VAL);
+      /*Cleanup intermediaries*/
+      xDelete<IssmDouble>(xyz_list);
+      delete gaussH;
+      delete gauss;
+   }
+
+   /*Assemble*/
+   velementerror->Assemble();
+
+   /*Serialize and set output*/
+   (*pelementerror)=velementerror->ToMPISerial();
+
+   /*Cleanup*/
+   xDelete<IssmDouble>(smoothed_dHdx);
+   xDelete<IssmDouble>(smoothed_dHdy);
+   xDelete<IssmDouble>(H);
+   xDelete<IssmDouble>(GradH);
+   xDelete<IssmDouble>(basis);
+   xDelete<int>(elem_vertices);
+   delete velementerror;
+}
+/*}}}*/
+void FemModel::MeanGroundedIceLevelSet(IssmDouble** pmasklevelset){/*{{{*/
+
+   int elementswidth                   = this->GetElementsWidth();
+   int numberofelements                = this->elements->NumberOfElements();
+   IssmDouble* elementlevelset         = xNew<IssmDouble>(elementswidth);
+   Vector<IssmDouble>* vmasklevelset   = new Vector<IssmDouble>(numberofelements);
+
+   for(int i=0;i<this->elements->Size();i++){
+      Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
+      element->GetInputListOnVertices(elementlevelset,MaskGroundediceLevelsetEnum);
+      int sid = element->Sid();
+      vmasklevelset->SetValue(sid,(elementlevelset[0]+elementlevelset[1]+elementlevelset[2])/3.,INS_VAL);
+   }
+
+   /*Assemble*/
+   vmasklevelset->Assemble();
+
+   /*Serialize and set output*/
+   (*pmasklevelset)=vmasklevelset->ToMPISerial();
+
+   /*Cleanup*/
+   xDelete<IssmDouble>(elementlevelset);
+   delete vmasklevelset;
+}
+/*}}}*/
+void FemModel::GetElementCenterCoordinates(IssmDouble** pxc,IssmDouble** pyc){/*{{{*/
+
+	/*Intermediaries*/
+   int elementswidth          = this->GetElementsWidth();
+   int numberofelements       = this->elements->NumberOfElements();
+   int* elem_vertices			= xNew<int>(elementswidth);
+   Vector<IssmDouble>* vxc		= new Vector<IssmDouble>(numberofelements);
+   Vector<IssmDouble>* vyc		= new Vector<IssmDouble>(numberofelements);
+	IssmDouble* x					= NULL;
+	IssmDouble* y					= NULL;
+	IssmDouble* z					= NULL;	
+	IssmDouble* xyz_list			= NULL;
+	IssmDouble x1,y1,x2,y2,x3,y3;
+
+	/*Insert the element center coordinates*/
+   for(int i=0;i<this->elements->Size();i++){
+      Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
+      //element->GetVerticesSidList(elem_vertices);
+      int sid = element->Sid();
+		element->GetVerticesCoordinates(&xyz_list); 
+		x1 = xyz_list[3*0+0];y1 = xyz_list[3*0+1];
+		x2 = xyz_list[3*1+0];y2 = xyz_list[3*1+1];
+		x3 = xyz_list[3*2+0];y3 = xyz_list[3*2+1];
+		vxc->SetValue(sid,(x1+x2+x3)/3.,INS_VAL);
+      vyc->SetValue(sid,(y1+y2+y3)/3.,INS_VAL);
+   }
+
+   /*Assemble*/
+   vxc->Assemble();
+   vyc->Assemble();
+
+   /*Serialize and set output*/
+   (*pxc)=vxc->ToMPISerial();
+   (*pyc)=vyc->ToMPISerial();
+
+   /*Cleanup*/
+	xDelete<IssmDouble>(x);
+	xDelete<IssmDouble>(y);
+	xDelete<IssmDouble>(z);
+	xDelete<IssmDouble>(xyz_list);
+   xDelete<int>(elem_vertices);
+   delete vxc;
+   delete vyc;
+}
+/*}}}*/
+void FemModel::GetZeroLevelSetPoints(IssmDouble** pzerolevelset_points,int &numberofpoints,int levelset_type){/*{{{*/
+
+	/*Here, "zero level set" means grounding line or ice front, depending on the level set type*/
+	/*pzerolevelset_points are the element center points with zero level set. X and Y coords*/
+	if(levelset_type!=MaskGroundediceLevelsetEnum && levelset_type!=MaskIceLevelsetEnum){
+		_error_("level set type not implemented yet!");
+	}
+	
+	/*Outputs*/
+	IssmDouble* zerolevelset_points			= NULL;
+	int npoints										= 0;
+	
+	/*Intermediaries*/
+ 	int elementswidth                   	= this->GetElementsWidth();
+   int numberofelements                	= this->elements->NumberOfElements();
+	int* elem_vertices         				= xNew<int>(elementswidth);
+   IssmDouble* levelset      					= xNew<IssmDouble>(elementswidth);
+   IssmDouble* xyz_list							= NULL;
+	Vector<IssmDouble>* vx_zerolevelset		= new Vector<IssmDouble>(numberofelements);
+	Vector<IssmDouble>* vy_zerolevelset		= new Vector<IssmDouble>(numberofelements);
+	IssmDouble* x_zerolevelset					= NULL;
+	IssmDouble* y_zerolevelset					= NULL;
+	int count,sid;
+	IssmDouble xc,yc,x1,y1,x2,y2,x3,y3;
+	
+	/*Use the element center coordinate if level set is zero (grounding line or ice front), otherwise set NAN*/
+   for(int i=0;i<this->elements->Size();i++){
+      Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
+      element->GetInputListOnVertices(levelset,levelset_type);
+		element->GetVerticesSidList(elem_vertices);
+		sid= element->Sid();
+		element->GetVerticesCoordinates(&xyz_list); 
+		x1 = xyz_list[3*0+0];y1 = xyz_list[3*0+1];
+		x2 = xyz_list[3*1+0];y2 = xyz_list[3*1+1];
+		x3 = xyz_list[3*2+0];y3 = xyz_list[3*2+1];
+		xc	= NAN;
+		yc	= NAN;	
+     	Tria* tria 	= xDynamicCast<Tria*>(element);
+		if(tria->IsIceInElement()){/*verify if there is ice in the element*/
+			if(levelset[0]*levelset[1]<0. || levelset[0]*levelset[2]<0. ||	
+				abs(levelset[0]*levelset[1])<DBL_EPSILON || abs(levelset[0]*levelset[2])<DBL_EPSILON) {
+				xc=(x1+x2+x3)/3.;
+				yc=(y1+y2+y3)/3.;
+			}
+		}
+		vx_zerolevelset->SetValue(sid,xc,INS_VAL);
+		vy_zerolevelset->SetValue(sid,yc,INS_VAL);
+		xDelete<IssmDouble>(xyz_list);
+	}
+   /*Assemble and serialize*/
+   vx_zerolevelset->Assemble();
+   vy_zerolevelset->Assemble();
+   x_zerolevelset=vx_zerolevelset->ToMPISerial();
+   y_zerolevelset=vy_zerolevelset->ToMPISerial();
+
+	/*Find the number of points*/
+	npoints=0;
+	for(int i=0;i<numberofelements;i++) if(!xIsNan<IssmDouble>(x_zerolevelset[i])) npoints++;
+
+	/*Keep just the element center coordinates with zero level set (compact the structure)*/
+	zerolevelset_points=xNew<IssmDouble>(2*npoints);//x and y
+	count=0;
+	for(int i=0;i<numberofelements;i++){
+		if(!xIsNan<IssmDouble>(x_zerolevelset[i])){
+			zerolevelset_points[2*count]	 = x_zerolevelset[i];
+			zerolevelset_points[2*count+1] = y_zerolevelset[i];
+			count++;
+		}
+	}
+	
+	/*Assign outputs*/
+	numberofpoints				= npoints;
+	(*pzerolevelset_points) = zerolevelset_points;
+
+	/*Cleanup*/
+   xDelete<int>(elem_vertices);
+   xDelete<IssmDouble>(levelset);
+	xDelete<IssmDouble>(x_zerolevelset);
+	xDelete<IssmDouble>(y_zerolevelset);
+   xDelete<IssmDouble>(xyz_list);
+	delete vx_zerolevelset;
+	delete vy_zerolevelset;
 }
 /*}}}*/
 #endif
+
+#ifdef  _HAVE_DAKOTA_
+void FemModel::DakotaResponsesx(double* d_responses,char** responses_descriptors,int numresponsedescriptors,int d_numresponses){/*{{{*/
+
+	int        i,j;
+	int        my_rank;
+
+	/*intermediary: */
+	char   root[50];
+	int    index;
+	int    npart;
+	double femmodel_response;
+	int    flag;
+	double *vertex_response   = NULL;
+	double *qmu_response      = NULL;
+	double *responses_pointer = NULL;
+
+	/*retrieve npart: */
+	parameters->FindParam(&npart,QmuNumberofpartitionsEnum);
+	my_rank=IssmComm::GetRank();
+
+	/*save the d_responses pointer: */
+	responses_pointer=d_responses;
+
+	//watch out, we have more d_numresponses than numresponsedescriptors, because the responses have been expanded if they were scaled. 
+	//because we don't know the d_responses descriptors (the scaled ones) we can't key off them, so we will key off the responses_descriptors: */
+
+	for(i=0;i<numresponsedescriptors;i++){
+
+		flag=DescriptorIndex(root,&index,responses_descriptors[i]);
+
+		if(flag==ScaledEnum){
+
+			/*this response was scaled. pick up the response from the inputs: */
+			GetVectorFromInputsx(&vertex_response,this, StringToEnumx(root),VertexPIdEnum);
+
+			/*Now, average it onto the partition nodes: */
+			AverageOntoPartitionx(&qmu_response,elements,nodes,vertices,loads,materials,parameters,vertex_response);
+
+			/*Copy onto our dakota responses: */
+			if(my_rank==0){
+				/*plug response: */
+				for(j=0;j<npart;j++)responses_pointer[j]=qmu_response[j];
+
+				/*increment response_pointer :*/
+				responses_pointer+=npart;
+			}
+
+			/*Free ressources:*/
+			xDelete<double>(vertex_response);
+			xDelete<double>(qmu_response);
+
+		}
+		else if (flag==IndexedEnum){
+
+			/*indexed response: plug index into parameters and call response module: */
+			parameters->SetParam(index,IndexEnum);
+
+			this->Responsex(&femmodel_response,root);
+
+			if(my_rank==0){
+				/*plug response: */
+				responses_pointer[0]=femmodel_response;
+
+				/*increment response_pointer :*/
+				responses_pointer++;
+			}
+		}
+		else if (flag==NodalEnum){
+			_error_("nodal response functions not supported yet!");
+
+			/*increment response_pointer :*/
+			responses_pointer++;
+		}
+		else if (flag==RegularEnum){
+
+			/*perfectly normal response function: */
+			this->Responsex(&femmodel_response,root);
+
+			if(my_rank==0){
+				/*plug response: */
+				responses_pointer[0]=femmodel_response;
+
+				/*increment response_pointer :*/
+				responses_pointer++;
+			}
+		}
+		else _error_("flag type " << flag << " not supported yet for response analysis");
+	}
+
+	/*Synthesize echo: {{{*/
+	if(my_rank==0){
+		_printf_("   responses: " << d_numresponses << ": ");
+		for(i=0;i<d_numresponses-1;i++)_printf_(d_responses[i] << "|");
+		_printf_(d_responses[d_numresponses-1]);
+		_printf_("\n");
+	}
+	/*}}}*/
+
+}
+/*}}}*/
+#endif
+#ifdef _HAVE_GIAIVINS_
+void FemModel::Deflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt, IssmDouble* x, IssmDouble* y){ /*{{{*/
+
+	/*Go through elements, and add contribution from each element to the deflection vector wg:*/
+	for(int i=0;i<elements->Size();i++){
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
+		element->GiaDeflection(wg,dwgdt, x,y);
+	}
+}
+/*}}}*/
+#endif
+#ifdef _HAVE_ESA_
+void FemModel::EsaGeodetic2D(Vector<IssmDouble>* pUp, Vector<IssmDouble>* pNorth, Vector<IssmDouble>* pEast, Vector<IssmDouble>* pX, Vector<IssmDouble>* pY, IssmDouble* xx, IssmDouble* yy){/*{{{*/
+
+	int         ns,nsmax;
+	
+	/*Go through elements, and add contribution from each element to the deflection vector wg:*/
+	ns = elements->Size();
+	
+	/*Figure out max of ns: */
+	ISSM_MPI_Reduce(&ns,&nsmax,1,ISSM_MPI_INT,ISSM_MPI_MAX,0,IssmComm::GetComm());
+	ISSM_MPI_Bcast(&nsmax,1,ISSM_MPI_INT,0,IssmComm::GetComm());
+
+	/*Call the esa geodetic core: */
+	for(int i=0;i<nsmax;i++){
+		if(i<ns){
+			Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
+			element->EsaGeodetic2D(pUp,pNorth,pEast,pX,pY,xx,yy);
+		}
+		if(i%100==0){
+			pUp->Assemble();
+			pNorth->Assemble();
+			pEast->Assemble();
+			pX->Assemble();
+			pY->Assemble();
+		}
+	}
+	
+	/*One last time: */
+	pUp->Assemble();
+	pNorth->Assemble();
+	pEast->Assemble();
+	pX->Assemble();
+	pY->Assemble();
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(xx);
+	xDelete<IssmDouble>(yy);
+}
+/*}}}*/
+void FemModel::EsaGeodetic3D(Vector<IssmDouble>* pUp, Vector<IssmDouble>* pNorth, Vector<IssmDouble>* pEast, IssmDouble* latitude, IssmDouble* longitude, IssmDouble* radius, IssmDouble* xx, IssmDouble* yy, IssmDouble* zz){/*{{{*/
+
+	IssmDouble  eartharea=0;
+	IssmDouble  eartharea_cpu=0;
+
+	int         ns,nsmax;
+	
+	/*Go through elements, and add contribution from each element to the deflection vector wg:*/
+	ns = elements->Size();
+	
+	/*First, figure out the surface area of Earth: */ 
+	for(int i=0;i<ns;i++){
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
+		eartharea_cpu += element->GetAreaSpherical();
+	}
+	ISSM_MPI_Reduce (&eartharea_cpu,&eartharea,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&eartharea,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+
+	/*Figure out max of ns: */
+	ISSM_MPI_Reduce(&ns,&nsmax,1,ISSM_MPI_INT,ISSM_MPI_MAX,0,IssmComm::GetComm());
+	ISSM_MPI_Bcast(&nsmax,1,ISSM_MPI_INT,0,IssmComm::GetComm());
+
+	/*Call the esa geodetic core: */
+	for(int i=0;i<nsmax;i++){
+		if(i<ns){
+			Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
+			element->EsaGeodetic3D(pUp,pNorth,pEast,latitude,longitude,radius,xx,yy,zz,eartharea);
+		}
+		if(i%100==0){
+			pUp->Assemble();
+			pNorth->Assemble();
+			pEast->Assemble();
+		}
+	}
+	
+	/*One last time: */
+	pUp->Assemble();
+	pNorth->Assemble();
+	pEast->Assemble();
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(latitude);
+	xDelete<IssmDouble>(longitude);
+	xDelete<IssmDouble>(radius);
+	xDelete<IssmDouble>(xx);
+	xDelete<IssmDouble>(yy);
+	xDelete<IssmDouble>(zz);
+}
+/*}}}*/
+#endif
+#ifdef _HAVE_SEALEVELRISE_
+void FemModel::SealevelriseEustatic(Vector<IssmDouble>* pSgi, IssmDouble* peustatic, IssmDouble* latitude, IssmDouble* longitude, IssmDouble* radius) { /*{{{*/
+
+	/*serialized vectors:*/
+	IssmDouble  eustatic       = 0.;
+	IssmDouble  eustatic_cpu   = 0.;
+	IssmDouble  eustatic_cpu_e = 0.;
+	IssmDouble  oceanarea      = 0.;
+	IssmDouble  oceanarea_cpu  = 0.;
+	IssmDouble  eartharea      = 0.;
+	IssmDouble  eartharea_cpu  = 0.;
+	int         ns,nsmax;
+	
+	/*Go through elements, and add contribution from each element to the deflection vector wg:*/
+	ns = elements->Size();
+
+	/*First, figure out the area of the ocean, which is needed to compute the eustatic component: */
+	for(int i=0;i<ns;i++){
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
+		oceanarea_cpu += element->OceanArea();
+		eartharea_cpu += element->GetAreaSpherical();
+	}
+	ISSM_MPI_Reduce (&oceanarea_cpu,&oceanarea,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&oceanarea,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+	_assert_(oceanarea>0.);
+
+	ISSM_MPI_Reduce (&eartharea_cpu,&eartharea,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&eartharea,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+
+	/*Figure out max of ns: */
+	ISSM_MPI_Reduce(&ns,&nsmax,1,ISSM_MPI_INT,ISSM_MPI_MAX,0,IssmComm::GetComm());
+	ISSM_MPI_Bcast(&nsmax,1,ISSM_MPI_INT,0,IssmComm::GetComm());
+
+	/*Call the sea level rise core: */
+	for(int i=0;i<nsmax;i++){
+		if(i<ns){
+		
+			if(VerboseConvergence())if(i%100==0)_printf0_("\r" << "      convolution progress: " << (double)i/(double)ns*100 << "%  ");
+		
+			Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
+			element->SealevelriseEustatic(pSgi,&eustatic_cpu_e,latitude,longitude,radius,oceanarea,eartharea);
+			eustatic_cpu+=eustatic_cpu_e;
+		}
+		if(i%100==0)pSgi->Assemble();
+	}
+	if(VerboseConvergence())_printf0_("\n");
+		
+	/*One last time: */
+	pSgi->Assemble();
+
+	/*Sum all eustatic components from all cpus:*/
+	ISSM_MPI_Reduce (&eustatic_cpu,&eustatic,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&eustatic,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+	_assert_(!xIsNan<IssmDouble>(eustatic));
+
+	/*Assign output pointers:*/
+	*peustatic=eustatic;
+
+}
+/*}}}*/
+void FemModel::SealevelriseNonEustatic(Vector<IssmDouble>* pSgo, Vector<IssmDouble>* pSg_old, IssmDouble* latitude, IssmDouble* longitude, IssmDouble* radius, bool verboseconvolution){/*{{{*/
+
+	/*serialized vectors:*/
+	IssmDouble* Sg_old=NULL;
+	
+	IssmDouble  eartharea=0;
+	IssmDouble  eartharea_cpu=0;
+
+	int         ns,nsmax;
+	
+	/*Serialize vectors from previous iteration:*/
+	Sg_old=pSg_old->ToMPISerial();
+
+	/*Go through elements, and add contribution from each element to the deflection vector wg:*/
+	ns = elements->Size();
+
+	/*First, figure out the area of the ocean, which is needed to compute the eustatic component: */
+	for(int i=0;i<ns;i++){
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
+		eartharea_cpu += element->GetAreaSpherical();
+	}
+	
+	ISSM_MPI_Reduce (&eartharea_cpu,&eartharea,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&eartharea,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+
+	/*Figure out max of ns: */
+	ISSM_MPI_Reduce(&ns,&nsmax,1,ISSM_MPI_INT,ISSM_MPI_MAX,0,IssmComm::GetComm());
+	ISSM_MPI_Bcast(&nsmax,1,ISSM_MPI_INT,0,IssmComm::GetComm());
+
+	/*Call the sea level rise core: */
+	for(int i=0;i<nsmax;i++){
+		if(i<ns){
+			if(verboseconvolution)if(VerboseConvergence())if(i%100==0)_printf_("\r" << "      convolution progress: " << (double)i/(double)ns*100 << "%   ");
+			Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
+			element->SealevelriseNonEustatic(pSgo,Sg_old,latitude,longitude,radius,eartharea);
+		}
+		if(i%100==0)pSgo->Assemble();
+	}
+	if(verboseconvolution)if(VerboseConvergence())_printf_("\n");
+	
+	/*Free ressources:*/
+	xDelete<IssmDouble>(Sg_old);
+}
+/*}}}*/
+void FemModel::SealevelriseRotationalFeedback(Vector<IssmDouble>* pSgo_rot, Vector<IssmDouble>* pSg_old, IssmDouble* pIxz, IssmDouble* pIyz, IssmDouble* pIzz, IssmDouble* latitude, IssmDouble* longitude, IssmDouble* radius){/*{{{*/
+
+	/*serialized vectors:*/
+	IssmDouble* Sg_old=NULL;
+	IssmDouble  eartharea=0;
+	IssmDouble  eartharea_cpu=0;
+	IssmDouble	tide_love_h, tide_love_k, fluid_love, moi_e, moi_p, omega, g;
+	IssmDouble	load_love_k2 = -0.30922675; //degree 2 load Love number 
+	IssmDouble	m1, m2, m3; 
+	IssmDouble	lati, longi, radi, value; 
+
+	/*Serialize vectors from previous iteration:*/
+	Sg_old=pSg_old->ToMPISerial();
+
+	/*First, figure out the area of the ocean, which is needed to compute the eustatic component: */
+	for(int i=0;i<elements->Size();i++){
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
+		eartharea_cpu += element->GetAreaSpherical();
+	}
+	ISSM_MPI_Reduce (&eartharea_cpu,&eartharea,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&eartharea,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+
+	IssmDouble moi_list[3]={0,0,0}; 
+	IssmDouble moi_list_cpu[3]={0,0,0}; 
+	for(int i=0;i<elements->Size();i++){
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
+		element->SealevelriseMomentOfInertia(&moi_list[0],Sg_old,eartharea);
+		moi_list_cpu[0] += moi_list[0]; 
+		moi_list_cpu[1] += moi_list[1]; 
+		moi_list_cpu[2] += moi_list[2]; 
+	}
+	ISSM_MPI_Reduce (&moi_list_cpu[0],&moi_list[0],1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&moi_list[0],1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+	// 	
+	ISSM_MPI_Reduce (&moi_list_cpu[1],&moi_list[1],1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&moi_list[1],1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+	// 	
+	ISSM_MPI_Reduce (&moi_list_cpu[2],&moi_list[2],1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&moi_list[2],1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+	
+	/*pull out some useful parameters: */
+	parameters->FindParam(&tide_love_h,SealevelriseTidalLoveHEnum);
+	parameters->FindParam(&tide_love_k,SealevelriseTidalLoveKEnum);
+	parameters->FindParam(&fluid_love,SealevelriseFluidLoveEnum);
+	parameters->FindParam(&moi_e,SealevelriseEquatorialMoiEnum);
+	parameters->FindParam(&moi_p,SealevelrisePolarMoiEnum);
+	parameters->FindParam(&omega,SealevelriseAngularVelocityEnum);
+
+	/*compute perturbation terms for angular velocity vector: */
+	m1 = 1/(1-tide_love_k/fluid_love) * (1+load_love_k2)/(moi_p-moi_e) * moi_list[0]; 
+	m2 = 1/(1-tide_love_k/fluid_love) * (1+load_love_k2)/(moi_p-moi_e) * moi_list[1]; 
+	m3 = -(1+load_love_k2)/moi_p * moi_list[2];	// term associated with fluid number (3-order-of-magnitude smaller) is negelected  
+
+	/* Green's function (1+k_2-h_2/g): checked against Glenn Milne's thesis Chapter 3 (eqs: 3.3-4, 3.10-11)
+	 * Perturbation terms for angular velocity vector (m1, m2, m3): checked against Mitrovica (2005 Appendix) & Jensen et al (2013 Appendix A3) 
+	 * Sea level rotational feedback: checked against GMD eqs 8-9 (only first order terms, i.e., degree 2 order 0 & 1 considered) 
+	 * all DONE in Geographic coordinates: theta \in [-90,90], lambda \in [-180 180] 
+	 */
+	for(int i=0;i<vertices->Size();i++){
+		int sid;
+		//Vertex* vertex=(Vertex*)vertices->GetObjectByOffset(i);
+		Vertex* vertex=xDynamicCast<Vertex*>(vertices->GetObjectByOffset(i));
+		sid=vertex->Sid();
+
+		lati=latitude[sid]/180*PI;	longi=longitude[sid]/180*PI; radi=radius[sid];
+
+		/*only first order terms are considered now: */ 
+		value=((1.0+tide_love_k-tide_love_h)/9.81)*pow(omega*radi,2.0)*
+						(-m3/6.0 + 0.5*m3*cos(2.0*lati) - 0.5*sin(2.*lati)*(m1*cos(longi)+m2*sin(longi))); 
+	
+		pSgo_rot->SetValue(sid,value,INS_VAL); //INS_VAL ensures that you don't add several times
+	}
+
+	/*Assemble mesh velocity*/
+	pSgo_rot->Assemble();
+	
+	/*Assign output pointers:*/
+	*pIxz=moi_list[0];
+	*pIyz=moi_list[1];
+	*pIzz=moi_list[2];
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(Sg_old);
+	
+}
+/*}}}*/
+void FemModel::SealevelriseGeodetic(Vector<IssmDouble>* pUp, Vector<IssmDouble>* pNorth, Vector<IssmDouble>* pEast, Vector<IssmDouble>* pSg, IssmDouble* latitude, IssmDouble* longitude, IssmDouble* radius, IssmDouble* xx, IssmDouble* yy, IssmDouble* zz){/*{{{*/
+
+	/*serialized vectors:*/
+	IssmDouble* Sg=NULL;
+	
+	IssmDouble  eartharea=0;
+	IssmDouble  eartharea_cpu=0;
+
+	int         ns,nsmax;
+	
+	/*Serialize vectors from previous iteration:*/
+	Sg=pSg->ToMPISerial();
+
+	/*Go through elements, and add contribution from each element to the deflection vector wg:*/
+	ns = elements->Size();
+	
+	/*First, figure out the area of the ocean, which is needed to compute the eustatic component: */
+	for(int i=0;i<ns;i++){
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
+		eartharea_cpu += element->GetAreaSpherical();
+	}
+	ISSM_MPI_Reduce (&eartharea_cpu,&eartharea,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&eartharea,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+
+	/*Figure out max of ns: */
+	ISSM_MPI_Reduce(&ns,&nsmax,1,ISSM_MPI_INT,ISSM_MPI_MAX,0,IssmComm::GetComm());
+	ISSM_MPI_Bcast(&nsmax,1,ISSM_MPI_INT,0,IssmComm::GetComm());
+
+	/*Call the sea level rise core: */
+	for(int i=0;i<nsmax;i++){
+		if(i<ns){
+			Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
+			element->SealevelriseGeodetic(pUp,pNorth,pEast,Sg,latitude,longitude,radius,xx,yy,zz,eartharea);
+		}
+		if(i%100==0){
+			pUp->Assemble();
+			pNorth->Assemble();
+			pEast->Assemble();
+		}
+	}
+	
+	/*One last time: */
+	pUp->Assemble();
+	pNorth->Assemble();
+	pEast->Assemble();
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(Sg);
+	xDelete<IssmDouble>(latitude);
+	xDelete<IssmDouble>(longitude);
+	xDelete<IssmDouble>(radius);
+	xDelete<IssmDouble>(xx);
+	xDelete<IssmDouble>(yy);
+	xDelete<IssmDouble>(zz);
+}
+/*}}}*/
+IssmDouble FemModel::SealevelriseOceanAverage(Vector<IssmDouble>* Sg) { /*{{{*/
+
+	IssmDouble* Sg_serial=NULL;
+	IssmDouble  oceanvalue,oceanvalue_cpu;
+	IssmDouble  oceanarea,oceanarea_cpu;
+
+	/*Serialize vectors from previous iteration:*/
+	Sg_serial=Sg->ToMPISerial();
+
+	/*Initialize:*/
+	oceanvalue_cpu=0;
+	oceanarea_cpu=0;
+
+	/*Go through elements, and add contribution from each element and divide by overall ocean area:*/
+	for(int i=0;i<elements->Size();i++){
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
+		oceanarea_cpu += element->OceanArea();
+		oceanvalue_cpu += element->OceanAverage(Sg_serial);
+	}
+	ISSM_MPI_Reduce (&oceanarea_cpu,&oceanarea,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&oceanarea,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+	
+	ISSM_MPI_Reduce (&oceanvalue_cpu,&oceanvalue,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&oceanvalue,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(Sg_serial);
+	
+	return oceanvalue/oceanarea;
+}
+/*}}}*/
+#endif
+void FemModel::HydrologyEPLupdateDomainx(IssmDouble* pEplcount){ /*{{{*/
+
+	Vector<IssmDouble>* mask							= NULL;
+	Vector<IssmDouble>* recurence  				= NULL;
+	Vector<IssmDouble>* active						= NULL;
+	IssmDouble*         serial_mask				= NULL;
+	IssmDouble*         serial_rec  			= NULL;
+	IssmDouble*         serial_active			= NULL;
+	IssmDouble*         old_active        = NULL;
+	int*                eplzigzag_counter =	NULL;
+	int                 eplflip_lock;
+	
+	HydrologyDCEfficientAnalysis* effanalysis =  new HydrologyDCEfficientAnalysis();
+	HydrologyDCInefficientAnalysis* inefanalysis =  new HydrologyDCInefficientAnalysis();
+
+	/*Step 1: update mask, the mask might be extended by residual and/or using downstream sediment head*/
+	mask=new Vector<IssmDouble>(this->nodes->NumberOfNodes(HydrologyDCEfficientAnalysisEnum));
+	recurence=new Vector<IssmDouble>(this->nodes->NumberOfNodes(HydrologyDCEfficientAnalysisEnum));
+	this->parameters->FindParam(&eplzigzag_counter,NULL,EplZigZagCounterEnum); 
+	this->parameters->FindParam(&eplflip_lock,HydrologydcEplflipLockEnum); 
+	GetVectorFromInputsx(&old_active,this,HydrologydcMaskEplactiveNodeEnum,NodeSIdEnum);
+	
+	for (int i=0;i<elements->Size();i++){
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
+		effanalysis->HydrologyEPLGetMask(mask,recurence,eplzigzag_counter,element);
+	}
+	/*check for changes and increment zigzag counter, change the mask if necessary*/
+	recurence->Assemble();
+	serial_rec=recurence->ToMPISerial();
+	for (int i=0;i<nodes->Size();i++){
+		Node* node=xDynamicCast<Node*>(nodes->GetObjectByOffset(i));
+		if(serial_rec[node->Sid()]==1.)eplzigzag_counter[node->Lid()] ++;
+		if(eplzigzag_counter[node->Lid()]>eplflip_lock & eplflip_lock!=0){
+			mask->SetValue(node->Sid(),old_active[node->Sid()],INS_VAL);
+		}
+	}
+	this->parameters->SetParam(eplzigzag_counter,this->nodes->Size(),EplZigZagCounterEnum);
+	/*Assemble and serialize*/
+	mask->Assemble();
+	serial_mask=mask->ToMPISerial();	
+	
+	xDelete<int>(eplzigzag_counter);
+	xDelete<IssmDouble>(serial_rec);
+	xDelete<IssmDouble>(old_active);
+	delete mask;
+	delete recurence;
+
+	/*Update Mask*/
+	InputUpdateFromVectorx(this,serial_mask,HydrologydcMaskEplactiveNodeEnum,NodeSIdEnum);
+	xDelete<IssmDouble>(serial_mask);
+	inefanalysis->ElementizeEplMask(this);
+	/*Step 2: update node activity. If one element is connected to mask=1, all nodes are active*/
+	active=new Vector<IssmDouble>(nodes->NumberOfNodes(HydrologyDCEfficientAnalysisEnum));
+	for (int i=0;i<elements->Size();i++){
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
+		effanalysis->HydrologyEPLGetActive(active,element);
+	}
+
+	/*Assemble and serialize*/
+	active->Assemble();
+	serial_active=active->ToMPISerial();
+	delete active;
+
+	/*Update node activation accordingly*/
+	int counter =0;
+	for (int i=0;i<nodes->Size();i++){
+		Node* node=xDynamicCast<Node*>(nodes->GetObjectByOffset(i));
+		if(node->InAnalysis(HydrologyDCEfficientAnalysisEnum)){
+			if(serial_active[node->Sid()]==1.){
+				node->Activate();
+				if(!node->IsClone()) counter++;
+			}
+			else{
+				node->Deactivate();
+			}
+		}
+	}
+	xDelete<IssmDouble>(serial_active);
+	delete effanalysis;
+	delete inefanalysis;
+	int sum_counter;
+	ISSM_MPI_Reduce(&counter,&sum_counter,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&sum_counter,1,ISSM_MPI_INT,0,IssmComm::GetComm());                
+	counter=sum_counter;
+	*pEplcount = counter;
+	if(VerboseSolution()) _printf0_("   Number of active nodes in EPL layer: "<< counter <<"\n");
+
+	/*Update dof indexings*/
+	this->UpdateConstraintsx();
+
+}
+/*}}}*/
+void FemModel::UpdateConstraintsL2ProjectionEPLx(IssmDouble* pL2count){ /*{{{*/
+
+	Vector<IssmDouble>* active        = NULL;
+	IssmDouble*         serial_active = NULL;
+	HydrologyDCEfficientAnalysis* effanalysis = new HydrologyDCEfficientAnalysis();
+
+	/*update node activity. If one element is connected to mask=1, all nodes are active*/
+	active=new Vector<IssmDouble>(nodes->NumberOfNodes(HydrologyDCEfficientAnalysisEnum));
+	for (int i=0;i<elements->Size();i++){
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
+		effanalysis->HydrologyEPLGetActive(active,element);
+	}
+
+	/*Assemble and serialize*/
+	active->Assemble();
+	serial_active=active->ToMPISerial();
+	delete active;
+	delete effanalysis;
+
+	/*Update node activation accordingly*/
+	int counter =0;
+	for (int i=0;i<nodes->Size();i++){
+		Node* node=xDynamicCast<Node*>(nodes->GetObjectByOffset(i));
+		if(node->InAnalysis(L2ProjectionEPLAnalysisEnum)){
+			if(serial_active[node->Sid()]==1.){
+				node->Activate();
+				if(!node->IsClone()) counter++;
+			}
+			else{
+				node->Deactivate();
+			}
+		}
+	}
+	xDelete<IssmDouble>(serial_active);
+	int sum_counter;
+	ISSM_MPI_Reduce(&counter,&sum_counter,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&sum_counter,1,ISSM_MPI_INT,0,IssmComm::GetComm());                
+	counter=sum_counter;
+	*pL2count = counter;
+	if(VerboseSolution()) _printf0_("   Number of active nodes L2 Projection: "<< counter <<"\n");
+}
+/*}}}*/
+void FemModel::InitTransientOutputx(int* input_enum,int numoutputs){ /*{{{*/
+
+  for(int i=0;i<numoutputs;i++){
+		if(input_enum[i]<0){
+			_error_("Can't deal with non enum fields for result Stack");
+		}
+		else{
+			for(int j=0;j<elements->Size();j++){
+				TransientInput* transient_input = new TransientInput(input_enum[i]);
+				/*Intermediaries*/
+				Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(j));
+				//transient_input->Configure(element->parameters);
+				element->inputs->AddInput(transient_input);
+			}
+		}
+	}
+}
+/*}}}*/
+void FemModel::StackTransientOutputx(int* input_enum,int* stackedinput_enum,IssmDouble hydrotime,int numoutputs){ /*{{{*/
+
+  for(int i=0;i<numoutputs;i++){
+		if(input_enum[i]<0){
+			_error_("Can't deal with non enum fields for result Stack");
+		}
+		else{
+			for(int j=0;j<elements->Size();j++){
+				/*Intermediaries*/
+				Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(j));
+				TransientInput* stacking_input=NULL;
+				Input* input=element->inputs->GetInput(stackedinput_enum[i]); _assert_(input);
+				Input* input_to_stack=element->GetInput(input_enum[i]); _assert_(input_to_stack);
+				stacking_input=dynamic_cast<TransientInput*>(input);
+
+				int  numvertices = element->GetNumberOfVertices();
+				IssmDouble* N=xNew<IssmDouble>(numvertices);
+				element->GetInputListOnVertices(&N[0],input_enum[i]);
+				switch(element->ObjectEnum()){
+				case TriaEnum:
+					stacking_input->AddTimeInput(new TriaInput(stackedinput_enum[i],&N[0],P1Enum),hydrotime);
+					break;
+				case PentaEnum:
+					stacking_input->AddTimeInput(new PentaInput(stackedinput_enum[i],&N[0],P1Enum),hydrotime);
+					break;
+				case TetraEnum:
+					stacking_input->AddTimeInput(new TetraInput(stackedinput_enum[i],&N[0],P1Enum),hydrotime);
+					break;
+				default: _error_("Not implemented yet");
+				}
+				xDelete<IssmDouble>(N);
+			}
+		}
+	}
+}
+/*}}}*/
+void FemModel::AverageTransientOutputx(int* input_enum,int* averagedinput_enum,IssmDouble init_time,int numoutputs){ /*{{{*/
+
+  for(int i=0;i<numoutputs;i++){
+		if(input_enum[i]<0){
+			_error_("Can't deal with non enum fields for result Stack");
+		}
+		else{
+			for(int j=0;j<elements->Size();j++){
+				/*Intermediaries*/
+				Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(j));
+				int  numvertices = element->GetNumberOfVertices();
+				IssmDouble* time_averaged=NULL;
+
+				Input* input=element->inputs->GetInput(input_enum[i]); _assert_(input);
+				TransientInput* stacking_input=NULL;
+				stacking_input=dynamic_cast<TransientInput*>(input);
+				stacking_input->GetInputAverageOnTimes(&time_averaged,init_time);
+
+				element->AddInput(averagedinput_enum[i],&time_averaged[0],P1Enum);
+				xDelete<IssmDouble>(time_averaged);
+			}
+		}
+	}
+}
+/*}}}*/
+#ifdef _HAVE_JAVASCRIPT_ 
+FemModel::FemModel(IssmDouble* buffer, int buffersize, char* toolkits, char* solution, char* modelname,ISSM_MPI_Comm incomm, bool trace){ /*{{{*/
+	/*configuration: */
+	int  solution_type;
+	int  ierr;
+
+	/*First things first, store the communicator, and set it as a global variable: */
+	IssmComm::SetComm(incomm);
+
+	/*Start profiler: */
+	this->profiler=new Profiler();
+	profiler->Start(TOTAL);
+
+	/*From command line arguments, retrieve different filenames needed to create the FemModel: */
+	solution_type=StringToEnumx(solution);
+	
+	/*Create femmodel from input files: */
+	profiler->Start(MPROCESSOR);
+	this->InitFromBuffers((char*)buffer,buffersize,toolkits, solution_type,trace,NULL);
+	profiler->Stop(MPROCESSOR);
+	
+	/*Save communicator in the parameters dataset: */
+	this->parameters->AddObject(new GenericParam<ISSM_MPI_Comm>(incomm,FemModelCommEnum));
+
+}
+/*}}}*/
+void FemModel::CleanUpJs(char** poutput, size_t* psize){/*{{{*/
+
+	/*Intermediary*/
+	FILE *output_fid;
+	GenericParam<char**>* outputbufferparam=NULL;
+	GenericParam<size_t*>* outputbuffersizeparam=NULL;
+	char** poutputbuffer;
+	size_t* poutputbuffersize;
+
+	
+	/*Before we delete the profiler, report statistics for this run: */
+	profiler->Stop(TOTAL);  //final tagging
+	_printf0_("\n");
+	_printf0_("   "<<setw(40)<<left<<"FemModel initialization elapsed time:"<<profiler->TotalTime(MPROCESSOR) << "\n");
+	_printf0_("   "<<setw(40)<<left<<"Core solution elapsed time:"<<profiler->TotalTime(CORE) << "\n");
+	_printf0_("\n");
+	_printf0_("   Total elapsed time: "
+				<<profiler->TotalTimeModHour(TOTAL)<<" hrs "
+				<<profiler->TotalTimeModMin(TOTAL)<<" min "
+				<<profiler->TotalTimeModSec(TOTAL)<<" sec"
+				);
+	_printf0_("\n");
+	
+	/*Before we close the output file, recover the buffer and size:*/
+	outputbufferparam = xDynamicCast<GenericParam<char**>*>(this->parameters->FindParamObject(OutputBufferPointerEnum));
+	poutputbuffer=outputbufferparam->GetParameterValue();
+	outputbuffersizeparam = xDynamicCast<GenericParam<size_t*>*>(this->parameters->FindParamObject(OutputBufferSizePointerEnum));
+	poutputbuffersize=outputbuffersizeparam->GetParameterValue();
+
+	/*Assign output values: */
+	*poutput=*poutputbuffer;
+	*psize=*poutputbuffersize;
+}
+/*}}}*/
+void FemModel::InitFromBuffers(char* buffer, int buffersize, char* toolkits, int in_solution_type, bool trace, IssmPDouble* X){/*{{{*/
+
+	/*intermediary*/
+	FILE       *IOMODEL = NULL;
+	FILE       *toolkitsoptionsfid = NULL;
+	FILE       *output_fid = NULL;
+	int         my_rank;
+	size_t      outputsize;
+	char       *outputbuffer;
+	const char *rootpath = "";   //needed for Dakota runs only, which we won't do here.
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	/*Open input file descriptor on cpu 0: */
+	if(my_rank==0) IOMODEL = fmemopen((void*)buffer, buffersize, "rb");
+
+	/*Open toolkits file descriptor: */
+	toolkitsoptionsfid=fmemopen((void*)toolkits, strlen(toolkits)+1, "r");
+
+	/*Now, go create FemModel:*/
+	this->InitFromFids((char*)rootpath,IOMODEL,toolkitsoptionsfid,in_solution_type,trace,X);
+
+	/*Close input file and toolkits file descriptors: */
+	if(my_rank==0) fclose(IOMODEL);
+	fclose(toolkitsoptionsfid);
+
+	/*Open output file once for all and add output file descriptor to parameters*/
+	output_fid=open_memstream(&outputbuffer,&outputsize); 
+	if(output_fid==NULL)_error_("could not initialize output stream");
+	this->parameters->SetParam(output_fid,OutputFilePointerEnum);
+	this->parameters->AddObject(new GenericParam<char**>(&outputbuffer,OutputBufferPointerEnum));
+	this->parameters->AddObject(new GenericParam<size_t*>(&outputsize,OutputBufferSizePointerEnum));
+
+}/*}}}*/
+#endif
+
+#if defined(_HAVE_BAMG_) && !defined(_HAVE_ADOLC_)
+void FemModel::ReMeshBamg(int* pnewnumberofvertices,int* pnewnumberofelements,IssmDouble** pnewx,IssmDouble** pnewy,IssmDouble** pnewz,int** pnewelementslist){/*{{{*/
+
+	/*Output*/
+	IssmDouble *newx			= NULL;
+	IssmDouble *newy			= NULL;
+	IssmDouble *newz			= NULL;
+	int *newelementslist		= NULL;
+	int newnumberofvertices	= -1;
+	int newnumberofelements = -1;
+
+	/*Get Rank*/
+	int my_rank	= IssmComm::GetRank();
+
+	/*Intermediaries*/
+	int numberofvertices 				= this->vertices->NumberOfVertices();
+	IssmDouble* vector_serial			= NULL;
+	IssmDouble* hmaxvertices_serial	= NULL;
+	Vector<IssmDouble> *vector			= NULL;
+
+	/*Get vector to create metric*/
+	if(this->amrbamg->fieldenum!=NoneEnum){
+		GetVectorFromInputsx(&vector,this,this->amrbamg->fieldenum,VertexSIdEnum);
+		vector->Assemble();
+		vector_serial = vector->ToMPISerial();
+	}
+
+	/*Get hmaxVertices to create metric*/
+	if(this->amrbamg->groundingline_distance>0||this->amrbamg->icefront_distance>0||
+		this->amrbamg->thicknesserror_threshold>0||this->amrbamg->deviatoricerror_threshold>0){
+		/*Initialize hmaxvertices with NAN*/
+		hmaxvertices_serial=xNew<IssmDouble>(numberofvertices);
+		for(int i=0;i<numberofvertices;i++) hmaxvertices_serial[i]=NAN; 
+		/*Fill hmaxvertices*/
+		if(this->amrbamg->groundingline_distance>0)		this->GethmaxVerticesFromZeroLevelSetDistance(hmaxvertices_serial,MaskGroundediceLevelsetEnum);
+		if(this->amrbamg->icefront_distance>0)				this->GethmaxVerticesFromZeroLevelSetDistance(hmaxvertices_serial,MaskIceLevelsetEnum);
+		if(this->amrbamg->thicknesserror_threshold>0)	this->GethmaxVerticesFromEstimators(hmaxvertices_serial,ThicknessErrorEstimatorEnum);
+		if(this->amrbamg->deviatoricerror_threshold>0)	this->GethmaxVerticesFromEstimators(hmaxvertices_serial,DeviatoricStressErrorEstimatorEnum);
+	}
+	
+	if(my_rank==0){
+		this->amrbamg->ExecuteRefinementBamg(vector_serial,hmaxvertices_serial,&newnumberofvertices,&newnumberofelements,&newx,&newy,&newz,&newelementslist);
+		if(newnumberofvertices<=0 || newnumberofelements<=0) _error_("Error in the refinement process.");
+	}
+
+	/*Cleanup*/
+	xDelete<IssmDouble>(vector_serial);
+	xDelete<IssmDouble>(hmaxvertices_serial);
+	delete vector;
+
+	/*Send new mesh to others CPU*/
+	ISSM_MPI_Bcast(&newnumberofvertices,1,ISSM_MPI_INT,0,IssmComm::GetComm());
+	ISSM_MPI_Bcast(&newnumberofelements,1,ISSM_MPI_INT,0,IssmComm::GetComm());
+	if(my_rank){
+		newx=xNew<IssmDouble>(newnumberofvertices);
+		newy=xNew<IssmDouble>(newnumberofvertices);
+		newz=xNew<IssmDouble>(newnumberofvertices);
+		newelementslist=xNew<int>(newnumberofelements*this->GetElementsWidth());
+	}
+	ISSM_MPI_Bcast(newx,newnumberofvertices,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());	
+	ISSM_MPI_Bcast(newy,newnumberofvertices,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());	
+	ISSM_MPI_Bcast(newz,newnumberofvertices,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());	
+	ISSM_MPI_Bcast(newelementslist,newnumberofelements*this->GetElementsWidth(),ISSM_MPI_INT,0,IssmComm::GetComm());	
+
+	/*Assign output pointers*/
+	*pnewnumberofvertices = newnumberofvertices;
+	*pnewnumberofelements = newnumberofelements;
+	*pnewx = newx;
+	*pnewy = newy;
+	*pnewz = newz;
+	*pnewelementslist = newelementslist;
+}
+/*}}}*/
+void FemModel::InitializeAdaptiveRefinementBamg(void){/*{{{*/
+
+	/*Define variables*/
+	int numberofvertices      = this->vertices->NumberOfVertices();
+	int numberofelements      = this->elements->NumberOfElements();
+	IssmDouble* x             = NULL;
+	IssmDouble* y             = NULL;
+	IssmDouble* z             = NULL;
+	int* elements             = NULL;
+	IssmDouble hmin,hmax,err,gradation;
+
+   /*Get rank*/
+	int my_rank = IssmComm::GetRank();
+
+	/*Initialize field as NULL for now*/
+	this->amrbamg = NULL;
+
+	/*Get vertices coordinates of the coarse mesh (father mesh)*/
+	this->GetMesh(this->vertices,this->elements,&x,&y,&z,&elements);
+
+	/*Create bamg data structures for bamg*/
+	this->amrbamg = new AmrBamg();
+	
+	/*Get amr parameters*/
+	this->parameters->FindParam(&hmin,AmrHminEnum);
+	this->parameters->FindParam(&hmax,AmrHmaxEnum);
+	this->parameters->FindParam(&err,AmrErrEnum);
+	this->parameters->FindParam(&gradation,AmrGradationEnum);
+	this->parameters->FindParam(&this->amrbamg->fieldenum,AmrFieldEnum);
+	this->parameters->FindParam(&this->amrbamg->keepmetric,AmrKeepMetricEnum);
+	this->parameters->FindParam(&this->amrbamg->groundingline_resolution,AmrGroundingLineResolutionEnum);
+	this->parameters->FindParam(&this->amrbamg->groundingline_distance,AmrGroundingLineDistanceEnum);
+	this->parameters->FindParam(&this->amrbamg->icefront_resolution,AmrIceFrontResolutionEnum);
+	this->parameters->FindParam(&this->amrbamg->icefront_distance,AmrIceFrontDistanceEnum);
+	this->parameters->FindParam(&this->amrbamg->thicknesserror_resolution,AmrThicknessErrorResolutionEnum);
+	this->parameters->FindParam(&this->amrbamg->thicknesserror_threshold,AmrThicknessErrorThresholdEnum);
+	this->parameters->FindParam(&this->amrbamg->thicknesserror_groupthreshold,AmrThicknessErrorGroupThresholdEnum);
+	this->parameters->FindParam(&this->amrbamg->thicknesserror_maximum,AmrThicknessErrorMaximumEnum);
+	this->parameters->FindParam(&this->amrbamg->deviatoricerror_resolution,AmrDeviatoricErrorResolutionEnum);
+	this->parameters->FindParam(&this->amrbamg->deviatoricerror_threshold,AmrDeviatoricErrorThresholdEnum);
+	this->parameters->FindParam(&this->amrbamg->deviatoricerror_groupthreshold,AmrDeviatoricErrorGroupThresholdEnum);
+	this->parameters->FindParam(&this->amrbamg->deviatoricerror_maximum,AmrDeviatoricErrorMaximumEnum);
+	/*Set BamgOpts*/
+	this->amrbamg->SetBamgOpts(hmin,hmax,err,gradation);
+
+	/*Re-create original mesh and put it in bamg structure (only cpu 0)*/
+	if(my_rank==0){ 
+		this->amrbamg->Initialize(elements,x,y,numberofvertices,numberofelements);
+	}
+
+	/*Free the vectors*/
+	xDelete<IssmDouble>(x);
+	xDelete<IssmDouble>(y);
+	xDelete<IssmDouble>(z);
+	xDelete<int>(elements);
+}
+/*}}}*/
+void FemModel::GethmaxVerticesFromZeroLevelSetDistance(IssmDouble* hmaxvertices,int levelset_type){/*{{{*/
+
+	if(!hmaxvertices) _error_("hmaxvertices is NULL!\n");
+	
+	/*Intermediaries*/
+	int numberofvertices			 = this->vertices->NumberOfVertices();
+	IssmDouble* verticedistance = NULL;
+	IssmDouble threshold,resolution;
+
+	switch(levelset_type){
+		case MaskGroundediceLevelsetEnum: 
+			threshold	= this->amrbamg->groundingline_distance;
+			resolution	= this->amrbamg->groundingline_resolution;
+			break;
+		case MaskIceLevelsetEnum:
+			threshold	= this->amrbamg->icefront_distance;
+			resolution	= this->amrbamg->icefront_resolution;
+			break;
+		default: _error_("not implemented yet");
+	}
+
+	/*Get vertice distance to zero level set points*/
+	this->GetVerticeDistanceToZeroLevelSet(&verticedistance,levelset_type);
+	if(!verticedistance) _error_("verticedistance is NULL!\n");
+	
+	/*Fill hmaxVertices*/
+	for(int i=0;i<numberofvertices;i++){
+		if(verticedistance[i]<threshold){
+			if(xIsNan<IssmDouble>(hmaxvertices[i])) hmaxvertices[i]=resolution;
+			else hmaxvertices[i]=min(resolution,hmaxvertices[i]);
+		}
+	}
+
+	/*Cleanup*/
+	xDelete<IssmDouble>(verticedistance);
+}
+/*}}}*/
+void FemModel::GethmaxVerticesFromEstimators(IssmDouble* hmaxvertices,int errorestimator_type){/*{{{*/
+   
+	if(!hmaxvertices) _error_("hmaxvertices is NULL!\n");
+
+	/*Intermediaries*/
+	int elementswidth							= this->GetElementsWidth();
+	int numberofelements						= this->elements->NumberOfElements();
+	int numberofvertices						= this->vertices->NumberOfVertices();
+	IssmDouble* maxlength					= xNew<IssmDouble>(numberofelements);
+	IssmDouble* error_vertices				= xNewZeroInit<IssmDouble>(numberofvertices);	
+	IssmDouble* error_elements				= NULL;
+	IssmDouble* x								= NULL;
+	IssmDouble* y								= NULL;
+	IssmDouble* z								= NULL;
+	int* index									= NULL;
+	IssmDouble maxerror,threshold,groupthreshold,resolution,length;
+	IssmDouble L1,L2,L3;
+	int vid,v1,v2,v3;
+	bool refine;
+
+	/*Fill variables*/
+	switch(errorestimator_type){
+		case ThicknessErrorEstimatorEnum: 
+			threshold		= this->amrbamg->thicknesserror_threshold;
+			groupthreshold	= this->amrbamg->thicknesserror_groupthreshold;
+			resolution		= this->amrbamg->thicknesserror_resolution;
+			maxerror			= this->amrbamg->thicknesserror_maximum;
+			this->ThicknessZZErrorEstimator(&error_elements);//error is serial, but the calculation is parallel
+			break;
+		case DeviatoricStressErrorEstimatorEnum:
+			threshold		= this->amrbamg->deviatoricerror_threshold;
+			groupthreshold	= this->amrbamg->deviatoricerror_groupthreshold;
+			resolution		= this->amrbamg->deviatoricerror_resolution;
+			maxerror			= this->amrbamg->deviatoricerror_maximum;
+			this->ZZErrorEstimator(&error_elements);//error is serial, but the calculation is parallel
+			break;
+		default: _error_("not implemented yet");
+	}
+	if(!error_elements) _error_("error_elements is NULL!\n");
+	if(groupthreshold<DBL_EPSILON) _error_("group threshold is too small!");
+
+	/*Find the max of the estimators if it was not provided*/
+	if(maxerror<DBL_EPSILON){
+		for(int i=0;i<numberofelements;i++) maxerror=max(maxerror,error_elements[i]);
+		switch(errorestimator_type){
+      	case ThicknessErrorEstimatorEnum:			this->amrbamg->thicknesserror_maximum 	= maxerror;break;
+      	case DeviatoricStressErrorEstimatorEnum: 	this->amrbamg->deviatoricerror_maximum = maxerror;break;
+   	}	
+	}
+
+	/*Get mesh*/
+	this->GetMesh(this->vertices,this->elements,&x,&y,&z,&index);
+	
+	/*Fill error_vertices (this is the sum of all elements connected to the vertex)*/
+	for(int i=0;i<numberofelements;i++){
+		v1=index[i*elementswidth+0]-1;//Matlab to C indexing
+		v2=index[i*elementswidth+1]-1;//Matlab to C indexing
+		v3=index[i*elementswidth+2]-1;//Matlab to C indexing
+		L1=sqrt(pow(x[v2]-x[v1],2)+pow(y[v2]-y[v1],2));
+		L2=sqrt(pow(x[v3]-x[v2],2)+pow(y[v3]-y[v2],2));
+		L3=sqrt(pow(x[v1]-x[v3],2)+pow(y[v1]-y[v3],2));
+		/*Fill the vectors*/
+		maxlength[i]		=max(L1,max(L2,L3));
+		error_vertices[v1]+=error_elements[i];
+		error_vertices[v2]+=error_elements[i];
+		error_vertices[v3]+=error_elements[i];
+	}	
+
+	/*Fill hmaxvertices with the criteria*/
+	for(int i=0;i<numberofelements;i++){
+		refine=false;
+		/*Refine any element if its error > phi*maxerror*/
+		if(error_elements[i]>threshold*maxerror) refine=true;
+		/*If the element size is closer to the resolution, verify the sum of error in the vertices*/
+		if(resolution/maxlength[i]>0.85){
+			for(int j=0;j<elementswidth;j++){
+				vid=index[i*elementswidth+j]-1;//Matlab to C indexing
+				if(error_vertices[vid]>groupthreshold*maxerror) refine=true;
+			}
+		}
+		/*Now, fill the hmaxvertices if requested*/	  
+		if(refine){
+			for(int j=0;j<elementswidth;j++){
+				vid=index[i*elementswidth+j]-1;//Matlab to C indexing
+				if(xIsNan<IssmDouble>(hmaxvertices[vid])) hmaxvertices[vid]=resolution;
+				else hmaxvertices[vid]=min(resolution,hmaxvertices[vid]);
+			}
+		}
+	}
+
+	/*Cleanup*/
+	xDelete<IssmDouble>(x);
+	xDelete<IssmDouble>(y);
+	xDelete<IssmDouble>(z);
+	xDelete<int>(index);
+   xDelete<IssmDouble>(error_elements);
+   xDelete<IssmDouble>(error_vertices);
+   xDelete<IssmDouble>(maxlength);
+}
+/*}}}*/
+void FemModel::GetVerticeDistanceToZeroLevelSet(IssmDouble** pverticedistance,int levelset_type){/*{{{*/
+
+	/*Here, "zero level set" means grounding line or ice front, depending on the level set type*/
+	/*pverticedistance is the minimal vertice distance to the grounding line or ice front*/
+	if(levelset_type!=MaskGroundediceLevelsetEnum && levelset_type!=MaskIceLevelsetEnum){
+		_error_("level set type not implemented yet!");
+	}
+
+	/*Output*/
+	IssmDouble* verticedistance;
+	
+	/*Intermediaries*/
+   int numberofvertices       = this->vertices->NumberOfVertices();
+   IssmDouble* levelset_points= NULL;
+   IssmDouble* x					= NULL;
+   IssmDouble* y					= NULL;
+   IssmDouble* z					= NULL;
+	int numberofpoints;
+	IssmDouble distance;
+
+	/*Get vertices coordinates*/
+	VertexCoordinatesx(&x,&y,&z,this->vertices,false) ;
+	
+	/*Get points which level set is zero (center of elements with zero level set)*/	
+	this->GetZeroLevelSetPoints(&levelset_points,numberofpoints,levelset_type);
+
+	/*Find the minimal vertice distance to the zero levelset (grounding line or ice front)*/
+	verticedistance=xNew<IssmDouble>(numberofvertices);
+	for(int i=0;i<numberofvertices;i++){
+		verticedistance[i]=INFINITY;
+		for(int j=0;j<numberofpoints;j++){
+			distance=sqrt((x[i]-levelset_points[2*j])*(x[i]-levelset_points[2*j])+(y[i]-levelset_points[2*j+1])*(y[i]-levelset_points[2*j+1]));
+			verticedistance[i]=min(distance,verticedistance[i]);		
+		}
+	}	
+
+	/*Assign the pointer*/
+	(*pverticedistance)=verticedistance;
+
+	/*Cleanup*/
+   xDelete<IssmDouble>(levelset_points);
+   xDelete<IssmDouble>(x);
+   xDelete<IssmDouble>(y);
+   xDelete<IssmDouble>(z);
+}
+/*}}}*/
+#endif
+
+#if defined(_HAVE_NEOPZ_) && !defined(_HAVE_ADOLC_)
+void FemModel::ReMeshNeopz(int* pnewnumberofvertices,int* pnewnumberofelements,IssmDouble** pnewx,IssmDouble** pnewy,IssmDouble** pnewz,int** pnewelementslist){/*{{{*/
+
+	/*pnewelementslist keep vertices in Matlab indexing*/
+   int my_rank						= IssmComm::GetRank();
+   int numberofelements			= this->elements->NumberOfElements();
+	IssmDouble* gl_distance		= NULL;
+	IssmDouble* if_distance		= NULL;
+	IssmDouble* deviatoricerror= NULL;
+	IssmDouble* thicknesserror	= NULL;
+	IssmDouble* newx				= NULL;
+   IssmDouble* newy				= NULL;
+   IssmDouble* newz				= NULL;
+   int* newelementslist			= NULL;
+   int newnumberofvertices		= -1;
+	int newnumberofelements		= -1;
+
+	/*Get fields, if requested*/
+	if(this->amr->groundingline_distance>0)		this->GetElementDistanceToZeroLevelSet(&gl_distance,MaskGroundediceLevelsetEnum);
+   if(this->amr->icefront_distance>0)				this->GetElementDistanceToZeroLevelSet(&if_distance,MaskIceLevelsetEnum);
+   if(this->amr->thicknesserror_threshold>0)		this->ThicknessZZErrorEstimator(&thicknesserror);	
+	if(this->amr->deviatoricerror_threshold>0)	this->ZZErrorEstimator(&deviatoricerror);	
+	
+	if(my_rank==0){
+		this->amr->ExecuteRefinement(gl_distance,if_distance,deviatoricerror,thicknesserror,
+												&newnumberofvertices,&newnumberofelements,&newx,&newy,&newelementslist); 
+		newz=xNewZeroInit<IssmDouble>(newnumberofvertices);
+		if(newnumberofvertices<=0 || newnumberofelements<=0) _error_("Error in the ReMeshNeopz.");
+	}
+
+	/*Send new mesh to others CPU*/
+	ISSM_MPI_Bcast(&newnumberofvertices,1,ISSM_MPI_INT,0,IssmComm::GetComm());
+	ISSM_MPI_Bcast(&newnumberofelements,1,ISSM_MPI_INT,0,IssmComm::GetComm());
+	if(my_rank){
+		newx=xNew<IssmDouble>(newnumberofvertices);
+		newy=xNew<IssmDouble>(newnumberofvertices);
+		newz=xNew<IssmDouble>(newnumberofvertices);
+		newelementslist=xNew<int>(newnumberofelements*this->GetElementsWidth());
+	}
+	ISSM_MPI_Bcast(newx,newnumberofvertices,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());	
+	ISSM_MPI_Bcast(newy,newnumberofvertices,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());	
+	ISSM_MPI_Bcast(newz,newnumberofvertices,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());	
+	ISSM_MPI_Bcast(newelementslist,newnumberofelements*this->GetElementsWidth(),ISSM_MPI_INT,0,IssmComm::GetComm());	
+
+	/*Assign the pointers*/	
+	(*pnewelementslist) 	= newelementslist; //Matlab indexing
+	(*pnewx)				  	= newx;
+	(*pnewy)				  	= newy;
+	(*pnewz)				  	= newz;
+	*pnewnumberofvertices= newnumberofvertices;
+	*pnewnumberofelements= newnumberofelements;
+
+	/*Cleanup*/
+	xDelete<IssmDouble>(deviatoricerror);
+	xDelete<IssmDouble>(thicknesserror);
+	xDelete<IssmDouble>(gl_distance);
+	xDelete<IssmDouble>(if_distance);
+}
+/*}}}*/
+void FemModel::InitializeAdaptiveRefinementNeopz(void){/*{{{*/
+	
+	/*Define variables*/
+	int my_rank										= IssmComm::GetRank();
+	int numberofvertices							= this->vertices->NumberOfVertices();
+	int numberofelements							= this->elements->NumberOfElements();
+	IssmDouble* x									= NULL;
+	IssmDouble* y									= NULL;
+	IssmDouble* z									= NULL;
+	int* elements									= NULL;
+	
+	/*Initialize field as NULL for now*/
+	this->amr = NULL;
+
+	/*Get vertices coordinates of the coarse mesh (father mesh)*/
+	/*elements comes in Matlab indexing*/
+	this->GetMesh(this->vertices,this->elements,&x,&y,&z,&elements);
+
+	/*Create initial mesh (coarse mesh) in neopz data structure*/ 
+	/*Just CPU #0 should keep AMR object*/
+   /*Initialize refinement pattern*/
+	this->SetRefPatterns();
+	this->amr = new AdaptiveMeshRefinement();
+	this->amr->refinement_type=1;//1 is refpattern; 0 is uniform (faster) 
+	/*Get amr parameters*/
+	this->parameters->FindParam(&this->amr->level_max,AmrLevelMaxEnum);
+	this->parameters->FindParam(&this->amr->gradation,AmrGradationEnum);
+	this->parameters->FindParam(&this->amr->lag,AmrLagEnum);
+	this->parameters->FindParam(&this->amr->groundingline_distance,AmrGroundingLineDistanceEnum);
+	this->parameters->FindParam(&this->amr->icefront_distance,AmrIceFrontDistanceEnum);
+	this->parameters->FindParam(&this->amr->thicknesserror_threshold,AmrThicknessErrorThresholdEnum);
+	this->parameters->FindParam(&this->amr->thicknesserror_groupthreshold,AmrThicknessErrorGroupThresholdEnum);
+	this->parameters->FindParam(&this->amr->thicknesserror_maximum,AmrThicknessErrorMaximumEnum);
+	this->parameters->FindParam(&this->amr->deviatoricerror_threshold,AmrDeviatoricErrorThresholdEnum);
+	this->parameters->FindParam(&this->amr->deviatoricerror_groupthreshold,AmrDeviatoricErrorGroupThresholdEnum);
+	this->parameters->FindParam(&this->amr->deviatoricerror_maximum,AmrDeviatoricErrorMaximumEnum);
+	if(my_rank==0){ 
+		this->amr->CreateInitialMesh(numberofvertices,numberofelements,x,y,elements);
+	}
+
+	/*Free the vectors*/
+	xDelete<IssmDouble>(x);
+	xDelete<IssmDouble>(y);
+	xDelete<IssmDouble>(z);
+	xDelete<int>(elements);
+}
+/*}}}*/
+void FemModel::GetElementDistanceToZeroLevelSet(IssmDouble** pelementdistance,int levelset_type){/*{{{*/
+
+	/*Here, "zero level set" means grounding line or ice front, depending on the level set type*/
+	/*pverticedistance is the minimal vertice distance to the grounding line or ice front*/
+	if(levelset_type!=MaskGroundediceLevelsetEnum && levelset_type!=MaskIceLevelsetEnum){
+		_error_("level set type not implemented yet!");
+	}
+
+	/*Output*/
+	IssmDouble* elementdistance;
+	
+	/*Intermediaries*/
+   int numberofelements							= this->elements->NumberOfElements();
+   Vector<IssmDouble>* velementdistance	= new Vector<IssmDouble>(numberofelements);
+   IssmDouble* levelset_points				= NULL;
+	IssmDouble* xyz_list							= NULL;
+	IssmDouble mindistance,distance;
+	IssmDouble xc,yc,x1,y1,x2,y2,x3,y3;
+	int numberofpoints;
+	
+	/*Get points which level set is zero (center of elements with zero level set, levelset_points is serial)*/	
+	this->GetZeroLevelSetPoints(&levelset_points,numberofpoints,levelset_type);
+
+	for(int i=0;i<this->elements->Size();i++){//parallel
+      Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
+      int sid = element->Sid();
+		element->GetVerticesCoordinates(&xyz_list); 
+		x1 = xyz_list[3*0+0];y1 = xyz_list[3*0+1];
+		x2 = xyz_list[3*1+0];y2 = xyz_list[3*1+1];
+		x3 = xyz_list[3*2+0];y3 = xyz_list[3*2+1];
+		xc = (x1+x2+x3)/3.;
+		yc = (y1+y2+y3)/3.;
+		mindistance=INFINITY;
+		/*Loop over each point (where level set is zero)*/
+		for(int j=0;j<numberofpoints;j++){
+			distance =sqrt((xc-levelset_points[2*j])*(xc-levelset_points[2*j])+(yc-levelset_points[2*j+1])*(yc-levelset_points[2*j+1]));
+			mindistance=min(distance,mindistance);		
+		}
+		velementdistance->SetValue(sid,mindistance,INS_VAL);
+		xDelete<IssmDouble>(xyz_list);
+	}	
+
+   /*Assemble*/
+   velementdistance->Assemble();
+
+	/*Assign the pointer*/
+	(*pelementdistance)=velementdistance->ToMPISerial();
+
+	/*Cleanup*/
+   xDelete<IssmDouble>(levelset_points);
+   xDelete<IssmDouble>(xyz_list);
+	delete velementdistance;
+}
+/*}}}*/
+void FemModel::SetRefPatterns(){/*{{{*/
+
+   /*Initialize the global variable of refinement patterns*/
+   gRefDBase.InitializeUniformRefPattern(ETriangle);
+
+	/*Insert specifics patterns to ISSM core*/
+   std::string filepath  = REFPATTERNDIR;
+   std::string filename1 = filepath + "/2D_Triang_Rib_3.rpt";
+   std::string filename2 = filepath + "/2D_Triang_Rib_4.rpt";
+   std::string filename3 = filepath + "/2D_Triang_Rib_5.rpt";
+   std::string filename4 = filepath + "/2D_Triang_Rib_OnlyTriang_Side_3_4.rpt";
+   std::string filename5 = filepath + "/2D_Triang_Rib_OnlyTriang_Side_3_4_permuted.rpt";
+   std::string filename6 = filepath + "/2D_Triang_Rib_OnlyTriang_Side_3_5.rpt";
+   std::string filename7 = filepath + "/2D_Triang_Rib_OnlyTriang_Side_3_5_permuted.rpt";
+   std::string filename8 = filepath + "/2D_Triang_Rib_OnlyTriang_Side_4_5.rpt";
+   std::string filename9 = filepath + "/2D_Triang_Rib_OnlyTriang_Side_4_5_permuted.rpt";
+
+   TPZAutoPointer<TPZRefPattern> refpat1 = new TPZRefPattern(filename1);
+   TPZAutoPointer<TPZRefPattern> refpat2 = new TPZRefPattern(filename2);
+   TPZAutoPointer<TPZRefPattern> refpat3 = new TPZRefPattern(filename3);
+   TPZAutoPointer<TPZRefPattern> refpat4 = new TPZRefPattern(filename4);
+   TPZAutoPointer<TPZRefPattern> refpat5 = new TPZRefPattern(filename5);
+   TPZAutoPointer<TPZRefPattern> refpat6 = new TPZRefPattern(filename6);
+   TPZAutoPointer<TPZRefPattern> refpat7 = new TPZRefPattern(filename7);
+   TPZAutoPointer<TPZRefPattern> refpat8 = new TPZRefPattern(filename8);
+   TPZAutoPointer<TPZRefPattern> refpat9 = new TPZRefPattern(filename9);
+
+   if(!gRefDBase.FindRefPattern(refpat1)) gRefDBase.InsertRefPattern(refpat1);
+   if(!gRefDBase.FindRefPattern(refpat2)) gRefDBase.InsertRefPattern(refpat2);
+   if(!gRefDBase.FindRefPattern(refpat3)) gRefDBase.InsertRefPattern(refpat3);
+   if(!gRefDBase.FindRefPattern(refpat4)) gRefDBase.InsertRefPattern(refpat4);
+   if(!gRefDBase.FindRefPattern(refpat5)) gRefDBase.InsertRefPattern(refpat5);
+   if(!gRefDBase.FindRefPattern(refpat6)) gRefDBase.InsertRefPattern(refpat6);
+   if(!gRefDBase.FindRefPattern(refpat7)) gRefDBase.InsertRefPattern(refpat7);
+   if(!gRefDBase.FindRefPattern(refpat8)) gRefDBase.InsertRefPattern(refpat8);
+   if(!gRefDBase.FindRefPattern(refpat9)) gRefDBase.InsertRefPattern(refpat9);
+}
+/*}}}*/
+#endif
Index: /issm/trunk/src/c/classes/FemModel.h
===================================================================
--- /issm/trunk/src/c/classes/FemModel.h	(revision 22757)
+++ /issm/trunk/src/c/classes/FemModel.h	(revision 22758)
@@ -20,6 +20,9 @@
 class Profiler;
 class Elements;
-#ifdef _HAVE_NEOPZ_
+#if defined(_HAVE_NEOPZ_) && !defined(_HAVE_ADOLC_)
 #include "./AdaptiveMeshRefinement.h"
+#endif
+#if defined(_HAVE_BAMG_) && !defined(_HAVE_ADOLC_)
+#include "./AmrBamg.h"
 #endif
 /*}}}*/
@@ -47,6 +50,11 @@
 		Vertices    *vertices;             //one set of vertices
 
-		#ifdef _HAVE_NEOPZ_
+		//FIXME: do we want only one class and have virtual functions? or keep 2 classes, at least rename AdaptiveMeshRefinement -> AmrNeopz
+		#if defined(_HAVE_NEOPZ_) && !defined(_HAVE_ADOLC_)
 		AdaptiveMeshRefinement *amr;		  //adaptive mesh refinement object. It keeps coarse mesh and execute refinement process
+		#endif
+
+		#if defined(_HAVE_BAMG_) && !defined(_HAVE_ADOLC_)
+		AmrBamg *amrbamg; //adaptive mesh refinement object. It keeps coarse mesh and execute refinement process
 		#endif
 
@@ -61,4 +69,5 @@
 		FemModel* copy();
 		void Echo();
+		int  GetElementsWidth(){return 3;};//just tria elements in this first version
 		void InitFromFiles(char* rootpath, char* inputfilename, char* outputfilename, char* petscfilename, char* lockfilename, char* restartfilename, const int solution_type,bool trace,IssmPDouble* X=NULL);
 		void InitFromFids(char* rootpath, FILE* IOMODEL, FILE* toolkitsoptionsfid, int in_solution_type, bool trace, IssmPDouble* X=NULL);
@@ -73,5 +82,5 @@
 		/*Modules*/ 
 		void BalancethicknessMisfitx(IssmDouble* pV);
-		void CalvingRateDevx();
+		void CalvingRateVonmisesx();
 		void CalvingRateLevermannx();
 		void DeviatoricStressx();
@@ -79,10 +88,10 @@
 		void ElementOperationx(void (Element::*function)(void));
 		void ElementResponsex(IssmDouble* presponse,int response_enum);
-		void FloatingAreax(IssmDouble* pV);
+		void FloatingAreax(IssmDouble* pV, bool scaled);
 		void GetInputLocalMinMaxOnNodesx(IssmDouble** pmin,IssmDouble** pmax,IssmDouble* ug);
-		void GroundedAreax(IssmDouble* pV);
-		void IceMassx(IssmDouble* pV);
-		void IceVolumex(IssmDouble* pV);
-		void IceVolumeAboveFloatationx(IssmDouble* pV);
+		void GroundedAreax(IssmDouble* pV, bool scaled);
+		void IceMassx(IssmDouble* pV, bool scaled);
+		void IceVolumex(IssmDouble* pV, bool scaled);
+		void IceVolumeAboveFloatationx(IssmDouble* pV, bool scaled);
 		void MassFluxx(IssmDouble* presponse);
 		void MaxAbsVxx(IssmDouble* presponse);
@@ -98,11 +107,13 @@
 		void MinVyx(IssmDouble* presponse);
 		void MinVzx(IssmDouble* presponse);
+		void DistanceToFieldValue(int fieldenum,IssmDouble fieldvalue,int distanceenum);
 		void ResetLevelset();
 		void StrainRateparallelx();
 		void StrainRateperpendicularx();
+		void StrainRateeffectivex();
 		void StressIntensityFactorx();
-		void TotalFloatingBmbx(IssmDouble* pFbmb);
-		void TotalGroundedBmbx(IssmDouble* pGbmb);
-		void TotalSmbx(IssmDouble* pSmb);
+		void TotalFloatingBmbx(IssmDouble* pFbmb, bool scaled);
+		void TotalGroundedBmbx(IssmDouble* pGbmb, bool scaled);
+		void TotalSmbx(IssmDouble* pSmb, bool scaled);
 		#ifdef  _HAVE_DAKOTA_
 		void DakotaResponsesx(double* d_responses,char** responses_descriptors,int numresponsedescriptors,int d_numresponses);
@@ -116,4 +127,6 @@
 		void Responsex(IssmDouble* presponse,const char* response_descriptor);
 		void SurfaceAbsMisfitx( IssmDouble* pJ);
+		void OmegaAbsGradientx( IssmDouble* pJ);
+		void EtaDiffx( IssmDouble* pJ);
 		void ThicknessAbsGradientx( IssmDouble* pJ);
 		void ThicknessPositivex(IssmDouble* pJ);
@@ -122,5 +135,5 @@
 		#endif
 		#ifdef _HAVE_ESA_
-		void EsaGeodetic2D(Vector<IssmDouble>* pUp, Vector<IssmDouble>* pNorth, Vector<IssmDouble>* pEast, IssmDouble* xx, IssmDouble* yy); 
+		void EsaGeodetic2D(Vector<IssmDouble>* pUp, Vector<IssmDouble>* pNorth, Vector<IssmDouble>* pEast, Vector<IssmDouble>* pX, Vector<IssmDouble>* pY, IssmDouble* xx, IssmDouble* yy); 
 		void EsaGeodetic3D(Vector<IssmDouble>* pUp, Vector<IssmDouble>* pNorth, Vector<IssmDouble>* pEast, IssmDouble* latitude, IssmDouble* longitude, IssmDouble* radius, IssmDouble* xx, IssmDouble* yy, IssmDouble* zz); 
 		#endif
@@ -128,5 +141,5 @@
 		void SealevelriseEustatic(Vector<IssmDouble>* pSgi, IssmDouble* peustatic, IssmDouble* latitude, IssmDouble* longitude, IssmDouble* radius);
 		void SealevelriseNonEustatic(Vector<IssmDouble>* pSgo, Vector<IssmDouble>* pSg_old, IssmDouble* latitude, IssmDouble* longitude, IssmDouble* radius,bool verboseconvolution);
-		void SealevelriseRotationalFeedback(Vector<IssmDouble>* pSgo_rot, Vector<IssmDouble>* pSg_old, IssmDouble* latitude, IssmDouble* longitude, IssmDouble* radius);
+		void SealevelriseRotationalFeedback(Vector<IssmDouble>* pSgo_rot, Vector<IssmDouble>* pSg_old, IssmDouble* pIxz, IssmDouble* pIyz, IssmDouble* pIzz, IssmDouble* latitude, IssmDouble* longitude, IssmDouble* radius);
 		void SealevelriseGeodetic(Vector<IssmDouble>* pUp, Vector<IssmDouble>* pNorth, Vector<IssmDouble>* pEast, Vector<IssmDouble>* pSg_old, IssmDouble* latitude, IssmDouble* longitude, IssmDouble* radius, IssmDouble* xx, IssmDouble* yy, IssmDouble* zz); 
 		IssmDouble SealevelriseOceanAverage(Vector<IssmDouble>* Sg);
@@ -137,4 +150,7 @@
 		void UpdateConstraintsExtrudeFromTopx();
 		void UpdateConstraintsL2ProjectionEPLx(IssmDouble* pL2count);
+		void InitTransientOutputx(int* input_enum, int numoutputs);
+		void StackTransientOutputx(int* input_enum,int* stackedinput_enum, IssmDouble hydrotime, int numoutputs);
+		void AverageTransientOutputx(int* input_enum,int* averagedinput_enum,IssmDouble hydrotime,int numoutputs);
 		void UpdateConstraintsx(void);
 		int  UpdateVertexPositionsx(void);
@@ -146,13 +162,11 @@
 		#endif
 
-		#ifdef _HAVE_NEOPZ_
-		/*Adaptive mesh refinement methods*/
-		void InitializeAdaptiveRefinement(void);
+		/*AMR*/
+		#if !defined(_HAVE_ADOLC_)
 		void ReMesh(void);
 		void BedrockFromMismipPlus(void);
 		void AdjustBaseThicknessAndMask(void);
 		void GetMesh(Vertices* femmodel_vertices,Elements* femmodel_elements,IssmDouble** px, IssmDouble** py, IssmDouble** pz, int** pelementslist);
-		int GetElementsWidth(){return 3;};//just tria elements in this first version
-		void ExecuteRefinement(int &numberofvertices,int &numberofelements,IssmDouble** px,IssmDouble** py,IssmDouble** pz,int** pelementslist);
+		void GetMeshOnPartition(Vertices* femmodel_vertices,Elements* femmodel_elements,IssmDouble** px, IssmDouble** py, IssmDouble** pz, int** pelementslist,int** psidtoindex);
 		void GetGroundediceLevelSet(IssmDouble** pmasklevelset);
 		void CreateVertices(int newnumberofvertices,int newnumberofelements,int elementswidth,int* newelementslist,int* my_vertices,IssmDouble* newx,IssmDouble* newy,IssmDouble* newz,Vertices* vertices);
@@ -160,13 +174,35 @@
 		void CreateMaterials(int newnumberofelements,bool* my_elements,Materials* materials);
 		void CreateNodes(int newnumberofvertices,int* my_vertices,int nodecounter,int analysis_enum,Nodes* nodes);
-		void CreateConstraints(int newnumberofvertices,int newnumberofelements,int nodecounter,int constraintcounter,IssmDouble* newx,IssmDouble* newy,int* my_vertices,Constraints* constraints);
+		void CreateConstraints(Vertices* newfemmodel_vertices,int nodecounter,int constraintcounter,int analysis_enum,Constraints* newfemmodel_constraints);
+		void GetInputs(int* pnumP0inputs,IssmDouble** pP0inputs,int** pP0input_enums,int** pP0input_interp,int* pnumP1inputs,IssmDouble** pP1inputs,int** pP1input_enums,int** pP1input_interp);
 		void InterpolateInputs(Vertices* newfemmodel_vertices,Elements* newfemmodel_elements);
 		void UpdateElements(int newnumberofelements,int* newelementslist,bool* my_elements,int nodecounter,int analysis_counter,Elements* newelements);
 		void ElementsAndVerticesPartitioning(int& newnumberofvertices,int& newnumberofelements,int& elementswidth,int* newelementslist,bool** pmy_elements,int** pmy_vertices);
 		void WriteMeshInResults(void);
+		void WriteErrorEstimatorsInResults(void);
+		void SmoothedDeviatoricStressTensor(IssmDouble** ptauxx,IssmDouble** ptauyy,IssmDouble** ptauxy); //nodal values, just for SSA-P1: TauXX, TauYY, TauXY
+		void ZZErrorEstimator(IssmDouble** pelementerror);
+		void SmoothedGradThickness(IssmDouble** pdHdx,IssmDouble** pdHdy);
+		void ThicknessZZErrorEstimator(IssmDouble** pelementerror);
+		void MeanGroundedIceLevelSet(IssmDouble** pmasklevelset);
+		void GetElementCenterCoordinates(IssmDouble** pxc,IssmDouble** pyc);
+		void GetZeroLevelSetPoints(IssmDouble** pzerolevelset_points,int &numberofpoints,int levelset_type);
+		#endif
+
+		#if defined(_HAVE_BAMG_) && !defined(_HAVE_ADOLC_)
+		void ReMeshBamg(int* pnewnumberofvertices,int* pnewnumberofelements,IssmDouble** pnewx,IssmDouble** pnewy,IssmDouble** pnewz,int** pnewelementslist);
+		void InitializeAdaptiveRefinementBamg(void);
+		void GethmaxVerticesFromZeroLevelSetDistance(IssmDouble* hmaxvertices,int levelset_type);
+		void GethmaxVerticesFromEstimators(IssmDouble* hmaxvertices,int errorestimator_type);
+		void GetVerticeDistanceToZeroLevelSet(IssmDouble** pverticedistance,int leveset_type);
+		#endif
+
+		#if defined(_HAVE_NEOPZ_) && !defined(_HAVE_ADOLC_)
+		void ReMeshNeopz(int* pnewnumberofvertices,int* pnewnumberofelements,IssmDouble** pnewx,IssmDouble** pnewy,IssmDouble** pnewz,int** pnewelementslist);
+		void InitializeAdaptiveRefinementNeopz(void);
+		void GetElementDistanceToZeroLevelSet(IssmDouble** pelementdistance,int levelset_type);
 		void SetRefPatterns(void);
 		#endif
 };
-		
 
 #endif
Index: /issm/trunk/src/c/classes/Inputs/BoolInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/BoolInput.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Inputs/BoolInput.cpp	(revision 22758)
@@ -157,7 +157,2 @@
 }
 /*}}}*/
-void BoolInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){/*{{{*/
-	/*square of a bool is the bool itself: */
-	*psquaremin=value;
-}
-/*}}}*/
Index: /issm/trunk/src/c/classes/Inputs/BoolInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/BoolInput.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Inputs/BoolInput.h	(revision 22758)
@@ -36,7 +36,4 @@
 		int  GetResultNumberOfNodes(void){return 1;};
 		int   InstanceEnum();
-		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
-		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
-		Input* PointwiseMax(Input* inputB){_error_("not implemented yet");};
 		Input* SpawnSegInput(int index1,int index2);
 		Input* SpawnTriaInput(int index1,int index2,int index3);
@@ -46,6 +43,4 @@
 		void AXPY(Input* xinput,IssmDouble scalar);
 		void ChangeEnum(int newenumtype);
-		void Constrain(IssmDouble cm_min, IssmDouble cm_max){_error_("Constrain not implemented for booleans");};
-		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
 		void Extrude(int start);
 		void GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes){_error_("not implemented yet");};
@@ -61,5 +56,5 @@
 		void GetInputValue(IssmDouble* pvalue,Gauss* gauss ,int index){_error_("not implemented yet");};
 		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
-		IssmDouble InfinityNorm(void){_error_("InfinityNorm not implemented for booleans");};
+		int  GetInputInterpolationType(){_error_("not implemented yet!");};
 		IssmDouble Max(void){_error_("Max not implemented for booleans");};
 		IssmDouble MaxAbs(void){_error_("Max not implemented for booleans");};
@@ -68,6 +63,4 @@
 		void Scale(IssmDouble scale_factor);
 		void Set(IssmDouble setvalue){_error_("Set not implemented yet");};
-		void SquareMin(IssmDouble* psquaremin, Parameters* parameters);
-		void VerticallyIntegrate(Input* thickness_input){_error_("not supported yet");};
 		/*}}}*/
 
Index: /issm/trunk/src/c/classes/Inputs/ControlInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/ControlInput.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Inputs/ControlInput.cpp	(revision 22758)
@@ -22,34 +22,53 @@
 }
 /*}}}*/
-ControlInput::ControlInput(int in_enum_type,int enum_input,IssmDouble* pvalues,IssmDouble* pmin,IssmDouble* pmax,int id){/*{{{*/
+ControlInput::ControlInput(int in_enum_type,int input_layout_enum,IssmDouble* pvalues,IssmDouble* pmin,IssmDouble* pmax,int interp,int id){/*{{{*/
 
 	control_id=id;
 	enum_type=in_enum_type;
-
-	switch(enum_input){
+	layout_enum = input_layout_enum;
+
+	_assert_(interp==P1Enum);
+
+	switch(input_layout_enum){
 		case TriaInputEnum:
-			values     =new TriaInput(enum_type,pvalues,P1Enum);
-			savedvalues=new TriaInput(enum_type,pvalues,P1Enum);
-			minvalues  =new TriaInput(enum_type,pmin,P1Enum);
-			maxvalues  =new TriaInput(enum_type,pmax,P1Enum);
+			values     =new TriaInput(enum_type,pvalues,interp);
+			savedvalues=new TriaInput(enum_type,pvalues,interp);
+			minvalues  =new TriaInput(enum_type,pmin,interp);
+			maxvalues  =new TriaInput(enum_type,pmax,interp);
 			break;
 		case PentaInputEnum:
-			values     =new PentaInput(enum_type,pvalues,P1Enum);
-			savedvalues=new PentaInput(enum_type,pvalues,P1Enum);
-			minvalues  =new PentaInput(enum_type,pmin,P1Enum);
-			maxvalues  =new PentaInput(enum_type,pmax,P1Enum);
+			values     =new PentaInput(enum_type,pvalues,interp);
+			savedvalues=new PentaInput(enum_type,pvalues,interp);
+			minvalues  =new PentaInput(enum_type,pmin,interp);
+			maxvalues  =new PentaInput(enum_type,pmax,interp);
 			break;
 		default:
-			_error_("Input of Enum " << EnumToStringx(enum_input) << " not supported yet by ControlInput");
+			_error_("Input of Enum " << EnumToStringx(input_layout_enum) << " not supported yet by ControlInput");
 	}
 	gradient   =NULL;
 }
 /*}}}*/
+ControlInput::ControlInput(int in_enum_type,int input_layout_enum,Input* input_pvalues,Input* input_pmin,Input* input_pmax,Input* input_pgrad,int interp,int id){/*{{{*/
+
+	this->control_id=id;
+	this->enum_type=in_enum_type;
+	this->layout_enum = input_layout_enum;
+
+	_assert_(interp==P1Enum);
+	if(input_layout_enum!=TransientInputEnum) _error_("Wrong type of layout_enum, needs to be a TransientInputEnum");
+
+			this->values = input_pvalues;
+			this->savedvalues= NULL;
+			this->minvalues  = input_pmin;
+			this->maxvalues  = input_pmax;
+			this->gradient =  input_pgrad;
+	}
+/*}}}*/
 ControlInput::~ControlInput(){/*{{{*/
-	delete values;
-	delete savedvalues;
-	delete minvalues;
-	delete maxvalues;
-	delete gradient;
+	if(values)      delete values;
+	if(savedvalues) delete savedvalues;
+	if(minvalues)   delete minvalues;
+	if(maxvalues)   delete maxvalues;
+	if(gradient)    delete gradient;
 }
 /*}}}*/
@@ -63,4 +82,5 @@
 	output->enum_type=this->enum_type;
 	output->control_id=this->control_id;
+	output->layout_enum = this->control_id;
 
 	if(values)      output->values      = xDynamicCast<Input*>(this->values->copy());
@@ -77,4 +97,5 @@
 	_printf_("ControlInput:\n");
 	_printf_(setw(15)<<"   ControlInput "<<setw(25)<<left<<EnumToStringx(this->enum_type)<<"\n");
+	_printf_(setw(15)<<"   ControlInput "<<setw(25)<<left<<EnumToStringx(this->layout_enum)<<"\n");
 	_printf_("---values: \n");     if (values)      values->Echo();
 	_printf_("---savedvalues: \n");if (savedvalues) savedvalues->Echo();
@@ -96,4 +117,5 @@
 	MARSHALLING(enum_type);
 	MARSHALLING(control_id);
+	MARSHALLING(layout_enum);
 
 	if (marshall_direction == MARSHALLING_BACKWARD){
@@ -113,4 +135,11 @@
 				gradient   =new PentaInput();
 				break;
+			case TransientInputEnum:
+				values	  =new TransientInput();
+				savedvalues=new TransientInput();
+				minvalues  =new TransientInput();
+				maxvalues  =new TransientInput();
+				gradient   =new TransientInput();
+				break;
 			default:
 				_error_("Input of Enum " << EnumToStringx(enum_type) << " not supported yet by ControlInput");
@@ -144,19 +173,13 @@
 }/*}}}*/
 void ControlInput::Configure(Parameters* parameters){/*{{{*/
+	if(this->values->ObjectEnum()==TransientInputEnum){
+		this->values->Configure(parameters);
+		this->minvalues->Configure(parameters);
+		this->maxvalues->Configure(parameters);
+		this->gradient->Configure(parameters);
+	}
 	/*do nothing: */
 }
 /*}}}*/
-void ControlInput::Constrain(void){/*{{{*/
-
-	Input* newvalues=NULL;
-
-	newvalues=this->values->PointwiseMin(maxvalues);
-	delete values; this->values=newvalues;
-	newvalues=this->values->PointwiseMax(minvalues);
-	delete values; this->values=newvalues;
-}/*}}}*/
-void ControlInput::Constrain(IssmDouble min, IssmDouble max){/*{{{*/
-	   values->Constrain(min,max);
-}/*}}}*/
 void ControlInput::Extrude(int start){/*{{{*/
 	values->Extrude(start);
@@ -204,5 +227,5 @@
 }/*}}}*/
 void ControlInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist,const char* data){/*{{{*/
-	 if(strcmp(data,"value")==0){
+	if(strcmp(data,"value")==0){
 		 _assert_(values);
 		 values->GetVectorFromInputs(vector,doflist);
@@ -236,9 +259,6 @@
 	this->savedvalues=xDynamicCast<Input*>(this->values->copy());
 }/*}}}*/
-void ControlInput::ScaleGradient(IssmDouble scaling_factor){/*{{{*/
-	if(!gradient) _error_("Gradient of ControlInput " << EnumToStringx(enum_type) << " not found");
-	gradient->Scale(scaling_factor);
-}/*}}}*/
-void ControlInput::SetGradient(Input* gradient_in){/*{{{*/
+void ControlInput::SetGradient(Input* gradient_in,int timestep){/*{{{*/
+if(this->values->ObjectEnum()!=TransientInputEnum)_error_("you are in the wrong place, go home");
 
 	/*Get enum for current gradient*/
@@ -257,4 +277,40 @@
 	}
 
+	TransientInput* transient_input = xDynamicCast<TransientInput*>(this->gradient);
+	TransientInput* values_input = xDynamicCast<TransientInput*>(this->values);
+	if(values_input->numtimesteps==transient_input->numtimesteps){
+		TransientInput* new_trans_input = new TransientInput(ControlInputGradEnum);
+		IssmDouble time = transient_input->GetTimeByOffset(timestep);
+		for(int i=0;i<transient_input->numtimesteps;i++){
+			if(transient_input->timesteps[i]==time) new_trans_input->AddTimeInput(xDynamicCast<TriaInput*>(gradient_in),time);
+			else {
+				Input* input = transient_input->GetTimeInput(transient_input->timesteps[i]);
+				new_trans_input->AddTimeInput(xDynamicCast<TriaInput*>(input),transient_input->timesteps[i]);
+			}
+		}
+		this->gradient=new_trans_input;
+	}
+	else{
+		IssmDouble time = values_input->GetTimeByOffset(timestep);
+		transient_input->AddTimeInput(gradient_in,time);
+	}
+}/*}}}*/
+void ControlInput::SetGradient(Input* gradient_in){/*{{{*/
+
+	/*Get enum for current gradient*/
+	switch(this->control_id){
+		case 1:
+			gradient_in->ChangeEnum(Gradient1Enum);
+			break;
+		case 2:
+			gradient_in->ChangeEnum(Gradient2Enum);
+			break;
+		case 3:
+			gradient_in->ChangeEnum(Gradient3Enum);
+			break;
+		default:
+			_error_("more than 3 controls not implemented yet (Gradient " << this->control_id << " was requested). EnumDefinitions.h needs to be updated.");
+	}
+
 	/*Delete old gradient and assign new gradient*/
 	if(gradient) delete gradient;
@@ -264,6 +320,27 @@
 void ControlInput::SetInput(Input* in_input){/*{{{*/
 
+	if(layout_enum==TransientInputEnum)_error_("need two arguments in SetInput for TransientInput Controls");
 	delete values; this->values=in_input;
 	this->SaveValue(); //because this is what SpawnResult saves FIXME
+
+}/*}}}*/
+void ControlInput::SetInput(Input* in_input,int timeoffset){/*{{{*/
+	Input* input = this->values;
+	if(input->ObjectEnum()!=TransientInputEnum)_error_("cannot have timeoffset argument if not TransientInput Control");
+	TransientInput* transient_input = xDynamicCast<TransientInput*>(input);
+	IssmDouble time = transient_input->GetTimeByOffset(timeoffset);
+	TransientInput* new_trans_input = new TransientInput(ControlInputValuesEnum);
+	for(int i=0;i<transient_input->numtimesteps;i++){
+		if(transient_input->timesteps[i]==time) new_trans_input->AddTimeInput(xDynamicCast<TriaInput*>(in_input),time);
+		else {
+			input = transient_input->GetTimeInput(transient_input->timesteps[i]);
+			new_trans_input->AddTimeInput(xDynamicCast<TriaInput*>(input),transient_input->timesteps[i]);
+		}
+	}
+	this->values=new_trans_input;
+
+	//	this->values->Echo();
+	//this->values->Echo();
+	//new_trans_input->Echo();
 
 }/*}}}*/
@@ -282,5 +359,2 @@
 	this->values->AXPY(gradient,scalar);
 }/*}}}*/
-void ControlInput::VerticallyIntegrate(Input* thickness_input){/*{{{*/
-	values->VerticallyIntegrate(thickness_input);
-}/*}}}*/
Index: /issm/trunk/src/c/classes/Inputs/ControlInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/ControlInput.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Inputs/ControlInput.h	(revision 22758)
@@ -18,4 +18,5 @@
 		int    control_id;
 		int    enum_type;
+		int	 layout_enum;
 		Input* gradient;
 		Input* maxvalues;
@@ -26,5 +27,6 @@
 		/*ControlInput constructors, destructors: {{{*/
 		ControlInput();
-		ControlInput(int enum_type,int enum_input,IssmDouble* pvalues,IssmDouble* pmin,IssmDouble* pmax,int id);
+		ControlInput(int enum_type,int enum_input,IssmDouble* pvalues,IssmDouble* pmin,IssmDouble* pmax,int interp,int id);
+		ControlInput(int enum_type,int enum_input,Input* pvalues,Input* pmin,Input* pmax,Input* pgrad,int interp,int id);
 		~ControlInput();
 		/*}}}*/
@@ -40,7 +42,4 @@
 		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
 		void Configure(Parameters* parameters);
-		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
-		Input* PointwiseMax(Input* inputB){_error_("not implemented yet");};
-		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
 		int    InstanceEnum();
 		Input* SpawnSegInput(int index1,int index2);
@@ -49,7 +48,4 @@
 		/*numerics: {{{*/
 		void AXPY(Input* xinput,IssmDouble scalar);
-		void Constrain(void);
-		void Constrain(IssmDouble min,IssmDouble max);
-		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
 		void ChangeEnum(int newenumtype){_error_("not implemented yet");};
 		void Extrude(int start);
@@ -67,4 +63,5 @@
 		void GetInputValue(IssmDouble* pvalue,Gauss* gauss,IssmDouble time){_error_("not implemented yet");};
 		void GetInputValue(IssmDouble* pvalue,Gauss* gauss ,int index){_error_("not implemented yet");};
+		int  GetInputInterpolationType(){_error_("not implemented yet!");};
 		int  GetResultArraySize(void){return 1;};
 		int  GetResultInterpolation(void);
@@ -72,5 +69,4 @@
 		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist,const char* data);
 		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
-		IssmDouble InfinityNorm(void){_error_("not implemented yet");};
 		IssmDouble Max(void){_error_("not implemented yet");};
 		IssmDouble MaxAbs(void){_error_("not implemented yet");};
@@ -80,11 +76,10 @@
 		void SaveValue(void);
 		void Scale(IssmDouble scale_factor){_error_("not implemented yet");};
-		void ScaleGradient(IssmDouble scale);
 		void Set(IssmDouble setvalue){_error_("Set not implemented yet");};
+		void SetGradient(Input* gradient_in,int timestep);
 		void SetGradient(Input* gradient_in);
 		void SetInput(Input* in_input);
-		void SquareMin(IssmDouble* psquaremin,Parameters* parameters){_error_("not implemented yet");};
+		void SetInput(Input* in_input, int timeoffset);
 		void UpdateValue(IssmDouble scalar);
-		void VerticallyIntegrate(Input* thickness_input);
 		/*}}}*/
 
Index: /issm/trunk/src/c/classes/Inputs/DatasetInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/DatasetInput.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Inputs/DatasetInput.cpp	(revision 22758)
@@ -167,5 +167,5 @@
 	/*Get requested input within dataset*/
 	for(int i=0;i<this->numids;i++) if(this->ids[i]==id) offset=i;
-	if(offset<0) _error_("Could not find input of id "<<id );
+	if(offset<0) _error_("Could not find input of id "<<id<<" (Enum: "<<EnumToStringx(id)<<")" );
 
 	Input* input=xDynamicCast<Input*>(this->inputs->GetObjectByOffset(offset));
Index: /issm/trunk/src/c/classes/Inputs/DatasetInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/DatasetInput.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Inputs/DatasetInput.h	(revision 22758)
@@ -39,7 +39,4 @@
 		void Configure(Parameters* parameters);
 		int    InstanceEnum();
-		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
-		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
-		Input* PointwiseMax(Input* inputB){_error_("not implemented yet");};
 		Input* SpawnSegInput(int index1,int index2);
 		Input* SpawnTriaInput(int index1,int index2,int index3);
@@ -48,7 +45,4 @@
 		void AXPY(Input* xinput,IssmDouble scalar){_error_("not implemented yet");};
 		void ChangeEnum(int newenumtype){_error_("not implemented yet");};
-		void Constrain(void){_error_("not implemented yet");};
-		void Constrain(IssmDouble min,IssmDouble max){_error_("not implemented yet");};
-		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
 		void Extrude(int start){_error_("not implemented yet");};
 		void GetGradient(Vector<IssmDouble>* gradient_vec,int* doflist){_error_("not implemented yet");};
@@ -64,9 +58,9 @@
 		void GetInputValue(IssmDouble* pvalue,Gauss* gauss ,int index);
 		void GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime){_error_("not implemented yet");};
+		int  GetInputInterpolationType(){_error_("not implemented yet!");};
 		int GetResultArraySize(void){_error_("not implemented yet");};
 		int GetResultInterpolation(void){_error_("not implemented yet");};
 		int GetResultNumberOfNodes(void){_error_("not implemented yet");};
 		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){_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");};
@@ -76,10 +70,7 @@
 		void SaveValue(void){_error_("not implemented yet");};
 		void Scale(IssmDouble scale_factor){_error_("not implemented yet");};
-		void ScaleGradient(IssmDouble scale){_error_("not implemented yet");};
 		void Set(IssmDouble setvalue){_error_("Set not implemented yet");};
 		void SetGradient(Input* gradient_in){_error_("not implemented yet");};
-		void SquareMin(IssmDouble* psquaremin,Parameters* parameters){_error_("not implemented yet");};
 		void UpdateValue(IssmDouble scalar){_error_("not implemented yet");};
-		void VerticallyIntegrate(Input* thickness_input){_error_("not implemented yet");};
 		/*}}}*/
 
Index: /issm/trunk/src/c/classes/Inputs/DoubleArrayInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/DoubleArrayInput.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Inputs/DoubleArrayInput.h	(revision 22758)
@@ -38,7 +38,4 @@
 		int  GetResultNumberOfNodes(void){return 1;};
 		int   InstanceEnum();
-		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
-		Input* PointwiseMax(Input* inputB){_error_("not implemented yet");};
-		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
 		void ResultToMatrix(IssmDouble* values,int ncols,int sid);
 		Input* SpawnSegInput(int index1,int index2){_error_("not implemented yet");};
@@ -48,6 +45,4 @@
 		void AXPY(Input* xinput,IssmDouble scalar){_error_("not implemented yet");};
 		void ChangeEnum(int newenumtype);
-		void Constrain(IssmDouble cm_min, IssmDouble cm_max){_error_("not implemented yet");};
-		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
 		void Extrude(int start){_error_("not supported yet");};
 		void GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes){_error_("not implemented yet");};
@@ -63,5 +58,5 @@
 		void GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime){_error_("not implemented yet");};
 		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){_error_("not implemented yet");};
-		IssmDouble InfinityNorm(void){_error_("not implemented yet");};
+		int  GetInputInterpolationType(){_error_("not implemented yet!");};
 		IssmDouble Max(void){_error_("not implemented yet");};
 		IssmDouble MaxAbs(void){_error_("not implemented yet");};
@@ -70,6 +65,4 @@
 		void Scale(IssmDouble scale_factor){_error_("not implemented yet");};
 		void Set(IssmDouble setvalue){_error_("Set not implemented yet");};
-		void SquareMin(IssmDouble* psquaremin,Parameters* parameters){_error_("not implemented yet");};
-		void VerticallyIntegrate(Input* thickness_input){_error_("not implemented yet");};
 		/*}}}*/
 
Index: /issm/trunk/src/c/classes/Inputs/DoubleInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/DoubleInput.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Inputs/DoubleInput.cpp	(revision 22758)
@@ -127,15 +127,4 @@
 }
 /*}}}*/
-void DoubleInput::Constrain(IssmDouble cm_min, IssmDouble cm_max){/*{{{*/
-
-	if(!xIsNan<IssmDouble>(cm_min)) if (this->value<cm_min)this->value=cm_min;
-	if(!xIsNan<IssmDouble>(cm_max)) if (this->value>cm_max)this->value=cm_max;
-
-}
-/*}}}*/
-void DoubleInput::ConstrainMin(IssmDouble minimum){/*{{{*/
-	if (value<minimum) value=minimum;
-}
-/*}}}*/
 void DoubleInput::GetInputAverage(IssmDouble* pvalue){/*{{{*/
 	*pvalue=value;
@@ -182,92 +171,6 @@
 }
 /*}}}*/
-Input* DoubleInput::PointwiseDivide(Input* inputB){/*{{{*/
-
-	/*Ouput*/
-	DoubleInput* outinput=NULL;
-
-	/*Intermediaries*/
-	IssmDouble       Bvalue;
-
-	/*Check that inputB is of the same type*/
-	inputB->GetInputAverage(&Bvalue);
-
-	/*Create new DoubleInput*/
-	outinput=new DoubleInput(this->enum_type,this->value/Bvalue);
-
-	/*Return output pointer*/
-	return outinput;
-
-}
-/*}}}*/
-Input* DoubleInput::PointwiseMax(Input* input){/*{{{*/
-
-	/*Ouput*/
-	DoubleInput* outinput=NULL;
-
-	/*Intermediaries*/
-	IssmDouble       max;
-
-	/*Check that inputB is of the same type*/
-	if (input->Max() > this->Max()) max=input->Max();
-	else max=this->Max();
-
-	/*Create new DoubleInput*/
-	outinput=new DoubleInput(this->enum_type,max);
-
-	/*Return output pointer*/
-	return outinput;
-
-}
-/*}}}*/
-Input* DoubleInput::PointwiseMin(Input* input){/*{{{*/
-
-	/*Ouput*/
-	DoubleInput* outinput=NULL;
-
-	/*Intermediaries*/
-	IssmDouble       min;
-
-	/*Check that inputB is of the same type*/
-	if (input->Min() < this->Min()) min=input->Min();
-	else min=this->Min();
-
-	/*Create new DoubleInput*/
-	outinput=new DoubleInput(this->enum_type,min);
-
-	/*Return output pointer*/
-	return outinput;
-
-}
-/*}}}*/
 void DoubleInput::Scale(IssmDouble scale_factor){/*{{{*/
 	value=value*scale_factor;
 }
 /*}}}*/
-void DoubleInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){/*{{{*/
-
-	/*square min of a IssmDouble is the square of the IssmDouble itself: */
-	*psquaremin=pow(value,2);
-}
-/*}}}*/
-void DoubleInput::VerticallyIntegrate(Input* thickness_input){/*{{{*/
-
-	/*Intermediaries*/
-	IssmDouble thickness_value;
-
-	/*Check that input provided is a thickness*/
-	if (thickness_input->InstanceEnum()!=ThicknessEnum) _error_("Input provided is not a Thickness (enum_type is " << EnumToStringx(thickness_input->InstanceEnum()) << ")");
-
-	/*vertically integrate depending on type:*/
-	switch(thickness_input->ObjectEnum()){
-
-		case PentaInputEnum:
-			thickness_input->GetInputAverage(&thickness_value);
-			this->value=this->value*thickness_value;
-			return;
-
-		default:
-			_error_("not implemented yet");
-	}
-}
-/*}}}*/
Index: /issm/trunk/src/c/classes/Inputs/DoubleInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/DoubleInput.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Inputs/DoubleInput.h	(revision 22758)
@@ -39,7 +39,4 @@
 		int  GetResultNumberOfNodes(void){return 1;};
 		int   InstanceEnum();
-		Input* PointwiseDivide(Input* inputB);
-		Input* PointwiseMax(Input* inputB);
-		Input* PointwiseMin(Input* inputB);
 		void ResultToPatch(IssmDouble* values,int nodesperelement,int sid){_error_("not supported yet");};
 		Input* SpawnSegInput(int index1,int index2);
@@ -49,6 +46,4 @@
 		void AXPY(Input* xinput,IssmDouble scalar);
 		void ChangeEnum(int newenumtype);
-		void Constrain(IssmDouble cm_min, IssmDouble cm_max);
-		void ConstrainMin(IssmDouble minimum);
 		void Extrude(int start){_error_("not supported yet");};
 		void GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes){_error_("not implemented yet");};
@@ -63,6 +58,6 @@
 		void GetInputValue(IssmDouble* pvalue,Gauss* gauss ,int index){_error_("not implemented yet");};
 		void GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime){_error_("not implemented yet");};
+		int  GetInputInterpolationType(){return P0Enum; };
 		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
-		IssmDouble InfinityNorm(void){_error_("not implemented yet");};
 		IssmDouble Max(void);
 		IssmDouble MaxAbs(void);
@@ -71,6 +66,4 @@
 		void Scale(IssmDouble scale_factor);
 		void Set(IssmDouble setvalue){_error_("Set not implemented yet");};
-		void SquareMin(IssmDouble* psquaremin,Parameters* parameters);
-		void VerticallyIntegrate(Input* thickness_input);
 		/*}}}*/
 
Index: /issm/trunk/src/c/classes/Inputs/Input.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/Input.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Inputs/Input.h	(revision 22758)
@@ -37,13 +37,11 @@
 		virtual void GetInputValue(IssmDouble* pvalue,Gauss* gauss,IssmDouble time)=0;
 		virtual void GetInputValue(IssmDouble* pvalue,Gauss* gauss,int index)=0;
+		virtual int  GetInputInterpolationType()=0;
 		virtual void GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime)=0;
 		virtual int  InstanceEnum()=0; 
 
 		virtual void   AXPY(Input* xinput,IssmDouble scalar)=0;
-		virtual void   Constrain(IssmDouble cm_min, IssmDouble cm_max)=0;
-		virtual void   ConstrainMin(IssmDouble minimum)=0;
 		virtual void   Extrude(int start)=0;
 		virtual void   GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist)=0;
-		virtual IssmDouble InfinityNorm(void)=0;
 		virtual IssmDouble Max(void)=0;
 		virtual IssmDouble MaxAbs(void)=0;
@@ -52,13 +50,8 @@
 		virtual void   Scale(IssmDouble scale_factor)=0;
 		virtual void   Set(IssmDouble setvalue)=0;
-		virtual void   SquareMin(IssmDouble* psquaremin,Parameters* parameters)=0;
-		virtual void   VerticallyIntegrate(Input* thickness_input)=0;
 
 		virtual int  GetResultArraySize(void)=0;
 		virtual int  GetResultInterpolation(void)=0;
 		virtual int  GetResultNumberOfNodes(void)=0;
-		virtual Input* PointwiseDivide(Input* inputB)=0;
-		virtual Input* PointwiseMax(Input* inputmax)=0;
-		virtual Input* PointwiseMin(Input* inputmin)=0;
 		virtual Input* SpawnSegInput(int index1,int index2)=0;
 		virtual Input* SpawnTriaInput(int index1,int index2,int index3)=0;
Index: /issm/trunk/src/c/classes/Inputs/Inputs.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/Inputs.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Inputs/Inputs.cpp	(revision 22758)
@@ -31,22 +31,21 @@
 int  Inputs::AddInput(Input* in_input){/*{{{*/
 
-	/*First, go through dataset of inputs and check whether any input 
-	 * with the same name is already in. If so, erase the corresponding 
-	 * object before adding this new one: */
-	vector<Object*>::iterator object;
-	Input* input=NULL;
-
-	/*In debugging mode, check that the input is not a NULL pointer*/
-	_assert_(in_input);
-
-	for ( object=objects.begin() ; object < objects.end(); object++ ){
-
-		input=xDynamicCast<Input*>(*object);
-
-		if (input->InstanceEnum()==in_input->InstanceEnum()){
-			this->DeleteObject(input);
-			break;
+	_assert_(in_input); 
+	int enum_name = in_input->InstanceEnum();
+
+	/*Go through current inputs*/
+	int size = this->Size();
+	for(int i=0;i<size;i++){
+		Input* input=xDynamicCast<Input*>(this->objects[i]);
+
+		/*If it's already there, remove it and replace it with in_input*/
+		if(input->InstanceEnum()==enum_name){
+			delete input;
+			this->objects[i] = in_input;
+			return 1;
 		}
 	}
+
+	/*It is new, add input to the dataset*/
 	this->AddObject(in_input);
 
@@ -54,47 +53,21 @@
 }
 /*}}}*/
-void  Inputs::AXPY(int inputy_enum, IssmDouble scalar, int inputx_enum){/*{{{*/
-
-	/*Find x and y inputs: */
-	Input* xinput=xDynamicCast<Input*>(this->GetInput(inputx_enum));
-	Input* yinput=xDynamicCast<Input*>(this->GetInput(inputy_enum));
-
-	/*some checks: */
-	if(!xinput) _error_("input " << EnumToStringx(inputx_enum) << " could not be found!");
-	if(!yinput) _error_("input " << EnumToStringx(inputy_enum) << " could not be found!");
-
-	/*Apply AXPY: */
-	yinput->AXPY(xinput,scalar);
-}
-/*}}}*/
 void  Inputs::ChangeEnum(int oldenumtype,int newenumtype){/*{{{*/
 
-	/*Go through dataset of inputs and look for input with 
-	 * same enum as input enum, once found, just change its name */
-	vector<Object*>::iterator object;
-	Input* input=NULL;
-
-	/*Delete existing input of newenumtype if it exists*/
-	for ( object=objects.begin() ; object < objects.end(); object++ ){
-		input=xDynamicCast<Input*>(*object);
-
-		if (input->InstanceEnum()==newenumtype){
-			this->DeleteObject(input);
-			break;
+	/*Delete input if it already exists*/
+	this->DeleteInput(newenumtype);
+
+	/*Go through current inputs*/
+	int size = this->Size();
+	for(int i=0;i<size;i++){
+		Input* input=xDynamicCast<Input*>(this->objects[i]);
+
+		/*If it's already there, remove it and replace it with in_input*/
+		if(input->InstanceEnum()==oldenumtype){
+			input->ChangeEnum(newenumtype);
+			return;
 		}
 	}
-
-	/*Change enum_type of input of oldenumtype*/
-	for ( object=objects.begin() ; object < objects.end(); object++ ){
-
-		input=xDynamicCast<Input*>(*object);
-
-		if (input->InstanceEnum()==oldenumtype){
-			input->ChangeEnum(newenumtype);
-			break;
-		}
-	}
-}
-/*}}}*/
+}/*}}}*/
 void Inputs::Configure(Parameters* parameters){/*{{{*/
 
@@ -111,31 +84,8 @@
 }
 /*}}}*/
-void  Inputs::ConstrainMin(int constrain_enum, IssmDouble minimum){/*{{{*/
-
-	/*Find x and y inputs: */
-	Input* constrain_input=xDynamicCast<Input*>(this->GetInput(constrain_enum));
-
-	/*some checks: */
-	if(!constrain_input) _error_("input " << EnumToStringx(constrain_enum) << " could not be found!");
-
-	/*Apply ContrainMin: */
-	constrain_input->ConstrainMin(minimum);
-}
-/*}}}*/
 int  Inputs::DeleteInput(int enum_type){/*{{{*/
 
-	vector<Object*>::iterator object;
-	Input* input=NULL;
-
-	for ( object=objects.begin() ; object < objects.end(); object++ ){
-
-		input=xDynamicCast<Input*>(*object);
-
-		if (input->InstanceEnum()==enum_type){
-			this->DeleteObject(input);
-			break;
-		}
-	}
-
+	Input* input=this->GetInput(enum_type);
+	if(input) this->DeleteObject(input);
 	return 1;
 
@@ -145,5 +95,5 @@
 
 	/*Make a copy of the original input: */
-	Input* original=xDynamicCast<Input*>(this->GetInput(original_enum));
+	Input* original=this->GetInput(original_enum);
 	if(!original)_error_("could not find input with enum: " << EnumToStringx(original_enum)); 
 	Input* copy=xDynamicCast<Input*>(original->copy());
@@ -162,11 +112,8 @@
 
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
-
 		input=xDynamicCast<Input*>(*object);
-
-		if (input->InstanceEnum()==enum_name){
-			return input;
-		}
-	}
+		if (input->InstanceEnum()==enum_name) return input;
+	}
+
 	return NULL;
 }
@@ -174,23 +121,7 @@
 void Inputs::GetInputAverage(IssmDouble* pvalue,int enum_type){/*{{{*/
 
-	vector<Object*>::iterator object;
-	Input* input=NULL;
-	bool   found=false;
-
-	/*Go through inputs and check whether any input with the same name is already in: */
-	for ( object=objects.begin() ; object < objects.end(); object++ ){
-
-		input=xDynamicCast<Input*>(*object);
-		if (input->InstanceEnum()==enum_type){
-			found=true;
-			break;
-		}
-	}
-
-	if (!found){
-		/*we could not find an input with the correct enum type. No defaults values were provided, 
-		 * error out: */
-		_error_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
-	}
+	/*Find input in current dataset*/
+	Input* input=this->GetInput(enum_type);
+	if (!input) _error_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
 
 	/*Ok, we have an input if we made it here, request the input to return the value: */
@@ -201,23 +132,7 @@
 void Inputs::GetInputValue(bool* pvalue,int enum_type){/*{{{*/
 
-	vector<Object*>::iterator object;
-	Input* input=NULL;
-	bool   found=false;
-
-	/*Go through inputs and check whether any input with the same name is already in: */
-	for ( object=objects.begin() ; object < objects.end(); object++ ){
-
-		input=xDynamicCast<Input*>(*object);
-		if (input->InstanceEnum()==enum_type){
-			found=true;
-			break;
-		}
-	}
-
-	if (!found){
-		/*we could not find an input with the correct enum type. No defaults values were provided, 
-		 * error out: */
-		_error_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
-	}
+	/*Find input in current dataset*/
+	Input* input=this->GetInput(enum_type);
+	if (!input) _error_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
 
 	/*Ok, we have an input if we made it here, request the input to return the value: */
@@ -228,156 +143,62 @@
 void Inputs::GetInputValue(int* pvalue,int enum_type){/*{{{*/
 
-	vector<Object*>::iterator object;
-	Input* input=NULL;
-	bool   found=false;
-
-	/*Go through inputs and check whether any input with the same name is already in: */
-	for ( object=objects.begin() ; object < objects.end(); object++ ){
-
-		input=xDynamicCast<Input*>(*object);
-		if (input->InstanceEnum()==enum_type){
-			found=true;
-			break;
-		}
-	}
-
-	if (!found){
-		/*we could not find an input with the correct enum type. No defaults values were provided, 
-		 * error out: */
-		_error_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
-	}
+	/*Find input in current dataset*/
+	Input* input=this->GetInput(enum_type);
+	if (!input) _error_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
 
 	/*Ok, we have an input if we made it here, request the input to return the value: */
 	input->GetInputValue(pvalue);
 
-}
-/*}}}*/
+}/*}}}*/
 void Inputs::GetInputValue(IssmDouble* pvalue,int enum_type){/*{{{*/
 
-	vector<Object*>::iterator object;
-	Input* input=NULL;
-	bool   found=false;
-
-	/*Go through inputs and check whether any input with the same name is already in: */
-	for ( object=objects.begin() ; object < objects.end(); object++ ){
-
-		input=xDynamicCast<Input*>(*object); 
-		if (input->InstanceEnum()==enum_type){
-			found=true;
-			break;
-		}
-	}
-
-	if (!found){
-		/*we could not find an input with the correct enum type. No defaults values were provided, 
-		 * error out: */
-		_error_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
-	}
+	/*Find input in current dataset*/
+	Input* input=this->GetInput(enum_type);
+	if (!input) _error_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
 
 	/*Ok, we have an input if we made it here, request the input to return the value: */
 	input->GetInputValue(pvalue);
 
-}
-/*}}}*/
-IssmDouble Inputs::InfinityNorm(int enumtype){/*{{{*/
-
-	/*Output*/
-	IssmDouble norm;
-
-	/*Get input*/
-	Input* input=xDynamicCast<Input*>(this->GetInput(enumtype));
-
-	/*Apply ContrainMin: */
-	if (input){
-		norm=input->InfinityNorm();
-	}
-	else{
-		norm=0;
-	}
-
-	/*Return output*/
-	return norm;
-}
-/*}}}*/
+}/*}}}*/
 IssmDouble Inputs::Max(int enumtype){/*{{{*/
 
-	/*Output*/
-	IssmDouble max;
-
-	/*Get input*/
-	Input* input=xDynamicCast<Input*>(this->GetInput(enumtype));
-
-	/*Apply ContrainMin: */
-	if (input){
-		max=input->Max();
-	}
-	else{
-		_error_("Input " << EnumToStringx(enumtype) << " not found");
-	}
-
-	/*Return output*/
-	return max;
-}
-/*}}}*/
+	/*Find input in current dataset*/
+	Input* input=this->GetInput(enumtype);
+	if (!input) _error_("could not find input with enum " << EnumToStringx(enumtype));
+
+	/*Return output*/
+	return input->Max();
+
+}/*}}}*/
 IssmDouble Inputs::MaxAbs(int enumtype){/*{{{*/
 
-	/*Output*/
-	IssmDouble max;
-
-	/*Get input*/
-	Input* input=xDynamicCast<Input*>(this->GetInput(enumtype));
-
-	/*Apply ContrainMin: */
-	if (input){
-		max=input->MaxAbs();
-	}
-	else{
-		_error_("Input " << EnumToStringx(enumtype) << " not found");
-	}
-
-	/*Return output*/
-	return max;
-}
-/*}}}*/
+	/*Find input in current dataset*/
+	Input* input=this->GetInput(enumtype);
+	if (!input) _error_("could not find input with enum " << EnumToStringx(enumtype));
+
+	/*Return output*/
+	return input->MaxAbs();
+
+}/*}}}*/
 IssmDouble Inputs::Min(int enumtype){/*{{{*/
 
-	/*Output*/
-	IssmDouble min;
-
-	/*Get input*/
-	Input* input=xDynamicCast<Input*>(this->GetInput(enumtype));
-
-	/*Apply ContrainMin: */
-	if (input){
-		min=input->Min();
-	}
-	else{
-		_error_("Input " << EnumToStringx(enumtype) << " not found");
-	}
-
-	/*Return output*/
-	return min;
-}
-/*}}}*/
+	/*Find input in current dataset*/
+	Input* input=this->GetInput(enumtype);
+	if (!input) _error_("could not find input with enum " << EnumToStringx(enumtype));
+
+	/*Return output*/
+	return input->Min();
+
+}/*}}}*/
 IssmDouble Inputs::MinAbs(int enumtype){/*{{{*/
 
-	/*Output*/
-	IssmDouble min;
-
-	/*Get input*/
-	Input* input=xDynamicCast<Input*>(this->GetInput(enumtype));
-
-	/*Apply ContrainMin: */
-	if (input){
-		min=input->MinAbs();
-	}
-	else{
-		_error_("Input " << EnumToStringx(enumtype) << " not found");
-	}
-
-	/*Return output*/
-	return min;
-}
-/*}}}*/
+	/*Find input in current dataset*/
+	Input* input=this->GetInput(enumtype);
+	if (!input) _error_("could not find input with enum " << EnumToStringx(enumtype));
+
+	/*Return output*/
+	return input->MinAbs();
+
+}/*}}}*/
 Inputs* Inputs::SpawnSegInputs(int index1,int index2){/*{{{*/
 
Index: /issm/trunk/src/c/classes/Inputs/Inputs.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/Inputs.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Inputs/Inputs.h	(revision 22758)
@@ -23,8 +23,6 @@
 		/*numerics*/
 		int         AddInput(Input* in_input);
-		void        AXPY(int inputy_enum, IssmDouble scalar, int inputx_enum);
 		void        ChangeEnum(int enumtype,int new_enumtype);
 		void        Configure(Parameters* parameters);
-		void        ConstrainMin(int constrain_enum, IssmDouble minimum);
 		int         DeleteInput(int enum_type);
 		void        DuplicateInput(int original_enum,int new_enum);
@@ -35,5 +33,4 @@
 		void        GetInputValue(int* pvalue,int enum_type);
 		void        GetInputValue(IssmDouble* pvalue,int enum_type);
-		IssmDouble  InfinityNorm(int enumtype);
 		IssmDouble  Max(int enumtype);
 		IssmDouble  MaxAbs(int enumtype);
Index: /issm/trunk/src/c/classes/Inputs/IntInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/IntInput.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Inputs/IntInput.cpp	(revision 22758)
@@ -127,11 +127,4 @@
 }
 /*}}}*/
-void IntInput::Constrain(IssmDouble cm_min, IssmDouble cm_max){/*{{{*/
-
-	if(!xIsNan<IssmDouble>(cm_min)) if (this->value<cm_min)this->value=reCast<int>(cm_min);
-	if(!xIsNan<IssmDouble>(cm_max)) if (this->value>cm_max)this->value=reCast<int>(cm_max);
-
-}
-/*}}}*/
 void IntInput::GetInputAverage(IssmDouble* pvalue){/*{{{*/
 	*pvalue=reCast<IssmDouble>(value);
@@ -161,8 +154,2 @@
 }
 /*}}}*/
-void IntInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){/*{{{*/
-
-	/*square min of an integer is the square of the integer itself: */
-	*psquaremin=pow((IssmDouble)value,2);
-}
-/*}}}*/
Index: /issm/trunk/src/c/classes/Inputs/IntInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/IntInput.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Inputs/IntInput.h	(revision 22758)
@@ -40,7 +40,4 @@
 		int  GetResultNumberOfNodes(void){return 1;};
 		int   InstanceEnum();
-		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
-		Input* PointwiseMax(Input* inputB){_error_("not implemented yet");};
-		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
 		void ResultToPatch(IssmDouble* values,int nodesperelement,int sid){_error_("not supported yet");};
 		Input* SpawnSegInput(int index1,int index2);
@@ -50,6 +47,4 @@
 		void AXPY(Input* xinput,IssmDouble scalar);
 		void ChangeEnum(int newenumtype);
-		void Constrain(IssmDouble cm_min, IssmDouble cm_max);
-		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
 		void Extrude(int start){_error_("not supported yet");};
 		void GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes){_error_("not implemented yet");};
@@ -64,6 +59,6 @@
 		void GetInputValue(IssmDouble* pvalue,Gauss* gauss ,int index){_error_("not implemented yet");};
 		void GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime){_error_("not implemented yet");};
+		int  GetInputInterpolationType(){_error_("not implemented yet!");};
 		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
-		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");};
@@ -72,6 +67,4 @@
 		void Scale(IssmDouble scale_factor);
 		void Set(IssmDouble setvalue){_error_("Set not implemented yet");};
-		void SquareMin(IssmDouble* psquaremin,Parameters* parameters);
-		void VerticallyIntegrate(Input* thickness_input){_error_("not supported yet");};
 		/*}}}*/
 
Index: /issm/trunk/src/c/classes/Inputs/PentaInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/PentaInput.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Inputs/PentaInput.cpp	(revision 22758)
@@ -219,20 +219,4 @@
 }
 /*}}}*/
-void PentaInput::Constrain(IssmDouble cm_min, IssmDouble cm_max){/*{{{*/
-
-	int i;
-	const int numnodes=this->NumberofNodes(this->interpolation_type);
-
-	if(!xIsNan<IssmDouble>(cm_min)) for(i=0;i<numnodes;i++)if (this->values[i]<cm_min)this->values[i]=cm_min;
-	if(!xIsNan<IssmDouble>(cm_max)) for(i=0;i<numnodes;i++)if (this->values[i]>cm_max)this->values[i]=cm_max;
-
-}
-/*}}}*/
-void PentaInput::ConstrainMin(IssmDouble minimum){/*{{{*/
-
-	int numnodes = this->NumberofNodes(this->interpolation_type);
-	for(int i=0;i<numnodes;i++) if (values[i]<minimum) values[i]=minimum;
-}
-/*}}}*/
 void PentaInput::Extrude(int start){/*{{{*/
 
@@ -246,4 +230,40 @@
 			}
 			break;
+		case P1xP2Enum:
+			if(start==-1){
+				for(int i=0+3;i<9;i+=3) this->values[i]=this->values[0];
+				for(int i=1+3;i<9;i+=3) this->values[i]=this->values[1];
+				for(int i=2+3;i<9;i+=3) this->values[i]=this->values[2];
+			}
+			else{
+				for(int i=0;i<6;i+=3) this->values[i]=this->values[6];
+				for(int i=1;i<6;i+=3) this->values[i]=this->values[7];
+				for(int i=2;i<6;i+=3) this->values[i]=this->values[8];
+			}
+			break;
+		case P1xP3Enum:
+			if(start==-1){
+				for(int i=0+3;i<12;i+=3) this->values[i]=this->values[0];
+				for(int i=1+3;i<12;i+=3) this->values[i]=this->values[1];
+				for(int i=2+3;i<12;i+=3) this->values[i]=this->values[2];
+			}
+			else{
+				for(int i=0;i<9;i+=3) this->values[i]=this->values[9];
+				for(int i=1;i<9;i+=3) this->values[i]=this->values[10];
+				for(int i=2;i<9;i+=3) this->values[i]=this->values[11];
+			}
+			break;
+		case P1xP4Enum:
+			if(start==-1){
+				for(int i=0+3;i<15;i+=3) this->values[i]=this->values[0];
+				for(int i=1+3;i<15;i+=3) this->values[i]=this->values[1];
+				for(int i=2+3;i<15;i+=3) this->values[i]=this->values[2];
+			}
+			else{
+				for(int i=0;i<12;i+=3) this->values[i]=this->values[12];
+				for(int i=1;i<12;i+=3) this->values[i]=this->values[13];
+				for(int i=2;i<12;i+=3) this->values[i]=this->values[14];
+			}
+			break;
 		default:
 			_error_("not supported yet for type "<<EnumToStringx(this->interpolation_type));
@@ -255,14 +275,4 @@
 	vector->SetValues(numvertices,doflist,this->values,INS_VAL);
 } /*}}}*/
-IssmDouble PentaInput::InfinityNorm(void){/*{{{*/
-
-	/*Output*/
-	IssmDouble norm=0.;
-	int numnodes=this->NumberofNodes(this->interpolation_type);
-
-	for(int i=0;i<numnodes;i++) if(fabs(values[i])>norm) norm=fabs(values[i]);
-	return norm;
-}
-/*}}}*/
 IssmDouble PentaInput::Max(void){/*{{{*/
 
@@ -309,96 +319,4 @@
 }
 /*}}}*/
-Input* PentaInput::PointwiseDivide(Input* inputB){/*{{{*/
-
-	/*Ouput*/
-	PentaInput* outinput=NULL;
-
-	/*Intermediaries*/
-	PentaInput *xinputB  = NULL;
-	const int   numnodes = this->NumberofNodes(this->interpolation_type);
-
-	/*Check that inputB is of the same type*/
-	if(inputB->ObjectEnum()!=PentaInputEnum)     _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
-	xinputB=(PentaInput*)inputB;
-	if(xinputB->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->interpolation_type));
-
-	/*Allocate intermediary*/
-	IssmDouble* AdotBvalues=xNew<IssmDouble>(numnodes);
-
-	/*Create point wise sum*/
-	for(int i=0;i<numnodes;i++){
-		_assert_(xinputB->values[i]!=0);
-		AdotBvalues[i]=this->values[i]/xinputB->values[i];
-	}
-
-	/*Create new Penta vertex input (copy of current input)*/
-	outinput=new PentaInput(this->enum_type,AdotBvalues,this->interpolation_type);
-
-	/*Return output pointer*/
-	xDelete<IssmDouble>(AdotBvalues);
-	return outinput;
-
-}
-/*}}}*/
-Input* PentaInput::PointwiseMax(Input* inputB){/*{{{*/
-
-	/*Ouput*/
-	PentaInput* outinput=NULL;
-
-	/*Intermediaries*/
-	int         i;
-	PentaInput  *xinputB   = NULL;
-	const int   numnodes  = this->NumberofNodes(this->interpolation_type);
-	IssmDouble *maxvalues = xNew<IssmDouble>(numnodes);
-
-	/*Check that inputB is of the same type*/
-	if(inputB->ObjectEnum()!=PentaInputEnum) _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
-	xinputB=(PentaInput*)inputB;
-	if(xinputB->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->interpolation_type));
-
-	/*Create point wise max*/
-	for(i=0;i<numnodes;i++){
-		if(this->values[i] < xinputB->values[i]) maxvalues[i]=xinputB->values[i];
-		else maxvalues[i]=this->values[i];
-	}
-
-	/*Create new Penta vertex input (copy of current input)*/
-	outinput=new PentaInput(this->enum_type,&maxvalues[0],this->interpolation_type);
-
-	/*Return output pointer*/
-	xDelete<IssmDouble>(maxvalues);
-	return outinput;
-}
-/*}}}*/
-Input* PentaInput::PointwiseMin(Input* inputB){/*{{{*/
-
-	/*Ouput*/
-	PentaInput* outinput=NULL;
-
-	/*Intermediaries*/
-	int         i;
-	PentaInput  *xinputB   = NULL;
-	const int   numnodes  = this->NumberofNodes(this->interpolation_type);
-	IssmDouble *minvalues = xNew<IssmDouble>(numnodes);
-
-	/*Check that inputB is of the same type*/
-	if(inputB->ObjectEnum()!=PentaInputEnum)       _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
-	xinputB=(PentaInput*)inputB;
-	if(xinputB->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->interpolation_type));
-
-	/*Create point wise min*/
-	for(i=0;i<numnodes;i++){
-		if(this->values[i] > xinputB->values[i]) minvalues[i]=xinputB->values[i];
-		else minvalues[i]=this->values[i];
-	}
-
-	/*Create new Penta vertex input (copy of current input)*/
-	outinput=new PentaInput(this->enum_type,&minvalues[0],this->interpolation_type);
-
-	/*Return output pointer*/
-	xDelete<IssmDouble>(minvalues);
-	return outinput;
-}
-/*}}}*/
 void PentaInput::Scale(IssmDouble scale_factor){/*{{{*/
 
@@ -407,48 +325,2 @@
 }
 /*}}}*/
-void PentaInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){/*{{{*/
-
-	int        numnodes=this->NumberofNodes(this->interpolation_type);
-	IssmDouble squaremin;
-
-	/*Now, figure out minimum of valuescopy: */
-	squaremin=pow(this->values[0],2);
-	for(int i=1;i<numnodes;i++){
-		if(pow(this->values[i],2)<squaremin)squaremin=pow(this->values[i],2);
-	}
-	/*Assign output pointers:*/
-	*psquaremin=squaremin;
-}
-/*}}}*/
-void PentaInput::VerticallyIntegrate(Input* thickness_input){/*{{{*/
-
-	IssmDouble thickness;
-	IssmDouble value=0.;
-
-	/*Check that input provided is a thickness*/
-	if (thickness_input->InstanceEnum()!=ThicknessEnum) _error_("Input provided is not a Thickness (enum_type is " << EnumToStringx(thickness_input->InstanceEnum()) << ")");
-
-	/*vertically integrate depending on type (and use P1 interpolation from now on)*/
-	switch(this->interpolation_type){
-		case P1Enum:
-		case P1bubbleEnum:
-		case P1xP2Enum:
-		case P1xP3Enum:
-		case P2Enum:
-			  {
-				this->interpolation_type=P1Enum;
-				GaussPenta *gauss=new GaussPenta();
-				for(int iv=0;iv<3;iv++){
-					gauss->GaussVertex(iv);
-					thickness_input->GetInputValue(&thickness,gauss);
-					this->values[iv]=0.5*(this->values[iv]+this->values[iv+3]) * thickness;
-					this->values[iv+3]=this->values[iv];
-				}
-				delete gauss;
-				return; 
-			  }
-		default:
-			_error_("not supported yet for type "<<EnumToStringx(this->interpolation_type));
-	}
-}
-/*}}}*/
Index: /issm/trunk/src/c/classes/Inputs/PentaInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/PentaInput.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Inputs/PentaInput.h	(revision 22758)
@@ -36,7 +36,4 @@
 		/*PentaInput management*/
 		int   InstanceEnum();
-		Input* PointwiseDivide(Input* inputB);
-		Input* PointwiseMin(Input* inputB);
-		Input* PointwiseMax(Input* inputB);
 		int  GetResultInterpolation(void);
 		int  GetResultNumberOfNodes(void);
@@ -48,6 +45,4 @@
 		void AXPY(Input* xinput,IssmDouble scalar);
 		void ChangeEnum(int newenumtype);
-		void Constrain(IssmDouble cm_min, IssmDouble cm_max);
-		void ConstrainMin(IssmDouble minimum);
 		void Extrude(int start);
 		void GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes){_error_("not implemented yet");};
@@ -63,5 +58,5 @@
 		void GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime){_error_("not implemented yet");};
 		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
-		IssmDouble InfinityNorm(void);
+		int  GetInputInterpolationType(){_error_("not implemented yet!");};
 		IssmDouble Max(void);
 		IssmDouble MaxAbs(void);
@@ -72,6 +67,4 @@
 		Input* SpawnTriaInput(int index1,int index2,int index3);
 		Input* SpawnSegInput(int index1,int index2);
-		void SquareMin(IssmDouble* psquaremin,Parameters* parameters);
-		void VerticallyIntegrate(Input* thickness_input);
 
 };
Index: /issm/trunk/src/c/classes/Inputs/SegInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/SegInput.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Inputs/SegInput.cpp	(revision 22758)
@@ -114,4 +114,15 @@
 }
 /*}}}*/
+IssmDouble SegInput::Max(void){/*{{{*/
+
+	const int  numnodes=this->NumberofNodes(this->interpolation_type);
+	IssmDouble max=values[0];
+
+	for(int i=1;i<numnodes;i++){
+		if(values[i]>max) max=values[i];
+	}
+	return max;
+}
+/*}}}*/
 IssmDouble SegInput::Min(void){/*{{{*/
 
Index: /issm/trunk/src/c/classes/Inputs/SegInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/SegInput.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Inputs/SegInput.h	(revision 22758)
@@ -41,7 +41,4 @@
 		int  GetResultNumberOfNodes(void){_error_("not implemented");};
 		int    InstanceEnum();
-		Input* PointwiseDivide(Input* inputB){_error_("not supported yet");};
-		Input* PointwiseMax(Input* inputB){_error_("not supported yet");};
-		Input* PointwiseMin(Input* inputB){_error_("not supported yet");};
 		void ResultToPatch(IssmDouble* values,int nodesperelement,int sid){_error_("not supported yet");};
 		Input* SpawnSegInput(int index1,int index2){_error_("not implemented yet");};
@@ -51,6 +48,4 @@
 		void AXPY(Input* xinput,IssmDouble scalar){_error_("not implemented yet");};
 		void ChangeEnum(int newenumtype){_error_("not implemented yet");};
-		void Constrain(IssmDouble cm_min, IssmDouble cm_max){_error_("not implemented yet");};
-		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
 		void Extrude(int start){_error_("not supported yet");};
 		void GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes){_error_("not implemented yet");};
@@ -66,6 +61,6 @@
 		void GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime){_error_("not implemented yet");};
 		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){_error_("not implemented yet");};
-		IssmDouble InfinityNorm(void){_error_("not implemented yet");};
-		IssmDouble Max(void){_error_("not implemented yet");};
+		int  GetInputInterpolationType(){_error_("not implemented yet!");};
+		IssmDouble Max(void);
 		IssmDouble MaxAbs(void){_error_("not implemented yet");};
 		IssmDouble Min(void);
@@ -73,6 +68,4 @@
 		void Scale(IssmDouble scale_factor){_error_("not implemented yet");};
 		void Set(IssmDouble setvalue){_error_("not implemented yet");};
-		void SquareMin(IssmDouble* psquaremin,Parameters* parameters){_error_("not implemented yet");};
-		void VerticallyIntegrate(Input* thickness_input){_error_("not supported yet");};
 
 };
Index: /issm/trunk/src/c/classes/Inputs/TetraInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/TetraInput.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Inputs/TetraInput.cpp	(revision 22758)
@@ -238,34 +238,8 @@
 }
 /*}}}*/
-void TetraInput::Constrain(IssmDouble cm_min, IssmDouble cm_max){/*{{{*/
-
-	int i;
-	const int numnodes=this->NumberofNodes(this->interpolation_type);
-
-	if(!xIsNan<IssmDouble>(cm_min)) for(i=0;i<numnodes;i++)if (this->values[i]<cm_min)this->values[i]=cm_min;
-	if(!xIsNan<IssmDouble>(cm_max)) for(i=0;i<numnodes;i++)if (this->values[i]>cm_max)this->values[i]=cm_max;
-
-}
-/*}}}*/
-void TetraInput::ConstrainMin(IssmDouble minimum){/*{{{*/
-
-	int numnodes = this->NumberofNodes(this->interpolation_type);
-	for(int i=0;i<numnodes;i++) if (values[i]<minimum) values[i]=minimum;
-}
-/*}}}*/
 void TetraInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){/*{{{*/
 	const int numvertices=4;
 	vector->SetValues(numvertices,doflist,this->values,INS_VAL);
 } /*}}}*/
-IssmDouble TetraInput::InfinityNorm(void){/*{{{*/
-
-	/*Output*/
-	IssmDouble norm=0.;
-	int numnodes=this->NumberofNodes(this->interpolation_type);
-
-	for(int i=0;i<numnodes;i++) if(fabs(values[i])>norm) norm=fabs(values[i]);
-	return norm;
-}
-/*}}}*/
 IssmDouble TetraInput::MinAbs(void){/*{{{*/
 
@@ -312,98 +286,4 @@
 }
 /*}}}*/
-Input* TetraInput::PointwiseDivide(Input* inputB){/*{{{*/
-
-	/*Ouput*/
-	TetraInput* outinput=NULL;
-
-	/*Intermediaries*/
-	TetraInput *xinputB  = NULL;
-	const int   numnodes = this->NumberofNodes(this->interpolation_type);
-
-	/*Check that inputB is of the same type*/
-	if(inputB->ObjectEnum()!=TetraInputEnum)     _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
-	xinputB=(TetraInput*)inputB;
-	if(xinputB->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->interpolation_type));
-
-	/*Allocate intermediary*/
-	IssmDouble* AdotBvalues=xNew<IssmDouble>(numnodes);
-
-	/*Create point wise division*/
-	for(int i=0;i<numnodes;i++){
-		_assert_(xinputB->values[i]!=0);
-		AdotBvalues[i]=this->values[i]/xinputB->values[i];
-	}
-
-	/*Create new Tetra vertex input (copy of current input)*/
-	outinput=new TetraInput(this->enum_type,AdotBvalues,this->interpolation_type);
-
-	/*Return output pointer*/
-	xDelete<IssmDouble>(AdotBvalues);
-	return outinput;
-
-}
-/*}}}*/
-Input* TetraInput::PointwiseMax(Input* inputB){/*{{{*/
-
-	/*Ouput*/
-	TetraInput* outinput=NULL;
-
-	/*Intermediaries*/
-	int         i;
-	TetraInput  *xinputB   = NULL;
-	const int   numnodes  = this->NumberofNodes(this->interpolation_type);
-	IssmDouble *maxvalues = xNew<IssmDouble>(numnodes);
-
-	/*Check that inputB is of the same type*/
-	if(inputB->ObjectEnum()!=TetraInputEnum) _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
-	xinputB=(TetraInput*)inputB;
-	if(xinputB->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->interpolation_type));
-
-	/*Create point wise max*/
-	for(i=0;i<numnodes;i++){
-		if(this->values[i] < xinputB->values[i]) maxvalues[i]=xinputB->values[i];
-		else maxvalues[i]=this->values[i];
-	}
-
-	/*Create new Tetra vertex input (copy of current input)*/
-	outinput=new TetraInput(this->enum_type,&maxvalues[0],this->interpolation_type);
-
-	/*Return output pointer*/
-	xDelete<IssmDouble>(maxvalues);
-	return outinput;
-
-}
-/*}}}*/
-Input* TetraInput::PointwiseMin(Input* inputB){/*{{{*/
-
-	/*Ouput*/
-	TetraInput* outinput=NULL;
-
-	/*Intermediaries*/
-	int         i;
-	TetraInput  *xinputB   = NULL;
-	const int   numnodes  = this->NumberofNodes(this->interpolation_type);
-	IssmDouble *minvalues = xNew<IssmDouble>(numnodes);
-
-	/*Check that inputB is of the same type*/
-	if(inputB->ObjectEnum()!=TetraInputEnum)       _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
-	xinputB=(TetraInput*)inputB;
-	if(xinputB->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->interpolation_type));
-
-	/*Create point wise min*/
-	for(i=0;i<numnodes;i++){
-		if(this->values[i] > xinputB->values[i]) minvalues[i]=xinputB->values[i];
-		else minvalues[i]=this->values[i];
-	}
-
-	/*Create new Tetra vertex input (copy of current input)*/
-	outinput=new TetraInput(this->enum_type,&minvalues[0],this->interpolation_type);
-
-	/*Return output pointer*/
-	xDelete<IssmDouble>(minvalues);
-	return outinput;
-
-}
-/*}}}*/
 void TetraInput::Scale(IssmDouble scale_factor){/*{{{*/
 
@@ -418,16 +298,2 @@
 }
 /*}}}*/
-void TetraInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){/*{{{*/
-
-	int        numnodes=this->NumberofNodes(this->interpolation_type);
-	IssmDouble squaremin;
-
-	/*Now, figure out minimum of valuescopy: */
-	squaremin=pow(this->values[0],2);
-	for(int i=1;i<numnodes;i++){
-		if(pow(this->values[i],2)<squaremin)squaremin=pow(this->values[i],2);
-	}
-	/*Assign output pointers:*/
-	*psquaremin=squaremin;
-}
-/*}}}*/
Index: /issm/trunk/src/c/classes/Inputs/TetraInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/TetraInput.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Inputs/TetraInput.h	(revision 22758)
@@ -41,7 +41,4 @@
 		int    GetResultNumberOfNodes(void);
 		int    InstanceEnum();
-		Input* PointwiseDivide(Input* inputB);
-		Input* PointwiseMax(Input* inputB);
-		Input* PointwiseMin(Input* inputB);
 		void   ResultToPatch(IssmDouble* values,int nodesperelement,int sid);
 		Input* SpawnSegInput(int index1,int index2){_error_("not supported yet");};
@@ -51,6 +48,4 @@
 		void AXPY(Input* xinput,IssmDouble scalar);
 		void ChangeEnum(int newenumtype);
-		void Constrain(IssmDouble cm_min, IssmDouble cm_max);
-		void ConstrainMin(IssmDouble minimum);
 		void Extrude(int start){_error_("not supported yet");};
 		void GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes);
@@ -66,5 +61,5 @@
 		void GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime);
 		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
-		IssmDouble InfinityNorm(void);
+		int  GetInputInterpolationType(){_error_("not implemented yet!");};
 		IssmDouble Max(void);
 		IssmDouble MaxAbs(void);
@@ -73,6 +68,4 @@
 		void Scale(IssmDouble scale_factor);
 		void Set(IssmDouble setvalue);
-		void SquareMin(IssmDouble* psquaremin,Parameters* parameters);
-		void VerticallyIntegrate(Input* thickness_input){_error_("not supported yet");};
 
 };
Index: /issm/trunk/src/c/classes/Inputs/TransientInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/TransientInput.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Inputs/TransientInput.cpp	(revision 22758)
@@ -70,6 +70,8 @@
 	output->numtimesteps=this->numtimesteps;
 	output->timesteps=xNew<IssmDouble>(this->numtimesteps);
-	xMemCpy(output->timesteps,this->timesteps,this->numtimesteps);
-	output->inputs=static_cast<Inputs*>(this->inputs->Copy());
+	if(this->numtimesteps>0){
+		xMemCpy(output->timesteps,this->timesteps,this->numtimesteps);
+		output->inputs=static_cast<Inputs*>(this->inputs->Copy());
+	}
 	output->parameters=this->parameters;
 
@@ -133,7 +135,9 @@
 	outinput->enum_type=this->enum_type;
 	outinput->numtimesteps=this->numtimesteps;
-	outinput->timesteps=xNew<IssmDouble>(this->numtimesteps);
-	xMemCpy(outinput->timesteps,this->timesteps,this->numtimesteps);
-	outinput->inputs=(Inputs*)this->inputs->SpawnSegInputs(index1,index2);
+	if(this->numtimesteps>0){
+		outinput->timesteps=xNew<IssmDouble>(this->numtimesteps);
+		xMemCpy(outinput->timesteps,this->timesteps,this->numtimesteps);
+		outinput->inputs=(Inputs*)this->inputs->SpawnSegInputs(index1,index2);
+	}
 	outinput->parameters=this->parameters;
 
@@ -152,7 +156,9 @@
 	outinput->enum_type=this->enum_type;
 	outinput->numtimesteps=this->numtimesteps;
-	outinput->timesteps=xNew<IssmDouble>(this->numtimesteps);
-	xMemCpy(outinput->timesteps,this->timesteps,this->numtimesteps);
-	outinput->inputs=(Inputs*)this->inputs->SpawnTriaInputs(index1,index2,index3);
+	if(this->numtimesteps>0){
+		outinput->timesteps=xNew<IssmDouble>(this->numtimesteps);
+		xMemCpy<IssmDouble>(outinput->timesteps,this->timesteps,this->numtimesteps);
+		outinput->inputs=(Inputs*)this->inputs->SpawnTriaInputs(index1,index2,index3);
+	}
 	outinput->parameters=this->parameters;
 
@@ -226,5 +232,5 @@
 
 	/*First, recover current time from parameters: */
-	this->parameters->FindParam(&time,TimeEnum);
+	parameters->FindParam(&time,TimeEnum);
 
 	/*Retrieve interpolated values for this time step: */
@@ -248,9 +254,28 @@
 }
 /*}}}*/
+int  TransientInput::GetTimeInputOffset(IssmDouble time){/*{{{*/
+
+	int        found;
+	int        offset;
+
+	/*go through the timesteps, and figure out which interval we
+	 *     *fall within. Then interpolate the values on this interval: */
+	found=binary_search(&offset,time,this->timesteps,this->numtimesteps);
+	if(!found) _error_("Input not found (is TransientInput sorted ?)");
+
+	return offset;
+}
+/*}}}*/
+IssmDouble  TransientInput::GetTimeByOffset(int offset){/*{{{*/
+	if (offset < 0) offset=0;
+	_assert_(offset<(this->numtimesteps));
+	return this->timesteps[offset];
+}
+/*}}}*/
 void TransientInput::GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime){/*{{{*/
 
 	int         i;
-	IssmDouble *times  = NULL;
-	IssmDouble *values = NULL;
+	IssmDouble* times  = NULL;
+	IssmDouble* values = NULL;
 	int         numsteps;
 	bool        iscurrenttime_included = false;
@@ -270,7 +295,5 @@
 
 	for(i=0;i<numsteps;i++){
-
 		if((iscurrenttime_included==false) && (i==(numsteps-1))){
-
 			/*Retrieve interpolated values for current time step: */
 			Input* input=GetTimeInput(currenttime);
@@ -290,4 +313,69 @@
 }
 /*}}}*/
+void TransientInput::GetInputAverageOnTimes(IssmDouble** pvalues, IssmDouble init_time){/*{{{*/
+
+	int					numnodes;
+	IssmDouble  subtimestep;
+	IssmDouble* values= NULL;
+	Input* input=NULL;
+
+	/*Initialize numnode from transientinput out of time loop*/
+	for(int i=0;i<this->numtimesteps;i++){
+		/*First compute the lengt of the sub-timestep*/
+		if(i==0){
+			subtimestep = this->timesteps[i]-init_time;
+		}
+		else{
+			subtimestep = this->timesteps[i]-this->timesteps[i-1];
+		}	
+		/*Figure out type of input and get it*/
+		input = xDynamicCast<Input*>(this->inputs->GetObjectByOffset(i)); _assert_(input);
+		switch(input->ObjectEnum()){
+		case TriaInputEnum:{
+			TriaInput* triainput = (TriaInput*)this->inputs->GetObjectByOffset(i); _assert_(triainput);
+			if(i==0){
+				numnodes= triainput->NumberofNodes(triainput->interpolation_type);
+				values=xNewZeroInit<IssmDouble>(numnodes);
+			}
+			/*Sum the values weighted by their respective sub-timestep*/
+			for(int j=0;j<numnodes;j++){
+				values[j]+=(triainput->values[j]*subtimestep);
+			}
+			break;
+		}
+		case PentaInputEnum:{
+			PentaInput*	pentainput = (PentaInput*)this->inputs->GetObjectByOffset(i); _assert_(pentainput);
+			if(i==0){
+				numnodes= pentainput->NumberofNodes(pentainput->interpolation_type);
+				values=xNewZeroInit<IssmDouble>(numnodes);
+			}
+			/*Sum the values weighted by their respective sub-timestep*/
+			for(int j=0;j<numnodes;j++){
+				values[j]+=(pentainput->values[j]*subtimestep);
+			}
+			break;
+		}
+		case TetraInputEnum:{
+			TetraInput*	tetrainput = (TetraInput*)this->inputs->GetObjectByOffset(i); _assert_(tetrainput);
+			if(i==0){
+				numnodes= tetrainput->NumberofNodes(tetrainput->interpolation_type);
+				values=xNewZeroInit<IssmDouble>(numnodes);
+			}
+			/*Sum the values weighted by their respective sub-timestep*/
+			for(int j=0;j<numnodes;j++){
+				values[j]+=(tetrainput->values[j]*subtimestep);
+			}
+			break;
+		}
+		default: _error_("not implemented yet");
+		}
+	}
+	/*Compute the average based on the length of the full timestep*/
+	for(int j=0;j<numnodes;j++){
+		values[j]=values[j]/(this->timesteps[this->numtimesteps-1]-init_time);
+	}
+	*pvalues=values;
+}
+/*}}}*/
 
 /*Intermediary*/
@@ -379,5 +467,5 @@
 	int        found;
 	int        offset;
-	bool       interp;
+	bool       interp=false;
 
 	/*First, recover interp bool: */
@@ -438,8 +526,8 @@
 
 } /*}}}*/
-IssmDouble TransientInput::InfinityNorm(void){/*{{{*/
-
-	IssmDouble time;
-	IssmDouble infnorm;
+IssmDouble TransientInput::Max(void){/*{{{*/
+
+	IssmDouble time;
+	IssmDouble max;
 
 	/*First, recover current time from parameters: */
@@ -450,15 +538,35 @@
 
 	/*Call input function*/
-	infnorm=input->InfinityNorm();
+	max=input->Max();
+
+	delete input;
+
+	return max;
+}
+/*}}}*/
+IssmDouble TransientInput::MaxAbs(void){/*{{{*/
+
+	IssmDouble time;
+	IssmDouble maxabs;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+	/*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	maxabs=input->MaxAbs();
 
 	/*Clean-up and return*/
 	delete input;
-	return infnorm;
-}
-/*}}}*/
-IssmDouble TransientInput::Max(void){/*{{{*/
-
-	IssmDouble time;
-	IssmDouble max;
+	return maxabs;
+
+}
+/*}}}*/
+IssmDouble TransientInput::Min(void){/*{{{*/
+
+	IssmDouble time;
+	IssmDouble min;
 
 	/*First, recover current time from parameters: */
@@ -469,15 +577,16 @@
 
 	/*Call input function*/
-	max=input->Max();
-
-	delete input;
-
-	return max;
-}
-/*}}}*/
-IssmDouble TransientInput::MaxAbs(void){/*{{{*/
-
-	IssmDouble time;
-	IssmDouble maxabs;
+	min=input->Min();
+
+	/*Clean-up and return*/
+	delete input;
+	return min;
+
+}
+/*}}}*/
+IssmDouble TransientInput::MinAbs(void){/*{{{*/
+
+	IssmDouble time;
+	IssmDouble minabs;
 
 	/*First, recover current time from parameters: */
@@ -488,66 +597,9 @@
 
 	/*Call input function*/
-	maxabs=input->MaxAbs();
+	minabs=input->MinAbs();
 
 	/*Clean-up and return*/
 	delete input;
-	return maxabs;
-
-}
-/*}}}*/
-IssmDouble TransientInput::Min(void){/*{{{*/
-
-	IssmDouble time;
-	IssmDouble min;
-
-	/*First, recover current time from parameters: */
-	parameters->FindParam(&time,TimeEnum);
-
-   /*Retrieve interpolated values for this time step: */
-	Input* input=GetTimeInput(time);
-
-	/*Call input function*/
-	min=input->Min();
-
-	/*Clean-up and return*/
-	delete input;
-	return min;
-
-}
-/*}}}*/
-IssmDouble TransientInput::MinAbs(void){/*{{{*/
-
-	IssmDouble time;
-	IssmDouble minabs;
-
-	/*First, recover current time from parameters: */
-	parameters->FindParam(&time,TimeEnum);
-
-	/*Retrieve interpolated values for this time step: */
-	Input* input=GetTimeInput(time);
-
-	/*Call input function*/
-	minabs=input->MinAbs();
-
-	/*Clean-up and return*/
-	delete input;
 	return minabs;
 }
 /*}}}*/
-void TransientInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){/*{{{*/
-
-	IssmDouble time;
-
-	/*First, recover current time from parameters: */
-	parameters->FindParam(&time,TimeEnum);
-
-   /*Retrieve interpolated values for this time step: */
-	Input* input=GetTimeInput(time);
-
-	/*Call input function*/
-	input->SquareMin(psquaremin,parameters);
-
-	delete input;
-
-}
-/*}}}*/
Index: /issm/trunk/src/c/classes/Inputs/TransientInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/TransientInput.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Inputs/TransientInput.h	(revision 22758)
@@ -45,7 +45,4 @@
 		int  GetResultNumberOfNodes(void);
 		int    InstanceEnum();
-		Input* PointwiseDivide(Input* input_in){_error_("not implemented yet");};
-		Input* PointwiseMax(Input* input_in){_error_("not implemented yet");};
-		Input* PointwiseMin(Input* input_in){_error_("not implemented yet");};
 		void ResultToPatch(IssmDouble* values,int nodesperelement,int sid){_error_("not supported yet");};
 		Input* SpawnSegInput(int index1,int index2);
@@ -55,6 +52,4 @@
 		void AXPY(Input* xforcing,IssmDouble scalar){_error_("not implemented yet");};
 		void ChangeEnum(int newenumtype);
-		void Constrain(IssmDouble cm_min, IssmDouble cm_max){_error_("not implemented yet");};
-		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
 		void Extrude(int start);
 		void GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes);
@@ -69,8 +64,11 @@
 		void GetInputValue(IssmDouble* pvalue,Gauss* gauss ,int index){_error_("not implemented yet");};
 		void GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime);
+		void GetInputAverageOnTimes(IssmDouble** pvalues, IssmDouble init_time);
+		int  GetInputInterpolationType(){_error_("not implemented yet!");};
+		IssmDouble  GetTimeByOffset(int offset);
 		Input* GetTimeInput(IssmDouble time);
+		int  GetTimeInputOffset(IssmDouble time);
 		void GetTimeValues(IssmDouble* values,IssmDouble time){_error_("not implemented yet");};
 		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
-		IssmDouble InfinityNorm(void);
 		IssmDouble Max(void);
 		IssmDouble MaxAbs(void);
@@ -79,6 +77,4 @@
 		void Scale(IssmDouble scale_factor){_error_("not implemented yet");};
 		void Set(IssmDouble setvalue){_error_("Set not implemented yet");};
-		void SquareMin(IssmDouble* psquaremin,Parameters* parameters);
-		void VerticallyIntegrate(Input* thickness_forcing){_error_("not supported yet");};
 		/*}}}*/
 
Index: /issm/trunk/src/c/classes/Inputs/TriaInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/TriaInput.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Inputs/TriaInput.cpp	(revision 22758)
@@ -223,4 +223,5 @@
 }
 /*}}}*/
+
 void TriaInput::GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime){/*{{{*/
 
@@ -271,34 +272,8 @@
 }
 /*}}}*/
-void TriaInput::Constrain(IssmDouble cm_min, IssmDouble cm_max){/*{{{*/
-
-	int i;
-	const int numnodes=this->NumberofNodes(this->interpolation_type);
-
-	if(!xIsNan<IssmDouble>(cm_min)) for(i=0;i<numnodes;i++)if (this->values[i]<cm_min)this->values[i]=cm_min;
-	if(!xIsNan<IssmDouble>(cm_max)) for(i=0;i<numnodes;i++)if (this->values[i]>cm_max)this->values[i]=cm_max;
-
-}
-/*}}}*/
-void TriaInput::ConstrainMin(IssmDouble minimum){/*{{{*/
-
-	int numnodes = this->NumberofNodes(this->interpolation_type);
-	for(int i=0;i<numnodes;i++) if (values[i]<minimum) values[i]=minimum;
-}
-/*}}}*/
 void TriaInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){/*{{{*/
 	const int numvertices=3;
 	vector->SetValues(numvertices,doflist,this->values,INS_VAL);
 } /*}}}*/
-IssmDouble TriaInput::InfinityNorm(void){/*{{{*/
-
-	/*Output*/
-	IssmDouble norm=0.;
-	int numnodes=this->NumberofNodes(this->interpolation_type);
-
-	for(int i=0;i<numnodes;i++) if(fabs(values[i])>norm) norm=fabs(values[i]);
-	return norm;
-}
-/*}}}*/
 IssmDouble TriaInput::Max(void){/*{{{*/
 
@@ -345,98 +320,4 @@
 }
 /*}}}*/
-Input* TriaInput::PointwiseMax(Input* inputB){/*{{{*/
-
-	/*Ouput*/
-	TriaInput* outinput=NULL;
-
-	/*Intermediaries*/
-	int         i;
-	TriaInput  *xinputB   = NULL;
-	const int   numnodes  = this->NumberofNodes(this->interpolation_type);
-	IssmDouble *maxvalues = xNew<IssmDouble>(numnodes);
-
-	/*Check that inputB is of the same type*/
-	if(inputB->ObjectEnum()!=TriaInputEnum) _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
-	xinputB=(TriaInput*)inputB;
-	if(xinputB->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->interpolation_type));
-
-	/*Create point wise max*/
-	for(i=0;i<numnodes;i++){
-		if(this->values[i] < xinputB->values[i]) maxvalues[i]=xinputB->values[i];
-		else maxvalues[i]=this->values[i];
-	}
-
-	/*Create new Tria vertex input (copy of current input)*/
-	outinput=new TriaInput(this->enum_type,&maxvalues[0],this->interpolation_type);
-
-	/*Return output pointer*/
-	xDelete<IssmDouble>(maxvalues);
-	return outinput;
-
-}
-/*}}}*/
-Input* TriaInput::PointwiseMin(Input* inputB){/*{{{*/
-
-	/*Ouput*/
-	TriaInput* outinput=NULL;
-
-	/*Intermediaries*/
-	int         i;
-	TriaInput  *xinputB   = NULL;
-	const int   numnodes  = this->NumberofNodes(this->interpolation_type);
-	IssmDouble *minvalues = xNew<IssmDouble>(numnodes);
-
-	/*Check that inputB is of the same type*/
-	if(inputB->ObjectEnum()!=TriaInputEnum)       _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
-	xinputB=(TriaInput*)inputB;
-	if(xinputB->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->interpolation_type));
-
-	/*Create point wise min*/
-	for(i=0;i<numnodes;i++){
-		if(this->values[i] > xinputB->values[i]) minvalues[i]=xinputB->values[i];
-		else minvalues[i]=this->values[i];
-	}
-
-	/*Create new Tria vertex input (copy of current input)*/
-	outinput=new TriaInput(this->enum_type,&minvalues[0],this->interpolation_type);
-
-	/*Return output pointer*/
-	xDelete<IssmDouble>(minvalues);
-	return outinput;
-
-}
-/*}}}*/
-Input* TriaInput::PointwiseDivide(Input* inputB){/*{{{*/
-
-	/*Ouput*/
-	TriaInput* outinput=NULL;
-
-	/*Intermediaries*/
-	TriaInput *xinputB  = NULL;
-	const int   numnodes = this->NumberofNodes(this->interpolation_type);
-
-	/*Check that inputB is of the same type*/
-	if(inputB->ObjectEnum()!=TriaInputEnum)     _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
-	xinputB=(TriaInput*)inputB;
-	if(xinputB->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->interpolation_type));
-
-	/*Allocate intermediary*/
-	IssmDouble* AdotBvalues=xNew<IssmDouble>(numnodes);
-
-	/*Create point wise division*/
-	for(int i=0;i<numnodes;i++){
-		_assert_(xinputB->values[i]!=0);
-		AdotBvalues[i]=this->values[i]/xinputB->values[i];
-	}
-
-	/*Create new Tria vertex input (copy of current input)*/
-	outinput=new TriaInput(this->enum_type,AdotBvalues,this->interpolation_type);
-
-	/*Return output pointer*/
-	xDelete<IssmDouble>(AdotBvalues);
-	return outinput;
-
-}
-/*}}}*/
 void TriaInput::Scale(IssmDouble scale_factor){/*{{{*/
 
@@ -451,16 +332,2 @@
 }
 /*}}}*/
-void TriaInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){/*{{{*/
-
-	int        numnodes=this->NumberofNodes(this->interpolation_type);
-	IssmDouble squaremin;
-
-	/*Now, figure out minimum of valuescopy: */
-	squaremin=pow(this->values[0],2);
-	for(int i=1;i<numnodes;i++){
-		if(pow(this->values[i],2)<squaremin)squaremin=pow(this->values[i],2);
-	}
-	/*Assign output pointers:*/
-	*psquaremin=squaremin;
-}
-/*}}}*/
Index: /issm/trunk/src/c/classes/Inputs/TriaInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/TriaInput.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Inputs/TriaInput.h	(revision 22758)
@@ -41,7 +41,4 @@
 		int    GetResultNumberOfNodes(void);
 		int    InstanceEnum();
-		Input* PointwiseDivide(Input* inputB);
-		Input* PointwiseMax(Input* inputB);
-		Input* PointwiseMin(Input* inputB);
 		void   ResultToPatch(IssmDouble* values,int nodesperelement,int sid);
 		Input* SpawnSegInput(int index1,int index2);
@@ -51,6 +48,4 @@
 		void AXPY(Input* xinput,IssmDouble scalar);
 		void ChangeEnum(int newenumtype);
-		void Constrain(IssmDouble cm_min, IssmDouble cm_max);
-		void ConstrainMin(IssmDouble minimum);
 		void Extrude(int start){_error_("not supported yet");};
 		void GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes);
@@ -65,6 +60,6 @@
 		void GetInputValue(IssmDouble* pvalue,Gauss* gauss,int index){_error_("not implemented yet");};
 		void GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime);
+		int  GetInputInterpolationType(){return interpolation_type;};
 		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
-		IssmDouble InfinityNorm(void);
 		IssmDouble Max(void);
 		IssmDouble MaxAbs(void);
@@ -73,6 +68,4 @@
 		void Scale(IssmDouble scale_factor);
 		void Set(IssmDouble setvalue);
-		void SquareMin(IssmDouble* psquaremin,Parameters* parameters);
-		void VerticallyIntegrate(Input* thickness_input){_error_("not supported yet");};
 
 };
Index: /issm/trunk/src/c/classes/IoModel.cpp
===================================================================
--- /issm/trunk/src/c/classes/IoModel.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/IoModel.cpp	(revision 22758)
@@ -22,4 +22,5 @@
 #include <stdlib.h>
 #include <stdarg.h>
+#include <stdint.h>
 
 #include "./classes.h"
@@ -603,4 +604,6 @@
 					if(strcmp(record_name,"md.hydrology.model")==0) integer = IoCodeToEnumHydrology(integer);
 					if(strcmp(record_name,"md.materials.type")==0) integer = IoCodeToEnumMaterials(integer);
+					if(strcmp(record_name,"md.timestepping.type")==0) integer = IoCodeToEnumTimestepping(integer);
+					if(strcmp(record_name,"md.amr.type")==0) integer = IoCodeToEnumAmr(integer);
 
 					/*Broadcast to other cpus*/
@@ -1172,5 +1175,5 @@
 
 			/*read time now*/
-			IssmPDouble* timematrix=xNew<IssmDouble>(N);
+			IssmPDouble* timematrix=xNew<IssmPDouble>(N);
 			if(my_rank==0) if(fread(timematrix,N*sizeof(IssmPDouble),1,fid)!=1) _error_("could not read time in compressed matrix");
 			ISSM_MPI_Bcast(timematrix,N,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm()); 
Index: /issm/trunk/src/c/classes/IoModel.h
===================================================================
--- /issm/trunk/src/c/classes/IoModel.h	(revision 22757)
+++ /issm/trunk/src/c/classes/IoModel.h	(revision 22758)
@@ -87,4 +87,5 @@
 		int loadcounter;         //keep track of how many loads are being created in each analysis
 		int nodecounter;         //keep track of how many nodes are being created in each analysis
+		int matparcounter;       //keep track of where we end up putting this object accessed by every element.
 
 		/*Methods*/
Index: /issm/trunk/src/c/classes/Loads/Friction.cpp
===================================================================
--- /issm/trunk/src/c/classes/Loads/Friction.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Loads/Friction.cpp	(revision 22758)
@@ -70,4 +70,5 @@
 	IssmDouble  vx,vy,vz,vmag;
 	IssmDouble  alpha_complement;
+	IssmDouble  base,sealevel,thickness;
 
 	/*Recover parameters: */
@@ -77,11 +78,25 @@
 	element->GetInputValue(&As,gauss,FrictionAsEnum);
 	element->GetInputValue(&n,gauss,MaterialsRheologyNEnum);
+	element->GetInputValue(&thickness, gauss,ThicknessEnum);
+	element->GetInputValue(&base, gauss,BaseEnum);
+	element->GetInputValue(&sealevel, gauss,SealevelEnum);
+
+	IssmDouble rho_water   = element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	IssmDouble rho_ice     = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble gravity     = element->GetMaterialParameter(ConstantsGEnum);
 	element->parameters->FindParam(&CoupledFlag,FrictionCouplingEnum);
 
-	if (CoupledFlag==1){
-		element->GetInputValue(&Neff,gauss,EffectivePressureEnum);
-	}
-	else{
-		element->GetInputValue(&Neff,gauss,FrictionEffectivePressureEnum);
+	switch(CoupledFlag){
+		case 0:
+			Neff=gravity*(rho_ice*thickness+rho_water*(base-sealevel));
+			break;
+		case 1:
+			element->GetInputValue(&Neff,gauss,FrictionEffectivePressureEnum);
+			break;
+		case 2:
+			element->GetInputValue(&Neff,gauss,EffectivePressureEnum);
+			break;
+		default:
+			_error_("not supported");
 	}
 
@@ -159,9 +174,10 @@
 void Friction::GetAlphaViscousComplement(IssmDouble* palpha_complement, Gauss* gauss){/*{{{*/
 
-	/* FrictionGetAlpha2 computes alpha2= drag^2 * Neff ^r * vel ^s, with Neff=rho_ice*g*thickness+rho_ice*g*bed, r=q/p and s=1/p. 
+	/* FrictionGetAlpha2 computes alpha2= drag^2 * Neff ^r * vel ^s, with Neff=rho_ice*g*thickness+rho_ice*g*base, r=q/p and s=1/p. 
 	 * FrictionGetAlphaComplement is used in control methods on drag, and it computes: 
 	 * alpha_complement= Neff ^r * vel ^s*/
 
 	/*diverse: */
+	int         CoupledFlag;
 	IssmDouble  r,s;
 	IssmDouble  vx,vy,vz,vmag;
@@ -169,103 +185,6 @@
 	IssmDouble  Neff;
 	IssmDouble  drag_coefficient;
-	IssmDouble  bed,thickness,sealevel;
+	IssmDouble  base,thickness,sealevel;
 	IssmDouble  alpha_complement;
-
-	/*Recover parameters: */
-	element->GetInputValue(&drag_p,FrictionPEnum);
-	element->GetInputValue(&drag_q,FrictionQEnum);
-	element->GetInputValue(&thickness, gauss,ThicknessEnum);
-	element->GetInputValue(&bed, gauss,BaseEnum);
-	element->GetInputValue(&sealevel, gauss,SealevelEnum);
-	element->GetInputValue(&drag_coefficient, gauss,FrictionCoefficientEnum);
-	IssmDouble rho_water   = element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
-	IssmDouble rho_ice     = element->GetMaterialParameter(MaterialsRhoIceEnum);
-	IssmDouble gravity     = element->GetMaterialParameter(ConstantsGEnum);
-
-	//compute r and q coefficients: */
-	r=drag_q/drag_p;
-	s=1./drag_p;
-
-	//From bed and thickness, compute effective pressure when drag is viscous:
-	Neff=gravity*(rho_ice*thickness+rho_water*(bed-sealevel));
-	if(Neff<0)Neff=0;
-
-	//We need the velocity magnitude to evaluate the basal stress:
-	switch(dim){
-		case 1:
-			element->GetInputValue(&vx,gauss,VxEnum);
-			vmag=sqrt(vx*vx);
-			break;
-		case 2:
-			element->GetInputValue(&vx,gauss,VxEnum);
-			element->GetInputValue(&vy,gauss,VyEnum);
-			vmag=sqrt(vx*vx+vy*vy);
-			break;
-		case 3:
-			element->GetInputValue(&vx,gauss,VxEnum);
-			element->GetInputValue(&vy,gauss,VyEnum);
-			element->GetInputValue(&vz,gauss,VzEnum);
-			vmag=sqrt(vx*vx+vy*vy+vz*vz);
-			break;
-		default:
-			_error_("not supported");
-	}
-
-	/*Check to prevent dividing by zero if vmag==0*/
-	if(vmag==0. && (s-1.)<0.) alpha_complement=0.;
-	else alpha_complement=pow(Neff,r)*pow(vmag,(s-1));_assert_(!xIsNan<IssmDouble>(alpha_complement));
-
-	/*Assign output pointers:*/
-	*palpha_complement=alpha_complement;
-}
-/*}}}*/
-void Friction::GetAlpha2(IssmDouble* palpha2, Gauss* gauss){/*{{{*/
-
-	switch(this->law){
-		case 1:
-			GetAlpha2Viscous(palpha2,gauss);
-			break;
-		case 2:
-			GetAlpha2Weertman(palpha2,gauss);
-			break;
-		case 3:
-			GetAlpha2Hydro(palpha2,gauss);
-			break;
-		case 4:
-			GetAlpha2Temp(palpha2,gauss);
-			break;
-		case 5:
-			GetAlpha2WaterLayer(palpha2,gauss);
-			break;
-		case 6:
-			GetAlpha2WeertmanTemp(palpha2,gauss);
-			break;
-		case 7:
-			GetAlpha2Coulomb(palpha2,gauss);
-			break;
-		case 8:
-			GetAlpha2Sommers(palpha2,gauss);
-			break;
-		case 9:
-			GetAlpha2Josh(palpha2,gauss);
-			break;
-	  default:
-			_error_("Friction law "<< this->law <<" not supported");
-	}
-
-}/*}}}*/
-void Friction::GetAlpha2Coulomb(IssmDouble* palpha2, Gauss* gauss){/*{{{*/
-
-	/*This routine calculates the basal friction coefficient 
-	  alpha2= drag^2 * Neff ^r * | vel | ^(s-1), with Neff=rho_ice*g*thickness+rho_ice*g*base, r=q/p and s=1/p**/
-
-	/*diverse: */
-	IssmDouble  r,s;
-	IssmDouble  drag_p, drag_q;
-	IssmDouble  Neff;
-	IssmDouble  thickness,base,bed,floatation_thickness,sealevel;
-	IssmDouble  vx,vy,vz,vmag;
-	IssmDouble  drag_coefficient,drag_coefficient_coulomb;
-	IssmDouble  alpha2,alpha2_coulomb;
 
 	/*Recover parameters: */
@@ -275,5 +194,114 @@
 	element->GetInputValue(&base, gauss,BaseEnum);
 	element->GetInputValue(&sealevel, gauss,SealevelEnum);
-	element->GetInputValue(&bed, gauss,BedEnum);
+	element->GetInputValue(&drag_coefficient, gauss,FrictionCoefficientEnum);
+	IssmDouble rho_water   = element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	IssmDouble rho_ice     = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble gravity     = element->GetMaterialParameter(ConstantsGEnum);
+	element->parameters->FindParam(&CoupledFlag,FrictionCouplingEnum);
+	//compute r and q coefficients: */
+	r=drag_q/drag_p;
+	s=1./drag_p;
+
+	//From base and thickness, compute effective pressure when drag is viscous, or get Neff from forcing or coupled to hydrologymodel:
+	switch(CoupledFlag){
+		case 0:
+			Neff=gravity*(rho_ice*thickness+rho_water*(base-sealevel));
+			break;	
+		case 1:
+			element->GetInputValue(&Neff,gauss,FrictionEffectivePressureEnum);
+			break;
+		case 2:
+			element->GetInputValue(&Neff,gauss,EffectivePressureEnum);
+			break;
+		default:
+			_error_("not supported");
+	}
+	if(Neff<0)Neff=0;
+
+	//We need the velocity magnitude to evaluate the basal stress:
+	switch(dim){
+		case 1:
+			element->GetInputValue(&vx,gauss,VxEnum);
+			vmag=sqrt(vx*vx);
+			break;
+		case 2:
+			element->GetInputValue(&vx,gauss,VxEnum);
+			element->GetInputValue(&vy,gauss,VyEnum);
+			vmag=sqrt(vx*vx+vy*vy);
+			break;
+		case 3:
+			element->GetInputValue(&vx,gauss,VxEnum);
+			element->GetInputValue(&vy,gauss,VyEnum);
+			element->GetInputValue(&vz,gauss,VzEnum);
+			vmag=sqrt(vx*vx+vy*vy+vz*vz);
+			break;
+		default:
+			_error_("not supported");
+	}
+
+	/*Check to prevent dividing by zero if vmag==0*/
+	if(vmag==0. && (s-1.)<0.) alpha_complement=0.;
+	else alpha_complement=pow(Neff,r)*pow(vmag,(s-1));_assert_(!xIsNan<IssmDouble>(alpha_complement));
+
+	/*Assign output pointers:*/
+	*palpha_complement=alpha_complement;
+}
+/*}}}*/
+void Friction::GetAlpha2(IssmDouble* palpha2, Gauss* gauss){/*{{{*/
+
+	switch(this->law){
+		case 1:
+			GetAlpha2Viscous(palpha2,gauss);
+			break;
+		case 2:
+			GetAlpha2Weertman(palpha2,gauss);
+			break;
+		case 3:
+			GetAlpha2Hydro(palpha2,gauss);
+			break;
+		case 4:
+			GetAlpha2Temp(palpha2,gauss);
+			break;
+		case 5:
+			GetAlpha2WaterLayer(palpha2,gauss);
+			break;
+		case 6:
+			GetAlpha2WeertmanTemp(palpha2,gauss);
+			break;
+		case 7:
+			GetAlpha2Coulomb(palpha2,gauss);
+			break;
+		case 8:
+			GetAlpha2Sommers(palpha2,gauss);
+			break;
+		case 9:
+			GetAlpha2Josh(palpha2,gauss);
+			break;
+	  default:
+			_error_("Friction law "<< this->law <<" not supported");
+	}
+
+}/*}}}*/
+void Friction::GetAlpha2Coulomb(IssmDouble* palpha2, Gauss* gauss){/*{{{*/
+
+	/*This routine calculates the basal friction coefficient 
+	  alpha2= drag^2 * Neff ^r * | vel | ^(s-1), with Neff=rho_ice*g*thickness+rho_ice*g*base, r=q/p and s=1/p**/
+
+	/*diverse: */
+	int         CoupledFlag;
+	IssmDouble  r,s;
+	IssmDouble  drag_p, drag_q;
+	IssmDouble  Neff;
+	IssmDouble  thickness,base,floatation_thickness,sealevel;
+	IssmDouble  vx,vy,vz,vmag;
+	IssmDouble  drag_coefficient,drag_coefficient_coulomb;
+	IssmDouble  alpha2,alpha2_coulomb;
+
+	/*Recover parameters: */
+	element->GetInputValue(&drag_p,FrictionPEnum);
+	element->GetInputValue(&drag_q,FrictionQEnum);
+	element->GetInputValue(&thickness, gauss,ThicknessEnum);
+	element->GetInputValue(&base, gauss,BaseEnum);
+	element->GetInputValue(&sealevel, gauss,SealevelEnum);
 	element->GetInputValue(&drag_coefficient, gauss,FrictionCoefficientEnum);
 	element->GetInputValue(&drag_coefficient_coulomb, gauss,FrictionCoefficientcoulombEnum);
@@ -281,4 +309,5 @@
 	IssmDouble rho_ice          = element->GetMaterialParameter(MaterialsRhoIceEnum);
 	IssmDouble gravity          = element->GetMaterialParameter(ConstantsGEnum);
+	element->parameters->FindParam(&CoupledFlag,FrictionCouplingEnum);
 
 	//compute r and q coefficients: */
@@ -287,5 +316,18 @@
 
 	//From base and thickness, compute effective pressure when drag is viscous:
-	Neff=gravity*(rho_ice*thickness+rho_water*(base-sealevel));
+	switch(CoupledFlag){
+		case 0:
+			Neff=gravity*(rho_ice*thickness+rho_water*(base-sealevel));
+			break;	
+		case 1:
+			element->GetInputValue(&Neff,gauss,FrictionEffectivePressureEnum);
+			break;
+		case 2:
+			element->GetInputValue(&Neff,gauss,EffectivePressureEnum);
+			break;
+		default:
+			_error_("not supported");
+	}
+
 	if(Neff<0)Neff=0;
 
@@ -315,7 +357,7 @@
 
 	floatation_thickness=0;
-	if(bed<0) floatation_thickness=-rho_water/rho_ice*bed;
+	if(base<0) floatation_thickness=-(rho_water/rho_ice)*base;
 	if(vmag==0.) alpha2_coulomb=0.;
-	else alpha2_coulomb=drag_coefficient_coulomb*drag_coefficient_coulomb*rho_water*gravity*(thickness-floatation_thickness)/vmag;
+	else alpha2_coulomb=drag_coefficient_coulomb*drag_coefficient_coulomb*rho_ice*gravity*(thickness-floatation_thickness)/vmag;
 
 	if(alpha2_coulomb<alpha2) alpha2=alpha2_coulomb;
@@ -349,4 +391,5 @@
 	IssmDouble  vx,vy,vz,vmag;
 	IssmDouble  alpha2;
+	IssmDouble  base,thickness,sealevel;
 
 	/*Recover parameters: */
@@ -355,13 +398,26 @@
 	element->GetInputValue(&As,gauss,FrictionAsEnum);
 	element->GetInputValue(&n,gauss,MaterialsRheologyNEnum);
+	element->GetInputValue(&thickness, gauss,ThicknessEnum);
+	element->GetInputValue(&base, gauss,BaseEnum);
+	element->GetInputValue(&sealevel, gauss,SealevelEnum);
+	IssmDouble rho_water   = element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	IssmDouble rho_ice     = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble gravity     = element->GetMaterialParameter(ConstantsGEnum);
+	element->parameters->FindParam(&CoupledFlag,FrictionCouplingEnum);
 	
-	element->parameters->FindParam(&CoupledFlag,FrictionCouplingEnum);
-	if (CoupledFlag==1){
-		element->GetInputValue(&Neff,gauss,EffectivePressureEnum);
-	}
-	else{
-		element->GetInputValue(&Neff,gauss,FrictionEffectivePressureEnum);
-	}
-		
+	switch(CoupledFlag){
+		case 0:
+			Neff=gravity*(rho_ice*thickness+rho_water*(base-sealevel));
+			break;	
+		case 1:
+			element->GetInputValue(&Neff,gauss,FrictionEffectivePressureEnum);
+			break;
+		case 2:
+			element->GetInputValue(&Neff,gauss,EffectivePressureEnum);
+			break;
+		default:
+			_error_("not supported");
+	}
+
 	if(Neff<0)Neff=0;
 
@@ -407,5 +463,5 @@
 void Friction::GetAlpha2Sommers(IssmDouble* palpha2, Gauss* gauss){/*{{{*/
 
-	/* FrictionGetAlpha2 computes alpha2= drag^2 * Neff, with Neff=rho_ice*g*thickness+rho_ice*g*(head-bed)*/
+	/* FrictionGetAlpha2 computes alpha2= drag^2 * Neff, with Neff=rho_ice*g*thickness+rho_ice*g*(head-base)*/
 
 	/*diverse: */
@@ -413,10 +469,10 @@
 	IssmDouble  Neff;
 	IssmDouble  drag_coefficient;
-	IssmDouble  bed,thickness,head,sealevel;
+	IssmDouble  base,thickness,head,sealevel;
 	IssmDouble  alpha2;
 
 	/*Recover parameters: */
 	element->GetInputValue(&thickness, gauss,ThicknessEnum);
-	element->GetInputValue(&bed, gauss,BaseEnum);
+	element->GetInputValue(&base, gauss,BaseEnum);
 	element->GetInputValue(&head, gauss,HydrologyHeadEnum);
 	element->GetInputValue(&sealevel, gauss,SealevelEnum);
@@ -426,7 +482,7 @@
 	IssmDouble gravity     = element->GetMaterialParameter(ConstantsGEnum);
 
-	//From bed and thickness, compute effective pressure when drag is viscous:
+	//From base and thickness, compute effective pressure when drag is viscous:
 	pressure_ice   = rho_ice*gravity*thickness;
-	pressure_water = rho_water*gravity*(head-bed+sealevel);
+	pressure_water = rho_water*gravity*(head-base+sealevel);
 	Neff=pressure_ice-pressure_water;
 	if(Neff<0.) Neff=0.;
@@ -505,4 +561,8 @@
 	alpha2 = alpha2 * exp((deltaTref - deltaT)/(2*gamma));
 
+	/*Final checks in debuging mode*/
+	_assert_(!xIsNan<IssmDouble>(alpha2));
+	_assert_(!xIsInf<IssmDouble>(alpha2));
+
 	/*Assign output pointers:*/
 	*palpha2=alpha2;
@@ -511,7 +571,8 @@
 
 	/*This routine calculates the basal friction coefficient 
-	  alpha2= drag^2 * Neff ^r * | vel | ^(s-1), with Neff=rho_ice*g*thickness+rho_ice*g*bed, r=q/p and s=1/p**/
+	  alpha2= drag^2 * Neff ^r * | vel | ^(s-1), with Neff=rho_ice*g*thickness+rho_ice*g*base, r=q/p and s=1/p**/
 
 	/*diverse: */
+	int         CoupledFlag;
 	IssmDouble  r,s;
 	IssmDouble  drag_p, drag_q;
@@ -532,11 +593,23 @@
 	IssmDouble rho_ice     = element->GetMaterialParameter(MaterialsRhoIceEnum);
 	IssmDouble gravity     = element->GetMaterialParameter(ConstantsGEnum);
-
+	element->parameters->FindParam(&CoupledFlag,FrictionCouplingEnum);
 	//compute r and q coefficients: */
 	r=drag_q/drag_p;
 	s=1./drag_p;
 
-	//From base and thickness, compute effective pressure when drag is viscous:
-	Neff=gravity*(rho_ice*thickness+rho_water*(base-sealevel));
+	//From base and thickness, compute effective pressure when drag is viscous, or get Neff from forcing:
+	switch(CoupledFlag){
+		case 0:
+			Neff=gravity*(rho_ice*thickness+rho_water*(base-sealevel));
+			break;
+		case 1:
+			element->GetInputValue(&Neff,gauss,FrictionEffectivePressureEnum);
+			break;
+		case 2:
+			element->GetInputValue(&Neff,gauss,EffectivePressureEnum);
+			break;
+		default:
+			_error_("not supported");
+	}
 	if(Neff<0)Neff=0;
 
@@ -572,5 +645,5 @@
 
 	/*This routine calculates the basal friction coefficient 
-	  alpha2= drag^2 * Neff ^r * | vel | ^(s-1), with Neff=rho_ice*g*thickness+rho_ice*g*bed, r=q/p and s=1/p**/
+	  alpha2= drag^2 * Neff ^r * | vel | ^(s-1), with Neff=rho_ice*g*thickness+rho_ice*g*base, r=q/p and s=1/p**/
 
 	/*diverse: */
@@ -578,5 +651,5 @@
 	IssmDouble  drag_p, drag_q;
 	IssmDouble  Neff,F;
-	IssmDouble  thickness,bed,sealevel;
+	IssmDouble  thickness,base,sealevel;
 	IssmDouble  vx,vy,vz,vmag;
 	IssmDouble  drag_coefficient,water_layer;
@@ -588,5 +661,5 @@
 	element->GetInputValue(&drag_q,FrictionQEnum);
 	element->GetInputValue(&thickness, gauss,ThicknessEnum);
-	element->GetInputValue(&bed, gauss,BaseEnum);
+	element->GetInputValue(&base, gauss,BaseEnum);
 	element->GetInputValue(&sealevel, gauss,SealevelEnum);
 	element->GetInputValue(&drag_coefficient, gauss,FrictionCoefficientEnum);
@@ -600,7 +673,7 @@
 	s=1./drag_p;
 
-	//From bed and thickness, compute effective pressure when drag is viscous:
-	if(bed>0) bed=0;
-	if(water_layer==0) Neff=gravity*rho_ice*thickness+gravity*rho_water*(bed-sealevel);
+	//From base and thickness, compute effective pressure when drag is viscous:
+	if(base>0) base=0;
+	if(water_layer==0) Neff=gravity*rho_ice*thickness+gravity*rho_water*(base-sealevel);
 	else if(water_layer>0) Neff=gravity*rho_ice*thickness*F;
 	else _error_("negative water layer thickness");
Index: /issm/trunk/src/c/classes/Loads/Pengrid.h
===================================================================
--- /issm/trunk/src/c/classes/Loads/Pengrid.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Loads/Pengrid.h	(revision 22758)
@@ -46,5 +46,5 @@
 		/*Pengrid constructors, destructors {{{*/
 		Pengrid();
-		Pengrid(int index, int id, IoModel* iomodel,int analysis_type);
+		Pengrid(int id, int index, IoModel* iomodel,int analysis_type);
 		~Pengrid();
 		/*}}}*/
Index: /issm/trunk/src/c/classes/Massfluxatgate.h
===================================================================
--- /issm/trunk/src/c/classes/Massfluxatgate.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Massfluxatgate.h	(revision 22758)
@@ -84,9 +84,11 @@
 		/*}}}*/
 		~Massfluxatgate(){/*{{{*/
-			xDelete<doubletype>(this->x1);
-			xDelete<doubletype>(this->y1);
-			xDelete<doubletype>(this->x2);
-			xDelete<doubletype>(this->y2);
-			xDelete<int>(this->elements);
+			if(this->numsegments){
+				xDelete<doubletype>(this->x1);
+				xDelete<doubletype>(this->y1);
+				xDelete<doubletype>(this->x2);
+				xDelete<doubletype>(this->y2);
+				xDelete<int>(this->elements);
+			}
 			xDelete<char>(this->name);
 		}
Index: /issm/trunk/src/c/classes/Materials/Material.h
===================================================================
--- /issm/trunk/src/c/classes/Materials/Material.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Materials/Material.h	(revision 22758)
@@ -27,19 +27,19 @@
 		virtual void       Configure(Elements* elements)=0;
 		virtual Material*  copy2(Element* element)=0;
-		virtual IssmDouble GetA()=0;
-		virtual IssmDouble GetAbar()=0;
-		virtual IssmDouble GetB()=0;
-		virtual IssmDouble GetBbar()=0;
-		virtual IssmDouble GetD()=0;
-		virtual IssmDouble GetDbar()=0;
+		virtual IssmDouble GetA(Gauss* gauss)=0;
+		virtual IssmDouble GetAbar(Gauss* gauss)=0;
+		virtual IssmDouble GetB(Gauss* gauss)=0;
+		virtual IssmDouble GetBbar(Gauss* gauss)=0;
+		virtual IssmDouble GetD(Gauss* gauss)=0;
+		virtual IssmDouble GetDbar(Gauss* gauss)=0;
 		virtual IssmDouble GetN()=0;
-		virtual void       GetViscosity(IssmDouble* pviscosity,IssmDouble epseff)=0;
-		virtual void       GetViscosityBar(IssmDouble* pviscosity,IssmDouble epseff)=0;
-		virtual void       GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon)=0;
-		virtual void       GetViscosityDComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon)=0;
-		virtual void       GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon)=0;
-		virtual void       GetViscosity_B(IssmDouble* pviscosity,IssmDouble epseff)=0;
-		virtual void       GetViscosity_D(IssmDouble* pviscosity,IssmDouble epseff)=0;
-		virtual void       GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon)=0;
+		virtual void       GetViscosity(IssmDouble* pviscosity,IssmDouble epseff,Gauss* gauss)=0;
+		virtual void       GetViscosityBar(IssmDouble* pviscosity,IssmDouble epseff,Gauss* gauss)=0;
+		virtual void       GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon,Gauss* gauss)=0;
+		virtual void       GetViscosityDComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon,Gauss* gauss)=0;
+		virtual void       GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon,Gauss* gauss)=0;
+		virtual void       GetViscosity_B(IssmDouble* pviscosity,IssmDouble epseff,Gauss* gauss)=0;
+		virtual void       GetViscosity_D(IssmDouble* pviscosity,IssmDouble epseff,Gauss* gauss)=0;
+		virtual void       GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon,Gauss* gauss)=0;
 		virtual bool       IsDamage()=0;
 		virtual bool       IsEnhanced()=0;
@@ -47,13 +47,13 @@
 
 		virtual void       ViscosityFS(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input)=0;
-		virtual void       ViscosityFSDerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon)=0;
+		virtual void       ViscosityFSDerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon,Gauss* gauss)=0;
 		virtual void       ViscosityHO(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input)=0;
-		virtual void       ViscosityHODerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon)=0;
+		virtual void       ViscosityHODerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon,Gauss* gauss)=0;
 		virtual void       ViscosityL1L2(IssmDouble* pviscosity,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* surf)=0;
 		virtual void       ViscositySSA(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input)=0;
-		virtual void       ViscositySSADerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon)=0;
-		virtual void       ViscosityBFS(IssmDouble* pmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input)=0;
-		virtual void       ViscosityBHO(IssmDouble* pmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input)=0;
-		virtual void       ViscosityBSSA(IssmDouble* pmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input)=0;
+		virtual void       ViscositySSADerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon,Gauss* gauss)=0;
+		virtual void       ViscosityBFS(IssmDouble* pmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input,IssmDouble epseff)=0;
+		virtual void       ViscosityBHO(IssmDouble* pmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,IssmDouble epseff)=0;
+		virtual void       ViscosityBSSA(IssmDouble* pmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,IssmDouble epseff)=0;
 
 };
Index: /issm/trunk/src/c/classes/Materials/Matestar.cpp
===================================================================
--- /issm/trunk/src/c/classes/Materials/Matestar.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Materials/Matestar.cpp	(revision 22758)
@@ -133,90 +133,92 @@
 }
 /*}}}*/
-IssmDouble Matestar::GetA(){/*{{{*/
-	/*
-	 * A = 1/B^n
-    */
-
-	IssmDouble B,n;
-
-	element->inputs->GetInputAverage(&B,MaterialsRheologyBEnum);
-	n=this->GetN();
-
-	return pow(B,-n);
-}
-/*}}}*/
-IssmDouble Matestar::GetAbar(){/*{{{*/
+IssmDouble Matestar::GetA(Gauss* gauss){/*{{{*/
 	/*
 	 * A = 1/B^n
 	 */
 
-	IssmDouble B,n;
-
-	element->inputs->GetInputAverage(&B,MaterialsRheologyBbarEnum);
-	n=this->GetN();
+	IssmDouble B=this->GetB(gauss);
+	IssmDouble n=this->GetN();
 
 	return pow(B,-n);
 }
 /*}}}*/
-IssmDouble Matestar::GetB(){/*{{{*/
+IssmDouble Matestar::GetAbar(Gauss* gauss){/*{{{*/
+	/*
+	 * A = 1/B^n
+	 */
+
+	IssmDouble B=this->GetBbar(gauss);
+	IssmDouble n=this->GetN();
+
+	return pow(B,-n);
+}
+/*}}}*/
+IssmDouble Matestar::GetB(Gauss* gauss){/*{{{*/
 
 	/*Output*/
 	IssmDouble B;
 
-	element->inputs->GetInputAverage(&B,MaterialsRheologyBEnum);
+	Input* B_input = element->GetInput(MaterialsRheologyBEnum); _assert_(B_input);
+	B_input->GetInputValue(&B,gauss);
 	return B;
 }
 /*}}}*/
-IssmDouble Matestar::GetBbar(){/*{{{*/
+IssmDouble Matestar::GetBbar(Gauss* gauss){/*{{{*/
 
 	/*Output*/
 	IssmDouble Bbar;
 
-	element->inputs->GetInputAverage(&Bbar,MaterialsRheologyBbarEnum);
+	Input* B_input = element->GetInput(MaterialsRheologyBbarEnum); _assert_(B_input);
+	B_input->GetInputValue(&Bbar,gauss);
 	return Bbar;
 }
 /*}}}*/
-IssmDouble Matestar::GetD(){/*{{{*/
-	_error_("not implemented yet");
-}
-/*}}}*/
-IssmDouble Matestar::GetDbar(){/*{{{*/
-
-	_error_("not implemented yet");
-}
-/*}}}*/
-IssmDouble Matestar::GetEc(){/*{{{*/
+IssmDouble Matestar::GetD(Gauss* gauss){/*{{{*/
+	_error_("not implemented yet");
+}
+/*}}}*/
+IssmDouble Matestar::GetDbar(Gauss* gauss){/*{{{*/
+
+	_error_("not implemented yet");
+}
+/*}}}*/
+IssmDouble Matestar::GetEc(Gauss* gauss){/*{{{*/
 
 	/*Output*/
 	IssmDouble Ec;
 
-	element->inputs->GetInputAverage(&Ec,MaterialsRheologyEcEnum);
+	Input* Ec_input = element->GetInput(MaterialsRheologyEcEnum); _assert_(Ec_input);
+	Ec_input->GetInputValue(&Ec,gauss);
 	return Ec;
 }
 /*}}}*/
-IssmDouble Matestar::GetEcbar(){/*{{{*/
+IssmDouble Matestar::GetEcbar(Gauss* gauss){/*{{{*/
 
 	/*Output*/
 	IssmDouble Ecbar;
 
-	element->inputs->GetInputAverage(&Ecbar,MaterialsRheologyEcbarEnum);
+	Input* Ecbar_input = element->GetInput(MaterialsRheologyEcbarEnum); _assert_(Ecbar_input);
+	Ecbar_input->GetInputValue(&Ecbar,gauss);
 	return Ecbar;
 }
 /*}}}*/
-IssmDouble Matestar::GetEs(){/*{{{*/
+IssmDouble Matestar::GetEs(Gauss* gauss){/*{{{*/
 
 	/*Output*/
 	IssmDouble Es;
 
-	element->inputs->GetInputAverage(&Es,MaterialsRheologyEsEnum);
+	Input* Es_input = element->GetInput(MaterialsRheologyEsEnum); _assert_(Es_input);
+	Es_input->GetInputValue(&Es,gauss);
 	return Es;
 }
 /*}}}*/
-IssmDouble Matestar::GetEsbar(){/*{{{*/
+IssmDouble Matestar::GetEsbar(Gauss* gauss){/*{{{*/
 
 	/*Output*/
 	IssmDouble Esbar;
 
-	element->inputs->GetInputAverage(&Esbar,MaterialsRheologyEsbarEnum);
+	Input* Esbar_input = element->GetInput(MaterialsRheologyEsbarEnum); _assert_(Esbar_input);
+	Esbar_input->GetInputValue(&Esbar,gauss);
 	return Esbar;
 }
@@ -229,25 +231,25 @@
 }
 /*}}}*/
-void  Matestar::GetViscosity(IssmDouble* pviscosity,IssmDouble eps_eff){/*{{{*/
-	_error_("not implemented yet");
-}
-/*}}}*/
-void  Matestar::GetViscosityBar(IssmDouble* pviscosity,IssmDouble eps_eff){/*{{{*/
-	_error_("not implemented yet");
-}
-/*}}}*/
-void  Matestar::GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* epsilon){/*{{{*/
-	_error_("not implemented yet");
-}
-/*}}}*/
-void  Matestar::GetViscosityDComplement(IssmDouble* pviscosity_complement, IssmDouble* epsilon){/*{{{*/
-	_error_("not implemented yet");
-}
-/*}}}*/
-void  Matestar::GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* epsilon){/*{{{*/
-	_error_("not implemented yet");
-}
-/*}}}*/
-IssmDouble Matestar::GetViscosityGeneral(IssmDouble vx,IssmDouble vy,IssmDouble vz,IssmDouble* dvx,IssmDouble* dvy,IssmDouble* dvz,bool isdepthaveraged){/*{{{*/
+void  Matestar::GetViscosity(IssmDouble* pviscosity,IssmDouble eps_eff,Gauss* gauss){/*{{{*/
+	_error_("not implemented yet");
+}
+/*}}}*/
+void  Matestar::GetViscosityBar(IssmDouble* pviscosity,IssmDouble eps_eff,Gauss* gauss){/*{{{*/
+	_error_("not implemented yet");
+}
+/*}}}*/
+void  Matestar::GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* epsilon,Gauss* gauss){/*{{{*/
+	_error_("not implemented yet");
+}
+/*}}}*/
+void  Matestar::GetViscosityDComplement(IssmDouble* pviscosity_complement, IssmDouble* epsilon,Gauss* gauss){/*{{{*/
+	_error_("not implemented yet");
+}
+/*}}}*/
+void  Matestar::GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* epsilon,Gauss* gauss){/*{{{*/
+	_error_("not implemented yet");
+}
+/*}}}*/
+IssmDouble Matestar::GetViscosityGeneral(IssmDouble vx,IssmDouble vy,IssmDouble vz,IssmDouble* dvx,IssmDouble* dvy,IssmDouble* dvz,IssmDouble eps_eff,bool isdepthaveraged,Gauss* gauss){/*{{{*/
 
 	/*output: */
@@ -255,5 +257,5 @@
 
 	/*Intermediaries*/
-	IssmDouble epseff,epsprime_norm;
+	IssmDouble epsprime_norm;
 	IssmDouble lambdas;
 	IssmDouble vmag,dvmag[3];
@@ -273,18 +275,17 @@
 	}
 
-	EstarStrainrateQuantities(&epseff,&epsprime_norm,vx,vy,vz,vmag,dvx,dvy,dvz,&dvmag[0]);
-	lambdas=EstarLambdaS(epseff,epsprime_norm);
+	EstarStrainrateQuantities(&epsprime_norm,vx,vy,vz,vmag,dvx,dvy,dvz,&dvmag[0]);
+	lambdas=EstarLambdaS(eps_eff,epsprime_norm);
 
 	/*Get B and enhancement*/
 	n=GetN(); _assert_(n>0.);
 	if (isdepthaveraged==0.){
-		B=GetB(); _assert_(B>0.);
-		Ec=GetEc(); _assert_(Ec>=0.);
-		Es=GetEs(); _assert_(Es>=0.);
-	}
-	else{
-		B=GetBbar(); _assert_(B>0.);
-		Ec=GetEcbar(); _assert_(Ec>=0.);
-		Es=GetEsbar(); _assert_(Es>=0.);
+		B=GetB(gauss);   _assert_(B>0.);
+		Ec=GetEc(gauss); _assert_(Ec>=0.); Es=GetEs(gauss); _assert_(Es>=0.);
+	}
+	else{
+		B=GetBbar(gauss);   _assert_(B>0.);
+		Ec=GetEcbar(gauss); _assert_(Ec>=0.);
+		Es=GetEsbar(gauss); _assert_(Es>=0.);
 	}
 
@@ -294,5 +295,5 @@
 	/*Compute viscosity*/
 	/*if no strain rate, return maximum viscosity*/
-	if(epseff==0.){
+	if(eps_eff==0.){
 		viscosity = 1.e+14/2.;
 		//viscosity = B;
@@ -300,6 +301,9 @@
 	}
 	else{
-		viscosity = B/(2.*pow(E,1./n)*pow(epseff,2./n));
-	}
+		viscosity = B/(2.*pow(E,1./n)*pow(eps_eff,2./n));
+	}
+
+   /*Checks in debugging mode*/
+	if(viscosity<=0) _error_("Negative viscosity");
 
 	/*Assign output pointer*/
@@ -307,9 +311,9 @@
 }
 /*}}}*/
-IssmDouble Matestar::GetViscosity_BGeneral(IssmDouble vx,IssmDouble vy,IssmDouble vz,IssmDouble* dvx,IssmDouble* dvy,IssmDouble* dvz,bool isdepthaveraged){/*{{{*/
+IssmDouble Matestar::GetViscosity_BGeneral(IssmDouble vx,IssmDouble vy,IssmDouble vz,IssmDouble* dvx,IssmDouble* dvy,IssmDouble* dvz,IssmDouble eps_eff,bool isdepthaveraged,Gauss* gauss){/*{{{*/
 
 	/*Intermediaries*/
 	IssmDouble dmudB;
-	IssmDouble epseff,epsprime_norm;
+	IssmDouble epsprime_norm;
 	IssmDouble lambdas;
 	IssmDouble vmag,dvmag[3];
@@ -329,15 +333,15 @@
 	}
 
-	EstarStrainrateQuantities(&epseff,&epsprime_norm,vx,vy,vz,vmag,dvx,dvy,dvz,&dvmag[0]);
-	lambdas=EstarLambdaS(epseff,epsprime_norm);
+	EstarStrainrateQuantities(&epsprime_norm,vx,vy,vz,vmag,dvx,dvy,dvz,&dvmag[0]);
+	lambdas=EstarLambdaS(eps_eff,epsprime_norm);
 
 	/*Get enhancement*/
 	if (isdepthaveraged==0.){
-		Ec=GetEc(); _assert_(Ec>=0.);
-		Es=GetEs(); _assert_(Es>=0.);
-	}
-	else{
-		Ec=GetEcbar(); _assert_(Ec>=0.);
-		Es=GetEsbar(); _assert_(Es>=0.);
+		Ec=GetEc(gauss); _assert_(Ec>=0.);
+		Es=GetEs(gauss); _assert_(Es>=0.);
+	}
+	else{
+		Ec=GetEcbar(gauss); _assert_(Ec>=0.);
+		Es=GetEsbar(gauss); _assert_(Es>=0.);
 	}
 
@@ -346,6 +350,6 @@
 
 	/*Compute dmudB*/
-	if(epseff==0.) dmudB = 0.;
-	else           dmudB = 1./(2.*pow(E,1./3.)*pow(epseff,2./3.));
+	if(eps_eff==0.) dmudB = 0.;
+	else            dmudB = 1./(2.*pow(E,1./3.)*pow(eps_eff,2./3.));
 
 	/*Assign output*/
@@ -354,13 +358,13 @@
 }
 /*}}}*/
-void  Matestar::GetViscosity_B(IssmDouble* pdmudB,IssmDouble eps_eff){/*{{{*/
+void  Matestar::GetViscosity_B(IssmDouble* pdmudB,IssmDouble eps_eff,Gauss* gauss){/*{{{*/
 	 _error_("not implemented yet");
 }
 /*}}}*/
-void  Matestar::GetViscosity_D(IssmDouble* pdmudD,IssmDouble eps_eff){/*{{{*/
+void  Matestar::GetViscosity_D(IssmDouble* pdmudD,IssmDouble eps_eff,Gauss* gauss){/*{{{*/
 	 _error_("not implemented yet");
 }
 /*}}}*/
-void  Matestar::GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* epsilon){/*{{{*/
+void  Matestar::GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* epsilon,Gauss* gauss){/*{{{*/
 	_error_("not implemented yet");
 }
@@ -408,5 +412,5 @@
 }
 /*}}}*/
-void  Matestar::ViscosityBFS(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input){/*{{{*/
+void  Matestar::ViscosityBFS(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input,IssmDouble eps_eff){/*{{{*/
 
 	/*Intermediaries*/
@@ -434,8 +438,8 @@
 
 	/*Compute dmudB*/
-	*pdmudB=GetViscosity_BGeneral(vx,vy,vz,&dvx[0],&dvy[0],&dvz[0],isdepthaveraged);
-}
-/*}}}*/
-void  Matestar::ViscosityBHO(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){/*{{{*/
+	*pdmudB=GetViscosity_BGeneral(vx,vy,vz,&dvx[0],&dvy[0],&dvz[0],eps_eff,isdepthaveraged,gauss);
+}
+/*}}}*/
+void  Matestar::ViscosityBHO(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,IssmDouble eps_eff){/*{{{*/
 
 	/*Intermediaries*/
@@ -463,7 +467,7 @@
 
 	/*Compute viscosity*/
-	*pdmudB=GetViscosity_BGeneral(vx,vy,vz,&dvx[0],&dvy[0],&dvz[0],isdepthaveraged);
-}/*}}}*/
-void  Matestar::ViscosityBSSA(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){/*{{{*/
+	*pdmudB=GetViscosity_BGeneral(vx,vy,vz,&dvx[0],&dvy[0],&dvz[0],eps_eff,isdepthaveraged,gauss);
+}/*}}}*/
+void  Matestar::ViscosityBSSA(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,IssmDouble eps_eff){/*{{{*/
 	/*Intermediaries*/
 	IssmDouble vx,vy,vz;
@@ -493,5 +497,5 @@
 
 	/*Compute viscosity*/
-	*pdmudB=GetViscosity_BGeneral(vx,vy,vz,&dvx[0],&dvy[0],&dvz[0],isdepthaveraged);
+	*pdmudB=GetViscosity_BGeneral(vx,vy,vz,&dvx[0],&dvy[0],&dvz[0],eps_eff,isdepthaveraged,gauss);
 }/*}}}*/
 void  Matestar::ViscosityFS(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input){/*{{{*/
@@ -500,4 +504,7 @@
 	IssmDouble vx,vy,vz;
 	IssmDouble dvx[3],dvy[3],dvz[3];
+	IssmDouble epsilon3d[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
+	IssmDouble epsilon2d[3]; /* epsilon=[exx,eyy,exy];*/
+	IssmDouble eps_eff,eps0=1.e-27;
 	bool isdepthaveraged=0.;
 
@@ -520,10 +527,21 @@
 	}
 
+	if(dim==3){
+      /* eps_eff^2 = exx^2 + eyy^2 + exy^2 + exz^2 + eyz^2 + exx*eyy */
+		element->StrainRateFS(&epsilon3d[0],xyz_list,gauss,vx_input,vy_input,vz_input);
+		eps_eff = sqrt(epsilon3d[0]*epsilon3d[0] + epsilon3d[1]*epsilon3d[1] + epsilon3d[3]*epsilon3d[3] +  epsilon3d[4]*epsilon3d[4] + epsilon3d[5]*epsilon3d[5] + epsilon3d[0]*epsilon3d[1]+eps0*eps0);
+	}
+	else{
+		/* eps_eff^2 = 1/2 ( exx^2 + eyy^2 + 2*exy^2 )*/
+		element->StrainRateSSA(&epsilon2d[0],xyz_list,gauss,vx_input,vy_input);
+		eps_eff = 1./sqrt(2.)*sqrt(epsilon2d[0]*epsilon2d[0] + epsilon2d[1]*epsilon2d[1] + 2.*epsilon2d[2]*epsilon2d[2]);
+	}
+
 	/*Compute viscosity*/
-	*pviscosity=GetViscosityGeneral(vx,vy,vz,&dvx[0],&dvy[0],&dvz[0],isdepthaveraged);
-}
-/*}}}*/
-void  Matestar::ViscosityFSDerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon){/*{{{*/
-	this->GetViscosityDerivativeEpsSquare(pmu_prime,epsilon);
+	*pviscosity=GetViscosityGeneral(vx,vy,vz,&dvx[0],&dvy[0],&dvz[0],eps_eff,isdepthaveraged,gauss);
+}
+/*}}}*/
+void  Matestar::ViscosityFSDerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon,Gauss* gauss){/*{{{*/
+	this->GetViscosityDerivativeEpsSquare(pmu_prime,epsilon,gauss);
 }/*}}}*/
 void  Matestar::ViscosityHO(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){/*{{{*/
@@ -532,5 +550,19 @@
 	IssmDouble vx,vy,vz;
 	IssmDouble dvx[3],dvy[3],dvz[3];
+	IssmDouble epsilon3d[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
+	IssmDouble epsilon2d[5]; /* epsilon=[exx,exy];*/
+	IssmDouble eps_eff;
 	bool isdepthaveraged=0.;
+
+   if(dim==3){
+		/* eps_eff^2 = exx^2 + eyy^2 + exy^2 + exz^2 + eyz^2 + exx*eyy */
+		element->StrainRateHO(&epsilon3d[0],xyz_list,gauss,vx_input,vy_input);
+		eps_eff = sqrt(epsilon3d[0]*epsilon3d[0] + epsilon3d[1]*epsilon3d[1] + epsilon3d[2]*epsilon3d[2] +  epsilon3d[3]*epsilon3d[3] + epsilon3d[4]*epsilon3d[4] + epsilon3d[0]*epsilon3d[1]);
+	}
+	else{
+		/* eps_eff^2 = 1/2 (2*exx^2 + 2*exy^2 ) (since eps_zz = - eps_xx)*/
+		element->StrainRateHO2dvertical(&epsilon2d[0],xyz_list,gauss,vx_input,vy_input);
+		eps_eff = 1./sqrt(2.)*sqrt(2*epsilon2d[0]*epsilon2d[0] + 2*epsilon2d[1]*epsilon2d[1]);
+	}
 
 	/*Get velocity derivatives in all directions*/
@@ -553,7 +585,7 @@
 
 	/*Compute viscosity*/
-	*pviscosity=GetViscosityGeneral(vx,vy,vz,&dvx[0],&dvy[0],&dvz[0],isdepthaveraged);
-}/*}}}*/
-void  Matestar::ViscosityHODerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon){/*{{{*/
+	*pviscosity=GetViscosityGeneral(vx,vy,vz,&dvx[0],&dvy[0],&dvz[0],eps_eff,isdepthaveraged,gauss);
+}/*}}}*/
+void  Matestar::ViscosityHODerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon,Gauss* gauss){/*{{{*/
 	_error_("not implemented yet");
 }/*}}}*/
@@ -566,4 +598,7 @@
 	IssmDouble vx,vy,vz;
 	IssmDouble dvx[3],dvy[3],dvz[3];
+	IssmDouble epsilon2d[3];/* epsilon=[exx,eyy,exy]; */
+	IssmDouble epsilon1d;   /* epsilon=[exx];         */
+	IssmDouble eps_eff;
 	bool isdepthaveraged=1.;
 
@@ -589,8 +624,19 @@
 	dvz[0] = 0.; dvz[1] = 0.; dvz[2] = -dvx[0]-dvy[1];
 
+   if(dim==2){
+		/* eps_eff^2 = exx^2 + eyy^2 + exy^2 + exx*eyy*/
+		element->StrainRateSSA(&epsilon2d[0],xyz_list,gauss,vx_input,vy_input);
+		eps_eff = sqrt(epsilon2d[0]*epsilon2d[0] + epsilon2d[1]*epsilon2d[1] + epsilon2d[2]*epsilon2d[2] + epsilon2d[0]*epsilon2d[1]);
+	}
+	else{
+		/* eps_eff^2 = exx^2*/
+		element->StrainRateSSA1d(&epsilon1d,xyz_list,gauss,vx_input);
+		eps_eff = fabs(epsilon1d);
+	}
+
 	/*Compute viscosity*/
-	*pviscosity=GetViscosityGeneral(vx,vy,vz,&dvx[0],&dvy[0],&dvz[0],isdepthaveraged);
-}/*}}}*/
-void  Matestar::ViscositySSADerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon){/*{{{*/
-	_error_("not implemented yet");
-}/*}}}*/
+	*pviscosity=GetViscosityGeneral(vx,vy,vz,&dvx[0],&dvy[0],&dvz[0],eps_eff,isdepthaveraged,gauss);
+}/*}}}*/
+void  Matestar::ViscositySSADerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon,Gauss* gauss){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
Index: /issm/trunk/src/c/classes/Materials/Matestar.h
===================================================================
--- /issm/trunk/src/c/classes/Materials/Matestar.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Materials/Matestar.h	(revision 22758)
@@ -28,4 +28,5 @@
 		Hook    *helement;
 		Element *element;
+		int      rheology_law;
 
 	public:
@@ -55,22 +56,22 @@
 		void   Configure(Elements* elements);
 		Material*  copy2(Element* element);
-		void       GetViscosity(IssmDouble* pviscosity, IssmDouble eps_eff);
-		void       GetViscosityBar(IssmDouble* pviscosity, IssmDouble eps_eff);
-		void       GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon);
-		void       GetViscosityDComplement(IssmDouble*, IssmDouble*);
-		void       GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon);
-		void       GetViscosity_B(IssmDouble* pviscosity, IssmDouble eps_eff);
-		void       GetViscosity_D(IssmDouble* pviscosity, IssmDouble eps_eff);
-		void       GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon);
-		IssmDouble GetA();
-		IssmDouble GetAbar();
-		IssmDouble GetB();
-		IssmDouble GetBbar();
-		IssmDouble GetD();
-		IssmDouble GetDbar();
-		IssmDouble GetEc();
-		IssmDouble GetEcbar();
-		IssmDouble GetEs();
-		IssmDouble GetEsbar();
+		void       GetViscosity(IssmDouble* pviscosity, IssmDouble eps_eff,Gauss* gauss);
+		void       GetViscosityBar(IssmDouble* pviscosity, IssmDouble eps_eff,Gauss* gauss);
+		void       GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon,Gauss* gauss);
+		void       GetViscosityDComplement(IssmDouble*, IssmDouble*,Gauss* gauss);
+		void       GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon,Gauss* gauss);
+		void       GetViscosity_B(IssmDouble* pviscosity, IssmDouble eps_eff,Gauss* gauss);
+		void       GetViscosity_D(IssmDouble* pviscosity, IssmDouble eps_eff,Gauss* gauss);
+		void       GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon,Gauss* gauss);
+		IssmDouble GetA(Gauss* gauss);
+		IssmDouble GetAbar(Gauss* gauss);
+		IssmDouble GetB(Gauss* gauss);
+		IssmDouble GetBbar(Gauss* gauss);
+		IssmDouble GetD(Gauss* gauss);
+		IssmDouble GetDbar(Gauss* gauss);
+		IssmDouble GetEc(Gauss* gauss);
+		IssmDouble GetEcbar(Gauss* gauss);
+		IssmDouble GetEs(Gauss* gauss);
+		IssmDouble GetEsbar(Gauss* gauss);
 		IssmDouble GetN();
 		bool       IsDamage();
@@ -80,16 +81,16 @@
 
 		void       ViscosityFS(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input);
-		void       ViscosityFSDerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon);
+		void       ViscosityFSDerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon,Gauss* gauss);
 		void       ViscosityHO(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
-		void       ViscosityHODerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon);
+		void       ViscosityHODerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon,Gauss* gauss);
 		void       ViscosityL1L2(IssmDouble* pviscosity,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* surf);
 		void       ViscositySSA(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
-		void       ViscositySSADerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon);
-		void       ViscosityBFS(IssmDouble* pmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input);
-		void       ViscosityBHO(IssmDouble* pmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
-		void       ViscosityBSSA(IssmDouble* pmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
+		void       ViscositySSADerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon,Gauss* gauss);
+		void       ViscosityBFS(IssmDouble* pmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input,IssmDouble eps_eff);
+		void       ViscosityBHO(IssmDouble* pmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,IssmDouble eps_eff);
+		void       ViscosityBSSA(IssmDouble* pmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,IssmDouble eps_eff);
 		/*}}}*/
-		IssmDouble GetViscosityGeneral(IssmDouble vx,IssmDouble vy,IssmDouble vz,IssmDouble* dvx,IssmDouble* dvy,IssmDouble* dvz,bool isdepthaveraged);
-		IssmDouble GetViscosity_BGeneral(IssmDouble vx,IssmDouble vy,IssmDouble vz,IssmDouble* dvx,IssmDouble* dvy,IssmDouble* dvz,bool isdepthaveraged);
+		IssmDouble GetViscosityGeneral(IssmDouble vx,IssmDouble vy,IssmDouble vz,IssmDouble* dvx,IssmDouble* dvy,IssmDouble* dvz,IssmDouble eps_eff,bool isdepthaveraged,Gauss* gauss);
+		IssmDouble GetViscosity_BGeneral(IssmDouble vx,IssmDouble vy,IssmDouble vz,IssmDouble* dvx,IssmDouble* dvy,IssmDouble* dvz,IssmDouble eps_eff,bool isdepthaveraged,Gauss* gauss);
 };
 
Index: /issm/trunk/src/c/classes/Materials/Matice.cpp
===================================================================
--- /issm/trunk/src/c/classes/Materials/Matice.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Materials/Matice.cpp	(revision 22758)
@@ -193,81 +193,97 @@
 }
 /*}}}*/
-IssmDouble Matice::GetA(){/*{{{*/
+IssmDouble Matice::GetA(Gauss* gauss){/*{{{*/
 	/*
 	 * A = 1/B^n
 	 */
 
-	IssmDouble B,n;
-
-	element->inputs->GetInputAverage(&B,MaterialsRheologyBEnum);
-	n=this->GetN();
+	IssmDouble B=this->GetB(gauss);
+	IssmDouble n=this->GetN();
 
 	return pow(B,-n);
 }
 /*}}}*/
-IssmDouble Matice::GetAbar(){/*{{{*/
+IssmDouble Matice::GetAbar(Gauss* gauss){/*{{{*/
 	/*
 	 * A = 1/B^n
 	 */
 
-	IssmDouble B,n;
-
-	element->inputs->GetInputAverage(&B,MaterialsRheologyBbarEnum);
-	n=this->GetN();
+	IssmDouble B=this->GetBbar(gauss);
+	IssmDouble n=this->GetN();
 
 	return pow(B,-n);
 }
 /*}}}*/
-IssmDouble Matice::GetB(){/*{{{*/
+IssmDouble Matice::GetB(Gauss* gauss){/*{{{*/
+
+	_assert_(gauss); 
 
 	/*Output*/
 	IssmDouble B;
 
-	element->inputs->GetInputAverage(&B,MaterialsRheologyBEnum);
+	Input* B_input = element->GetInput(MaterialsRheologyBEnum); _assert_(B_input);
+	B_input->GetInputValue(&B,gauss);
 	return B;
 }
 /*}}}*/
-IssmDouble Matice::GetBbar(){/*{{{*/
+IssmDouble Matice::GetBbar(Gauss* gauss){/*{{{*/
+
+	_assert_(gauss); 
 
 	/*Output*/
 	IssmDouble Bbar;
 
-	element->inputs->GetInputAverage(&Bbar,MaterialsRheologyBbarEnum);
+	Input* B_input = element->GetInput(MaterialsRheologyBbarEnum); _assert_(B_input);
+	B_input->GetInputValue(&Bbar,gauss);
 	return Bbar;
 }
 /*}}}*/
-IssmDouble Matice::GetD(){/*{{{*/
+IssmDouble Matice::GetD(Gauss* gauss){/*{{{*/
 
 	_assert_(this->isdamaged);
 	/*Output*/
 	IssmDouble D;
-	if(this->isdamaged)element->inputs->GetInputAverage(&D,DamageDEnum);
+	if(this->isdamaged){
+		Input* D_input = element->GetInput(DamageDEnum); _assert_(D_input);
+		D_input->GetInputValue(&D,gauss);
+	}
+	else{
+		_error_("Cannot get DamageD for non damaged ice");
+	}
 	return D;
 }
 /*}}}*/
-IssmDouble Matice::GetDbar(){/*{{{*/
+IssmDouble Matice::GetDbar(Gauss* gauss){/*{{{*/
 
 	_assert_(this->isdamaged);
 	/*Output*/
 	IssmDouble Dbar;
-	if(this->isdamaged)element->inputs->GetInputAverage(&Dbar,DamageDbarEnum);
+	if(this->isdamaged){
+		Input* D_input = element->GetInput(DamageDbarEnum); _assert_(D_input);
+		D_input->GetInputValue(&Dbar,gauss);
+	}
+	else{
+		_error_("Cannot get DamageD for non damaged ice");
+	}
 	return Dbar;
 }
 /*}}}*/
-IssmDouble Matice::GetE(){/*{{{*/
+IssmDouble Matice::GetE(Gauss* gauss){/*{{{*/
 
 	_assert_(this->isenhanced);
 	/*Output*/
 	IssmDouble E;
-	if(this->isenhanced)element->inputs->GetInputAverage(&E,MaterialsRheologyEEnum);
+	Input* E_input = element->GetInput(MaterialsRheologyEEnum); _assert_(E_input);
+	E_input->GetInputValue(&E,gauss);
 	return E;
 }
 /*}}}*/
-IssmDouble Matice::GetEbar(){/*{{{*/
+IssmDouble Matice::GetEbar(Gauss* gauss){/*{{{*/
 
 	_assert_(this->isenhanced);
 	/*Output*/
 	IssmDouble Ebar;
-	if(this->isenhanced)element->inputs->GetInputAverage(&Ebar,MaterialsRheologyEbarEnum);
+	Input* E_input = element->GetInput(MaterialsRheologyEbarEnum); _assert_(E_input);
+	E_input->GetInputValue(&Ebar,gauss);
 	return Ebar;
 }
@@ -292,5 +308,5 @@
 }
 /*}}}*/
-void  Matice::GetViscosity(IssmDouble* pviscosity,IssmDouble eps_eff){/*{{{*/
+void  Matice::GetViscosity(IssmDouble* pviscosity,IssmDouble eps_eff,Gauss* gauss){/*{{{*/
 	/*From a string tensor and a material object, return viscosity, using Glen's flow law.
 								(1-D) B
@@ -312,12 +328,12 @@
 
 	/*Get B and n*/
-	B=GetB(); _assert_(B>0.);
+	B=GetB(gauss); _assert_(B>0.);
 	n=GetN(); _assert_(n>0.);
 	if(this->isdamaged){
-		D=GetD();
+		D=GetD(gauss);
 		_assert_(D>=0. && D<1.);
 	}
 	if(this->isenhanced){
-		E=GetE();
+		E=GetE(gauss);
 		_assert_(E>0.);
 	}
@@ -348,5 +364,5 @@
 }
 /*}}}*/
-void  Matice::GetViscosityBar(IssmDouble* pviscosity,IssmDouble eps_eff){/*{{{*/
+void  Matice::GetViscosityBar(IssmDouble* pviscosity,IssmDouble eps_eff,Gauss* gauss){/*{{{*/
 	/*From a string tensor and a material object, return viscosity, using Glen's flow law.
 								(1-D) B
@@ -368,12 +384,12 @@
 
 	/*Get B and n*/
-	B=GetBbar(); _assert_(B>0.);
+	B=GetBbar(gauss); _assert_(B>0.);
 	n=GetN();    _assert_(n>0.);
 	if(this->isdamaged){
-		D=GetDbar();
+		D=GetDbar(gauss);
 		_assert_(D>=0. && D<1.);
 	}
 	if(this->isenhanced){
-		E=GetEbar();
+		E=GetEbar(gauss);
 		_assert_(E>0.);
 	}
@@ -403,5 +419,5 @@
 }
 /*}}}*/
-void  Matice::GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* epsilon){/*{{{*/
+void  Matice::GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* epsilon,Gauss* gauss){/*{{{*/
 	/*Return viscosity accounting for steady state power law creep [Thomas and SSA, 1982]: 
 	 *
@@ -426,5 +442,5 @@
 	/*Get D and n*/
 	if(this->isdamaged){
-		D=GetDbar(); /* GetD()? */
+		D=GetDbar(gauss); /* GetD()? */
 		_assert_(D>=0. && D<1.);
 	}
@@ -461,5 +477,5 @@
 }
 /*}}}*/
-void  Matice::GetViscosityDComplement(IssmDouble* pviscosity_complement, IssmDouble* epsilon){/*{{{*/
+void  Matice::GetViscosityDComplement(IssmDouble* pviscosity_complement, IssmDouble* epsilon,Gauss* gauss){/*{{{*/
 	/*Return viscosity derivative for control method d(mu)/dD: 
 	 *
@@ -483,5 +499,5 @@
 
 	/*Get B and n*/
-	B=GetBbar();
+	B=GetBbar(gauss);
 	n=GetN();
 
@@ -516,5 +532,5 @@
 }
 /*}}}*/
-void  Matice::GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* epsilon){/*{{{*/
+void  Matice::GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* epsilon,Gauss* gauss){/*{{{*/
 
 	/*output: */
@@ -532,5 +548,5 @@
 	else{
 
-		/*Retrive strain rate components: */
+		/*Retrieve strain rate components: */
 		exx=epsilon[0];
 		eyy=epsilon[1];
@@ -540,5 +556,5 @@
 		eff2 = exx*exx + eyy*eyy + exx*eyy + exy*exy + exz*exz + eyz*eyz;
 
-		GetViscosity(&mu,sqrt(eff2));
+		GetViscosity(&mu,sqrt(eff2),gauss);
 		n=GetN();
 		mu_prime=(1.-n)/(2.*n) * mu/eff2;
@@ -549,5 +565,5 @@
 }
 /*}}}*/
-void  Matice::GetViscosity_B(IssmDouble* pdmudB,IssmDouble eps_eff){/*{{{*/
+void  Matice::GetViscosity_B(IssmDouble* pdmudB,IssmDouble eps_eff,Gauss* gauss){/*{{{*/
 
 	/*output: */
@@ -560,9 +576,9 @@
 	n=GetN(); _assert_(n>0.);
 	if(this->isdamaged){
-		D=GetD();
+		D=GetD(gauss);
 		_assert_(D>=0. && D<1.);
 	}
 	if(this->isenhanced){
-		E=GetE();
+		E=GetE(gauss);
 		_assert_(E>0.);
 	}
@@ -581,5 +597,5 @@
 }
 /*}}}*/
-void  Matice::GetViscosity_D(IssmDouble* pdmudD,IssmDouble eps_eff){/*{{{*/
+void  Matice::GetViscosity_D(IssmDouble* pdmudD,IssmDouble eps_eff,Gauss* gauss){/*{{{*/
 
 	/*output: */
@@ -591,8 +607,8 @@
 	/*Get B and n*/
 	n=GetN(); _assert_(n>0.);
-	B=GetBbar();
+	B=GetBbar(gauss);
 	_assert_(this->isdamaged);
 	if(this->isenhanced){
-		E=GetE();
+		E=GetE(gauss);
 		_assert_(E>0.);
 	}
@@ -611,5 +627,5 @@
 }
 /*}}}*/
-void  Matice::GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* epsilon){/*{{{*/
+void  Matice::GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* epsilon,Gauss* gauss){/*{{{*/
 
 	/*output: */
@@ -630,5 +646,5 @@
 		eff2 = exx*exx + eyy*eyy + exx*eyy + exy*exy ;
 
-		GetViscosityBar(&mu,sqrt(eff2));
+		GetViscosityBar(&mu,sqrt(eff2),gauss);
 		n=GetN();
 		mu_prime=(1.-n)/(2.*n)*mu/eff2;
@@ -709,5 +725,5 @@
 
 	/*Get viscosity*/
-	this->GetViscosity(&viscosity,eps_eff);
+	this->GetViscosity(&viscosity,eps_eff,gauss);
 
 	/*Assign output pointer*/
@@ -715,6 +731,6 @@
 }
 /*}}}*/
-void  Matice::ViscosityFSDerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon){/*{{{*/
-	this->GetViscosityDerivativeEpsSquare(pmu_prime,epsilon);
+void  Matice::ViscosityFSDerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon,Gauss* gauss){/*{{{*/
+	this->GetViscosityDerivativeEpsSquare(pmu_prime,epsilon,gauss);
 }/*}}}*/
 void  Matice::ViscosityHO(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){/*{{{*/
@@ -724,5 +740,5 @@
 	IssmDouble epsilon3d[5];/* epsilon=[exx,eyy,exy,exz,eyz];*/
 	IssmDouble epsilon2d[2];/* epsilon=[exx,exy];            */
-	IssmDouble eps_eff,E=1.0;
+	IssmDouble eps_eff;
 
 	if(dim==3){
@@ -738,5 +754,5 @@
 
 	/*Get viscosity*/
-	this->GetViscosity(&viscosity,eps_eff);
+	this->GetViscosity(&viscosity,eps_eff,gauss);
 	_assert_(!xIsNan<IssmDouble>(viscosity));
 
@@ -744,6 +760,6 @@
 	*pviscosity=viscosity;
 }/*}}}*/
-void  Matice::ViscosityHODerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon){/*{{{*/
-	this->GetViscosityDerivativeEpsSquare(pmu_prime,epsilon);
+void  Matice::ViscosityHODerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon,Gauss* gauss){/*{{{*/
+	this->GetViscosityDerivativeEpsSquare(pmu_prime,epsilon,gauss);
 }/*}}}*/
 void  Matice::ViscosityL1L2(IssmDouble* pviscosity,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* surface_input){/*{{{*/
@@ -789,5 +805,5 @@
 	/*Get A*/
 	_assert_(this->GetN()==3.0);
-	A=this->GetA();
+	A=this->GetA(gauss);
 
 	/*Solve for tau_perp (http://fr.wikipedia.org/wiki/Méthode_de_Cardan)*/
@@ -826,10 +842,10 @@
 
 	/*Get viscosity*/
-	this->GetViscosityBar(&viscosity,eps_eff);
+	this->GetViscosityBar(&viscosity,eps_eff,gauss);
 
 	/*Assign output pointer*/
 	*pviscosity=viscosity;
 }/*}}}*/
-void  Matice::ViscositySSADerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon){/*{{{*/
-	this->GetViscosity2dDerivativeEpsSquare(pmu_prime,epsilon);
+void  Matice::ViscositySSADerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon,Gauss* gauss){/*{{{*/
+	this->GetViscosity2dDerivativeEpsSquare(pmu_prime,epsilon,gauss);
 }/*}}}*/
Index: /issm/trunk/src/c/classes/Materials/Matice.h
===================================================================
--- /issm/trunk/src/c/classes/Materials/Matice.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Materials/Matice.h	(revision 22758)
@@ -28,4 +28,5 @@
 		bool     isdamaged;
 		bool     isenhanced;
+		int      rheology_law;
 		Hook    *helement;
 		Element *element;
@@ -59,20 +60,20 @@
 		void   Configure(Elements* elements);
 		Material*  copy2(Element* element);
-		void       GetViscosity(IssmDouble* pviscosity, IssmDouble eps_eff);
-		void       GetViscosityBar(IssmDouble* pviscosity, IssmDouble eps_eff);
-		void       GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon);
-		void       GetViscosityDComplement(IssmDouble*, IssmDouble*);
-		void       GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon);
-		void       GetViscosity_B(IssmDouble* pviscosity, IssmDouble eps_eff);
-		void       GetViscosity_D(IssmDouble* pviscosity, IssmDouble eps_eff);
-		void       GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon);
-		IssmDouble GetA();
-		IssmDouble GetAbar();
-		IssmDouble GetB();
-		IssmDouble GetBbar();
-		IssmDouble GetD();
-		IssmDouble GetDbar();
-		IssmDouble GetE();
-		IssmDouble GetEbar();
+		void       GetViscosity(IssmDouble* pviscosity, IssmDouble eps_eff,Gauss* gauss);
+		void       GetViscosityBar(IssmDouble* pviscosity, IssmDouble eps_eff,Gauss* gauss);
+		void       GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon,Gauss* gauss);
+		void       GetViscosityDComplement(IssmDouble*, IssmDouble*,Gauss* gauss);
+		void       GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon,Gauss* gauss);
+		void       GetViscosity_B(IssmDouble* pviscosity, IssmDouble eps_eff,Gauss* gauss);
+		void       GetViscosity_D(IssmDouble* pviscosity, IssmDouble eps_eff,Gauss* gauss);
+		void       GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon,Gauss* gauss);
+		IssmDouble GetA(Gauss* gauss);
+		IssmDouble GetAbar(Gauss* gauss);
+		IssmDouble GetB(Gauss* gauss);
+		IssmDouble GetBbar(Gauss* gauss);
+		IssmDouble GetD(Gauss* gauss);
+		IssmDouble GetDbar(Gauss* gauss);
+		IssmDouble GetE(Gauss* gauss);
+		IssmDouble GetEbar(Gauss* gauss);
 		IssmDouble GetN();
 		bool       IsDamage();
@@ -82,13 +83,13 @@
 
 		void       ViscosityFS(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input);
-		void       ViscosityFSDerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon);
+		void       ViscosityFSDerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon,Gauss* gauss);
 		void       ViscosityHO(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
-		void       ViscosityHODerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon);
+		void       ViscosityHODerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon,Gauss* gauss);
 		void       ViscosityL1L2(IssmDouble* pviscosity,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* surf);
 		void       ViscositySSA(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
-		void       ViscositySSADerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon);
-		void       ViscosityBFS(IssmDouble* pmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input){_error_("not supported");};
-		void       ViscosityBHO(IssmDouble* pmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){_error_("not supported");};
-		void       ViscosityBSSA(IssmDouble* pmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){_error_("not supported");};
+		void       ViscositySSADerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon,Gauss* gauss);
+		void       ViscosityBFS(IssmDouble* pmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input,IssmDouble eps_eff){_error_("not supported");};
+		void       ViscosityBHO(IssmDouble* pmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,IssmDouble eps_eff){_error_("not supported");};
+		void       ViscosityBSSA(IssmDouble* pmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,IssmDouble eps_eff){_error_("not supported");};
 		/*}}}*/
 };
Index: /issm/trunk/src/c/classes/Materials/Matlitho.cpp
===================================================================
--- /issm/trunk/src/c/classes/Materials/Matlitho.cpp	(revision 22758)
+++ /issm/trunk/src/c/classes/Materials/Matlitho.cpp	(revision 22758)
@@ -0,0 +1,197 @@
+/*!\file Matlitho.c
+ * \brief: implementation of the Matlitho object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+
+/*Matlitho constructors and destructor*/
+Matlitho::Matlitho(){/*{{{*/
+	this->numlayers=0;
+	this->radius=NULL;
+	this->viscosity=NULL;
+	this->lame_lambda=NULL;
+	this->lame_mu=NULL;
+	this->burgers_viscosity=NULL;
+	this->burgers_mu=NULL;
+	this->density=NULL;
+	this->isburgers=NULL;
+	this->issolid=NULL;
+	return;
+}
+/*}}}*/
+Matlitho::Matlitho(int matlitho_mid, IoModel* iomodel){/*{{{*/
+
+	IssmDouble* isburgersd=NULL;
+	IssmDouble* issolidd=NULL;
+
+	this->mid=matlitho_mid;
+	iomodel->FindConstant(&this->numlayers,"md.materials.numlayers");
+
+	this->radius=xNew<IssmDouble>(this->numlayers+1);
+	xMemCpy<IssmDouble>(this->radius, iomodel->Data("md.materials.radius"),this->numlayers+1);
+	
+	this->viscosity=xNew<IssmDouble>(this->numlayers);
+	xMemCpy<IssmDouble>(this->viscosity, iomodel->Data("md.materials.viscosity"),this->numlayers);
+	
+	this->lame_lambda=xNew<IssmDouble>(this->numlayers);
+	xMemCpy<IssmDouble>(this->lame_lambda, iomodel->Data("md.materials.lame_lambda"),this->numlayers);
+	
+	this->lame_mu=xNew<IssmDouble>(this->numlayers);
+	xMemCpy<IssmDouble>(this->lame_mu, iomodel->Data("md.materials.lame_mu"),this->numlayers);
+
+	this->burgers_viscosity=xNew<IssmDouble>(this->numlayers);
+	xMemCpy<IssmDouble>(this->burgers_viscosity, iomodel->Data("md.materials.burgers_viscosity"),this->numlayers);
+
+	this->burgers_mu=xNew<IssmDouble>(this->numlayers);
+	xMemCpy<IssmDouble>(this->burgers_mu, iomodel->Data("md.materials.burgers_mu"),this->numlayers);
+
+	this->density=xNew<IssmDouble>(this->numlayers);
+	xMemCpy<IssmDouble>(this->density, iomodel->Data("md.materials.density"),this->numlayers);
+
+	this->isburgers=xNew<IssmDouble>(this->numlayers);
+	xMemCpy<IssmDouble>(this->isburgers, iomodel->Data("md.materials.isburgers"),this->numlayers);
+
+	this->issolid=xNew<IssmDouble>(this->numlayers);
+	xMemCpy<IssmDouble>(this->issolid, iomodel->Data("md.materials.issolid"),this->numlayers);
+	
+	/*isburgersd= xNew<IssmDouble>(this->numlayers);
+	this->isburgers=xNew<bool>(this->numlayers);
+	xMemCpy<IssmDouble>(isburgersd, iomodel->Data("md.materials.isburgers"),this->numlayers);
+	for (int i=0;i<this->numlayers;i++)this->isburgers[i]=reCast<bool,IssmDouble>(isburgersd[i]);
+	
+	issolidd= xNew<IssmDouble>(this->numlayers);
+	this->issolid=xNew<bool>(this->numlayers);
+	xMemCpy<IssmDouble>(issolidd, iomodel->Data("md.materials.issolid"),this->numlayers);
+	for (int i=0;i<this->numlayers;i++)this->issolid[i]=reCast<bool,IssmDouble>(issolidd[i]);*/
+	
+	/*free ressources: */
+	xDelete<IssmDouble>(isburgersd);
+	xDelete<IssmDouble>(issolidd);
+}
+/*}}}*/
+Matlitho::~Matlitho(){/*{{{*/
+	
+	xDelete<IssmDouble>(radius);
+	xDelete<IssmDouble>(viscosity);
+	xDelete<IssmDouble>(lame_lambda);
+	xDelete<IssmDouble>(lame_mu);
+	xDelete<IssmDouble>(burgers_viscosity);
+	xDelete<IssmDouble>(burgers_mu);
+	xDelete<IssmDouble>(density);
+	xDelete<IssmDouble>(isburgers);
+	xDelete<IssmDouble>(issolid);
+
+	return;
+}
+/*}}}*/
+void Matlitho::SetMid(int matlitho_mid){/*{{{*/
+	this->mid=matlitho_mid;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+Object* Matlitho::copy() {/*{{{*/
+
+	/*Output*/
+	Matlitho* matlitho;
+
+	/*Initialize output*/
+	matlitho=new Matlitho(*this);
+
+	/*copy fields: */
+	matlitho->mid=this->mid;
+	matlitho->numlayers=this->numlayers;
+	if(matlitho->numlayers){
+		matlitho->radius=xNew<IssmDouble>(this->numlayers+1); xMemCpy<IssmDouble>(matlitho->radius, this->radius,this->numlayers+1);
+		matlitho->viscosity=xNew<IssmDouble>(this->numlayers); xMemCpy<IssmDouble>(matlitho->viscosity, this->viscosity,this->numlayers);
+		matlitho->lame_lambda=xNew<IssmDouble>(this->numlayers); xMemCpy<IssmDouble>(matlitho->lame_lambda, this->lame_lambda,this->numlayers);
+		matlitho->lame_mu=xNew<IssmDouble>(this->numlayers); xMemCpy<IssmDouble>(matlitho->lame_mu, this->lame_mu,this->numlayers);
+		matlitho->burgers_viscosity=xNew<IssmDouble>(this->numlayers); xMemCpy<IssmDouble>(matlitho->burgers_viscosity, this->burgers_viscosity,this->numlayers);
+		matlitho->burgers_mu=xNew<IssmDouble>(this->numlayers); xMemCpy<IssmDouble>(matlitho->burgers_mu, this->burgers_mu,this->numlayers);
+		matlitho->density=xNew<IssmDouble>(this->numlayers); xMemCpy<IssmDouble>(matlitho->density, this->density,this->numlayers);
+		matlitho->isburgers=xNew<IssmDouble>(this->numlayers); xMemCpy<IssmDouble>(matlitho->isburgers, this->isburgers,this->numlayers);
+		matlitho->issolid=xNew<IssmDouble>(this->numlayers); xMemCpy<IssmDouble>(matlitho->issolid, this->issolid,this->numlayers);
+		/*matlitho->isburgers=xNew<bool>(this->numlayers); for(int i=0;i<this->numlayers;i++)matlitho->isburgers[i]=this->isburgers[i]; 
+		matlitho->issolid=xNew<bool>(this->numlayers); for(int i=0;i<this->numlayers;i++)matlitho->issolid[i]=this->issolid[i];*/ 
+	}
+
+	return matlitho;
+}
+/*}}}*/
+void Matlitho::DeepEcho(void){/*{{{*/
+
+	this->Echo();
+}		
+/*}}}*/
+void Matlitho::Echo(void){/*{{{*/
+
+	_printf_("Matlitho:\n");
+	_printf_("   mid: " << mid << "\n");
+	_printf_("   numlayers: " << numlayers << "\n");
+	_printf_("layer radius viscosity lame_lambda lame_mu burgers_viscosity burgers_mu density isburgers issolid\n");
+	for (int i=0;i<numlayers;i++){
+		_printf_(i << " " << radius[i] << " " << viscosity[i] << " " << lame_lambda[i] << " " << lame_mu[i] << " " << burgers_viscosity[i] << " " << burgers_mu[i] << " " << density[i] << " " << isburgers[i] << " " << issolid[i]);
+	}
+	return;
+}
+/*}}}*/
+int  Matlitho::Id(void){ return mid; }/*{{{*/
+/*}}}*/
+void Matlitho::Marshall(char** pmarshalled_data,int* pmarshalled_data_size, int marshall_direction){ /*{{{*/
+
+	MARSHALLING_ENUM(MatlithoEnum);
+
+	MARSHALLING(numlayers);
+	if(numlayers) { 
+		MARSHALLING_DYNAMIC(radius,IssmDouble,numlayers+1);
+		MARSHALLING_DYNAMIC(viscosity,IssmDouble,numlayers);
+		MARSHALLING_DYNAMIC(lame_lambda,IssmDouble,numlayers);
+		MARSHALLING_DYNAMIC(lame_mu,IssmDouble,numlayers);
+		MARSHALLING_DYNAMIC(burgers_viscosity,IssmDouble,numlayers);
+		MARSHALLING_DYNAMIC(burgers_mu,IssmDouble,numlayers);
+		MARSHALLING_DYNAMIC(density,IssmDouble,numlayers);
+		MARSHALLING_DYNAMIC(isburgers,IssmDouble,numlayers);
+		MARSHALLING_DYNAMIC(issolid,IssmDouble,numlayers);
+	}
+	else{
+		radius=NULL;
+		viscosity=NULL;
+		lame_lambda=NULL;
+		lame_mu=NULL;
+		burgers_viscosity=NULL;
+		burgers_mu=NULL;
+		density=NULL;
+		isburgers=NULL;
+		issolid=NULL;
+	}
+
+}
+/*}}}*/
+int  Matlitho::ObjectEnum(void){/*{{{*/
+
+	return MatlithoEnum;
+
+}
+/*}}}*/
+
+/*Update virtual functions definitions:*/
+
+/*Matlitho management: */
+void       Matlitho::Configure(Elements* elementsin){/*{{{*/
+	/*don't do anything, we don't have a hook to an element! As there is only 
+	 * one Matlitho object!*/
+}
+/*}}}*/
+void       Matlitho::ResetHooks(){/*{{{*/
+	/*don't do anything, we don't have a hook to an element! As there is only 
+	 * one Matlitho object!*/
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Materials/Matlitho.h
===================================================================
--- /issm/trunk/src/c/classes/Materials/Matlitho.h	(revision 22758)
+++ /issm/trunk/src/c/classes/Materials/Matlitho.h	(revision 22758)
@@ -0,0 +1,97 @@
+/*!\file Matlitho.h
+ * \brief: header file for matlitho object
+ */
+
+#ifndef _MATLITHO_H_
+#define _MATLITHO_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Material.h"
+class IoModel;
+/*}}}*/
+
+class Matlitho: public Material{
+
+	public: 
+		int	      mid;
+		int          numlayers;
+		IssmDouble*  radius;
+		IssmDouble*  viscosity;
+		IssmDouble*  lame_lambda;
+		IssmDouble*  lame_mu;
+		IssmDouble*  burgers_viscosity;
+		IssmDouble*  burgers_mu;
+		IssmDouble*  density;
+		IssmDouble*  isburgers;
+		IssmDouble*  issolid;
+
+		Matlitho();
+		Matlitho(int matlitho_id, IoModel* iomodel);
+		~Matlitho();
+		void SetMid(int matlitho_mid);
+
+		/*Object virtual functions definitions:{{{ */
+		Object *copy();
+		void    DeepEcho();
+		void    Echo();
+		int     Id();
+		void Marshall(char** pmarshalled_data,int* pmarshalled_data_size, int marshall_direction);
+		int     ObjectEnum();
+		/*}}}*/
+		/*Update virtual functions resolution: {{{*/
+		void   InputUpdateFromConstant(IssmDouble constant, int name){_error_("not implemented");};
+		void   InputUpdateFromConstant(int constant, int name){_error_("not implemented");};
+		void   InputUpdateFromConstant(bool constant, int name){_error_("not implemented");};
+		void   InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented");};
+		void   InputUpdateFromMatrixDakota(IssmDouble* matrix,int nrows,int ncols, int name, int type){_error_("not implemented");};
+		void   InputUpdateFromVector(IssmDouble* vector, int name, int type){_error_("not implemented");};
+		void   InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){_error_("not implemented");};
+		/*}}}*/
+		/*Material virtual functions resolution: {{{*/
+		Material*  copy2(Element* element){_error_("not implemented");};
+		void       Configure(Elements* elements);
+		void       GetViscosity(IssmDouble* pviscosity,IssmDouble eps_eff,Gauss* gauss){_error_("not supported");};
+		void       GetViscosityBar(IssmDouble* pviscosity,IssmDouble eps_eff,Gauss* gauss){_error_("not supported");};
+		void       GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon,Gauss* gauss){_error_("not supported");};
+		void       GetViscosityDComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon,Gauss* gauss){_error_("not supported");};
+		void       GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon,Gauss* gauss){_error_("not supported");};
+		void       GetViscosity_B(IssmDouble* pviscosity,IssmDouble eps_eff,Gauss* gauss){_error_("not supported");};
+		void       GetViscosity_D(IssmDouble* pviscosity,IssmDouble eps_eff,Gauss* gauss){_error_("not supported");};
+		void       GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon,Gauss* gauss){_error_("not supported");};
+		IssmDouble GetA(Gauss* gauss){_error_("not supported");};
+		IssmDouble GetAbar(Gauss* gauss){_error_("not supported");};
+		IssmDouble GetB(Gauss* gauss){_error_("not supported");};
+		IssmDouble GetBbar(Gauss* gauss){_error_("not supported");};
+		IssmDouble GetD(Gauss* gauss){_error_("not supported");};
+		IssmDouble GetDbar(Gauss* gauss){_error_("not supported");};
+		IssmDouble GetN(){_error_("not supported");};
+		bool       IsDamage(){_error_("not supported");};
+		bool       IsEnhanced(){_error_("not supported");};
+		void       ResetHooks();
+
+		void       ViscosityFS(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input){_error_("not supported");};
+		void       ViscosityFSDerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon,Gauss* gauss){_error_("not supported");};
+		void       ViscosityHO(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){_error_("not supported");};
+		void       ViscosityHODerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon,Gauss* gauss){_error_("not supported");};
+		void       ViscosityL1L2(IssmDouble* pviscosity,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* surf){_error_("not supported");};
+		void       ViscositySSA(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){_error_("not supported");};
+		void       ViscositySSADerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon,Gauss* gauss){_error_("not supported");};
+		void       ViscosityBFS(IssmDouble* pmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input,IssmDouble epseff){_error_("not supported");};
+		void       ViscosityBHO(IssmDouble* pmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,IssmDouble epseff){_error_("not supported");};
+		void       ViscosityBSSA(IssmDouble* pmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,IssmDouble epseff){_error_("not supported");};
+
+		/*}}}*/
+		/*Numerics: {{{*/
+		void       EnthalpyToThermal(IssmDouble* ptemperature,IssmDouble* pwaterfraction,IssmDouble enthalpy,IssmDouble pressure){_error_("not supported");};
+		IssmDouble GetEnthalpyDiffusionParameter(IssmDouble enthalpy,IssmDouble pressure){_error_("not supported");};
+		IssmDouble GetEnthalpyDiffusionParameterVolume(int numvertices,IssmDouble* enthalpy,IssmDouble* pressure){_error_("not supported");};
+		IssmDouble GetMaterialParameter(int in_enum){_error_("not supported");}; 
+		IssmDouble PureIceEnthalpy(IssmDouble pressure){_error_("not supported");};
+		void       ThermalToEnthalpy(IssmDouble* penthalpy,IssmDouble temperature,IssmDouble waterfraction,IssmDouble pressure){_error_("not supported");};
+		IssmDouble TMeltingPoint(IssmDouble pressure){_error_("not supported");};
+		/*}}}*/
+
+};
+
+#endif  /* _MATLITHO_H_ */
Index: /issm/trunk/src/c/classes/Materials/Matpar.cpp
===================================================================
--- /issm/trunk/src/c/classes/Materials/Matpar.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Materials/Matpar.cpp	(revision 22758)
@@ -17,5 +17,5 @@
 }
 /*}}}*/
-Matpar::Matpar(int matpar_mid, IoModel* iomodel){/*{{{*/
+Matpar::Matpar(IoModel* iomodel){/*{{{*/
 
 	rho_ice                   = 0;
@@ -38,4 +38,5 @@
 	rlapslgm                  = 0;
 	dpermil                   = 0;
+	rheology_law              = 0;
 
 	albedo_snow               = 0;
@@ -61,13 +62,6 @@
 	earth_density             = 0;
 
-	poisson                   = 0;
-	young_modulus             = 0;
-	ridging_exponent          = 0;
-	cohesion                  = 0;
-	internal_friction_coef    = 0;
-	compression_coef          = 0;
-	traction_coef             = 0;
-	time_relaxation_stress    = 0;
-	time_relaxation_damage    = 0;
+	int nnat,dummy;
+	int* nature=NULL;
 
 	bool isefficientlayer;
@@ -77,5 +71,5 @@
 	iomodel->FindConstant(&materials_type,"md.materials.type");
 
-	this->mid = matpar_mid;
+	this->mid = iomodel->matparcounter;
 
 	switch(materials_type){
@@ -98,4 +92,5 @@
 			iomodel->FindConstant(&this->thermal_exchange_velocity,"md.materials.thermal_exchange_velocity");
 			iomodel->FindConstant(&this->g,"md.constants.g");
+			iomodel->FindConstant(&this->rheology_law,"md.materials.rheology_law");
 
 			switch(smb_model){
@@ -169,4 +164,115 @@
 			/*slr:*/
 			iomodel->FindConstant(&this->earth_density,"md.materials.earth_density");
+
+			break;
+		case MaterialsEnum:
+			//we have several types of materials. Retrieve this info first: 
+			iomodel->FetchData(&nature,&nnat,&dummy,"md.materials.nature");
+
+			//go through list of materials, and create constant parameters accordingly: 
+			for(int i=0;i<nnat;i++){ 
+				switch(IoCodeToEnumMaterials(nature[i])){ //{{{
+					case MatlithoEnum:
+						break;
+					case MaticeEnum:
+					case MatdamageiceEnum:
+					case MatenhancediceEnum:
+					case MatestarEnum:
+						iomodel->FindConstant(&this->rho_ice,"md.materials.rho_ice");
+						iomodel->FindConstant(&this->rho_water,"md.materials.rho_water");
+						iomodel->FindConstant(&this->rho_freshwater,"md.materials.rho_freshwater");
+						iomodel->FindConstant(&this->mu_water,"md.materials.mu_water");
+						iomodel->FindConstant(&this->heatcapacity,"md.materials.heatcapacity");
+						iomodel->FindConstant(&this->thermalconductivity,"md.materials.thermalconductivity");
+						iomodel->FindConstant(&this->temperateiceconductivity,"md.materials.temperateiceconductivity");
+						iomodel->FindConstant(&this->latentheat,"md.materials.latentheat");
+						iomodel->FindConstant(&this->beta,"md.materials.beta");
+						iomodel->FindConstant(&this->meltingpoint,"md.materials.meltingpoint");
+						iomodel->FindConstant(&this->referencetemperature,"md.constants.referencetemperature");
+						iomodel->FindConstant(&this->mixed_layer_capacity,"md.materials.mixed_layer_capacity");
+						iomodel->FindConstant(&this->thermal_exchange_velocity,"md.materials.thermal_exchange_velocity");
+						iomodel->FindConstant(&this->g,"md.constants.g");
+						iomodel->FindConstant(&this->rheology_law,"md.materials.rheology_law");
+
+						switch(smb_model){ //{{{
+							case SMBforcingEnum:
+								/*Nothing to add*/
+								break;
+							case SMBgembEnum:
+								iomodel->FindConstant(&this->albedo_ice,"md.smb.aIce");
+								iomodel->FindConstant(&this->albedo_snow,"md.smb.aSnow");
+								break;
+							case SMBpddEnum:
+								iomodel->FindConstant(&this->desfac,"md.smb.desfac");
+								iomodel->FindConstant(&this->rlaps,"md.smb.rlaps");
+								iomodel->FindConstant(&this->rlapslgm,"md.smb.rlapslgm");
+								break;
+							case SMBd18opddEnum:
+								iomodel->FindConstant(&this->desfac,"md.smb.desfac");
+								iomodel->FindConstant(&this->rlaps,"md.smb.rlaps");
+								iomodel->FindConstant(&this->rlapslgm,"md.smb.rlapslgm");
+								iomodel->FindConstant(&this->dpermil,"md.smb.dpermil");					
+							case SMBgradientsEnum:
+								/*Nothing to add*/
+								break;
+							case SMBgradientselaEnum:
+								/*Nothing to add*/
+								break;
+							case SMBhenningEnum:
+								/*Nothing to add*/
+								break;
+							case SMBcomponentsEnum:
+								/*Nothing to add*/
+								break;
+							case SMBmeltcomponentsEnum:
+								/*Nothing to add*/
+								break;
+							default:
+								_error_("Surface mass balance model "<<EnumToStringx(smb_model)<<" not supported yet");
+						} 
+						if(hydrology_model==HydrologydcEnum){
+							iomodel->FindConstant(&this->sediment_compressibility,"md.hydrology.sediment_compressibility");
+							iomodel->FindConstant(&this->sediment_porosity,"md.hydrology.sediment_porosity");
+							iomodel->FindConstant(&this->sediment_thickness,"md.hydrology.sediment_thickness");
+							iomodel->FindConstant(&this->water_compressibility,"md.hydrology.water_compressibility");
+							iomodel->FindConstant(&isefficientlayer,"md.hydrology.isefficientlayer");
+
+							if(isefficientlayer){
+								iomodel->FindConstant(&this->epl_compressibility,"md.hydrology.epl_compressibility");
+								iomodel->FindConstant(&this->epl_porosity,"md.hydrology.epl_porosity");
+								iomodel->FindConstant(&this->epl_init_thickness,"md.hydrology.epl_initial_thickness");
+								iomodel->FindConstant(&this->epl_colapse_thickness,"md.hydrology.epl_colapse_thickness");
+								iomodel->FindConstant(&this->epl_max_thickness,"md.hydrology.epl_max_thickness");
+								iomodel->FindConstant(&this->epl_conductivity,"md.hydrology.epl_conductivity");
+							}
+						}
+						else if(hydrology_model==HydrologyshreveEnum){
+							/*Nothing to add*/
+						}
+						else if(hydrology_model==HydrologysommersEnum){
+							/*Nothing to add*/
+						}
+						else{
+							_error_("Hydrology model "<<EnumToStringx(hydrology_model)<<" not supported yet");
+						}
+
+						/*gia: */
+						iomodel->FindConstant(&this->lithosphere_shear_modulus,"md.materials.lithosphere_shear_modulus");
+						iomodel->FindConstant(&this->lithosphere_density,"md.materials.lithosphere_density");
+						iomodel->FindConstant(&this->mantle_shear_modulus,"md.materials.mantle_shear_modulus");
+						iomodel->FindConstant(&this->mantle_density,"md.materials.mantle_density");
+
+						/*slr:*/
+						iomodel->FindConstant(&this->earth_density,"md.materials.earth_density");
+						//}}}
+						break;
+					default:
+						_error_("Materials "<<EnumToStringx(IoCodeToEnumMaterials(nature[i]))<<" not supported");
+
+				} //}}}
+			}
+			//Free ressources:
+			xDelete<int>(nature);
+			break;
 
 			break;
@@ -214,4 +320,5 @@
 	matpar->rlapslgm=this->rlapslgm;
 	matpar->dpermil=this->dpermil;
+	matpar->rheology_law=this->rheology_law;
 
 	matpar->sediment_compressibility=this->sediment_compressibility;
@@ -265,4 +372,5 @@
 	_printf_("   rlapslgm: " << rlapslgm << "\n");
 	_printf_("   dpermil: " << dpermil << "\n");
+	_printf_("   rheology_law: " << rheology_law << "\n");
 	_printf_("   albedo_ice: " << albedo_ice << "\n");
 	_printf_("   albedo_snow: " << albedo_snow << "\n");
@@ -282,13 +390,4 @@
 	_printf_("   mantle_density: " << mantle_density << "\n");	
 	_printf_("   earth_density: " << earth_density << "\n");	
-	_printf_("   poisson: " << poisson << "\n");	
-	_printf_("   young_modulus: " << young_modulus << "\n");	
-	_printf_("   ridging_exponent: " << ridging_exponent << "\n");	
-	_printf_("   cohesion: " << cohesion << "\n");	
-	_printf_("   internal_friction_coef: " << internal_friction_coef << "\n");	
-	_printf_("   compression_coef: " << compression_coef << "\n");	
-	_printf_("   traction_coef: " << traction_coef << "\n");	
-	_printf_("   time_relaxation_stress: " << time_relaxation_stress << "\n");	
-	_printf_("   time_relaxation_damage: " << time_relaxation_damage << "\n");	
 	return;
 }
@@ -320,4 +419,5 @@
 	MARSHALLING(rlapslgm);
 	MARSHALLING(dpermil);
+	MARSHALLING(rheology_law);
 
 	//hydrology Dual Porous Continuum:
@@ -342,16 +442,4 @@
 	//slr:
 	MARSHALLING(earth_density);
-
-	//Sea ice:
-	MARSHALLING(poisson);
-	MARSHALLING(young_modulus);
-	MARSHALLING(ridging_exponent);
-	MARSHALLING(cohesion);
-	MARSHALLING(internal_friction_coef);
-	MARSHALLING(compression_coef);
-	MARSHALLING(traction_coef);
-	MARSHALLING(time_relaxation_stress);
-	MARSHALLING(time_relaxation_damage);
-
 }
 /*}}}*/
@@ -554,8 +642,8 @@
 		case HydrologydcWaterCompressibilityEnum:    return this->water_compressibility;
 		case ConstantsGEnum:                         return this->g;
-		case SmbDesfacEnum:              return this->desfac;
-		case SmbRlapsEnum:               return this->rlaps;
-		case SmbRlapslgmEnum:            return this->rlapslgm;
-		case SmbDpermilEnum:             return this->dpermil;
+		case SmbDesfacEnum:                          return this->desfac;
+		case SmbRlapsEnum:                           return this->rlaps;
+		case SmbRlapslgmEnum:                        return this->rlapslgm;
+		case SmbDpermilEnum:                         return this->dpermil;
 		case MaterialsLithosphereShearModulusEnum:   return this->lithosphere_shear_modulus;
 		case MaterialsLithosphereDensityEnum:        return this->lithosphere_density;
@@ -568,4 +656,13 @@
 }
 /*}}}*/
+int        Matpar::GetIntegerMaterialParameter(int enum_in){/*{{{*/
+
+	switch(enum_in){
+		case MaterialsRheologyLawEnum:               return this->rheology_law;
+		default: _error_("Enum "<<EnumToStringx(enum_in)<<" not supported yet");
+	}
+
+}
+/*}}}*/
 IssmDouble Matpar::PureIceEnthalpy(IssmDouble pressure){/*{{{*/
 	return heatcapacity*(TMeltingPoint(pressure)-referencetemperature);
Index: /issm/trunk/src/c/classes/Materials/Matpar.h
===================================================================
--- /issm/trunk/src/c/classes/Materials/Matpar.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Materials/Matpar.h	(revision 22758)
@@ -35,4 +35,5 @@
 		IssmDouble  rlapslgm;
 		IssmDouble  dpermil;
+		int         rheology_law;
 
 		/*albedo: */
@@ -62,18 +63,7 @@
 		IssmDouble earth_density;
 
-		/*Sea ice*/
-		IssmDouble poisson;
-		IssmDouble young_modulus;
-		IssmDouble ridging_exponent;
-		IssmDouble cohesion;
-		IssmDouble internal_friction_coef;
-		IssmDouble compression_coef;
-		IssmDouble traction_coef;
-		IssmDouble time_relaxation_stress;
-		IssmDouble time_relaxation_damage;
-
 	public:
 		Matpar();
-		Matpar(int matpar_id, IoModel* iomodel);
+		Matpar(IoModel* iomodel);
 		~Matpar();
 		void SetMid(int matpar_mid);
@@ -99,18 +89,18 @@
 		Material*  copy2(Element* element){_error_("not implemented");};
 		void       Configure(Elements* elements);
-		void       GetViscosity(IssmDouble* pviscosity,IssmDouble eps_eff){_error_("not supported");};
-		void       GetViscosityBar(IssmDouble* pviscosity,IssmDouble eps_eff){_error_("not supported");};
-		void       GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon){_error_("not supported");};
-		void       GetViscosityDComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon){_error_("not supported");};
-		void       GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon){_error_("not supported");};
-		void       GetViscosity_B(IssmDouble* pviscosity,IssmDouble eps_eff){_error_("not supported");};
-		void       GetViscosity_D(IssmDouble* pviscosity,IssmDouble eps_eff){_error_("not supported");};
-		void       GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon){_error_("not supported");};
-		IssmDouble GetA(){_error_("not supported");};
-		IssmDouble GetAbar(){_error_("not supported");};
-		IssmDouble GetB(){_error_("not supported");};
-		IssmDouble GetBbar(){_error_("not supported");};
-		IssmDouble GetD(){_error_("not supported");};
-		IssmDouble GetDbar(){_error_("not supported");};
+		void       GetViscosity(IssmDouble* pviscosity,IssmDouble eps_eff,Gauss* gauss){_error_("not supported");};
+		void       GetViscosityBar(IssmDouble* pviscosity,IssmDouble eps_eff,Gauss* gauss){_error_("not supported");};
+		void       GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon,Gauss* gauss){_error_("not supported");};
+		void       GetViscosityDComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon,Gauss* gauss){_error_("not supported");};
+		void       GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon,Gauss* gauss){_error_("not supported");};
+		void       GetViscosity_B(IssmDouble* pviscosity,IssmDouble eps_eff,Gauss* gauss){_error_("not supported");};
+		void       GetViscosity_D(IssmDouble* pviscosity,IssmDouble eps_eff,Gauss* gauss){_error_("not supported");};
+		void       GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon,Gauss* gauss){_error_("not supported");};
+		IssmDouble GetA(Gauss* gauss){_error_("not supported");};
+		IssmDouble GetAbar(Gauss* gauss){_error_("not supported");};
+		IssmDouble GetB(Gauss* gauss){_error_("not supported");};
+		IssmDouble GetBbar(Gauss* gauss){_error_("not supported");};
+		IssmDouble GetD(Gauss* gauss){_error_("not supported");};
+		IssmDouble GetDbar(Gauss* gauss){_error_("not supported");};
 		IssmDouble GetN(){_error_("not supported");};
 		bool       IsDamage(){_error_("not supported");};
@@ -119,13 +109,13 @@
 
 		void       ViscosityFS(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input){_error_("not supported");};
-		void       ViscosityFSDerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon){_error_("not supported");};
+		void       ViscosityFSDerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon,Gauss* gauss){_error_("not supported");};
 		void       ViscosityHO(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){_error_("not supported");};
-		void       ViscosityHODerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon){_error_("not supported");};
+		void       ViscosityHODerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon,Gauss* gauss){_error_("not supported");};
 		void       ViscosityL1L2(IssmDouble* pviscosity,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* surf){_error_("not supported");};
 		void       ViscositySSA(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){_error_("not supported");};
-		void       ViscositySSADerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon){_error_("not supported");};
-		void       ViscosityBFS(IssmDouble* pmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input){_error_("not supported");};
-		void       ViscosityBHO(IssmDouble* pmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){_error_("not supported");};
-		void       ViscosityBSSA(IssmDouble* pmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){_error_("not supported");};
+		void       ViscositySSADerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon,Gauss* gauss){_error_("not supported");};
+		void       ViscosityBFS(IssmDouble* pmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input,IssmDouble eps_eff){_error_("not supported");};
+		void       ViscosityBHO(IssmDouble* pmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,IssmDouble eps_eff){_error_("not supported");};
+		void       ViscosityBSSA(IssmDouble* pmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,IssmDouble eps_eff){_error_("not supported");};
 		/*}}}*/
 		/*Numerics: {{{*/
@@ -134,4 +124,5 @@
 		IssmDouble GetEnthalpyDiffusionParameterVolume(int numvertices,IssmDouble* enthalpy,IssmDouble* pressure);
 		IssmDouble GetMaterialParameter(int in_enum); 
+		int        GetIntegerMaterialParameter(int in_enum); 
 		IssmDouble PureIceEnthalpy(IssmDouble pressure);
 		void       ThermalToEnthalpy(IssmDouble* penthalpy,IssmDouble temperature,IssmDouble waterfraction,IssmDouble pressure);
Index: /issm/trunk/src/c/classes/Misfit.cpp
===================================================================
--- /issm/trunk/src/c/classes/Misfit.cpp	(revision 22758)
+++ /issm/trunk/src/c/classes/Misfit.cpp	(revision 22758)
@@ -0,0 +1,253 @@
+/*!\file Misfit.cpp
+ * \brief: Misfit object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+   #include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./classes.h"
+#include "./ExternalResults/ExternalResult.h"
+#include "./ExternalResults/Results.h"
+#include "../datastructures/datastructures.h"
+#include "./Elements/Element.h"
+#include "./Elements/Elements.h"
+#include "./FemModel.h"
+#include "../modules/SurfaceAreax/SurfaceAreax.h"
+#include "../classes/Params/Parameters.h"
+#include "../classes/Inputs/Input.h"
+#include "../classes/gauss/Gauss.h"
+/*}}}*/
+		
+/*Misfit constructors, destructors :*/
+Misfit::Misfit(){/*{{{*/
+
+	this->definitionenum = -1;
+	this->name = NULL;
+	this->model_enum = UNDEF;
+	this->observation_enum = UNDEF;
+	this->weights_enum = UNDEF;
+	this->timeinterpolation=NULL;
+	this->local=1;
+	this->misfit=0;
+	this->lock=0;
+
+}
+/*}}}*/
+Misfit::Misfit(char* in_name, int in_definitionenum, int in_model_enum, int in_observation_enum, char* in_timeinterpolation, int in_local, int in_weights_enum){/*{{{*/
+
+	this->definitionenum=in_definitionenum;
+	
+	this->name		= xNew<char>(strlen(in_name)+1);
+	xMemCpy<char>(this->name,in_name,strlen(in_name)+1);
+
+	this->timeinterpolation = xNew<char>(strlen(in_timeinterpolation)+1);
+	xMemCpy<char>(this->timeinterpolation,in_timeinterpolation,strlen(in_timeinterpolation)+1);
+				
+	this->model_enum=in_model_enum;
+	this->observation_enum=in_observation_enum;
+	this->weights_enum=in_weights_enum;
+	this->local=in_local;
+	
+	this->misfit=0;
+	this->lock=0;
+}
+/*}}}*/
+Misfit::~Misfit(){/*{{{*/
+	if(this->name)xDelete(this->name);
+	if(this->timeinterpolation)xDelete(this->timeinterpolation);
+	this->misfit=0;
+	this->lock=0;
+}
+/*}}}*/
+/*Object virtual function resolutoin: */
+Object* Misfit::copy() {/*{{{*/
+	Misfit* mf = new Misfit(this->name,this->definitionenum, this->model_enum,this->observation_enum,this->timeinterpolation,this->local,this->weights_enum);
+	mf->misfit=this->misfit;
+	mf->lock=this->lock;
+	return (Object*) mf;
+}
+/*}}}*/
+void Misfit::DeepEcho(void){/*{{{*/
+	this->Echo();
+}
+/*}}}*/
+void Misfit::Echo(void){/*{{{*/
+	_printf_(" Misfit: " << name << " " << this->definitionenum << "\n");
+	_printf_("    model_enum: " << model_enum << " " << EnumToStringx(model_enum) << "\n");
+	_printf_("    observation_enum: " << observation_enum << " " << EnumToStringx(observation_enum) << "\n");
+	_printf_("    weights_enum: " << weights_enum << " " << EnumToStringx(weights_enum) << "\n");
+	_printf_("    timeinterpolation: " << timeinterpolation << "\n");
+	_printf_("    local: " << local << "\n");
+}
+/*}}}*/
+int Misfit::Id(void){/*{{{*/
+	return -1;
+}
+/*}}}*/
+void Misfit::Marshall(char** pmarshalled_data,int* pmarshalled_data_size, int marshall_direction){/*{{{*/
+	_error_("not implemented yet!"); 
+} 
+/*}}}*/
+int Misfit::ObjectEnum(void){/*{{{*/
+	return MisfitEnum;
+}
+/*}}}*/
+/*Definition virtual function resolutoin: */
+int Misfit::DefinitionEnum(){/*{{{*/
+	return this->definitionenum;
+}
+/*}}}*/
+char* Misfit::Name(){/*{{{*/
+	char* name2=xNew<char>(strlen(this->name)+1);
+	xMemCpy(name2,this->name,strlen(this->name)+1);
+
+	return name2;
+}
+/*}}}*/
+IssmDouble Misfit::Response(FemModel* femmodel){/*{{{*/
+		 
+	 /*diverse: */
+	 IssmDouble time,starttime,finaltime;
+	 IssmDouble dt;
+	 
+	 /*recover time parameters: */
+	 femmodel->parameters->FindParam(&starttime,TimesteppingStartTimeEnum);
+	 femmodel->parameters->FindParam(&finaltime,TimesteppingFinalTimeEnum);
+	 femmodel->parameters->FindParam(&time,TimeEnum);
+	 femmodel->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+
+	 if (this->local==1){ /*area integration using elements: {{{*/
+
+		 int i;
+		 IssmDouble misfit_t=0.;
+		 IssmDouble all_misfit_t=0.;
+		 IssmDouble area_t=0.;
+		 IssmDouble all_area_t;
+
+	
+		 /*If we are locked, return time average: */
+		 if(this->lock)return misfit/(time-starttime);
+
+		 for(i=0;i<femmodel->elements->Size();i++){
+			 Element* element=(Element*)femmodel->elements->GetObjectByOffset(i);
+			 misfit_t+=element->Misfit(model_enum,observation_enum,weights_enum);
+			 area_t+=element->MisfitArea(weights_enum);
+		 }
+
+		 ISSM_MPI_Allreduce ( (void*)&misfit_t,(void*)&all_misfit_t,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
+		 ISSM_MPI_Allreduce ( (void*)&area_t,(void*)&all_area_t,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
+		 area_t=all_area_t;
+		 misfit_t=all_misfit_t;
+		 
+		 /*Divide by surface area if not nill!: */
+		 if (area_t!=0) misfit_t=misfit_t/area_t;
+
+		 /*Add this time's contribution to curent misfit: */
+		 misfit+=dt*misfit_t;
+
+		 /*Do we lock? i.e. are we at final_time? :*/
+		 if(time==finaltime)this->lock=1;
+
+		 /*What we return is the value of misfit / time if transient*/
+		 if(time!=0.) return misfit/(time-starttime); 
+		 return misfit;
+	 } /*}}}*/
+	 else if (this->local==2){ /*vertex by vertex computation: {{{*/
+
+		 IssmDouble* model = NULL;
+		 IssmDouble* observation= NULL;
+		 IssmDouble* weights= NULL;
+		 int msize,osize,wsize;
+		 
+		 /*Are we transient?:*/
+		 if (time==0){
+			 IssmDouble misfit_t=0.;
+			 
+			 /*get global vectors: */
+			 GetVectorFromInputsx(&model,&msize,femmodel,model_enum);
+			 GetVectorFromInputsx(&observation,&osize,femmodel,observation_enum);_assert_(msize==osize);
+			 GetVectorFromInputsx(&weights,&wsize,femmodel,weights_enum); _assert_(wsize==msize);
+
+			 int count=0;
+			 for (int i=0;i<msize;i++){
+				 misfit_t += pow(model[i]-observation[i],2)*weights[i];
+				 if (weights[i]!=0)count++;
+			 }
+			 misfit=sqrt(misfit_t/count);
+
+			 /*Free ressources:*/
+			 xDelete<IssmDouble>(model);
+			 xDelete<IssmDouble>(observation);
+			 xDelete<IssmDouble>(weights);
+
+			 /*return value: */
+			 return misfit;
+		 }
+		 else{
+			 
+			 IssmDouble misfit_t=0.;
+			 IssmDouble all_misfit_t=0.;
+
+			 /*If we are locked, return time average: */
+			 if(this->lock)return misfit/(time-starttime);
+
+			 /*get global vectors: */
+			 GetVectorFromInputsx(&model,&msize,femmodel,model_enum);
+			 GetVectorFromInputsx(&observation,&osize,femmodel,observation_enum);_assert_(msize==osize);
+			 GetVectorFromInputsx(&weights,&wsize,femmodel,weights_enum); _assert_(wsize==msize);
+			 
+			 int count=0;
+			 for (int i=0;i<msize;i++){
+				 misfit_t += pow(model[i]-observation[i],2)*weights[i];
+				 if (weights[i]!=0)count++;
+			 }
+			 misfit=sqrt(misfit_t/count);
+
+			 /*Add this time's contribution to curent misfit: */
+			 misfit=sqrt(misfit_t)/count;
+			 misfit+=dt*misfit_t;
+
+			 /*Do we lock? i.e. are we at final_time? :*/
+			 if(time==finaltime)this->lock=1;
+			 
+			 /*Free ressources:*/
+			 xDelete<IssmDouble>(model);
+			 xDelete<IssmDouble>(observation);
+			 xDelete<IssmDouble>(weights);
+
+			 /*What we return is the value of misfit / time: */
+			 return misfit/(time-starttime);
+		 }
+
+	 } /*}}}*/
+	 else{ /*global computation: {{{ */
+		 
+		 IssmDouble model, observation;
+		 
+		 /*If we are locked, return time average: */
+		 if(this->lock)return misfit/(time-starttime);
+
+		 /*First, the global  model response: */
+		 model=OutputDefinitionsResponsex(femmodel,this->model_enum);
+		 /*Now, the observation is buried inside the elements, go fish it in the first element (cludgy, needs fixing): */
+		 Element* element=(Element*)femmodel->elements->GetObjectByOffset(0); _assert_(element);
+		 Input* input = element->GetInput(observation_enum); _assert_(input);
+		 input->GetInputAverage(&observation);
+		 
+		 /*Add this time's contribution to curent misfit: */
+		 misfit+=dt*(model-observation);
+		 
+		 /*Do we lock? i.e. are we at final_time? :*/
+		 if(time==finaltime)this->lock=1;
+		 
+		 /*What we return is the value of misfit / time: */
+		 return misfit/(time-starttime);
+	 } /*}}}*/
+
+ }
+	/*}}}*/
Index: /issm/trunk/src/c/classes/Misfit.h
===================================================================
--- /issm/trunk/src/c/classes/Misfit.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Misfit.h	(revision 22758)
@@ -7,16 +7,9 @@
 
 /*Headers:*/
-/*{{{*/
 #include "./Definition.h"
-#include "../datastructures/datastructures.h"
-#include "./Elements/Element.h"
-#include "./Elements/Elements.h"
 #include "./FemModel.h"
-#include "../modules/SurfaceAreax/SurfaceAreax.h"
-#include "../classes/Params/Parameters.h"
-#include "../classes/Inputs/Input.h"
-#include "../classes/gauss/Gauss.h"
-/*}}}*/
+
 IssmDouble OutputDefinitionsResponsex(FemModel* femmodel,int output_enum);
+void  GetVectorFromInputsx( IssmDouble** pvector, int* pvector_size, FemModel* femmodel,int name);
 
 class Misfit: public Object, public Definition{
@@ -25,5 +18,5 @@
 
 		int         definitionenum;
-		bool        local;     
+		int         local;     
 		int         model_enum;
 		char*       name;
@@ -36,163 +29,20 @@
 		
 		/*Misfit constructors, destructors :*/
-		Misfit(){/*{{{*/
-
-			this->definitionenum = -1;
-			this->name = NULL;
-			this->model_enum = UNDEF;
-			this->observation_enum = UNDEF;
-			this->weights_enum = UNDEF;
-			this->timeinterpolation=NULL;
-			this->local=true;
-			this->misfit=0;
-			this->lock=0;
-
-		}
-		/*}}}*/
-		Misfit(char* in_name, int in_definitionenum, int in_model_enum, int in_observation_enum, char* in_timeinterpolation, bool in_local, int in_weights_enum){/*{{{*/
-
-			this->definitionenum=in_definitionenum;
-			
-			this->name		= xNew<char>(strlen(in_name)+1);
-			xMemCpy<char>(this->name,in_name,strlen(in_name)+1);
-
-			this->timeinterpolation = xNew<char>(strlen(in_timeinterpolation)+1);
-			xMemCpy<char>(this->timeinterpolation,in_timeinterpolation,strlen(in_timeinterpolation)+1);
-						
-			this->model_enum=in_model_enum;
-			this->observation_enum=in_observation_enum;
-			this->weights_enum=in_weights_enum;
-			this->local=in_local;
-			
-			this->misfit=0;
-			this->lock=0;
-		}
-		/*}}}*/
-		~Misfit(){/*{{{*/
-			if(this->name)xDelete(this->name);
-			if(this->timeinterpolation)xDelete(this->timeinterpolation);
-			this->misfit=0;
-			this->lock=0;
-		}
-		/*}}}*/
+		Misfit();
+		Misfit(char* in_name, int in_definitionenum, int in_model_enum, int in_observation_enum, char* in_timeinterpolation, int in_local, int in_weights_enum);
+		~Misfit();
+		
 		/*Object virtual function resolutoin: */
-		Object* copy() {/*{{{*/
-			Misfit* mf = new Misfit(this->name,this->definitionenum, this->model_enum,this->observation_enum,this->timeinterpolation,this->local,this->weights_enum);
-			mf->misfit=this->misfit;
-			mf->lock=this->lock;
-			return (Object*) mf;
-		}
-		/*}}}*/
-		void DeepEcho(void){/*{{{*/
-			this->Echo();
-		}
-		/*}}}*/
-		void Echo(void){/*{{{*/
-			_printf_(" Misfit: " << name << " " << this->definitionenum << "\n");
-			_printf_("    model_enum: " << model_enum << " " << EnumToStringx(model_enum) << "\n");
-			_printf_("    observation_enum: " << observation_enum << " " << EnumToStringx(observation_enum) << "\n");
-			_printf_("    weights_enum: " << weights_enum << " " << EnumToStringx(weights_enum) << "\n");
-			_printf_("    timeinterpolation: " << timeinterpolation << "\n");
-			_printf_("    local: " << local << "\n");
-		}
-		/*}}}*/
-		int Id(void){/*{{{*/
-			return -1;
-		}
-		/*}}}*/
-		void Marshall(char** pmarshalled_data,int* pmarshalled_data_size, int marshall_direction){/*{{{*/
-			_error_("not implemented yet!"); 
-		} 
-		/*}}}*/
-		int ObjectEnum(void){/*{{{*/
-			return MisfitEnum;
-		}
-		/*}}}*/
+		Object* copy();
+		void DeepEcho(void);
+		void Echo(void);
+		int Id(void);
+		void Marshall(char** pmarshalled_data,int* pmarshalled_data_size, int marshall_direction);
+		int ObjectEnum(void);
+		
 		/*Definition virtual function resolutoin: */
-		int DefinitionEnum(){/*{{{*/
-			return this->definitionenum;
-		}
-		/*}}}*/
-		char* Name(){/*{{{*/
-			char* name2=xNew<char>(strlen(this->name)+1);
-			xMemCpy(name2,this->name,strlen(this->name)+1);
-
-			return name2;
-		}
-		/*}}}*/
-		 IssmDouble Response(FemModel* femmodel){/*{{{*/
-				 
-			 /*diverse: */
-			 IssmDouble time,starttime,finaltime;
-			 IssmDouble dt;
-			 
-			 /*recover time parameters: */
-			 femmodel->parameters->FindParam(&starttime,TimesteppingStartTimeEnum);
-			 femmodel->parameters->FindParam(&finaltime,TimesteppingFinalTimeEnum);
-			 femmodel->parameters->FindParam(&time,TimeEnum);
-			 femmodel->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
-
-			 if (this->local){ /*local computation: {{{*/
-
-				 int i;
-				 IssmDouble misfit_t=0.;
-				 IssmDouble all_misfit_t=0.;
-				 IssmDouble area_t=0.;
-				 IssmDouble all_area_t;
-
-			
-				 /*If we are locked, return time average: */
-				 if(this->lock)return misfit/(time-starttime);
-
-				 for(i=0;i<femmodel->elements->Size();i++){
-					 Element* element=(Element*)femmodel->elements->GetObjectByOffset(i);
-					 misfit_t+=element->Misfit(model_enum,observation_enum,weights_enum);
-					 area_t+=element->MisfitArea(weights_enum);
-				 }
-
-				 ISSM_MPI_Allreduce ( (void*)&misfit_t,(void*)&all_misfit_t,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
-				 ISSM_MPI_Allreduce ( (void*)&area_t,(void*)&all_area_t,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
-				 area_t=all_area_t;
-				 misfit_t=all_misfit_t;
-				 
-				 /*Divide by surface area if not nill!: */
-				 if (area_t!=0) misfit_t=misfit_t/area_t;
-
-				 /*Add this time's contribution to curent misfit: */
-				 misfit+=dt*misfit_t;
-
-				 /*Do we lock? i.e. are we at final_time? :*/
-				 if(time==finaltime)this->lock=1;
-
-				 /*What we return is the value of misfit / time: */
-				 return misfit/(time-starttime);
-			 } /*}}}*/
-			 else{ /*global computation: {{{ */
-				 
-				 IssmDouble model, observation;
-				 
-				 /*If we are locked, return time average: */
-				 if(this->lock)return misfit/(time-starttime);
-
-				 /*First, the global  model response: */
-				 model=OutputDefinitionsResponsex(femmodel,this->model_enum);
-				 /*Now, the observation is buried inside the elements, go fish it in the first element (cludgy, needs fixing): */
-				 Element* element=(Element*)femmodel->elements->GetObjectByOffset(0); _assert_(element);
-				 Input* input = element->GetInput(observation_enum); _assert_(input);
-				 input->GetInputAverage(&observation);
-				 
-				 /*Add this time's contribution to curent misfit: */
-				 misfit+=dt*(model-observation);
-				 
-				 /*Do we lock? i.e. are we at final_time? :*/
-				 if(time==finaltime)this->lock=1;
-				 
-				 /*What we return is the value of misfit / time: */
-				 return misfit/(time-starttime);
-			 } /*}}}*/
-
-		 }
-			/*}}}*/
+		int DefinitionEnum();
+		char* Name();
+		IssmDouble Response(FemModel* femmodel);
 };
-
 #endif  /* _MISFIT_H_ */
Index: /issm/trunk/src/c/classes/Nodalvalue.cpp
===================================================================
--- /issm/trunk/src/c/classes/Nodalvalue.cpp	(revision 22758)
+++ /issm/trunk/src/c/classes/Nodalvalue.cpp	(revision 22758)
@@ -0,0 +1,103 @@
+/*!\file Nodalvalue.h
+ * \brief: header file for Nodalvalue object
+ */
+#ifdef HAVE_CONFIG_H
+   #include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*Headers:*/
+/*{{{*/
+#include "./Elements/Element.h"
+#include "./Elements/Elements.h"
+#include "./FemModel.h"
+#include "../modules/SurfaceAreax/SurfaceAreax.h"
+#include "../classes/Params/Parameters.h"
+#include "../classes/Inputs/Input.h"
+#include "../classes/gauss/Gauss.h"
+#include "./classes.h"
+/*}}}*/
+
+		/*Nodalvalue constructors, destructors :*/
+Nodalvalue::Nodalvalue(){/*{{{*/
+
+	this->definitionenum = -1;
+	this->name = NULL;
+	this->model_enum = UNDEF;
+	this->node = -1;
+
+}
+/*}}}*/
+Nodalvalue::Nodalvalue(char* in_name, int in_definitionenum, int in_model_enum, int in_node){/*{{{*/
+
+	this->definitionenum=in_definitionenum;
+	this->name   = xNew<char>(strlen(in_name)+1);
+	xMemCpy<char>(this->name,in_name,strlen(in_name)+1);
+
+	this->model_enum=in_model_enum;
+	this->node=in_node;
+}
+/*}}}*/
+Nodalvalue::~Nodalvalue(){/*{{{*/
+	if(this->name)xDelete(this->name);
+}
+/*}}}*/
+/*Object virtual function resolutoin: */
+Object* Nodalvalue::copy() {/*{{{*/
+	Nodalvalue* mf = new Nodalvalue(this->name,this->definitionenum, this->model_enum,this->node);
+	return (Object*) mf;
+}
+/*}}}*/
+void Nodalvalue::DeepEcho(void){/*{{{*/
+	this->Echo();
+}
+/*}}}*/
+void Nodalvalue::Echo(void){/*{{{*/
+	_printf_(" Nodalvalue: " << name << " " << this->definitionenum << "\n");
+	_printf_("    model_enum: " << model_enum << " " << EnumToStringx(model_enum) << "\n");
+	_printf_("    node: " << node << "\n");
+}
+/*}}}*/
+int Nodalvalue::Id(void){/*{{{*/
+	return -1;
+}
+/*}}}*/
+void Nodalvalue::Marshall(char** pmarshalled_data,int* pmarshalled_data_size, int marshall_direction){/*{{{*/
+	_error_("not implemented yet!"); 
+} 
+/*}}}*/
+int Nodalvalue::ObjectEnum(void){/*{{{*/
+	return NodalvalueEnum;
+}
+/*}}}*/
+/*Definition virtual function resolutoin: */
+int Nodalvalue::DefinitionEnum(){/*{{{*/
+
+	return this->definitionenum;
+}
+/*}}}*/
+char* Nodalvalue::Name(){/*{{{*/
+
+	char* name2=xNew<char>(strlen(this->name)+1);
+	xMemCpy(name2,this->name,strlen(this->name)+1);
+
+	return name2;
+}
+/*}}}*/
+IssmDouble Nodalvalue::Response(FemModel* femmodel){/*{{{*/
+	
+	 /*output:*/
+	 IssmDouble value;
+
+	 /*set index, which will be used by the NodalValue module: */
+	 femmodel->parameters->SetParam(node,IndexEnum);
+
+	 /*call Nodalvalue:*/
+	 NodalValuex(&value, model_enum, femmodel->elements, femmodel->nodes, femmodel->vertices, femmodel->loads, 
+			 femmodel->materials, femmodel->parameters);
+
+	 /*done:*/
+	 return value;
+ }
+ /*}}}*/
Index: /issm/trunk/src/c/classes/Nodalvalue.h
===================================================================
--- /issm/trunk/src/c/classes/Nodalvalue.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Nodalvalue.h	(revision 22758)
@@ -9,12 +9,5 @@
 /*{{{*/
 #include "./Definition.h"
-#include "../datastructures/datastructures.h"
-#include "./Elements/Element.h"
-#include "./Elements/Elements.h"
 #include "./FemModel.h"
-#include "../modules/SurfaceAreax/SurfaceAreax.h"
-#include "../classes/Params/Parameters.h"
-#include "../classes/Inputs/Input.h"
-#include "../classes/gauss/Gauss.h"
 /*}}}*/
 
@@ -32,85 +25,20 @@
 		
 		/*Nodalvalue constructors, destructors :*/
-		Nodalvalue(){/*{{{*/
+Nodalvalue();
+Nodalvalue(char* in_name, int in_definitionenum, int in_model_enum, int in_node);
+~Nodalvalue();
 
-			this->definitionenum = -1;
-			this->name = NULL;
-			this->model_enum = UNDEF;
-			this->node = -1;
+/*Object virtual function resolutoin: */
+Object* copy();
+void DeepEcho(void);
+void Echo(void);
+int Id(void);
+void Marshall(char** pmarshalled_data,int* pmarshalled_data_size, int marshall_direction);
+int ObjectEnum(void);
 
-		}
-		/*}}}*/
-		Nodalvalue(char* in_name, int in_definitionenum, int in_model_enum, int in_node){/*{{{*/
-
-			this->definitionenum=in_definitionenum;
-			this->name   = xNew<char>(strlen(in_name)+1);
-			xMemCpy<char>(this->name,in_name,strlen(in_name)+1);
-
-			this->model_enum=in_model_enum;
-			this->node=in_node;
-		}
-		/*}}}*/
-		~Nodalvalue(){/*{{{*/
-			if(this->name)xDelete(this->name);
-		}
-		/*}}}*/
-		/*Object virtual function resolutoin: */
-		Object* copy() {/*{{{*/
-			Nodalvalue* mf = new Nodalvalue(this->name,this->definitionenum, this->model_enum,this->node);
-			return (Object*) mf;
-		}
-		/*}}}*/
-		void DeepEcho(void){/*{{{*/
-			this->Echo();
-		}
-		/*}}}*/
-		void Echo(void){/*{{{*/
-			_printf_(" Nodalvalue: " << name << " " << this->definitionenum << "\n");
-			_printf_("    model_enum: " << model_enum << " " << EnumToStringx(model_enum) << "\n");
-			_printf_("    node: " << node << "\n");
-		}
-		/*}}}*/
-		int Id(void){/*{{{*/
-			return -1;
-		}
-		/*}}}*/
-		void Marshall(char** pmarshalled_data,int* pmarshalled_data_size, int marshall_direction){/*{{{*/
-			_error_("not implemented yet!"); 
-		} 
-		/*}}}*/
-		int ObjectEnum(void){/*{{{*/
-			return NodalvalueEnum;
-		}
-		/*}}}*/
-		/*Definition virtual function resolutoin: */
-		int DefinitionEnum(){/*{{{*/
-
-			return this->definitionenum;
-		}
-		/*}}}*/
-		char* Name(){/*{{{*/
-
-			char* name2=xNew<char>(strlen(this->name)+1);
-			xMemCpy(name2,this->name,strlen(this->name)+1);
-
-			return name2;
-		}
-		/*}}}*/
-		 IssmDouble Response(FemModel* femmodel){/*{{{*/
-			
-			 /*output:*/
-			 IssmDouble value;
-
-			 /*set index, which will be used by the NodalValue module: */
-			 femmodel->parameters->SetParam(node,IndexEnum);
-
-			 /*call Nodalvalue:*/
-			 NodalValuex(&value, model_enum, femmodel->elements, femmodel->nodes, femmodel->vertices, femmodel->loads, 
-					 femmodel->materials, femmodel->parameters);
-
-			 /*done:*/
-			 return value;
-		 }
-		 /*}}}*/
+/*Definition virtual function resolutoin: */
+int DefinitionEnum();
+char* Name();
+IssmDouble Response(FemModel* femmodel);
 };
 
Index: /issm/trunk/src/c/classes/Numberedcostfunction.cpp
===================================================================
--- /issm/trunk/src/c/classes/Numberedcostfunction.cpp	(revision 22758)
+++ /issm/trunk/src/c/classes/Numberedcostfunction.cpp	(revision 22758)
@@ -0,0 +1,159 @@
+/*!\file Numberedcostfunction.cpp
+ * \brief: implementation for the Numberedcostfunction object
+ */
+/*Include files: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+
+/*Headers:*/
+//#include "./Definition.h"
+//#include "../datastructures/datastructures.h"
+#include "./classes.h"
+#include "./Elements/Element.h"
+#include "./Elements/Elements.h"
+#include "./FemModel.h"
+#include "./ExternalResults/ExternalResult.h"
+#include "./ExternalResults/Results.h"
+#include "../modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h"
+#include "../modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h"
+#include "../modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.h"
+#include "../modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.h"
+#include "../modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h"
+#include "../modules/ThicknessAlongGradientx/ThicknessAlongGradientx.h"
+#include "../modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.h"
+#include "../modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h"
+#include "../modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h"
+
+/*}}}*/
+		
+/*Numberedcostfunction constructors, destructors :*/
+Numberedcostfunction::Numberedcostfunction(){/*{{{*/
+
+	this->definitionenum = -1;
+	this->name = NULL;
+	this->number_cost_functions = -1;
+	this->cost_functions_list = NULL;
+
+}
+/*}}}*/
+Numberedcostfunction::Numberedcostfunction(char* in_name, int in_definitionenum,int number_cost_functions_in,int* cost_functions_list_in){/*{{{*/
+	_assert_(number_cost_functions_in>0); 
+	_assert_(cost_functions_list_in); 
+
+	this->definitionenum=in_definitionenum;
+	this->name   = xNew<char>(strlen(in_name)+1);
+	xMemCpy<char>(this->name,in_name,strlen(in_name)+1);
+
+	this->number_cost_functions = number_cost_functions_in;
+	this->cost_functions_list = xNew<int>(number_cost_functions_in);
+
+	for(int i=0;i<number_cost_functions_in;i++){
+		this->cost_functions_list[i] = cost_functions_list_in[i];
+	}
+}
+/*}}}*/
+Numberedcostfunction::~Numberedcostfunction(){/*{{{*/
+	xDelete<int>(this->cost_functions_list);
+	if(this->name)xDelete(this->name);
+}
+/*}}}*/
+
+/*Object virtual function resolutoin: */
+Object* Numberedcostfunction::copy() {/*{{{*/
+	Numberedcostfunction* out = new Numberedcostfunction(this->name,this->definitionenum,this->number_cost_functions,this->cost_functions_list);
+	return (Object*)out;
+}
+/*}}}*/
+void Numberedcostfunction::DeepEcho(void){/*{{{*/
+	this->Echo();
+}
+/*}}}*/
+void Numberedcostfunction::Echo(void){/*{{{*/
+	_printf_(" Numberedcostfunction: " << this->name << " " << this->definitionenum << "\n");
+	_printf_("    number_cost_functions: "<<this->number_cost_functions<<"\n");
+	_printf_("    ");
+	for(int i=0;i<this->number_cost_functions;i++){
+		_printf_(this->cost_functions_list[i]<< "  ");
+	}
+	_printf_("\n");
+}
+/*}}}*/
+int Numberedcostfunction::Id(void){/*{{{*/
+	return -1;
+}
+/*}}}*/
+void Numberedcostfunction::Marshall(char** pmarshalled_data,int* pmarshalled_data_size, int marshall_direction){/*{{{*/
+	_error_("not implemented yet!"); 
+} 
+/*}}}*/
+int Numberedcostfunction::ObjectEnum(void){/*{{{*/
+	return NumberedcostfunctionEnum;
+}
+/*}}}*/
+
+/*Definition virtual function resolutoin: */
+int Numberedcostfunction::DefinitionEnum(){/*{{{*/
+	return this->definitionenum;
+}
+/*}}}*/
+char* Numberedcostfunction::Name(){/*{{{*/
+
+	char* name2=xNew<char>(strlen(this->name)+1);
+	xMemCpy(name2,this->name,strlen(this->name)+1);
+
+	return name2;
+}
+/*}}}*/
+IssmDouble Numberedcostfunction::Response(FemModel* femmodel){/*{{{*/
+	
+	 _assert_(number_cost_functions>0 && number_cost_functions<1e3); 
+
+	 /*output:*/
+	 IssmDouble value;
+	 IssmDouble value_sum = 0.;
+
+		/*Scalar control output*/
+	 for(int i=0;i<this->number_cost_functions;i++){
+		 switch(this->cost_functions_list[i]){
+			 case SurfaceAbsVelMisfitEnum:
+				 SurfaceAbsVelMisfitx(&value,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);        
+				 break;
+			 case SurfaceRelVelMisfitEnum:            
+				 SurfaceRelVelMisfitx(&value, femmodel->elements,femmodel->nodes,femmodel-> vertices,femmodel-> loads,femmodel-> materials,femmodel->parameters); 
+				 break;
+			 case SurfaceLogVelMisfitEnum:            
+				 SurfaceLogVelMisfitx(&value,femmodel-> elements,femmodel->nodes,femmodel-> vertices,femmodel-> loads,femmodel-> materials,femmodel->parameters); 
+				 break;
+			 case SurfaceLogVxVyMisfitEnum:           
+				 SurfaceLogVxVyMisfitx(&value,femmodel-> elements,femmodel->nodes,femmodel-> vertices,femmodel-> loads,femmodel-> materials,femmodel->parameters); 
+				 break;
+			 case ThicknessAbsMisfitEnum:             
+				 ThicknessAbsMisfitx(&value,femmodel-> elements,femmodel->nodes,femmodel-> vertices,femmodel-> loads,femmodel-> materials,femmodel-> parameters); 
+				 break;
+			 case ThicknessAlongGradientEnum:         
+				 ThicknessAlongGradientx(&value,femmodel-> elements,femmodel->nodes,femmodel-> vertices,femmodel-> loads,femmodel-> materials,femmodel-> parameters); 
+				 break;
+			 case ThicknessAcrossGradientEnum:        
+				 ThicknessAcrossGradientx(&value,femmodel-> elements,femmodel->nodes,femmodel-> vertices,femmodel-> loads,femmodel-> materials,femmodel-> parameters); 
+				 break;
+			 case RheologyBbarAbsGradientEnum:        
+				 RheologyBbarAbsGradientx(&value,femmodel-> elements,femmodel->nodes,femmodel-> vertices,femmodel-> loads,femmodel-> materials,femmodel-> parameters); 
+				 break;
+			 case DragCoefficientAbsGradientEnum:     
+				 DragCoefficientAbsGradientx(&value,femmodel-> elements,femmodel->nodes,femmodel-> vertices,femmodel-> loads,femmodel-> materials,femmodel-> parameters); 
+				 break;
+			 default:
+				 _error_("not supported");
+		 }
+		 value_sum += value;
+ }
+
+	 /*done:*/
+	return value_sum;
+ }
+ /*}}}*/
+
Index: /issm/trunk/src/c/classes/Numberedcostfunction.h
===================================================================
--- /issm/trunk/src/c/classes/Numberedcostfunction.h	(revision 22758)
+++ /issm/trunk/src/c/classes/Numberedcostfunction.h	(revision 22758)
@@ -0,0 +1,43 @@
+/*!\file Numberedcostfunction.h
+ * \brief: header file for Numberedcostfunction object
+ */
+
+#ifndef _NUMBEREDCOSTFUNCTION_H_
+#define _NUMBEREDCOSTFUNCTION_H_
+
+/*Headers:*/
+#include "./Definition.h"
+#include "./FemModel.h"
+
+
+IssmDouble OutputDefinitionsResponsex(FemModel* femmodel,int output_enum);
+
+class Numberedcostfunction: public Object, public Definition{
+
+public: 
+
+int   definitionenum;
+char* name;
+int   number_cost_functions;
+int*  cost_functions_list;
+
+/*Numberedcostfunction constructors, destructors :*/
+Numberedcostfunction();
+Numberedcostfunction(char* in_name, int in_definitionenum,int number_cost_functions_in,int* cost_functions_list_in);
+~Numberedcostfunction();
+
+/*Object virtual function resolutoin: */
+Object*	copy();
+void		DeepEcho(void);
+void		Echo(void);
+int		Id(void);
+void		Marshall(char** pmarshalled_data,int* pmarshalled_data_size, int marshall_direction);
+int		ObjectEnum(void);
+
+/*Definition virtual function resolutoin: */
+int		DefinitionEnum();
+char*		Name();
+IssmDouble Response(FemModel* femmodel);
+};
+
+#endif  /* _NUMBEREDCOSTFUNCTION_H_ */
Index: /issm/trunk/src/c/classes/Options/GenericOption.h
===================================================================
--- /issm/trunk/src/c/classes/Options/GenericOption.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Options/GenericOption.h	(revision 22758)
@@ -102,5 +102,6 @@
 };
 
-#if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)  //We hook off this specific specialization when not running ADOLC, otherwise we get a redeclaration with the next specialization. 
+#if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_) 
+/*We hook off this specific specialization when not running ADOLC, otherwise we get a redeclaration with the next specialization*/
 template <> inline void GenericOption<IssmPDouble*>::Get(IssmPDouble** pvalue){ /*{{{*/
 
Index: /issm/trunk/src/c/classes/Options/OptionUtilities.cpp
===================================================================
--- /issm/trunk/src/c/classes/Options/OptionUtilities.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Options/OptionUtilities.cpp	(revision 22758)
@@ -15,84 +15,4 @@
 /*}}}*/
 
-int ColumnWiseDimsFromIndex(int* dims,int index,int* size,int ndims){/*{{{*/
-
-	int   i;
-	int   aprod=1;
-
-	/*check for index too large  */
-	for (i=0;i<ndims;i++) aprod*=size[i];
-	if (index >= aprod) _error_("Index " << index << " exceeds number of elements " << aprod << ".");
-
-	/*calculate the dimensions (being careful of integer division)  */
-	for (i=ndims-1; i>=0; i--) {
-		aprod=reCast<int>(((IssmPDouble)aprod+0.5)/(IssmPDouble)size[i]);
-		dims[i]=(int)floor(((IssmPDouble)index+0.5)/(IssmPDouble)aprod);
-		index-=dims[i]*aprod;
-	}
-
-	return(0);
-}/*}}}*/
-int IndexFromColumnWiseDims(int* dims, int* size, int ndims) {/*{{{*/
-
-	int   i;
-	int   index=0;
-
-	/*check for any dimension too large  */
-	for (i=0;i<ndims;i++){
-		if (dims[i] >= size[i]) _error_("Dimension " << i << " of " << dims[i] << " exceeds size of " << size[i] << ".");
-	}
-
-	/*calculate the index  */
-	for (i=ndims-1; i>=0; i--){
-		index*=size[i];
-		index+=dims[i];
-	}
-
-	return(index);
-}/*}}}*/
-int IndexFromRowWiseDims(int* dims, int* size, int ndims) {/*{{{*/
-
-	int   i;
-	int   index=0;
-
-	/*check for any dimension too large  */
-	for (i=0; i<ndims; i++){
-		if (dims[i] >= size[i]) _error_("Dimension " << i << " of " << dims[i] << " exceeds size of " << size[i] << ".");
-	}
-
-	/*calculate the index  */
-	for (i=0; i<ndims; i++) {
-		index*=size[i];
-		index+=dims[i];
-	}
-
-	return(index);
-}/*}}}*/
-int RowWiseDimsFromIndex(int* dims, int index, int* size, int ndims) {/*{{{*/
-
-	int   i;
-	int   aprod=1;
-
-	/*check for index too large  */
-	for (i=0; i<ndims; i++) aprod*=size[i];
-	if (index >= aprod) _error_("Index " << index << " exceeds number of elements " << aprod << ".");
-
-	/*calculate the dimensions (being careful of integer division)  */
-	for (i=0; i<ndims; i++) {
-		aprod=(int)(((IssmPDouble)aprod+0.5)/(IssmPDouble)size[i]);
-		dims[i]=(int)floor(((IssmPDouble)index+0.5)/(IssmPDouble)aprod);
-		index-=dims[i]*aprod;
-	}
-
-	return(0);
-}/*}}}*/
-int StringFromDims(char* cstr, int* dims, int ndims) {/*{{{*/
-
-	sprintf(&cstr[0],"[");
-	for(int i=0; i<ndims-1; i++) sprintf(&cstr[strlen(cstr)],"%d,",dims[i]);
-	sprintf(&cstr[strlen(cstr)],"%d]",dims[ndims-1]);
-
-	return(0);
-}/*}}}*/
 int StringFromSize(char* cstr, int* size, int ndims) {/*{{{*/
 
Index: /issm/trunk/src/c/classes/Options/OptionUtilities.h
===================================================================
--- /issm/trunk/src/c/classes/Options/OptionUtilities.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Options/OptionUtilities.h	(revision 22758)
@@ -13,9 +13,4 @@
 /*}}}*/
 
-int ColumnWiseDimsFromIndex(int* dims, int index, int* size, int ndims);
-int IndexFromColumnWiseDims(int* dims, int* size, int ndims);
-int IndexFromRowWiseDims(int* dims, int* size, int ndims);
-int RowWiseDimsFromIndex(int* dims, int index, int* size, int ndims);
-int StringFromDims(char* cstr, int* dims, int ndims);
 int StringFromSize(char* cstr, int* size, int ndims);
 
Index: /issm/trunk/src/c/classes/Options/Options.cpp
===================================================================
--- /issm/trunk/src/c/classes/Options/Options.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Options/Options.cpp	(revision 22758)
@@ -79,5 +79,5 @@
 			_printf_("The dynamic_cast from Object* to Option* is failing.\n");
 			_printf_("\n");
-			_printf_("A quick qorkaround consists of using a C-like cast\n");
+			_printf_("A quick workaround consists of using a C-like cast\n");
 			_printf_("\n");
 			_printf_("Open Options.cpp and change the dynamic_cast in Options::GetOption by a C-like cast\n");
@@ -94,21 +94,5 @@
 			}
 			else{
-				/*If the object is a Cell, recursive call to its options*/ 
-				if(option->ObjectEnum()==OptionCellEnum){
-					GenericOption<Options*>* celloption=(GenericOption<Options*>*)option;
-					return celloption->value->GetOption(name);
-				}
-				/*If the object is a Struct loop over its size and recursive call*/
-				else if(option->ObjectEnum()==OptionStructEnum){
-					for(int i=0;i<option->NumEl();i++){
-						GenericOption<Options**>* structoption=(GenericOption<Options**>*)option;
-						_assert_(structoption->value[i]);
-						return structoption->value[i]->GetOption(name);
-					}
-				}
-				/*Else: not supported*/
-				else{
-					_error_("Cannot recover field \"" << name << "\" for an option of type " << EnumToStringx(option->ObjectEnum()));
-				}
+				_error_("Cannot recover field \"" << name << "\" for an option of type " << EnumToStringx(option->ObjectEnum()));
 			}
 		}
Index: /issm/trunk/src/c/classes/Options/Options.h
===================================================================
--- /issm/trunk/src/c/classes/Options/Options.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Options/Options.h	(revision 22758)
@@ -7,8 +7,4 @@
 #include "./GenericOption.h"
 
-/*!\brief Declaration of Options class. 
- * 
- * Declaration of Options class.  Options are vector lists (Containers) of Option objects.
- */ 
 class Options: public DataSet{
 
@@ -20,5 +16,5 @@
 
 		/*numerics*/
-		int  AddOption(Option* in_oobject);
+		int     AddOption(Option* in_oobject);
 		Option* GetOption(const char* name);
 
@@ -31,20 +27,4 @@
 			if(genericoption){
 				genericoption->Get(pvalue);
-			}
-			/*Else, the Option does not exist, no default provided*/
-			else{
-				_error_("option of name \"" << name << "\" not found, and no default value has been provided");
-			}
-		}
-		/*}}}*/
-		template <class OptionType> void Get(OptionType* pvalue,int* pnumel, const char* name){ /*{{{*/
-
-			/*Get option*/
-			GenericOption<OptionType>* genericoption=xDynamicCast<GenericOption<OptionType>*>(GetOption(name));
-
-			/*If the pointer is not NULL, the option has been found*/
-			if(genericoption){
-				genericoption->Get(pvalue);
-				*pnumel=genericoption->NumEl();
 			}
 			/*Else, the Option does not exist, no default provided*/
@@ -65,19 +45,4 @@
 			else{
 				if(GetOption(name)) _printf_("WARNING: option "<<name<<" found but fetched format not consistent, defaulting...\n");
-				*pvalue=default_value;
-			}
-		}
-		/*}}}*/
-		template <class OptionType> void Get(OptionType* pvalue,int* pnumel, const char* name,OptionType default_value){ /*{{{*/
-
-			/*Get option*/
-			GenericOption<OptionType>* genericoption=xDynamicCast<GenericOption<OptionType>*>(GetOption(name));
-
-			/*If the pointer is not NULL, the option has been found*/
-			if(genericoption){
-				genericoption->Get(pvalue);
-				*pnumel=genericoption->NumEl();
-			}
-			else{
 				*pvalue=default_value;
 			}
Index: /issm/trunk/src/c/classes/Params/DataSetParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/DataSetParam.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Params/DataSetParam.cpp	(revision 22758)
@@ -24,5 +24,5 @@
 
 	enum_type=in_enum_type;
-	value=in_value->Copy();;
+	value=in_value->Copy();
 }
 /*}}}*/
@@ -74,2 +74,6 @@
 }
 /*}}}*/
+void DataSetParam::SetValue(DataSet* dataset){/*{{{*/
+	this->value=dataset;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Params/DataSetParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/DataSetParam.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Params/DataSetParam.h	(revision 22758)
@@ -70,5 +70,5 @@
 		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
 		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
-		void  SetValue(DataSet* dataset){_error_("DataSet param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a DataSet yet");}
+		void  SetValue(DataSet* dataset);
 		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("DataSet param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold an array of matrices");}
 		/*}}}*/
Index: /issm/trunk/src/c/classes/Params/DoubleParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/DoubleParam.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Params/DoubleParam.h	(revision 22758)
@@ -44,7 +44,7 @@
 		void  GetParameterValue(int** pintarray,int* pM);
 		void  GetParameterValue(int** pintarray,int* pM,int* pN);
-		void  GetParameterValue(IssmDouble* pIssmDouble){*pIssmDouble=value;}
+		void  GetParameterValue(IssmDouble* pIssmDouble){*pIssmDouble=value;};
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){*pdouble=value;};
 		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
-		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
 		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
 		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM);
Index: /issm/trunk/src/c/classes/Params/DoubleVecParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/DoubleVecParam.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Params/DoubleVecParam.cpp	(revision 22758)
@@ -77,31 +77,23 @@
 
 /*DoubleVecParam virtual functions definitions: */
-void  DoubleVecParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){/*{{{*/
-	IssmDouble* output=NULL;
-	int M;
+void  DoubleVecParam::GetParameterValue(IssmDouble** poutput,int* pM){/*{{{*/
 
-	M=this->M;
-	output=xNew<IssmDouble>(M);
+	IssmDouble* output=xNew<IssmDouble>(M);
 	xMemCpy<IssmDouble>(output,values,M);
 
 	/*Assign output pointers:*/
 	if(pM) *pM=M;
-	*pIssmDoublearray=output;
+	*poutput=output;
 }
 /*}}}*/
-void  DoubleVecParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){/*{{{*/
-	IssmDouble* output=NULL;
-	int M;
-	int N;
+void  DoubleVecParam::GetParameterValue(IssmDouble** poutput,int* pM,int* pN){/*{{{*/
 
-	N=1;
-	M=this->M;
-	output=xNew<IssmDouble>(M);
+	IssmDouble* output=xNew<IssmDouble>(this->M);
 	xMemCpy<IssmDouble>(output,values,M);
 
 	/*Assign output pointers:*/
-	if(pM) *pM=M;
-	if(pN) *pN=N;
-	*pIssmDoublearray=output;
+	if(pM) *pM=this->M;
+	if(pN) *pN=1;
+	*poutput=output;
 }
 /*}}}*/
Index: /issm/trunk/src/c/classes/Params/IntParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/IntParam.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Params/IntParam.h	(revision 22758)
@@ -39,5 +39,5 @@
 		int   ObjectEnum();
 		/*}}}*/
-		/*Param vritual function definitions: {{{*/
+		/*Param virtual function definitions: {{{*/
 		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
 		void  GetParameterValue(int* pinteger){*pinteger=value;}
Index: /issm/trunk/src/c/classes/Params/IntVecParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/IntVecParam.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Params/IntVecParam.cpp	(revision 22758)
@@ -58,21 +58,12 @@
 /*}}}*/
 void IntVecParam::DeepEcho(void){/*{{{*/
-
-	int i;
-
-	_printf_("IntVecParam:\n");
-	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
-	_printf_("   vector size: " << this->M << "\n");
-	for(i=0;i<this->M;i++){
-		_printf_(i << " " << this->values[i] << "\n");
-	}
+	_printf_(setw(22)<<"   IntVecParam "<<setw(35)<<left<<EnumToStringx(this->enum_type)<<" [");
+	for(int i=0;i<this->M;i++) _printf_(" "<<this->values[i]);
+	_printf_("]\n");
 }
 /*}}}*/
 void IntVecParam::Echo(void){/*{{{*/
 
-	_printf_("IntVecParam:\n");
-	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
-	_printf_("   vector size: " << this->M << "\n");
-
+	this->DeepEcho();
 }
 /*}}}*/
Index: /issm/trunk/src/c/classes/Params/Param.h
===================================================================
--- /issm/trunk/src/c/classes/Params/Param.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Params/Param.h	(revision 22758)
@@ -19,5 +19,5 @@
 /*}}}*/
 
-class Param{
+class Param: public Object{
 
 	public: 
@@ -34,4 +34,5 @@
 		virtual void  GetParameterValue(IssmDouble* pIssmDouble)=0;
 		virtual void  GetParameterValue(IssmDouble* pdouble,IssmDouble time)=0;
+		virtual void  GetParameterValue(IssmDouble* pdouble,int row, IssmDouble time){_error_("not implemented yet");};
 		virtual void  GetParameterValue(char** pstring)=0;
 		virtual void  GetParameterValue(char*** pstringarray,int* pM)=0;
@@ -53,4 +54,5 @@
 		virtual void  SetValue(char* string)=0;
 		virtual void  SetValue(char** stringarray,int M)=0;
+		virtual void  SetValue(DataSet* dataset){_error_("not implemented yet");};
 		virtual void  SetValue(IssmDouble* IssmDoublearray,int M)=0;
 		virtual void  SetValue(IssmDouble* pIssmDoublearray,int M,int N)=0;
Index: /issm/trunk/src/c/classes/Params/Parameters.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/Parameters.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Params/Parameters.cpp	(revision 22758)
@@ -34,4 +34,5 @@
 #include "./DoubleMatArrayParam.h"
 #include "./TransientParam.h"
+#include "./TransientArrayParam.h"
 
 #include "../../shared/shared.h"
@@ -63,6 +64,6 @@
 	/*Get index in array*/
 	#ifdef _ISSM_DEBUG_
-	if(param_enum<=ParametersSTARTEnum) _error_("Enum "<<EnumToStringx(param_enum)<<" should appear after ParametersSTARTEnum");
-	if(param_enum>=ParametersENDEnum)   _error_("Enum "<<EnumToStringx(param_enum)<<" should appear before ParametersENDEnum");
+	if(param_enum<=ParametersSTARTEnum) _error_("Cannot add param: Enum "<<EnumToStringx(param_enum)<<" should appear after ParametersSTARTEnum");
+	if(param_enum>=ParametersENDEnum)   _error_("Cannot add param: Enum "<<EnumToStringx(param_enum)<<" should appear before ParametersENDEnum");
 	#endif
 	int index = param_enum - ParametersSTARTEnum -1;
@@ -220,4 +221,10 @@
 				this->AddObject(transparam);
 			}
+			else if(obj_enum==TransientArrayParamEnum){
+				TransientArrayParam* transarrayparam=NULL;
+				transarrayparam=new TransientArrayParam();
+				transarrayparam->Marshall(pmarshalled_data,pmarshalled_data_size,marshall_direction);
+				this->AddObject(transarrayparam);
+			}
 			else if(obj_enum==GenericParamEnum){
 				/*Skip for now (we don't want to Marhsall Comms*/
@@ -275,5 +282,4 @@
 /*}}}*/
 void Parameters::FindParam(IssmDouble* pscalar,int param_enum){ _assert_(this);/*{{{*/
-
 	_assert_(param_enum>ParametersSTARTEnum);
 	_assert_(param_enum<ParametersENDEnum);
@@ -294,4 +300,14 @@
 }
 /*}}}*/
+void Parameters::FindParam(IssmDouble* pscalar,int row,IssmDouble time, int param_enum){ _assert_(this);/*{{{*/
+
+	_assert_(param_enum>ParametersSTARTEnum);
+	_assert_(param_enum<ParametersENDEnum);
+
+	int index = param_enum - ParametersSTARTEnum -1;
+	if(!this->params[index]) _error_("Parameter " << EnumToStringx(param_enum) <<" not set");
+	this->params[index]->GetParameterValue(pscalar,row,time);
+}
+/*}}}*/
 void Parameters::FindParam(char** pstring,int param_enum){ _assert_(this);/*{{{*/
 
@@ -343,6 +359,8 @@
 
 	int index = param_enum - ParametersSTARTEnum -1;
+
 	if(!this->params[index]) _error_("Parameter " << EnumToStringx(param_enum) <<" not set");
 	this->params[index]->GetParameterValue(pIssmDoublearray,pM);
+
 }
 /*}}}*/
@@ -408,4 +426,27 @@
 }
 /*}}}*/
+void Parameters::FindParamInDataset(IssmDouble** pIssmDoublearray,int* pM,int* pN,int dataset_type,int enum_type){/*{{{*/
+	_assert_(this);
+
+	_assert_(dataset_type>ParametersSTARTEnum);
+	_assert_(dataset_type<ParametersENDEnum);
+
+	int index = dataset_type - ParametersSTARTEnum -1;
+	if(!this->params[index]) _error_("Parameter " << EnumToStringx(dataset_type) <<" not set");
+	if(this->params[index]->ObjectEnum()!=DataSetParamEnum) _error_("Parameter " << EnumToStringx(dataset_type) <<" is not a DataSetParam!");
+
+	DataSetParam* dataset_param = xDynamicCast<DataSetParam*>(this->params[index]);
+	for( vector<Object*>::iterator object=dataset_param->value->objects.begin() ; object < dataset_param->value->objects.end(); object++ ){
+		Param* param = xDynamicCast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pIssmDoublearray,pM,pN);
+			return;
+		}
+	}
+
+	/*Error out if we reached this point*/
+	_error_("Could not find Enum "<<EnumToStringx(enum_type)<<" in dataset param "<<EnumToStringx(dataset_type));
+}
+/*}}}*/
 
 void   Parameters::SetParam(bool boolean,int enum_type){/*{{{*/
@@ -548,6 +589,10 @@
 	param=xDynamicCast<Param*>(this->FindParamObject(enum_type));
 
-	if(param) param->SetValue(dataset); //already exists, just set it.
-	else this->AddObject(new DataSetParam(enum_type,dataset)); //just add the new parameter.
+	if(param){
+		param->SetValue(dataset); //already exists, just set it.
+	}
+	else{
+		this->AddObject(new DataSetParam(enum_type,dataset)); //just add the new parameter.
+	}
 }
 /*}}}*/
@@ -556,6 +601,6 @@
 
 	#ifdef _ISSM_DEBUG_
-	if(param_enum<=ParametersSTARTEnum) _error_("Enum "<<EnumToStringx(param_enum)<<" should appear after ParametersSTARTEnum");
-	if(param_enum>=ParametersENDEnum)   _error_("Enum "<<EnumToStringx(param_enum)<<" should appear before ParametersENDEnum");
+	if(param_enum<=ParametersSTARTEnum) _error_("Cannot find param: Enum "<<EnumToStringx(param_enum)<<" should appear after ParametersSTARTEnum");
+	if(param_enum>=ParametersENDEnum)   _error_("Cannot find param: Enum "<<EnumToStringx(param_enum)<<" should appear before ParametersENDEnum");
 	#endif
 
@@ -566,24 +611,26 @@
 
 /*Methods relating to parameters: */
-char* OptionsFromAnalysis(Parameters* parameters,int analysis_type){ /*{{{*/
+char* OptionsFromAnalysis(char** pouttoolkit,Parameters* parameters,int analysis_type){ /*{{{*/
 
 	/* figure out ISSM options for current analysis, return a string. */ 
 
 	/*output: */
-	char*   outstring=NULL;
+	char *outstring  = NULL;
+	char *outtoolkit = NULL;
 
 	/*intermediary: */
 	int          dummy;
-	IssmDouble  *analyses    = NULL;
+	int         *analyses    = NULL;
 	char       **strings     = NULL;
 	char        *string      = NULL;
+	char       **toolkits    = NULL;
+	char        *toolkit     = NULL;
 	int          numanalyses;
 	int          found       = -1;
 	int          i;
 
-	numanalyses=0;
 	parameters->FindParam(&strings,&numanalyses,ToolkitsOptionsStringsEnum);
-
-	parameters->FindParam(&analyses,&dummy,ToolkitsOptionsAnalysesEnum);
+	parameters->FindParam(&toolkits,&dummy,ToolkitsTypesEnum); _assert_(dummy==numanalyses); 
+	parameters->FindParam(&analyses,&dummy,ToolkitsOptionsAnalysesEnum); _assert_(dummy==numanalyses); 
 
 	if(numanalyses==0)return NULL; //we did not find petsc options, don't bother.
@@ -605,19 +652,25 @@
 		}
 	}
-	if (found==-1){
+	if(found==-1){
 		_error_("could find neither a default analysis nor analysis " << EnumToStringx(analysis_type));
 	}
 
-	/*ok, grab the option string: */
+	/*1. Grab the option toolkit: */
+	outtoolkit=xNew<char>(strlen(toolkits[found])+1);
+	strcpy(outtoolkit,toolkits[found]);
+	*pouttoolkit = outtoolkit;
+
+	/*2. Grab the option string: */
 	outstring=xNew<char>(strlen(strings[found])+1);
 	strcpy(outstring,strings[found]);
 
 	/*Free ressources*/
-	xDelete<IssmDouble>(analyses);
 	for(i=0;i<numanalyses;i++){
-		string=strings[i];
-		xDelete<char>(string);
-	}
+		xDelete<char>(toolkits[i]);
+		xDelete<char>(strings[i]);
+	}
+	xDelete<char*>(toolkits);
 	xDelete<char*>(strings);
+	xDelete<int>(analyses);
 	return outstring;
 } 
@@ -632,38 +685,52 @@
 	 */ 
 
-	char* options=NULL;
+	char* options = NULL;
+	char* toolkit = NULL;
 
 	/*Recover first the options string for this analysis: */
-	options=OptionsFromAnalysis(parameters,analysis_type);
+	options=OptionsFromAnalysis(&toolkit,parameters,analysis_type);
 
 	/*Initialize our Toolkit Options: */
-	ToolkitOptions::Init(options);
+	ToolkitOptions::Init(toolkit,options);
 
 	#ifdef _HAVE_PETSC_
 		/*In case we are using PETSC, we do not rely on issmoptions. Instead, we dump issmoptions into the Petsc 
 		 * options database: */
-
-		#if _PETSC_MAJOR_ == 2 
-		PetscOptionsDestroy();
-		PetscOptionsCreate();
-		//PetscOptionsCheckInitial_Private();
-		//PetscOptionsCheckInitial_Components();
-		PetscOptionsSetFromOptions();
-		PetscOptionsInsertMultipleString(options); //our patch
-		#else
 		#if (_PETSC_MINOR_>=7)
 		PetscOptionsSetFromOptions(NULL);
 		PetscOptionsClear(NULL);
+		int ierr = PetscOptionsInsertString(NULL,options);
+		//int ierr = PetscOptionsInsertString(NULL,"-mat_type mpiaij -ksp_type preonly -pc_type lu -pc_factor_mat_solver_package mumps -mat_mumps_icntl_14 120 -mat_mumps_icntl_28 2 -mat_mumps_icntl_29 2");
+		//int ierr = PetscOptionsInsertString(NULL,"-mat_type mpiaij -ksp_type preonly -pc_type lu -pc_factor_mat_solver_package mumps -mat_mumps_icntl_14 120");
 		#else
 		PetscOptionsSetFromOptions();
 		PetscOptionsClear();
+		int ierr = PetscOptionsInsertString(options);
 		#endif
-		//PetscOptionsSetFromOptions();
-		PetscOptionsInsertMultipleString(options); //our patch
-		#endif
+
+		if(ierr) _error_("Could not enter PETSc options");
 
 	#endif
 
 	xDelete<char>(options);
-}
-/*}}}*/
+	xDelete<char>(toolkit);
+}
+/*}}}*/
+
+/*Specific case with ADOL-C, we might need to get double params for m1qn3*/
+#if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_) 
+void Parameters::FindParamAndMakePassive(double* pscalar,int param_enum){ _assert_(this);/*{{{*/
+	_assert_(param_enum>ParametersSTARTEnum);
+	_assert_(param_enum<ParametersENDEnum);
+
+	/*Get "active" parameter*/
+	IssmDouble intermediary;
+	int index = param_enum - ParametersSTARTEnum -1;
+	if(!this->params[index]) _error_("Parameter " << EnumToStringx(param_enum) <<" not set");
+	this->params[index]->GetParameterValue(&intermediary);
+
+	/*cast to "passive"*/
+	*pscalar=reCast<double>(intermediary);
+}
+/*}}}*/
+#endif
Index: /issm/trunk/src/c/classes/Params/Parameters.h
===================================================================
--- /issm/trunk/src/c/classes/Params/Parameters.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Params/Parameters.h	(revision 22758)
@@ -40,4 +40,5 @@
 		void  FindParam(IssmDouble* pscalar, int enum_type);
 		void  FindParam(IssmDouble* pscalar, int enum_type,IssmDouble time);
+		void  FindParam(IssmDouble* pscalar, int row,IssmDouble time,int enum_type);
 		void  FindParam(char** pstring,int enum_type);
 		void  FindParam(char*** pstringarray,int* pM,int enum_type);
@@ -51,4 +52,5 @@
 		void  FindParam(FILE** pfid,int enum_type);
 		void  FindParam(DataSet** pdataset, int enum_type);
+		void  FindParamInDataset(IssmDouble** pIssmDoublearray,int* pM,int* pN,int dataset_type,int enum_type);
 
 		void  SetParam(bool boolean,int enum_type);
@@ -68,8 +70,13 @@
 		Param* FindParamObject(int enum_type);
 
+		/*Specific instantiations for IssmDouble*: */
+		#if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_) 
+		void  FindParamAndMakePassive(double* pscalar, int enum_type);
+		#endif
+
 };
 
 /*Methods relating to parameters: */
-char *OptionsFromAnalysis(Parameters *parameters,int analysis_type);
+char *OptionsFromAnalysis(char** ptoolkit,Parameters *parameters,int analysis_type);
 void  ToolkitsOptionsFromAnalysis(Parameters* parameters,int analysis_type);
 
Index: /issm/trunk/src/c/classes/Params/StringArrayParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/StringArrayParam.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Params/StringArrayParam.cpp	(revision 22758)
@@ -22,21 +22,19 @@
 StringArrayParam::StringArrayParam(int in_enum_type,char** in_values, int in_numstrings){/*{{{*/
 
-	int i;
-	int size;
-
-	enum_type=in_enum_type;
-	numstrings=in_numstrings;
+	this->enum_type=in_enum_type;
+	this->numstrings=in_numstrings;
 
 	if(numstrings){
-		value=xNew<char*>(numstrings);
-		for(i=0;i<numstrings;i++){
-			char* string=NULL;
-			size=strlen(in_values[i])+1;
-			string=xNew<char>(size);
+		this->value=xNew<char*>(numstrings);
+		for(int i=0;i<numstrings;i++){
+			int   size=strlen(in_values[i])+1;
+			char* string=xNew<char>(size);
 			xMemCpy<char>(string,in_values[i],size);
-			value[i]=string;
+			this->value[i]=string;
 		}
 	}
-	else value=NULL;
+	else{
+		this->value=NULL;
+	}
 
 }
Index: /issm/trunk/src/c/classes/Params/StringParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/StringParam.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Params/StringParam.cpp	(revision 22758)
@@ -52,5 +52,5 @@
 void StringParam::Marshall(char** pmarshalled_data,int* pmarshalled_data_size, int marshall_direction){ /*{{{*/
 
-	int size;
+	int size = 0;
 
 	if(marshall_direction==MARSHALLING_FORWARD || marshall_direction == MARSHALLING_SIZE)size=strlen(value)+1;
Index: /issm/trunk/src/c/classes/Params/TransientArrayParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/TransientArrayParam.cpp	(revision 22758)
+++ /issm/trunk/src/c/classes/Params/TransientArrayParam.cpp	(revision 22758)
@@ -0,0 +1,142 @@
+/*!\file TransientArrayParam.c
+ * \brief: implementation of the TransientArrayParam object
+ */
+
+/*header files: */
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+/*TransientArrayParam constructors and destructor*/
+TransientArrayParam::TransientArrayParam(){/*{{{*/
+	return;
+}
+/*}}}*/
+TransientArrayParam::TransientArrayParam(int in_enum_type,IssmDouble* in_values,IssmDouble* in_time,bool interpolation_on,int in_N,int in_M){/*{{{*/
+
+	_assert_(in_values && in_time);
+
+	this->enum_type=in_enum_type;
+	this->M=in_M; //Number of rows
+	this->N=in_N; //Number of timesteps
+	this->interpolation=interpolation_on;
+
+	this->values=xNew<IssmDouble>(M*N);
+	xMemCpy<IssmDouble>(values,in_values,M*N);
+
+	this->timesteps=xNew<IssmDouble>(N);
+	xMemCpy<IssmDouble>(timesteps,in_time,N);
+}
+/*}}}*/
+TransientArrayParam::~TransientArrayParam(){/*{{{*/
+	xDelete<IssmDouble>(values);
+	xDelete<IssmDouble>(timesteps);
+}/*}}}*/
+
+/*Object virtual functions definitions:*/
+Param* TransientArrayParam::copy() {/*{{{*/
+
+	return new TransientArrayParam(this->enum_type,this->values,this->timesteps,this->interpolation,this->M,this->N);
+
+}
+/*}}}*/
+void TransientArrayParam::DeepEcho(void){/*{{{*/
+
+	_printf_("TransientArrayParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   number of time steps: " << this->N << "\n");
+	_printf_("   number of rows: " << this->M << "\n");
+	for(int i=0;i<this->N;i++){
+		_printf_("	time: " << this->timesteps[i] << "\n");
+		for(int k=0;k<this->M;k++){
+			_printf_("		values: " << this->values[k*N+i] << "\n");
+		}
+		_printf_("\n");
+	}
+}
+/*}}}*/
+void TransientArrayParam::Echo(void){/*{{{*/
+
+	_printf_("TransientArrayParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   size: " << this->M << " by " << this->N << "\n");
+
+}
+/*}}}*/
+int  TransientArrayParam::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+void TransientArrayParam::Marshall(char** pmarshalled_data,int* pmarshalled_data_size, int marshall_direction){ /*{{{*/
+
+	MARSHALLING_ENUM(TransientArrayParamEnum);
+
+	MARSHALLING(enum_type);
+	MARSHALLING(interpolation);
+	MARSHALLING(M);
+	MARSHALLING(N);
+	if(marshall_direction==MARSHALLING_BACKWARD){
+		values    = xNew<IssmDouble>(M*N);
+		timesteps = xNew<IssmDouble>(N);
+	}
+	MARSHALLING_ARRAY(values,IssmDouble,M*N);
+	MARSHALLING_ARRAY(timesteps,IssmDouble,N);
+
+}/*}}}*/
+int  TransientArrayParam::ObjectEnum(void){/*{{{*/
+
+	return TransientArrayParamEnum;
+
+}/*}}}*/
+
+/*TransientArrayParam virtual functions definitions: */
+void  TransientArrayParam::GetParameterValue(IssmDouble* pdouble,int row,IssmDouble time){/*{{{*/
+
+	IssmDouble output;
+	bool       found;
+	_assert_(row>=0 && row<this->M); 
+
+	/*Ok, we have the time and row, go through the timesteps, and figure out which interval we 
+	 *fall within. Then interpolate the values on this interval: */
+	if(time<this->timesteps[0]){
+		/*get values for the first time: */
+		output=this->values[row*this->N];
+		found=true;
+	}
+	else if(time>this->timesteps[this->N-1]){
+		/*get values for the last time: */
+		output=this->values[(row+1)*this->N-1];
+		found=true;
+	}
+	else{
+		/*Find which interval we fall within: */
+		for(int i=0;i<this->N;i++){
+			if(time==this->timesteps[i]){
+				/*We are right on one step time: */
+				output = this->values[row*this->N+i];
+				found=true;
+				break; //we are done with the time interpolation.
+			}
+			else{
+				if(this->timesteps[i]<time && time<this->timesteps[i+1]){
+					/*ok, we have the interval [i:i+1]. Interpolate linearly for now: */
+					IssmDouble deltat = this->timesteps[i+1]-this->timesteps[i];
+					IssmDouble alpha  = (time-this->timesteps[i])/deltat;
+					if(interpolation==true) output=(1.0-alpha)*this->values[row*this->N+i] + alpha*this->values[row*this->N+i+1];
+					else output=this->values[row*this->N+i];
+					found=true;
+					break;
+				}
+				else continue; //keep looking on the next interval
+			}
+		}
+	}
+	if(!found)_error_("did not find time interval on which to interpolate values");
+	*pdouble=output;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Params/TransientArrayParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/TransientArrayParam.h	(revision 22758)
+++ /issm/trunk/src/c/classes/Params/TransientArrayParam.h	(revision 22758)
@@ -0,0 +1,79 @@
+/*! \file TransientArrayParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _TRANSIENTARRAYPARAM_H_
+#define _TRANSIENTARRAYPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class TransientArrayParam: public Param{
+
+	protected: 
+		int         enum_type;
+		int         N;
+		int         M;
+		bool        interpolation;
+		IssmDouble *values;
+		IssmDouble *timesteps;
+
+	public:
+		/*TransientArrayParam constructors, destructors: {{{*/
+		TransientArrayParam();
+		TransientArrayParam(int in_enum_type,IssmDouble* in_values,IssmDouble* in_time,bool interpolation_on,int in_N,int in_M);
+		~TransientArrayParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		Param* copy();
+		void  DeepEcho();
+		void  Echo();
+		int   Id(); 
+		void Marshall(char** pmarshalled_data,int* pmarshalled_data_size, int marshall_direction);
+		int   ObjectEnum();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		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,int row,IssmDouble time);
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Parameter " <<EnumToStringx(enum_type) << " needs row to be specified");}
+		void  GetParameterValue(char** pstring){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
+		int   InstanceEnum(){return enum_type;}
+
+		void  SetEnum(int enum_in){this->enum_type = enum_in;};
+		void  SetValue(bool boolean){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a IssmDouble vec array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M,int N){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a int vec array");}
+		void  SetValue(int* intarray,int M,int N){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a int mat array");};
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		/*}}}*/
+};
+#endif  /* _TRANSIENTARRAYPARAM_H */
Index: /issm/trunk/src/c/classes/Params/TransientParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/TransientParam.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Params/TransientParam.cpp	(revision 22758)
@@ -104,5 +104,5 @@
 		found=true;
 	}
-	else if(time>this->timesteps[this->N-1] || !interpolation){
+	else if(time>this->timesteps[this->N-1]){
 		/*get values for the last time: */
 		output=this->values[this->N-1];
@@ -123,5 +123,6 @@
 					IssmDouble deltat=this->timesteps[i+1]-this->timesteps[i];
 					IssmDouble alpha=(time-this->timesteps[i])/deltat;
-					output=(1.0-alpha)*this->values[i] + alpha*this->values[i+1];
+					if(interpolation==true) output=(1.0-alpha)*this->values[i] + alpha*this->values[i+1];
+					else output=this->values[i];
 					found=true;
 					break;
Index: /issm/trunk/src/c/classes/Profiler.cpp
===================================================================
--- /issm/trunk/src/c/classes/Profiler.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Profiler.cpp	(revision 22758)
@@ -3,5 +3,5 @@
  */
 
-/*Include files: {{{*/
+/*Include files*/
 #ifdef HAVE_CONFIG_H
 	#include <config.h>
@@ -11,14 +11,16 @@
 
 #include "./Profiler.h"
-#include "./Params/DoubleParam.h"
 #include "../toolkits/toolkits.h"
-/*}}}*/
 
 /*Profiler constructors and destructors:*/
 Profiler::Profiler(){/*{{{*/
 	for(int i=0;i<MAXIMUMSIZE;i++){
-		this->time[i]  =NAN;
-		this->flops[i] =NAN;
-		this->memory[i]=NAN;
+		this->time[i]          = 0.;
+		this->time_start[i]    = 0.;
+		this->flops[i]         = 0.;
+		this->flops_start[i]   = 0.;
+		this->memory[i]        = 0.;
+		this->memory_start[i]  = 0.;
+		this->running[i]       = false;
 	}
 } /*}}}*/
@@ -42,9 +44,6 @@
 /*Object virtual functions definitions:*/
 void Profiler::DeepEcho(void){/*{{{*/
-
 	this->Echo();
-
-}
-/*}}}*/
+}/*}}}*/
 void Profiler::Echo(void){/*{{{*/
 
@@ -52,108 +51,99 @@
 	for(int i=0;i<MAXIMUMSIZE;i++){
 		_printf_("    Tag "<<i<<":\n");
-		_printf_("       flops:  "<<this->flops[i]<<"\n");
-		_printf_("       memory: "<<this->memory[i]<<"\n");
-		_printf_("       time:   "<<this->time[i]<<"\n");
-	}
-
-}
-/*}}}*/
-int  Profiler::Id(void){ return -1; }/*{{{*/
+		_printf_("       flops:   "<<this->flops[i]<<"\n");
+		_printf_("       memory:  "<<this->memory[i]<<"\n");
+		_printf_("       time:    "<<this->time[i]<<"\n");
+		_printf_("       running: "<<this->time[i]<<"\n");
+	}
+
+}
+/*}}}*/
+int  Profiler::Id(void){ /*{{{*/
+	return -1; 
+}
 /*}}}*/
 void Profiler::Marshall(char** pmarshalled_data,int* pmarshalled_data_size, int marshall_direction){ /*{{{*/
 
-	IssmDouble* pointer = NULL;
+	IssmPDouble* pointer = NULL;
+	bool*       bpointer = NULL;
 
 	MARSHALLING_ENUM(ProfilerEnum);
 	pointer = &this->time[0];
-	MARSHALLING_DYNAMIC(pointer,IssmDouble,MAXIMUMSIZE);
+	MARSHALLING_DYNAMIC(pointer,IssmPDouble,MAXIMUMSIZE);
 	pointer = &this->flops[0];
-	MARSHALLING_DYNAMIC(pointer,IssmDouble,MAXIMUMSIZE);
+	MARSHALLING_DYNAMIC(pointer,IssmPDouble,MAXIMUMSIZE);
 	pointer = &this->memory[0];
-	MARSHALLING_DYNAMIC(pointer,IssmDouble,MAXIMUMSIZE);
+	MARSHALLING_DYNAMIC(pointer,IssmPDouble,MAXIMUMSIZE);
+	bpointer = &this->running[0];
+	MARSHALLING_DYNAMIC(bpointer,bool,MAXIMUMSIZE);
 
 } /*}}}*/
 int  Profiler::ObjectEnum(void){/*{{{*/
-
 	return ProfilerEnum;
-
-}
-/*}}}*/
+}/*}}}*/
 
 /*Profiler routines:*/
-IssmDouble  Profiler::DeltaFlops(int inittag, int finaltag){/*{{{*/
+IssmPDouble  Profiler::TotalFlops(int tag){/*{{{*/
+
+	/*Get tag*/
+	_assert_(tag>=0); 
+	_assert_(tag<MAXIMUMSIZE); 
+	if(this->running[tag]) _error_("Tag "<<tag<<" has not been stopped");
+
+	return this->flops[tag];
+}/*}}}*/
+IssmPDouble  Profiler::TotalTime(int tag){/*{{{*/
+
+	/*Get tag*/
+	_assert_(tag>=0); 
+	_assert_(tag<MAXIMUMSIZE); 
+	if(this->running[tag]) _error_("Tag "<<tag<<" has not been stopped");
+
+
+	#ifdef _HAVE_MPI_
+	return this->time[tag];
+	#else
+	return this->time[tag]/CLOCKS_PER_SEC;
+	#endif
+}
+/*}}}*/
+int Profiler::TotalTimeModHour(int tag){/*{{{*/
+
+	IssmPDouble delta = this->TotalTime(tag);
+	return int((reCast<int,IssmPDouble>(delta))/3600);
+
+}
+/*}}}*/
+int Profiler::TotalTimeModMin(int tag){/*{{{*/
+
+	IssmPDouble delta = this->TotalTime(tag);
+	return int(int(reCast<int,IssmPDouble>(delta))%3600/60);
+}
+/*}}}*/
+int Profiler::TotalTimeModSec(int tag){/*{{{*/
+
+	IssmPDouble delta = this->TotalTime(tag);
+	return int(reCast<int,IssmPDouble>(delta)%60);
+}
+/*}}}*/
+IssmPDouble  Profiler::Memory(int tag){/*{{{*/
 
 	/*Get initial flops*/
-	_assert_(inittag>=0); 
-	_assert_(inittag<MAXIMUMSIZE); 
-	if(xIsNan<IssmDouble>(this->flops[inittag])) _error_("Tag not set");
-	IssmDouble init = this->flops[inittag];
-
-	/*Get final flops*/
-	_assert_(finaltag>=0); 
-	_assert_(finaltag<MAXIMUMSIZE); 
-	if(xIsNan<IssmDouble>(this->flops[finaltag])) _error_("Tag not set");
-	IssmDouble final = this->flops[finaltag];
-
-	return final-init;
-}
-/*}}}*/
-IssmDouble  Profiler::DeltaTime(int inittag, int finaltag){/*{{{*/
-
-	/*Get initial time*/
-	_assert_(inittag>=0); 
-	_assert_(inittag<MAXIMUMSIZE); 
-	if(xIsNan<IssmDouble>(this->time[inittag])) _error_("Tag "<<inittag<<" not set");
-	IssmDouble init = this->time[inittag];
-
-	/*Get final time*/
-	_assert_(finaltag>=0); 
-	_assert_(finaltag<MAXIMUMSIZE); 
-	if(xIsNan<IssmDouble>(this->time[finaltag])) _error_("Tag "<<finaltag<<" not set");
-	IssmDouble final = this->time[finaltag];
-
-	#ifdef _HAVE_MPI_
-	return final-init;
-	#else
-	return (final-init)/CLOCKS_PER_SEC;
-	#endif
-}
-/*}}}*/
-int Profiler::DeltaTimeModHour(int inittag, int finishtag){/*{{{*/
-
-	IssmDouble delta = this->DeltaTime(inittag,finishtag);
-	return int((reCast<int,IssmDouble>(delta))/3600);
-
-}
-/*}}}*/
-int Profiler::DeltaTimeModMin(int inittag, int finishtag){/*{{{*/
-
-	IssmDouble delta = this->DeltaTime(inittag,finishtag);
-	return int(int(reCast<int,IssmDouble>(delta))%3600/60);
-}
-/*}}}*/
-int Profiler::DeltaTimeModSec(int inittag, int finishtag){/*{{{*/
-
-	IssmDouble delta = this->DeltaTime(inittag,finishtag);
-	return int(reCast<int,IssmDouble>(delta)%60);
-}
-/*}}}*/
-IssmDouble  Profiler::Memory(int tag){/*{{{*/
-
-	/*Get initial flops*/
-	_assert_(tag>=0); 
-	_assert_(tag<MAXIMUMSIZE); 
-	if(xIsNan<IssmDouble>(this->flops[tag])) _error_("Tag not set");
+	_assert_(tag>=0); 
+	_assert_(tag<MAXIMUMSIZE); 
+	if(this->running[tag]) _error_("Tag "<<tag<<" has not been stopped");
+
 	return this->memory[tag];
 }
 /*}}}*/
-void  Profiler::Tag(int tagenum,bool dontmpisync){/*{{{*/
-
-	IssmDouble t;
-	IssmDouble f;
-	IssmDouble m;
-
-	/*If mpisync requested, make sure all the cpus are at the same point 
-	 *in the execution: */
+void  Profiler::Start(int tag,bool dontmpisync){/*{{{*/
+
+	/*Check tag*/
+	_assert_(tag>=0); 
+	_assert_(tag<MAXIMUMSIZE); 
+	if(this->running[tag]) _error_("Tag "<<tag<<" is already running");
+
+
+	/*If mpisync requested, make sure all the cpus are at the same point in the execution: */
 	if(!dontmpisync){
 		ISSM_MPI_Barrier(IssmComm::GetComm()); 
@@ -162,10 +152,12 @@
 	/*Capture time: */
 	#ifdef _HAVE_MPI_
-	t=ISSM_MPI_Wtime();
-	#else
-	t=(IssmPDouble)clock();
+	IssmPDouble t=ISSM_MPI_Wtime();
+	#else
+	IssmPDouble t=(IssmPDouble)clock();
 	#endif
 
 	/*Capture flops: */
+	IssmPDouble f = 0.;
+	IssmPDouble m = 0.;
 	#ifdef _HAVE_PETSC_
 		PetscGetFlops(&f);
@@ -176,13 +168,51 @@
 
 	/*Plug into this->time: */
-	_assert_(tagenum>=0); 
-	_assert_(tagenum<MAXIMUMSIZE); 
-	if(!xIsNan<IssmDouble>(this->time[tagenum])) _error_("Tag already exists");
-	this->time[tagenum]  = t;
-	if(!xIsNan<IssmDouble>(this->flops[tagenum])) _error_("Tag already exists");
-	this->flops[tagenum] = f;
-	if(!xIsNan<IssmDouble>(this->memory[tagenum])) _error_("Tag already exists");
-	this->memory[tagenum]= m;
-
-}
-/*}}}*/
+	_assert_(tag>=0); 
+	_assert_(tag<MAXIMUMSIZE); 
+	this->time_start[tag]   = t;
+	this->flops_start[tag]  = f;
+	this->memory_start[tag] = m;
+
+	/*turn on running*/
+	this->running[tag] = true;
+}/*}}}*/
+void  Profiler::Stop(int tag,bool dontmpisync){/*{{{*/
+
+	/*Check tag*/
+	_assert_(tag>=0); 
+	_assert_(tag<MAXIMUMSIZE); 
+	if(!this->running[tag]) _error_("Tag "<<tag<<" is not running");
+
+
+	/*If mpisync requested, make sure all the cpus are at the same point in the execution: */
+	if(!dontmpisync){
+		ISSM_MPI_Barrier(IssmComm::GetComm()); 
+	}
+
+	/*Capture time: */
+	#ifdef _HAVE_MPI_
+	IssmPDouble t=ISSM_MPI_Wtime();
+	#else
+	IssmPDouble t=(IssmPDouble)clock();
+	#endif
+
+	/*Capture flops: */
+	IssmPDouble f = 0.;
+	IssmPDouble m = 0.;
+	#ifdef _HAVE_PETSC_
+	PetscGetFlops(&f);
+	PetscMemoryGetCurrentUsage(&m);
+	#else
+	/*do nothing for now:*/
+	#endif
+
+	/*Plug into this->time: */
+	_assert_(tag>=0); 
+	_assert_(tag<MAXIMUMSIZE); 
+	this->time[tag]   += t - this->time_start[tag];
+	this->flops[tag]  += f - this->flops_start[tag];
+	this->memory[tag] += m - this->memory_start[tag];
+
+	/*turn off running*/
+	this->running[tag] = false;
+}/*}}}*/
Index: /issm/trunk/src/c/classes/Profiler.h
===================================================================
--- /issm/trunk/src/c/classes/Profiler.h	(revision 22757)
+++ /issm/trunk/src/c/classes/Profiler.h	(revision 22758)
@@ -7,49 +7,47 @@
 
 /*Headers:*/
-/*{{{*/
+#include "../shared/shared.h"
 #include "../datastructures/datastructures.h"
-#include "../shared/shared.h"
-/*}}}*/
 
-class DoubleParam;
-
-#define START 0
-#define STARTINIT 1
-#define FINISHINIT 2
-#define STARTCORE 3
-#define FINISHCORE 4
-#define STARTADCORE 5
-#define FINISHADCORE 6
-#define FINISH 7
-#define MAXIMUMSIZE 8 
+/*Macros*/
+#define TOTAL 0      /*Profiling Total time */ 
+#define MPROCESSOR 1 /*Profiling Model processor*/ 
+#define CORE 2       /*Profiling solution */ 
+#define SOLVER 3     /*Profiling solution */ 
+#define ADCORE 4     /*Profiling AD */ 
+#define MAXIMUMSIZE 5
 
 class Profiler: public Object{
 
 	public: 
-		IssmDouble flops[MAXIMUMSIZE];
-		IssmDouble memory[MAXIMUMSIZE];
-		IssmDouble time[MAXIMUMSIZE];
+		IssmPDouble flops[MAXIMUMSIZE];
+		IssmPDouble flops_start[MAXIMUMSIZE];
+		IssmPDouble memory[MAXIMUMSIZE];
+		IssmPDouble memory_start[MAXIMUMSIZE];
+		IssmPDouble time[MAXIMUMSIZE];
+		IssmPDouble time_start[MAXIMUMSIZE];
+		bool        running[MAXIMUMSIZE];
 
-		/*Profiler constructors, destructors {{{*/
+		/*Profiler constructors, destructors */
 		Profiler();
 		~Profiler();
-		/*}}}*/
-		/*Object virtual functions definitions:{{{ */
+
+		/*Object virtual functions definitions*/
 		Object *copy();
 		void    DeepEcho();
 		void    Echo();
 		int     Id();
-		void Marshall(char** pmarshalled_data,int* pmarshalled_data_size, int marshall_direction);
+		void    Marshall(char** pmarshalled_data,int* pmarshalled_data_size, int marshall_direction);
 		int     ObjectEnum();
-		/*}}}*/
-		/*Profiler routines {{{*/
-		IssmDouble  DeltaFlops(int inittag, int finaltag);
-		IssmDouble  DeltaTime(int inittag, int finaltag);
-		int     DeltaTimeModHour(int inittag, int finaltag);
-		int     DeltaTimeModMin(int inittag, int finaltag);
-		int     DeltaTimeModSec(int inittag, int finaltag);
-		IssmDouble  Memory(int tag);
-		void    Tag(int tagenum,bool dontmpisync=false);
-		/*}}}*/
+
+		/*Profiler routines*/
+		IssmPDouble  TotalFlops(int tag);
+		IssmPDouble  TotalTime(int tag);
+		int          TotalTimeModHour(int tag);
+		int          TotalTimeModMin(int tag);
+		int          TotalTimeModSec(int tag);
+		IssmPDouble  Memory(int tag);
+		void         Start(int tagenum,bool dontmpisync=false);
+		void         Stop(int tagenum,bool dontmpisync=false);
 };
 
Index: /issm/trunk/src/c/classes/Regionaloutput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Regionaloutput.cpp	(revision 22758)
+++ /issm/trunk/src/c/classes/Regionaloutput.cpp	(revision 22758)
@@ -0,0 +1,157 @@
+/*!\file Regionaloutput.cpp
+ * \brief: implementation for the Regionaloutput object
+ */
+
+/*Include files: {{{*/
+#ifdef HAVE_CONFIG_H
+   #include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*Headers:*/
+#include "./classes.h"
+#include "./Definition.h"
+#include "./Elements/Element.h"
+#include "./Elements/Elements.h"
+#include "./FemModel.h"
+#include "../classes/Params/Parameters.h"
+
+/*}}}*/
+
+Regionaloutput::Regionaloutput(char* in_name, int in_definitionenum, char* in_outputname, IssmDouble* maskin, int Min){ /*{{{*/
+
+	this->definitionenum=in_definitionenum;
+	this->outputname = xNew<char>(strlen(in_outputname)+1);
+	xMemCpy<char>(this->outputname,in_outputname,strlen(in_outputname)+1);
+	this->name = xNew<char>(strlen(in_name)+1);
+	xMemCpy<char>(this->name,in_name,strlen(in_name)+1);
+
+	this->mask   = xNew<IssmDouble>(Min);
+	xMemCpy<IssmDouble>(this->mask, maskin, Min);
+
+	this->M=Min;
+
+}
+/*}}}*/
+Regionaloutput::~Regionaloutput(){/*{{{*/
+	if(this->name)xDelete(this->name); 
+	if(this->outputname)xDelete(this->outputname);
+	if(this->mask)xDelete(this->mask);
+}
+/*}}}*/
+
+/*Object virtual function resolutoin: */
+Object* Regionaloutput::copy() {/*{{{*/
+	Regionaloutput* mf = new Regionaloutput(this->name,this->definitionenum,this->outputname,this->mask,this->M);
+	return (Object*) mf;
+}
+/*}}}*/
+void Regionaloutput::DeepEcho(void){/*{{{*/
+	this->Echo();
+}
+/*}}}*/
+void Regionaloutput::Echo(void){/*{{{*/
+	_printf_(" Regionaloutput: " << this->name << " " << this->definitionenum << "\n");
+	_printf_("    outputname enum: " << this->outputname << "Enum\n");
+	_printf_("    mask: " << this->mask << "\n");
+	_printf_("    M: " << this->M << "\n");
+}
+/*}}}*/
+int Regionaloutput::Id(void){/*{{{*/
+	return -1;
+}
+/*}}}*/
+void Regionaloutput::Marshall(char** pmarshalled_data,int* pmarshalled_data_size, int marshall_direction){/*{{{*/
+	_error_("not implemented yet!"); 
+} 
+/*}}}*/
+int Regionaloutput::ObjectEnum(void){/*{{{*/
+	return RegionaloutputEnum;
+}
+/*}}}*/
+
+/*Definition virtual function resolutoin: */
+int Regionaloutput::DefinitionEnum(){/*{{{*/
+
+	return this->definitionenum;
+}
+/*}}}*/
+char* Regionaloutput::Name(){/*{{{*/
+
+	char* name2=xNew<char>(strlen(this->name)+1);
+	xMemCpy(name2,this->name,strlen(this->name)+1);
+
+	return name2;
+}
+/*}}}*/
+IssmDouble Regionaloutput::Response(FemModel* femmodel){/*{{{*/
+
+	int i;
+	IssmDouble val_t=0.;
+	IssmDouble all_val_t=0.;
+	int outputenum = StringToEnumx(this->outputname);
+
+	for(i=0;i<femmodel->elements->Size();i++){
+		Element* element=(Element*)femmodel->elements->GetObjectByOffset(i);
+		switch(outputenum){
+			case GroundedAreaEnum:
+				val_t+=element->GroundedArea(this->mask,false);
+				break;
+			case GroundedAreaScaledEnum:
+				val_t+=element->GroundedArea(this->mask,true);
+				break;
+			case FloatingAreaEnum:
+				val_t+=element->FloatingArea(this->mask,false);
+				break;
+			case FloatingAreaScaledEnum:
+				val_t+=element->FloatingArea(this->mask,true);
+				break;
+			case IceMassEnum:
+				val_t+=element->IceMass(this->mask,false);
+				break;
+			case IceMassScaledEnum:
+				val_t+=element->IceMass(this->mask,true);
+				break;
+			case IceVolumeEnum:
+				val_t+=element->IceVolume(this->mask,false);
+				break;
+			case IceVolumeScaledEnum:
+				val_t+=element->IceVolume(this->mask,true);
+				break;
+			case IceVolumeAboveFloatationEnum:
+				val_t+=element->IceVolumeAboveFloatation(this->mask,false);
+				break;
+			case IceVolumeAboveFloatationScaledEnum:
+				val_t+=element->IceVolumeAboveFloatation(this->mask,true);
+				break;
+			case TotalFloatingBmbEnum:
+				val_t+=element->TotalFloatingBmb(this->mask,false);
+				break;
+			case TotalFloatingBmbScaledEnum:
+				val_t+=element->TotalFloatingBmb(this->mask,true);
+				break;
+			case TotalGroundedBmbEnum:
+				val_t+=element->TotalGroundedBmb(this->mask,false);
+				break;
+			case TotalGroundedBmbScaledEnum:
+				val_t+=element->TotalGroundedBmb(this->mask,true);
+				break;
+			case TotalSmbEnum:
+				val_t+=element->TotalSmb(this->mask,false);
+				break;
+			case TotalSmbScaledEnum:
+				val_t+=element->TotalSmb(this->mask,true);
+				break;
+			default:
+				_error_("Regional output type " << this->outputname << " not supported yet!");
+		}
+	}
+
+	ISSM_MPI_Allreduce ( (void*)&val_t,(void*)&all_val_t,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
+	val_t=all_val_t;
+
+	return val_t;
+}
+/*}}}*/
+
Index: /issm/trunk/src/c/classes/Regionaloutput.h
===================================================================
--- /issm/trunk/src/c/classes/Regionaloutput.h	(revision 22758)
+++ /issm/trunk/src/c/classes/Regionaloutput.h	(revision 22758)
@@ -0,0 +1,43 @@
+/*!\file Regionaloutput.h
+ * \brief: header file for Regionaloutput object
+ */
+
+#ifndef _REGIONALOUTPUT_H_
+#define _REGIONALOUTPUT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Definition.h"
+#include "./FemModel.h"
+
+/*}}}*/
+
+class Regionaloutput: public Object, public Definition{
+
+public: 
+
+	int         definitionenum;
+	char*       outputname;
+	char*       name;
+	IssmDouble* mask;
+	int         M;
+	
+/*Regionalicevolume: constructors, destructors :*/
+Regionaloutput();
+Regionaloutput(char* in_name, int in_definitionenum, char* in_outputname, IssmDouble* maskin, int Min);
+~Regionaloutput();
+
+/*Object virtual function resolutoin: */
+Object* copy();
+void DeepEcho(void);
+void Echo(void);
+int Id(void);
+void Marshall(char** pmarshalled_data,int* pmarshalled_data_size, int marshall_direction);
+int ObjectEnum(void);
+
+/*Definition virtual function resolutoin: */
+int DefinitionEnum();
+char* Name();
+IssmDouble Response(FemModel* femmodel);
+};
+#endif  /* _REGIONALOUTPUT_H_ */
Index: /issm/trunk/src/c/classes/Vertices.cpp
===================================================================
--- /issm/trunk/src/c/classes/Vertices.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/Vertices.cpp	(revision 22758)
@@ -144,4 +144,6 @@
 	int vertex_max_sid;
 
+	if (this->Size()==0)return 0;
+
 	for(i=0;i<this->Size();i++){
 		Vertex* vertex=xDynamicCast<Vertex*>(this->GetObjectByOffset(i));
Index: /issm/trunk/src/c/classes/classes.h
===================================================================
--- /issm/trunk/src/c/classes/classes.h	(revision 22757)
+++ /issm/trunk/src/c/classes/classes.h	(revision 22758)
@@ -19,6 +19,11 @@
 #include "./Misfit.h"
 #include "./Nodalvalue.h"
+#include "./Numberedcostfunction.h"
+#include "./Cfsurfacesquare.h"
+#include "./Cfdragcoeffabsgrad.h"
+#include "./Cfsurfacelogvel.h"
 #include "./Masscon.h"
 #include "./Massconaxpby.h"
+#include "./Regionaloutput.h"
 
 /*Constraints: */
@@ -83,4 +88,5 @@
 #include "./Materials/Material.h"
 #include "./Materials/Matice.h"
+#include "./Materials/Matlitho.h"
 #include "./Materials/Matestar.h"
 #include "./Materials/Matpar.h"
@@ -105,4 +111,5 @@
 #include "./Params/StringParam.h"
 #include "./Params/TransientParam.h"
+#include "./Params/TransientArrayParam.h"
 #include "./Params/DataSetParam.h"
 
Index: /issm/trunk/src/c/classes/gauss/GaussPenta.cpp
===================================================================
--- /issm/trunk/src/c/classes/gauss/GaussPenta.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/gauss/GaussPenta.cpp	(revision 22758)
@@ -601,4 +601,27 @@
 			}
 			break;
+		case P1xP4Enum: 
+			switch(iv){
+				case 0 : coord1=1.; coord2=0.; coord3=0.; coord4=-1.; break;
+				case 1 : coord1=0.; coord2=1.; coord3=0.; coord4=-1.; break;
+				case 2 : coord1=0.; coord2=0.; coord3=1.; coord4=-1.; break;
+				case 3 : coord1=1.; coord2=0.; coord3=0.; coord4=+1.; break;
+				case 4 : coord1=0.; coord2=1.; coord3=0.; coord4=+1.; break;
+				case 5 : coord1=0.; coord2=0.; coord3=1.; coord4=+1.; break;
+
+				case 6 : coord1=1.; coord2=0.; coord3=0.; coord4=0.; break;
+				case 7 : coord1=0.; coord2=1.; coord3=0.; coord4=0.; break;
+				case 8 : coord1=0.; coord2=0.; coord3=1.; coord4=0.; break;
+
+				case 9 : coord1=1.; coord2=0.; coord3=0.; coord4=-0.5; break;
+				case 10: coord1=0.; coord2=1.; coord3=0.; coord4=-0.5; break;
+				case 11: coord1=0.; coord2=0.; coord3=1.; coord4=-0.5; break;
+
+				case 12: coord1=1.; coord2=0.; coord3=0.; coord4=+0.5; break;
+				case 13: coord1=0.; coord2=1.; coord3=0.; coord4=+0.5; break;
+				case 14: coord1=0.; coord2=0.; coord3=1.; coord4=+0.5; break;
+				default: _error_("node index should be in [0 14]");
+			}
+			break;
 		case P2xP1Enum: 
 			switch(iv){
Index: /issm/trunk/src/c/classes/gauss/GaussTria.cpp
===================================================================
--- /issm/trunk/src/c/classes/gauss/GaussTria.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/gauss/GaussTria.cpp	(revision 22758)
@@ -287,4 +287,61 @@
 }
 /*}}}*/
+GaussTria::GaussTria(int index,IssmDouble r1,IssmDouble r2,int order){/*{{{*/
+
+	/*
+	 *  ^ 
+	 *  ------------------
+	 * 1|\              |
+	 *  |  \            |
+	 *  |    \          |
+	 *  |      \        |
+	 *  |        \      |
+	 *  |          \    |
+	 *  |    +(x,y)  \  |
+	 *  |              \|
+	 *  +---------------+-->
+	 *  0               1
+	 *
+	 */
+	int         ig;
+	IssmDouble x,y;
+	IssmDouble xy_list[3][2];
+
+	/*Double number of gauss points*/
+	GaussTria *gauss1    = NULL;
+	GaussTria *gauss2    = NULL;
+	gauss1=new GaussTria(index,r1,r2,1,order); //for the mainly floating part
+	gauss2=new GaussTria(index,r1,r2,0,order); //for the mainly grounded part
+
+	this->numgauss = gauss1->numgauss + gauss2->numgauss;
+	this->coords1=xNew<IssmDouble>(this->numgauss);
+	this->coords2=xNew<IssmDouble>(this->numgauss);
+	this->coords3=xNew<IssmDouble>(this->numgauss);
+	this->weights=xNew<IssmDouble>(this->numgauss);
+
+	for(ig=0;ig<gauss1->numgauss;ig++){ // Add the first triangle gauss points
+		this->coords1[ig]=gauss1->coords1[ig];
+		this->coords2[ig]=gauss1->coords2[ig];
+		this->coords3[ig]=gauss1->coords3[ig];
+		this->weights[ig]=gauss1->weights[ig];
+	}
+	for(ig=0;ig<gauss2->numgauss;ig++){ // Add the second triangle gauss points
+		this->coords1[gauss1->numgauss+ig]=gauss2->coords1[ig];
+		this->coords2[gauss1->numgauss+ig]=gauss2->coords2[ig];
+		this->coords3[gauss1->numgauss+ig]=gauss2->coords3[ig];
+		this->weights[gauss1->numgauss+ig]=gauss2->weights[ig];
+	}
+
+	/*Delete gauss points*/
+	delete gauss1;
+	delete gauss2;
+
+	/*Initialize static fields as undefined*/
+	weight=UNDEF;
+	coord1=UNDEF;
+	coord2=UNDEF;
+	coord3=UNDEF;
+}
+/*}}}*/
 GaussTria::~GaussTria(){/*{{{*/
 	xDelete<IssmDouble>(weights);
Index: /issm/trunk/src/c/classes/gauss/GaussTria.h
===================================================================
--- /issm/trunk/src/c/classes/gauss/GaussTria.h	(revision 22757)
+++ /issm/trunk/src/c/classes/gauss/GaussTria.h	(revision 22758)
@@ -31,4 +31,5 @@
 		GaussTria(int index1,int index2,int order);
 		GaussTria(int index,IssmDouble r1, IssmDouble r2,bool maintlyfloating,int order);
+		GaussTria(int index,IssmDouble r1, IssmDouble r2,int order);
 		GaussTria(IssmDouble area_coordinates[2][3],int order);
 		~GaussTria();
Index: /issm/trunk/src/c/classes/kriging/Observations.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/Observations.cpp	(revision 22757)
+++ /issm/trunk/src/c/classes/kriging/Observations.cpp	(revision 22758)
@@ -256,4 +256,7 @@
 	/*If radius is not provided or is 0, return all observations*/
 	if(radius==0) radius=this->quadtree->root->length;
+
+	/*For CPPcheck*/
+	hmin = 2*radius;
 
 	/*First, find closest point in Quadtree (fast but might not be the true closest obs)*/
Index: /issm/trunk/src/c/cores/CorePointerFromSolutionEnum.cpp
===================================================================
--- /issm/trunk/src/c/cores/CorePointerFromSolutionEnum.cpp	(revision 22757)
+++ /issm/trunk/src/c/cores/CorePointerFromSolutionEnum.cpp	(revision 22758)
@@ -75,4 +75,12 @@
 			solutioncore=&damage_core;
 			break;
+		case LoveSolutionEnum:
+			#if _HAVE_LOVE_
+			solutioncore=&love_core;
+			#else
+			_error_("ISSM not compiled with Love capability");
+			#endif
+			break;
+
 		default:
 			_error_("solution type: " << EnumToStringx(solutiontype) << " not supported yet!");
Index: /issm/trunk/src/c/cores/WrapperCorePointerFromSolutionEnum.cpp
===================================================================
--- /issm/trunk/src/c/cores/WrapperCorePointerFromSolutionEnum.cpp	(revision 22757)
+++ /issm/trunk/src/c/cores/WrapperCorePointerFromSolutionEnum.cpp	(revision 22758)
@@ -47,5 +47,5 @@
 			case 2: solutioncore=controlm1qn3_core; break;
 			case 3: solutioncore=controlvalidation_core; break;
-			case 4: solutioncore=controlad_core; break;
+			case 4: solutioncore=controladm1qn3_core; break;
 			default: _error_("control type not supported");
 		}
Index: /issm/trunk/src/c/cores/ad_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/ad_core.cpp	(revision 22757)
+++ /issm/trunk/src/c/cores/ad_core.cpp	(revision 22758)
@@ -26,5 +26,5 @@
 	int     num_dependents=0;
 	int     num_independents=0;
-	bool    isautodiff       = false;
+	bool    isautodiff,iscontrol;
 	char   *driver           = NULL;
 	size_t  tape_stats[15];
@@ -37,6 +37,7 @@
 	/*AD mode on?: */
 	femmodel->parameters->FindParam(&isautodiff,AutodiffIsautodiffEnum);
-
-	if(isautodiff){
+	femmodel->parameters->FindParam(&iscontrol,InversionIscontrolEnum);
+
+	if(isautodiff && !iscontrol){
 
 		#ifdef _HAVE_ADOLC_
Index: /issm/trunk/src/c/cores/adjointbalancethickness2_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/adjointbalancethickness2_core.cpp	(revision 22757)
+++ /issm/trunk/src/c/cores/adjointbalancethickness2_core.cpp	(revision 22758)
@@ -24,5 +24,5 @@
 
 	/*Call SurfaceAreax, because some it might be needed by PVector*/
-	SurfaceAreax(NULL,femmodel);
+	//SurfaceAreax(NULL,femmodel);
 
 	/*compute adjoint*/
Index: /issm/trunk/src/c/cores/balancethickness2_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/balancethickness2_core.cpp	(revision 22757)
+++ /issm/trunk/src/c/cores/balancethickness2_core.cpp	(revision 22758)
@@ -13,11 +13,11 @@
 
 	/*parameters: */
-	bool        save_results;
-	IssmDouble  l = 3.;
+	bool save_results;
+	//IssmDouble  l = 3.;
 
 	/*recover parameters: */
 	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
 
-	if(VerboseSolution()) _printf0_("computing smooth surface slopes:\n");
+	//if(VerboseSolution()) _printf0_("computing smooth surface slopes:\n");
 	//femmodel->parameters->SetParam(l,SmoothThicknessMultiplierEnum);
 	//femmodel->SetCurrentConfiguration(SmoothAnalysisEnum);
@@ -26,5 +26,5 @@
 	//femmodel->parameters->SetParam(SurfaceSlopeYEnum,InputToSmoothEnum);
 	//solutionsequence_linear(femmodel);
-	surfaceslope_core(femmodel);
+	//surfaceslope_core(femmodel);
 
 	if(VerboseSolution()) _printf0_("call computational core:\n");
@@ -35,8 +35,6 @@
 	if(save_results){
 		if(VerboseSolution()) _printf0_("   saving results\n");
-		const int numoutputs = 6;
-		int outputs[numoutputs] = {SurfaceEnum,SurfaceSlopeXEnum,SurfaceSlopeYEnum,VxEnum,VyEnum,VelEnum};
-		//const int numoutputs = 4;
-		//int outputs[numoutputs] = {SurfaceEnum,VxEnum,VyEnum,VelEnum};
+		const int numoutputs = 1;
+		int outputs[numoutputs] = {ThicknessEnum};
 		femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],numoutputs);
 	}
Index: /issm/trunk/src/c/cores/control_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/control_core.cpp	(revision 22757)
+++ /issm/trunk/src/c/cores/control_core.cpp	(revision 22758)
@@ -186,4 +186,5 @@
 	/*output: */
 	IssmDouble J;
+	int        temp;
 
 	/*parameters: */
@@ -203,5 +204,5 @@
 	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
 	femmodel->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
-	femmodel->parameters->FindParam(&scalar_list,NULL,NULL,InversionGradientScalingEnum);
+	femmodel->parameters->FindParam(&scalar_list,&temp,&temp,InversionGradientScalingEnum);
 	femmodel->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);   _assert_(num_controls);
 	numvertices=femmodel->vertices->NumberOfVertices();
Index: /issm/trunk/src/c/cores/controladm1qn3_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/controladm1qn3_core.cpp	(revision 22758)
+++ /issm/trunk/src/c/cores/controladm1qn3_core.cpp	(revision 22758)
@@ -0,0 +1,515 @@
+/*!\file: controladm1qn3_core.cpp
+ * \brief: core of the control solution 
+ */ 
+
+#include <config.h>
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+#if defined (_HAVE_M1QN3_) && defined(_HAVE_ADOLC_)
+/*m1qn3 prototypes*/
+extern "C" void *ctonbe_; // DIS mode : Conversion
+extern "C" void *ctcabe_; // DIS mode : Conversion
+extern "C" void *euclid_; // Scalar product
+typedef void (*SimulFunc) (long* indic,long* n, double* x,double* pf,double* g,long [],float [],void* dzs);
+extern "C" void m1qn3_ (void f(long* indic,long* n, double* x,double* pf,double* g,long [],float [],void* dzs),
+			void **, void **, void **,
+			long *, double [],double *, double[], double*, double *,
+			double *, char [], long *, long *, long *, long *, long *, long *, long [],double [], long *,
+			long *, long *, long [], float [],void* );
+
+/*Use struct to provide arguments*/
+typedef struct{
+	FemModel   * femmodel;
+	IssmPDouble* Jlist;
+	int          M;
+	int          N;
+	int*         i;
+} m1qn3_struct;
+
+/*m1qm3 functions*/
+void simul_starttrace(FemModel* femmodel){/*{{{*/
+
+	/*Retrive ADOLC parameters*/
+	IssmDouble gcTriggerRatio;
+	IssmDouble gcTriggerMaxSize;
+	IssmDouble obufsize;
+	IssmDouble lbufsize;
+	IssmDouble cbufsize;
+	IssmDouble tbufsize;
+	femmodel->parameters->FindParam(&gcTriggerRatio,AutodiffGcTriggerRatioEnum);
+	femmodel->parameters->FindParam(&gcTriggerMaxSize,AutodiffGcTriggerMaxSizeEnum);
+	femmodel->parameters->FindParam(&obufsize,AutodiffObufsizeEnum);
+	femmodel->parameters->FindParam(&lbufsize,AutodiffLbufsizeEnum);
+	femmodel->parameters->FindParam(&cbufsize,AutodiffCbufsizeEnum);
+	femmodel->parameters->FindParam(&tbufsize,AutodiffTbufsizeEnum);
+
+	/*Set garbage collection parameters: */
+	setStoreManagerControl(reCast<IssmPDouble>(gcTriggerRatio),reCast<size_t>(gcTriggerMaxSize));
+
+	/*Start trace: */
+	int skipFileDeletion=1;
+	int keepTaylors=1;
+	int my_rank=IssmComm::GetRank();
+	trace_on(my_rank,keepTaylors,reCast<size_t>(obufsize),reCast<size_t>(lbufsize),reCast<size_t>(cbufsize),reCast<size_t>(tbufsize),skipFileDeletion);
+}/*}}}*/
+void simul_ad(long* indic,long* n,double* X,double* pf,double* G,long izs[1],float rzs[1],void* dzs){/*{{{*/
+
+	/*Get rank*/
+	int my_rank=IssmComm::GetRank();
+
+	/*Recover Arguments*/
+	m1qn3_struct *input_struct = (m1qn3_struct*)dzs;
+
+	FemModel* femmodel = input_struct->femmodel;
+	int num_responses,num_controls,numberofvertices,solution_type;
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	int* N = NULL;
+	int N_add = 0;
+
+	if (solution_type == TransientSolutionEnum){
+		femmodel = input_struct->femmodel->copy();
+	}
+
+	IssmPDouble  *Jlist        = input_struct->Jlist;
+	int           JlistM       = input_struct->M;
+	int           JlistN       = input_struct->N;
+	int          *Jlisti       = input_struct->i;
+	int           intn         = (int)*n;
+
+	/*Recover some parameters*/
+	IssmDouble* scaling_factors = NULL;
+	femmodel->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	femmodel->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+	femmodel->parameters->FindParam(&scaling_factors,NULL,InversionControlScalingFactorsEnum);
+	femmodel->parameters->FindParam(&N,NULL,ControlInputSizeNEnum);
+	numberofvertices=femmodel->vertices->NumberOfVertices();
+
+	/*Constrain input vector and update controls*/
+	double  *XL = NULL;
+	double  *XU = NULL;
+	GetPassiveVectorFromControlInputsx(&XL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
+	GetPassiveVectorFromControlInputsx(&XU,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
+
+	N_add = 0;
+	for (int c=0;c<num_controls;c++){
+		for(int i=0;i<numberofvertices*N[c];i++){
+			int index = N_add*numberofvertices+i;
+			X[index] = X[index]*reCast<double>(scaling_factors[c]);
+			if(X[index]>XU[index]) X[index]=XU[index];
+			if(X[index]<XL[index]) X[index]=XL[index];
+		}
+	}
+
+	/*Start Tracing*/
+	simul_starttrace(femmodel);
+	/*Set X as our new control input and as INDEPENDENT*/
+#ifdef _HAVE_AD_
+	IssmDouble* aX=xNew<IssmDouble>(intn,"t");
+#else
+	IssmDouble* aX=xNew<IssmDouble>(intn);
+#endif
+	if(my_rank==0){
+		for(int i=0;i<intn;i++){
+			aX[i]<<=X[i];
+		}
+	}
+
+	ISSM_MPI_Bcast(aX,intn,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+	SetControlInputsFromVectorx(femmodel,aX);
+	xDelete<IssmDouble>(aX);
+	
+	/*Compute solution (forward)*/
+	void (*solutioncore)(FemModel*)=NULL;
+	CorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type);
+	solutioncore(femmodel);
+
+	/*Reset the time to zero for next optimization*/
+	if(solution_type==TransientSolutionEnum){
+		IssmDouble restart_time;
+		femmodel->parameters->FindParam(&restart_time,TimesteppingStartTimeEnum);
+		femmodel->parameters->SetParam(restart_time,TimeEnum);
+
+	}
+
+	/*Get Dependents*/
+	IssmDouble  output_value;
+	int         num_dependents;
+	IssmPDouble *dependents;
+	DataSet*    dependent_objects=NULL;
+	IssmDouble	J=0.;
+	femmodel->parameters->FindParam(&num_dependents,AutodiffNumDependentsEnum);
+	femmodel->parameters->FindParam(&dependent_objects,AutodiffDependentObjectsEnum);
+
+	/*Go through our dependent variables, and compute the response:*/
+	dependents=xNew<IssmPDouble>(num_dependents);
+	for(int i=0;i<dependent_objects->Size();i++){
+		DependentObject* dep=(DependentObject*)dependent_objects->GetObjectByOffset(i);
+		if(solution_type==TransientSolutionEnum) output_value = dep->GetValue();
+		if(solution_type!=TransientSolutionEnum) dep->Responsex(&output_value,femmodel);
+		if (my_rank==0) {
+			output_value>>=dependents[i];
+			J+=output_value;
+		}
+	}
+
+	/*Turning off trace tape*/
+	trace_off();
+
+	/*Print tape statistics so that user can kill this run if something is off already:*/
+	if(VerboseAutodiff()){ /*{{{*/
+		size_t  tape_stats[15];
+		tapestats(my_rank,tape_stats); //reading of tape statistics
+		int commSize=IssmComm::GetSize();
+		int *sstats=new int[7];
+		sstats[0]=tape_stats[NUM_OPERATIONS];
+		sstats[1]=tape_stats[OP_FILE_ACCESS];
+		sstats[2]=tape_stats[NUM_LOCATIONS];
+		sstats[3]=tape_stats[LOC_FILE_ACCESS];
+		sstats[4]=tape_stats[NUM_VALUES];
+		sstats[5]=tape_stats[VAL_FILE_ACCESS];
+		sstats[6]=tape_stats[TAY_STACK_SIZE];
+		int *rstats=NULL;
+		if (my_rank==0) rstats=new int[commSize*7];
+		ISSM_MPI_Gather(sstats,7,ISSM_MPI_INT,rstats,7,ISSM_MPI_INT,0,IssmComm::GetComm());
+		if (my_rank==0) {
+			int offset=50;
+			int rOffset=(commSize/10)+1;
+			_printf_("   ADOLC statistics: \n");
+			_printf_("     "<<setw(offset)<<left<<"#independents: " <<setw(12)<<right<<tape_stats[NUM_INDEPENDENTS] << "\n");
+			_printf_("     "<<setw(offset)<<left<<"#dependents: " <<setw(12)<<right<<tape_stats[NUM_DEPENDENTS] << "\n");
+			_printf_("     "<<setw(offset)<<left<<"max #live active variables: " <<setw(12)<<right<<tape_stats[NUM_MAX_LIVES] << "\n");
+			_printf_("     operations: entry size "<< sizeof(unsigned char) << " Bytes \n");
+			_printf_("     "<<setw(offset)<<left<<"  #entries in buffer (AutodiffObufsizeEnum) " <<setw(12)<<right<<tape_stats[OP_BUFFER_SIZE] << "\n");
+			for (int r=0;r<commSize;++r)
+			 _printf_("       ["<<setw(rOffset)<<right<<r<<"]"<<setw(offset-rOffset-4)<<left<<" #entries total" <<setw(12)<<right<<rstats[r*7+0] << (rstats[r*7+1]?" ->file":"") << "\n");
+			_printf_("     locations: entry size " << sizeof(locint) << " Bytes\n");
+			_printf_("     "<<setw(offset)<<left<<"  #entries in buffer (AutodiffLbufsizeEnum) " <<setw(12)<<right<<tape_stats[LOC_BUFFER_SIZE] << "\n");
+			for (int r=0;r<commSize;++r)
+			 _printf_("       ["<<setw(rOffset)<<right<<r<<"]"<<setw(offset-rOffset-4)<<left<<" #entries total" <<setw(12)<<right<<rstats[r*7+2] << (rstats[r*7+3]?" ->file":"") << "\n");
+			_printf_("     constant values: entry size " << sizeof(double) << " Bytes\n");
+			_printf_("     "<<setw(offset)<<left<<"  #entries in buffer (AutodiffCbufsizeEnum) " <<setw(12)<<right<<tape_stats[VAL_BUFFER_SIZE] << "\n");
+			for (int r=0;r<commSize;++r)
+			 _printf_("       ["<<setw(rOffset)<<right<<r<<"]"<<setw(offset-rOffset-4)<<left<<" #entries total" <<setw(12)<<right<<rstats[r*7+4] << (rstats[r*7+5]?" ->file":"") << "\n");
+			_printf_("     Taylor stack: entry size " << sizeof(revreal) << " Bytes\n");
+			_printf_("     "<<setw(offset)<<left<<"  #entries in buffer (AutodiffTbufsizeEnum) " <<setw(12)<<right<<tape_stats[TAY_BUFFER_SIZE] << "\n");
+			for (int r=0;r<commSize;++r)
+			 _printf_("       ["<<setw(rOffset)<<right<<r<<"]"<<setw(offset-rOffset-4)<<left<<" #entries total" <<setw(12)<<right<<rstats[r*7+6] << (rstats[r*7+6]>tape_stats[TAY_BUFFER_SIZE]?" ->file":"") << "\n");
+			delete []rstats;
+		}
+		delete [] sstats;
+	} /*}}}*/
+
+	/*diverse: */
+	int  dummy;
+	int  num_independents=0;
+
+	/*intermediary: */
+	IssmPDouble *aWeightVector=NULL;
+	IssmPDouble *weightVectorTimesJac=NULL;
+
+	/*output: */
+	IssmPDouble *totalgradient=NULL;
+
+	/*retrieve parameters: */
+	num_independents = intn;
+
+	/*if no dependents, no point in running a driver: */
+	if(!(num_dependents*num_independents)) _error_("this is not allowed");
+
+	/*for adolc to run in parallel, we 0 out on rank~=0. But we still keep track of num_dependents:*/
+	int num_dependents_old   = num_dependents;
+	int num_independents_old = num_independents;
+	if(my_rank!=0){
+		num_dependents   = 0;
+		num_independents = 0;
+	}
+
+	/*get the EDF pointer:*/
+	ext_diff_fct *anEDF_for_solverx_p=xDynamicCast<GenericParam<Adolc_edf> * >(femmodel->parameters->FindParamObject(AdolcParamEnum))->GetParameterValue().myEDF_for_solverx_p;
+
+	/* these are always needed regardless of the interpreter */
+	anEDF_for_solverx_p->dp_x=xNew<double>(anEDF_for_solverx_p->max_n);
+	anEDF_for_solverx_p->dp_y=xNew<double>(anEDF_for_solverx_p->max_m);
+
+	/* Ok, now we are going to call the fos_reverse in a loop on the index, from 0 to num_dependents, so
+	 * as to generate num_dependents gradients: */
+	totalgradient=xNewZeroInit<IssmPDouble>(num_independents_old);
+
+	for(int aDepIndex=0;aDepIndex<num_dependents_old;aDepIndex++){
+
+		/*initialize direction index in the weights vector: */
+		aWeightVector=xNewZeroInit<IssmPDouble>(num_dependents);
+		if (my_rank==0) aWeightVector[aDepIndex]=1.;
+
+		/*initialize output gradient: */
+		weightVectorTimesJac=xNew<IssmPDouble>(num_independents);
+
+		/*set the forward method function pointer: */
+		#ifdef _HAVE_GSL_
+		anEDF_for_solverx_p->fos_reverse=EDF_fos_reverse_for_solverx;
+		#endif
+		#ifdef _HAVE_MUMPS_
+		anEDF_for_solverx_p->fos_reverse_iArr=fos_reverse_mumpsSolveEDF;
+		#endif
+
+		anEDF_for_solverx_p->dp_U=xNew<IssmPDouble>(anEDF_for_solverx_p->max_m);
+		anEDF_for_solverx_p->dp_Z=xNew<IssmPDouble>(anEDF_for_solverx_p->max_n);
+
+		/*call driver: */
+		fos_reverse(my_rank,num_dependents,num_independents, aWeightVector, weightVectorTimesJac );
+
+		/*Add to totalgradient: */
+		if(my_rank==0) for(int i=0;i<num_independents;i++) {
+			totalgradient[i]+=weightVectorTimesJac[i];
+		}
+
+		/*free resources :*/
+		xDelete(weightVectorTimesJac);
+		xDelete(aWeightVector);
+	}
+
+	/*Broadcast gradient to other ranks*/
+	ISSM_MPI_Bcast(totalgradient,num_independents_old,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm());
+	/*Check size of Jlist to avoid crashes*/
+	_assert_((*Jlisti)<JlistM);
+	_assert_(JlistN==num_responses+1);
+
+	/*Compute objective function and broadcast it to other cpus*/
+	*pf = reCast<double>(J);
+	ISSM_MPI_Bcast(pf,1,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm());
+	_printf0_("f(x) = "<<setw(12)<<setprecision(7)<<*pf<<"  |  ");
+
+	/*Record cost function values and delete Jtemp*/
+	for(int i=0;i<num_responses;i++) Jlist[(*Jlisti)*JlistN+i] = reCast<IssmPDouble>(dependents[i]);
+	Jlist[(*Jlisti)*JlistN+num_responses] = reCast<IssmPDouble>(J);
+
+	if(*indic==0){
+		/*dry run, no gradient required*/
+
+		/*Retrieve objective functions independently*/
+		_printf0_("            N/A |\n");
+		for(int i=0;i<num_responses;i++) _printf0_(" "<<setw(12)<<setprecision(7)<<Jlist[(*Jlisti)*JlistN+i]);
+		_printf0_("\n");
+
+		*Jlisti = (*Jlisti) +1;
+		xDelete<double>(XU);
+		xDelete<double>(XL);
+		return;
+	}
+
+	/*Compute gradient*/
+	for(long i=0;i<num_independents_old;i++) G[i] = totalgradient[i];
+
+	/*Constrain Gradient*/
+	IssmDouble  Gnorm = 0.;
+	N_add = 0;
+	for (int c=0;c<num_controls;c++){
+		for(int i=0;i<numberofvertices*N[c];i++){
+			int index = N_add*numberofvertices+i;
+			if(X[index]>=XU[index]) G[index]=0.;
+			if(X[index]<=XL[index]) G[index]=0.;
+			G[index] = G[index]*reCast<double>(scaling_factors[c]);
+			X[index] = X[index]/reCast<double>(scaling_factors[c]);
+			Gnorm += G[index]*G[index];
+		}
+	}
+	Gnorm = sqrt(Gnorm);
+
+	/*Print info*/
+	_printf0_("       "<<setw(12)<<setprecision(7)<<Gnorm<<" |");
+	for(int i=0;i<num_responses;i++) _printf0_(" "<<setw(12)<<setprecision(7)<<Jlist[(*Jlisti)*JlistN+i]);
+	_printf0_("\n");
+
+	/*Clean-up and return*/
+	*Jlisti = (*Jlisti) +1;
+	xDelete<double>(XU);
+	xDelete<double>(XL);
+	xDelete<IssmDouble>(scaling_factors);
+	xDelete<IssmPDouble>(totalgradient);
+
+}/*}}}*/
+void controladm1qn3_core(FemModel* femmodel){/*{{{*/
+
+	/*Intermediaries*/
+	long         omode;
+	double		 f;
+	double		 dxmin,gttol; 
+	int          maxsteps,maxiter;
+	int          intn,numberofvertices,num_controls,num_cost_functions,solution_type;
+	IssmDouble	*scaling_factors = NULL;
+	double      *X  = NULL;
+	double      *G  = NULL;
+	int*			N	= NULL;
+	int offset = 0;
+	int N_add;
+
+	/*Recover some parameters*/
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+	femmodel->parameters->FindParam(&num_cost_functions,InversionNumCostFunctionsEnum);
+	femmodel->parameters->FindParam(&maxsteps,InversionMaxstepsEnum);
+	femmodel->parameters->FindParam(&maxiter,InversionMaxiterEnum);
+	femmodel->parameters->FindParamAndMakePassive(&dxmin,InversionDxminEnum);
+	femmodel->parameters->FindParamAndMakePassive(&gttol,InversionGttolEnum);
+	femmodel->parameters->FindParam(&scaling_factors,NULL,InversionControlScalingFactorsEnum);
+	femmodel->parameters->SetParam(false,SaveResultsEnum);
+	femmodel->parameters->FindParam(&N,NULL,ControlInputSizeNEnum);
+	numberofvertices=femmodel->vertices->NumberOfVertices();
+
+	/*Initialize M1QN3 parameters*/
+	if(VerboseControl())_printf0_("   Initialize M1QN3 parameters\n");
+	SimulFunc simul_ptr    = &simul_ad; /*Cost function address*/
+	void**    prosca       = &euclid_;  /*Dot product function (euclid is the default)*/
+	char      normtype[]   = "dfn";     /*Norm type: dfn = scalar product defined by prosca*/
+	long      izs[5];                   /*Arrays used by m1qn3 subroutines*/
+	long      iz[5];                    /*Integer m1qn3 working array of size 5*/
+	float     rzs[1];                   /*Arrays used by m1qn3 subroutines*/
+	long      impres       = 0;         /*verbosity level*/
+	long      imode[3]     = {0};       /*scaling and starting mode, 0 by default*/
+	long      indic        = 4;         /*compute f and g*/
+	long      reverse      = 0;         /*reverse or direct mode*/
+	long      io           = 6;         /*Channel number for the output*/
+
+	/*Optimization criterions*/
+	long niter = long(maxsteps); /*Maximum number of iterations*/
+	long nsim  = long(maxiter);/*Maximum number of function calls*/
+	
+	/*Get initial guess*/
+	Vector<double> *Xpetsc = NULL;
+
+	GetPassiveVectorFromControlInputsx(&Xpetsc,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"value");
+	X = Xpetsc->ToMPISerial();
+	Xpetsc->GetSize(&intn);
+	delete Xpetsc;
+	//_assert_(intn==numberofvertices*num_controls);
+ 
+	/*Get problem dimension and initialize gradient and initial guess*/
+	long n = long(intn);
+	G = xNew<double>(n);
+
+	/*Scale control for M1QN3*/
+	N_add = 0;
+	for (int c=0;c<num_controls;c++){
+		for(int i=0;i<numberofvertices*N[c];i++){
+			int index = N_add*numberofvertices+i;
+			X[index] = X[index]/reCast<IssmPDouble>(scaling_factors[c]);
+		}
+		N_add+=N[c];
+	}
+	
+	/*Allocate m1qn3 working arrays (see documentation)*/
+	long      m   = 100;
+	long      ndz = 4*n+m*(2*n+1);
+	double*   dz  = xNew<double>(ndz);
+
+	if(VerboseControl())_printf0_("   Computing initial solution\n");
+	_printf0_("\n");
+	_printf0_("Cost function f(x)   | Gradient norm |g(x)| |  List of contributions\n");
+	_printf0_("____________________________________________________________________\n");
+
+	/*Prepare structure for m1qn3*/
+	m1qn3_struct mystruct;
+	mystruct.femmodel = femmodel;
+	mystruct.M        = maxiter;
+	mystruct.N        = num_cost_functions+1;
+	mystruct.Jlist    = xNewZeroInit<IssmPDouble>(mystruct.M*mystruct.N);
+	mystruct.i        = xNewZeroInit<int>(1);
+	/*Initialize Gradient and cost function of M1QN3*/
+	indic = 4; /*gradient required*/
+	simul_ad(&indic,&n,X,&f,G,izs,rzs,(void*)&mystruct);
+	/*Estimation of the expected decrease in f during the first iteration*/
+	double df1=f;
+
+	/*Call M1QN3 solver*/
+	m1qn3_(simul_ptr,prosca,&ctonbe_,&ctcabe_,
+				&n,X,&f,G,&dxmin,&df1,
+				&gttol,normtype,&impres,&io,imode,&omode,&niter,&nsim,iz,dz,&ndz,
+				&reverse,&indic,izs,rzs,(void*)&mystruct);
+	switch(int(omode)){
+		case 0:  _printf0_("   Stop requested (indic = 0)\n"); break;
+		case 1:  _printf0_("   Convergence reached (gradient satisfies stopping criterion)\n"); break;
+		case 2:  _printf0_("   Bad initialization\n"); break;
+		case 3:  _printf0_("   Line search failure\n"); break;
+		case 4:  _printf0_("   Maximum number of iterations exceeded\n");break;
+		case 5:  _printf0_("   Maximum number of function calls exceeded\n"); break;
+		case 6:  _printf0_("   stopped on dxmin during line search\n"); break;
+		case 7:  _printf0_("   <g,d> > 0  or  <y,s> <0\n"); break;
+		default: _printf0_("   Unknown end condition\n");
+	}
+
+	/*Constrain solution vector*/
+	double  *XL = NULL;
+	double  *XU = NULL;
+	GetPassiveVectorFromControlInputsx(&XL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
+	GetPassiveVectorFromControlInputsx(&XU,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
+
+	N_add = 0;
+	for (int c=0;c<num_controls;c++){
+		for(int i=0;i<numberofvertices*N[c];i++){
+			int index = N_add*numberofvertices+i;
+			X[index] = X[index]*reCast<double>(scaling_factors[c]);
+			if(X[index]>XU[index]) X[index]=XU[index];
+			if(X[index]<XL[index]) X[index]=XL[index];
+		}
+		N_add +=N[c];
+	}
+		
+	/*Set X as our new control*/
+	IssmDouble* aX=xNew<IssmDouble>(intn);
+	for(int i=0;i<intn;i++) {
+		aX[i] = reCast<IssmDouble>(X[i]); 
+		}
+	SetControlInputsFromVectorx(femmodel,aX);
+	xDelete(aX);
+
+	/*Set final gradient in inputs*/
+	IssmDouble* aG=xNew<IssmDouble>(intn);
+	for(int i=0;i<intn;i++) {
+		aG[i] = reCast<IssmDouble>(G[i]);
+	}
+	ControlInputSetGradientx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,aG);
+
+	if (solution_type == TransientSolutionEnum){
+		int step = 1;
+		femmodel->parameters->SetParam(step,StepEnum);
+		femmodel->OutputControlsx(&femmodel->results);
+		femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,JEnum,mystruct.Jlist,(*mystruct.i),mystruct.N,1,0));
+		femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,Gradient1Enum,G,numberofvertices,intn/numberofvertices,1,0));
+		femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,InversionControlParametersEnum,X,numberofvertices,intn/numberofvertices,1,0));
+	}
+	else{
+		femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,JEnum,mystruct.Jlist,(*mystruct.i),mystruct.N,0,0));
+
+	femmodel->OutputControlsx(&femmodel->results);
+	}
+
+	xDelete(aG);
+
+	/*Add last cost function to results*/
+
+	/*Finalize*/
+	if(VerboseControl()) _printf0_("   preparing final solution\n");
+	femmodel->parameters->SetParam(true,SaveResultsEnum);
+	void (*solutioncore)(FemModel*)=NULL;
+	CorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type);
+	solutioncore(femmodel);
+
+	/*Clean-up and return*/
+	xDelete<double>(G);
+	xDelete<double>(X);
+	xDelete<double>(dz);
+	xDelete<double>(XU);
+	xDelete<double>(XL);
+	xDelete<IssmDouble>(scaling_factors);
+	xDelete<IssmPDouble>(mystruct.Jlist);
+	xDelete<int>(mystruct.i);
+}/*}}}*/
+
+#else
+void controladm1qn3_core(FemModel* femmodel){_error_("M1QN3 or ADOLC not installed");}
+#endif //_HAVE_M1QN3_
Index: /issm/trunk/src/c/cores/controlm1qn3_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/controlm1qn3_core.cpp	(revision 22757)
+++ /issm/trunk/src/c/cores/controlm1qn3_core.cpp	(revision 22758)
@@ -11,5 +11,5 @@
 #include "../solutionsequences/solutionsequences.h"
 
-#if defined (_HAVE_M1QN3_) & !defined(_HAVE_ADOLC_)
+#if defined (_HAVE_M1QN3_) && !defined(_HAVE_ADOLC_)
 /*m1qn3 prototypes*/
 extern "C" void *ctonbe_; // DIS mode : Conversion
Index: /issm/trunk/src/c/cores/controlvalidation_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/controlvalidation_core.cpp	(revision 22757)
+++ /issm/trunk/src/c/cores/controlvalidation_core.cpp	(revision 22758)
@@ -104,3 +104,4 @@
 	xDelete<IssmDouble>(X);
 	xDelete<IssmDouble>(X0);
+	xDelete<IssmDouble>(scaling_factors);
 }
Index: /issm/trunk/src/c/cores/cores.h
===================================================================
--- /issm/trunk/src/c/cores/cores.h	(revision 22757)
+++ /issm/trunk/src/c/cores/cores.h	(revision 22758)
@@ -30,4 +30,5 @@
 void controltao_core(FemModel* femmodel);
 void controlm1qn3_core(FemModel* femmodel);
+void controladm1qn3_core(FemModel* femmodel);
 void controlad_core(FemModel* femmodel);
 void controlvalidation_core(FemModel* femmodel);
@@ -47,4 +48,5 @@
 void dummy_core(FemModel* femmodel);
 void gia_core(FemModel* femmodel);
+void love_core(FemModel* femmodel);
 void esa_core(FemModel* femmodel);
 void smb_core(FemModel* femmodel);
Index: /issm/trunk/src/c/cores/depthaverage_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/depthaverage_core.cpp	(revision 22757)
+++ /issm/trunk/src/c/cores/depthaverage_core.cpp	(revision 22758)
@@ -16,5 +16,5 @@
 	int inputenum,input_average_enum;
 
-	if(VerboseSolution()) _printf0_("depth averaging solution...\n");
+	if(VerboseSolution()) _printf0_("   depth averaging solution...\n");
 
 	/*Get parameters*/
Index: /issm/trunk/src/c/cores/esa_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/esa_core.cpp	(revision 22757)
+++ /issm/trunk/src/c/cores/esa_core.cpp	(revision 22758)
@@ -15,4 +15,6 @@
 	Vector<IssmDouble> *U_north   = NULL; 
 	Vector<IssmDouble> *U_east    = NULL; 
+	Vector<IssmDouble> *U_x   = NULL; 
+	Vector<IssmDouble> *U_y    = NULL; 
 	bool save_results,isesa,iscoupler;
 	int configuration_type;
@@ -76,4 +78,6 @@
 		U_north = new Vector<IssmDouble>(gsize);
 		U_east = new Vector<IssmDouble>(gsize);
+		U_x = new Vector<IssmDouble>(gsize);
+		U_y = new Vector<IssmDouble>(gsize);
 		
 		/*call the geodetic main modlule:*/ 
@@ -82,5 +86,7 @@
 		}
 		if(domaintype==Domain2DhorizontalEnum){
-			femmodel->EsaGeodetic2D(U_radial,U_north,U_east,xx,yy); 
+			femmodel->EsaGeodetic2D(U_radial,U_north,U_east,U_x,U_y,xx,yy); 
+			InputUpdateFromVectorx(femmodel,U_x,EsaXmotionEnum,VertexSIdEnum);
+			InputUpdateFromVectorx(femmodel,U_y,EsaYmotionEnum,VertexSIdEnum);
 		}
 
@@ -102,4 +108,6 @@
 		delete U_north;
 		delete U_east;
+		delete U_x; 
+		delete U_y; 
 		if(numoutputs){for(int i=0;i<numoutputs;i++){xDelete<char>(requested_outputs[i]);} xDelete<char*>(requested_outputs);}
 	}
Index: /issm/trunk/src/c/cores/extrudefrombase_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/extrudefrombase_core.cpp	(revision 22757)
+++ /issm/trunk/src/c/cores/extrudefrombase_core.cpp	(revision 22758)
@@ -15,5 +15,5 @@
 	int elementtype,domaintype;
 
-	if(VerboseSolution()) _printf0_("extruding solution from base...\n");
+	if(VerboseSolution()) _printf0_("   extruding solution from base...\n");
 
 	/*Get parameters*/
Index: /issm/trunk/src/c/cores/extrudefromtop_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/extrudefromtop_core.cpp	(revision 22757)
+++ /issm/trunk/src/c/cores/extrudefromtop_core.cpp	(revision 22758)
@@ -15,5 +15,5 @@
 	int elementtype,domaintype;
 
-	if(VerboseSolution()) _printf0_("extruding solution from top...\n");
+	if(VerboseSolution()) _printf0_("   extruding solution from top...\n");
 
 	/*Get parameters*/
Index: /issm/trunk/src/c/cores/gia_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/gia_core.cpp	(revision 22757)
+++ /issm/trunk/src/c/cores/gia_core.cpp	(revision 22758)
@@ -56,5 +56,3 @@
 	xDelete<IssmDouble>(x);
 	xDelete<IssmDouble>(y);
-
-
 }
Index: /issm/trunk/src/c/cores/hydrology_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/hydrology_core.cpp	(revision 22757)
+++ /issm/trunk/src/c/cores/hydrology_core.cpp	(revision 22758)
@@ -14,22 +14,23 @@
 	/*intermediary*/
 	int  hydrology_model;
+	int  solution_type;
+	int  numoutputs=0;
 	bool save_results;
 	bool modify_loads=true;
-	bool isefficientlayer;
+	char **requested_outputs = NULL;
 
 	/*first recover parameters common to all solutions*/
 	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
 	femmodel->parameters->FindParam(&hydrology_model,HydrologyModelEnum);
-	
-	if(VerboseSolution()) _printf0_("   computing water heads\n");
-			
-	/*first compute slopes: */
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);	
+	femmodel->parameters->FindParam(&numoutputs,HydrologyNumRequestedOutputsEnum);
+	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,HydrologyRequestedOutputsEnum);
+	/*Using the Shreve based Model*/
 	if (hydrology_model==HydrologyshreveEnum){
+		if(VerboseSolution()) _printf0_("   computing water heads\n");
+		/*first compute slopes: */
 		surfaceslope_core(femmodel);
 		bedslope_core(femmodel);
-	}
-
-	/*Using the Shreve based Model*/
-	if (hydrology_model==HydrologyshreveEnum){
+		/*and then go to water column*/
 		if(VerboseSolution()) _printf0_("   computing water column\n");
 		femmodel->SetCurrentConfiguration(HydrologyShreveAnalysisEnum);
@@ -39,66 +40,97 @@
 		InputDuplicatex(femmodel,WatercolumnEnum,WaterColumnOldEnum);
 		
-		if(save_results){
-			if(VerboseSolution()) _printf0_("   saving results \n");
-			int outputs[3] = {WatercolumnEnum,HydrologyWaterVxEnum,HydrologyWaterVyEnum};
-			femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],3);
-			
-			/*unload results*/
-			if(VerboseSolution()) _printf0_("   saving temporary results\n");
-			OutputResultsx(femmodel);
-		}
 	}
 
 	/*Using the double continuum model*/
 	else if (hydrology_model==HydrologydcEnum){
-		InputDuplicatex(femmodel,SedimentHeadEnum,SedimentHeadOldEnum);
+		/*intermediary: */
+		bool       isefficientlayer;
+		int        step,hydroslices;
+		IssmDouble time,init_time,hydrotime,yts;
+		IssmDouble dt,hydrodt;
+
 		femmodel->parameters->FindParam(&isefficientlayer,HydrologydcIsefficientlayerEnum);
-		if (isefficientlayer){
-			InputDuplicatex(femmodel,EplHeadEnum,EplHeadOldEnum);
-			InputDuplicatex(femmodel,HydrologydcEplThicknessEnum,HydrologydcEplThicknessOldEnum);
-		}
-		
-		/*Proceed now to heads computations*/
-		solutionsequence_hydro_nonlinear(femmodel);
+		femmodel->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+		femmodel->parameters->FindParam(&step,StepEnum);
+		femmodel->parameters->FindParam(&time,TimeEnum);
+		femmodel->parameters->FindParam(&hydroslices,HydrologyStepsPerStepEnum);
+		femmodel->parameters->FindParam(&yts,ConstantsYtsEnum);
 
-		if(save_results){
-			if(VerboseSolution()) _printf0_("   saving results \n");
-			if(isefficientlayer){
-				int outputs[9] = {SedimentHeadEnum,SedimentHeadResidualEnum,EplHeadEnum,HydrologydcMaskEplactiveNodeEnum,HydrologydcMaskEplactiveEltEnum,EplHeadSlopeXEnum,EplHeadSlopeYEnum,HydrologydcEplThicknessEnum,EffectivePressureEnum};
-				femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],9);
+		init_time = time-dt; //getting the time back to the start of the timestep
+		hydrotime=init_time;
+		hydrodt=dt/hydroslices; //computing hydro dt from dt and a divider
+		femmodel->parameters->AddObject(new DoubleParam(HydrologydtEnum,hydrodt));
+		if(hydroslices>1){
+			/*define which variable needs to be averaged on the sub-timestep and initialize as needed*/
+			if (isefficientlayer){
+				int inputtostack[4]={EffectivePressureEnum,SedimentHeadEnum,EplHeadEnum,HydrologydcEplThicknessEnum};
+				int stackedinput[4]={EffectivePressureStackedEnum,SedimentHeadStackedEnum,EplHeadStackedEnum,HydrologydcEplThicknessStackedEnum};
+				int averagedinput[4]={EffectivePressureTimeAverageEnum,SedimentHeadTimeAverageEnum,EplHeadTimeAverageEnum,HydrologydcEplThicknessTimeAverageEnum};
+				femmodel->InitTransientOutputx(&stackedinput[0],4);
+				while(hydrotime<time-(yts*DBL_EPSILON)){ //loop on hydro dts
+					hydrotime+=hydrodt;
+					/*save preceding timestep*/
+					InputDuplicatex(femmodel,SedimentHeadEnum,SedimentHeadOldEnum);
+					InputDuplicatex(femmodel,EplHeadEnum,EplHeadOldEnum);
+					InputDuplicatex(femmodel,HydrologydcEplThicknessEnum,HydrologydcEplThicknessOldEnum);
+					/*Proceed now to heads computations*/
+					solutionsequence_hydro_nonlinear(femmodel);
+					/*If we have a sub-timestep we stack the variables here*/
+					femmodel->StackTransientOutputx(&inputtostack[0],&stackedinput[0],hydrotime,4);
+				}
+				femmodel->AverageTransientOutputx(&stackedinput[0],&averagedinput[0],init_time,4);
 			}
 			else{
-				int outputs[3] = {SedimentHeadEnum,SedimentHeadResidualEnum,EffectivePressureEnum};
-				femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],3);
+				int inputtostack[2]={EffectivePressureEnum,SedimentHeadEnum};
+				int stackedinput[2]={EffectivePressureStackedEnum,SedimentHeadStackedEnum};
+				int averagedinput[2]={EffectivePressureTimeAverageEnum,SedimentHeadTimeAverageEnum};
+				femmodel->InitTransientOutputx(&stackedinput[0],2);
+				while(hydrotime<time-(yts*DBL_EPSILON)){ //loop on hydro dts
+					hydrotime+=hydrodt;
+					/*save preceding timestep*/
+					InputDuplicatex(femmodel,SedimentHeadEnum,SedimentHeadOldEnum);
+					InputDuplicatex(femmodel,EplHeadEnum,EplHeadOldEnum);
+					InputDuplicatex(femmodel,HydrologydcEplThicknessEnum,HydrologydcEplThicknessOldEnum);
+					/*Proceed now to heads computations*/
+					solutionsequence_hydro_nonlinear(femmodel);
+					/*If we have a sub-timestep we stack the variables here*/
+					femmodel->StackTransientOutputx(&inputtostack[0],&stackedinput[0],hydrotime,2);
+				}
+				femmodel->AverageTransientOutputx(&stackedinput[0],&averagedinput[0],init_time,2);
 			}
-			/*unload results*/
-			if(VerboseSolution()) _printf0_("   saving temporary results\n");
-			OutputResultsx(femmodel);
+		}
+		else{
+			InputDuplicatex(femmodel,SedimentHeadEnum,SedimentHeadOldEnum);
+			if (isefficientlayer){
+				InputDuplicatex(femmodel,EplHeadEnum,EplHeadOldEnum);
+				InputDuplicatex(femmodel,HydrologydcEplThicknessEnum,HydrologydcEplThicknessOldEnum);
+			}
+			/*Proceed now to heads computations*/
+			solutionsequence_hydro_nonlinear(femmodel);
 		}
 	}
-
 	else if (hydrology_model==HydrologysommersEnum){	
 		femmodel->SetCurrentConfiguration(HydrologySommersAnalysisEnum);	
       InputDuplicatex(femmodel,HydrologyHeadEnum,HydrologyHeadOldEnum);	
-		solutionsequence_nonlinear(femmodel,modify_loads); 
+		solutionsequence_shakti_nonlinear(femmodel); 
 		if(VerboseSolution()) _printf0_("   updating gap height\n");
 		HydrologySommersAnalysis* analysis = new HydrologySommersAnalysis();
 		analysis->UpdateGapHeight(femmodel);
 		delete analysis;
-		
-		if(save_results){
-			if(VerboseSolution()) _printf0_("   saving results \n");
-			int outputs[4] = {HydrologyHeadEnum,HydrologyGapHeightEnum,EffectivePressureEnum,HydrologyBasalFluxEnum};
-			femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],4);
-			
-			/*unload results*/
-			if(VerboseSolution()) _printf0_("   saving temporary results\n");
-			OutputResultsx(femmodel);
-		}
 	}
-
 	else{
 		_error_("Hydrology model "<< EnumToStringx(hydrology_model) <<" not supported yet");
 	}
+	if(save_results){
+		if(VerboseSolution()) _printf0_("   saving results \n");
+		femmodel->RequestedOutputsx(&femmodel->results,requested_outputs,numoutputs);
+	}
+	/*Free ressources:*/	
+	if(numoutputs){
+		for(int i=0;i<numoutputs;i++){
+			xDelete<char>(requested_outputs[i]);
+		}
+		xDelete<char*>(requested_outputs);
+	}
 }
 
Index: /issm/trunk/src/c/cores/levelsetfunctionslope_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/levelsetfunctionslope_core.cpp	(revision 22757)
+++ /issm/trunk/src/c/cores/levelsetfunctionslope_core.cpp	(revision 22758)
@@ -36,17 +36,3 @@
 		extrudefrombase_core(femmodel);
 	}
-
-	if(save_results){
-		if(VerboseSolution()) _printf0_("saving results:\n");
-		if(domaintype!=Domain2DverticalEnum){
-			int outputs[2] = {LevelsetfunctionSlopeXEnum,LevelsetfunctionSlopeYEnum};
-			femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],2);
-
-		}
-		else{
-			int outputs = LevelsetfunctionSlopeXEnum;
-			femmodel->RequestedOutputsx(&femmodel->results,&outputs,1);
-		}
-	}
-
 }
Index: /issm/trunk/src/c/cores/love_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/love_core.cpp	(revision 22758)
+++ /issm/trunk/src/c/cores/love_core.cpp	(revision 22758)
@@ -0,0 +1,98 @@
+/*!\file: love_core.cpp
+ * \brief: core of the LOVE numbers solution 
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+void love_core(FemModel* femmodel){
+
+	Vector<IssmDouble> *wg    = NULL;
+	Vector<IssmDouble> *dwdtg = NULL;
+	IssmDouble          *x    = NULL;
+	IssmDouble          *y    = NULL;
+
+	/*love parameters: */
+	IssmDouble *frequencies = NULL;
+	int         nfreq,dummy;
+	int         sh_nmin,sh_nmax;
+	IssmDouble  g0,r0,mu0;
+	bool        allow_layer_deletion;
+	bool        love_kernels;
+	int         forcing_type;
+	bool        verbosemod = (int)VerboseModule();
+
+	/*parameters: */
+	bool save_results;
+	
+	if(VerboseSolution()) _printf0_("   computing LOVE numbers\n");
+
+	/*Recover some parameters: */
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+	
+	/*recover love number parameters: */
+	femmodel->parameters->FindParam(&nfreq,LoveNfreqEnum);
+	femmodel->parameters->FindParam(&frequencies,&dummy,LoveFrequenciesEnum); _assert_(nfreq==dummy);
+	femmodel->parameters->FindParam(&sh_nmax,LoveShNmaxEnum);
+	femmodel->parameters->FindParam(&sh_nmin,LoveShNminEnum);
+	femmodel->parameters->FindParam(&g0,LoveG0Enum);
+	femmodel->parameters->FindParam(&r0,LoveR0Enum);
+	femmodel->parameters->FindParam(&mu0,LoveMu0Enum);
+	femmodel->parameters->FindParam(&allow_layer_deletion,LoveAllowLayerDeletionEnum);
+	femmodel->parameters->FindParam(&love_kernels,LoveKernelsEnum);
+	femmodel->parameters->FindParam(&forcing_type,LoveForcingTypeEnum);
+	
+	/*recover materials parameters: there is only one Matlitho, chase it down the hard way:*/
+	Matlitho* matlitho=NULL;
+	for (int i=femmodel->materials->Size()-1;i>=0;i--){
+		Material* material=xDynamicCast<Material*>(femmodel->materials->GetObjectByOffset(i));
+		if (material->ObjectEnum()==MatlithoEnum)matlitho=xDynamicCast<Matlitho*>(material);
+	}
+	_assert_(matlitho);
+
+	/*Initialize three love matrices: geoid, vertical and horizontal displacement (real and imaginary parts) */
+	IssmDouble*  LoveKr = xNewZeroInit<IssmDouble>(nfreq*(sh_nmax+1));
+	IssmDouble*  LoveHr = xNewZeroInit<IssmDouble>(nfreq*(sh_nmax+1));
+	IssmDouble*  LoveLr = xNewZeroInit<IssmDouble>(nfreq*(sh_nmax+1));
+	IssmDouble*  LoveKi = xNewZeroInit<IssmDouble>(nfreq*(sh_nmax+1));
+	IssmDouble*  LoveHi = xNewZeroInit<IssmDouble>(nfreq*(sh_nmax+1));
+	IssmDouble*  LoveLi = xNewZeroInit<IssmDouble>(nfreq*(sh_nmax+1));
+
+	/*Initialize love kernels (real and imaginary parts): */
+	IssmDouble*  LoveKernelsReal = xNewZeroInit<IssmDouble>(nfreq*(sh_nmax+1)*(matlitho->numlayers+1)*6);
+	IssmDouble*  LoveKernelsImag = xNewZeroInit<IssmDouble>(nfreq*(sh_nmax+1)*(matlitho->numlayers+1)*6);
+
+	/*call the main module: */
+	FourierLoveCorex(LoveKr,LoveKi,LoveHr,LoveHi,LoveLr,LoveLi,LoveKernelsReal,LoveKernelsImag,  //output
+			nfreq,frequencies,sh_nmax,sh_nmin,g0,r0,mu0,allow_layer_deletion,forcing_type,verbosemod, //parameter inputs
+			matlitho->numlayers, matlitho->radius, matlitho->viscosity, matlitho->lame_lambda, matlitho->lame_mu, 
+			matlitho->burgers_viscosity, matlitho->burgers_mu, matlitho->density, matlitho->isburgers, matlitho->issolid //matlitho inputs
+			); 
+
+	/*Add love matrices to results:*/
+	femmodel->results->AddObject(new GenericExternalResult<IssmDouble*>(femmodel->results->Size()+1,LoveKrEnum,LoveKr,sh_nmax+1,nfreq,0,0));
+	femmodel->results->AddObject(new GenericExternalResult<IssmDouble*>(femmodel->results->Size()+1,LoveHrEnum,LoveHr,sh_nmax+1,nfreq,0,0));
+	femmodel->results->AddObject(new GenericExternalResult<IssmDouble*>(femmodel->results->Size()+1,LoveLrEnum,LoveLr,sh_nmax+1,nfreq,0,0));
+	femmodel->results->AddObject(new GenericExternalResult<IssmDouble*>(femmodel->results->Size()+1,LoveKiEnum,LoveKi,sh_nmax+1,nfreq,0,0));
+	femmodel->results->AddObject(new GenericExternalResult<IssmDouble*>(femmodel->results->Size()+1,LoveHiEnum,LoveHi,sh_nmax+1,nfreq,0,0));
+	femmodel->results->AddObject(new GenericExternalResult<IssmDouble*>(femmodel->results->Size()+1,LoveLiEnum,LoveLi,sh_nmax+1,nfreq,0,0));
+	/*Only when love_kernels is set unity*/
+	if (love_kernels==1) {
+		femmodel->results->AddObject(new GenericExternalResult<IssmDouble*>(femmodel->results->Size()+1,LoveKernelsRealEnum,LoveKernelsReal,(sh_nmax+1)*(matlitho->numlayers+1)*6,nfreq,0,0));
+		femmodel->results->AddObject(new GenericExternalResult<IssmDouble*>(femmodel->results->Size()+1,LoveKernelsImagEnum,LoveKernelsImag,(sh_nmax+1)*(matlitho->numlayers+1)*6,nfreq,0,0));
+	}
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(frequencies);
+	xDelete<IssmDouble>(LoveKr);
+	xDelete<IssmDouble>(LoveHr);
+	xDelete<IssmDouble>(LoveLr);
+	xDelete<IssmDouble>(LoveKi);
+	xDelete<IssmDouble>(LoveHi);
+	xDelete<IssmDouble>(LoveLi);
+	xDelete<IssmDouble>(LoveKernelsReal);
+	xDelete<IssmDouble>(LoveKernelsImag);
+}
Index: sm/trunk/src/c/cores/meshdeformation_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/meshdeformation_core.cpp	(revision 22757)
+++ 	(revision )
@@ -1,30 +1,0 @@
-/*!\file: meshdeformation_core.cpp
- * \brief: core of the slope solution 
- */ 
-
-#include "./cores.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../solutionsequences/solutionsequences.h"
-#include "../modules/modules.h"
-
-void meshdeformation_core(FemModel* femmodel){
-
-	/*parameters: */
-	bool save_results;
-
-	/*Recover some parameters: */
-	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
-
-	if(VerboseSolution()) _printf0_("computing mesh deformation (elasticity)...\n");
-
-	/*Call on core computations: */
-	femmodel->SetCurrentConfiguration(MeshdeformationAnalysisEnum);
-	solutionsequence_linear(femmodel);
-
-	if(save_results){
-		if(VerboseSolution()) _printf0_("saving results:\n");
-	}
-
-}
Index: /issm/trunk/src/c/cores/movingfront_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/movingfront_core.cpp	(revision 22757)
+++ /issm/trunk/src/c/cores/movingfront_core.cpp	(revision 22758)
@@ -40,5 +40,10 @@
 	/* determine variables for extrapolation */
 	num_extrapol_vars=0;
-	if(isstressbalance) num_extrapol_vars+=2;
+	if(isstressbalance){
+		if(domaintype==Domain3DEnum)
+		 num_extrapol_vars+=3;
+		else
+		 num_extrapol_vars+=2;
+	}
 	if(ismasstransport) num_extrapol_vars+=1;
 	if(isthermal && domaintype==Domain3DEnum) num_extrapol_vars+=1;
@@ -48,9 +53,18 @@
 		extrapol_vars[index]=VxEnum; index++;
 		extrapol_vars[index]=VyEnum; index++;
+		if(domaintype==Domain3DEnum){
+			extrapol_vars[index]=VzEnum; index++;
+		}
 	}
-	if(ismasstransport){extrapol_vars[index]=ThicknessEnum; index++;}
+	if(ismasstransport){
+		extrapol_vars[index]=ThicknessEnum; index++;
+	}
 	if(isthermal && domaintype==Domain3DEnum){
-		if(isenthalpy){extrapol_vars[index]=EnthalpyEnum;}
-		else{extrapol_vars[index]=TemperatureEnum;}
+		if(isenthalpy){
+			extrapol_vars[index]=EnthalpyEnum;
+		}
+		else{
+			extrapol_vars[index]=TemperatureEnum;
+		}
 		index++;
 	}
Index: /issm/trunk/src/c/cores/sealevelrise_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/sealevelrise_core.cpp	(revision 22757)
+++ /issm/trunk/src/c/cores/sealevelrise_core.cpp	(revision 22758)
@@ -15,4 +15,5 @@
 	Vector<IssmDouble> *Sg_absolute  = NULL; 
 	Vector<IssmDouble> *Sg_eustatic  = NULL; 
+	Vector<IssmDouble> *steric_rate_g  = NULL; 
 	Vector<IssmDouble> *U_radial  = NULL; 
 	Vector<IssmDouble> *U_north   = NULL; 
@@ -33,4 +34,5 @@
 	IssmDouble          *yy     = NULL;
 	IssmDouble          *zz     = NULL;
+	IssmDouble          dt;
 
 	/*Recover some parameters: */
@@ -80,8 +82,4 @@
 
 		Sg=sealevelrise_core_noneustatic(femmodel,Sg_eustatic); //ocean loading tems  (2nd and 5th terms on the RHS of Farrel and Clark)
-		
-		/*get results into elements:*/
-		//InputUpdateFromSolutionx(femmodel,Sg);		// from Eric 
-		InputUpdateFromVectorx(femmodel,Sg,SealevelEnum,VertexSIdEnum);
 
 		/*compute other geodetic signatures, such as absolute sea level chagne, components of 3-D crustal motion: */
@@ -95,4 +93,9 @@
 		femmodel->SealevelriseGeodetic(U_radial,U_north,U_east,Sg,latitude,longitude,radius,xx,yy,zz); 
 
+		/*Now deal with steric ocean expansion by just shifting Sg by a spatial rate pattern : */
+		femmodel->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+		GetVectorFromInputsx(&steric_rate_g,femmodel,SealevelriseStericRateEnum,VertexSIdEnum);
+		Sg->AXPY(steric_rate_g,dt);
+		
 		/*compute: absolute sea level change = relative sea level change + vertical motion*/
 		Sg->Copy(Sg_absolute); Sg_absolute->AXPY(U_radial,1); 
@@ -102,5 +105,6 @@
 		InputUpdateFromVectorx(femmodel,U_north,SealevelNmotionEnum,VertexSIdEnum);	// north motion 
 		InputUpdateFromVectorx(femmodel,U_east,SealevelEmotionEnum,VertexSIdEnum);		// east motion 
-		InputUpdateFromVectorx(femmodel,Sg_absolute,SealevelAbsoluteEnum,VertexSIdEnum);
+		InputUpdateFromVectorx(femmodel,Sg_absolute,SealevelAbsoluteEnum,VertexSIdEnum); //absolute sea level
+		InputUpdateFromVectorx(femmodel,Sg,SealevelEnum,VertexSIdEnum); //relative sea level
 		
 		if(save_results){
@@ -119,4 +123,5 @@
 		delete U_east;
 		delete Sg_absolute;
+		delete steric_rate_g;
 		if(numoutputs){for(int i=0;i<numoutputs;i++){xDelete<char>(requested_outputs[i]);} xDelete<char*>(requested_outputs);}
 	}
Index: /issm/trunk/src/c/cores/sealevelrise_core_noneustatic.cpp
===================================================================
--- /issm/trunk/src/c/cores/sealevelrise_core_noneustatic.cpp	(revision 22757)
+++ /issm/trunk/src/c/cores/sealevelrise_core_noneustatic.cpp	(revision 22758)
@@ -37,4 +37,7 @@
 	IssmDouble          *radius    = NULL;
 	IssmDouble           eustatic;
+	IssmDouble				Ixz; 
+	IssmDouble				Iyz; 
+	IssmDouble				Izz; 
 
 	/*Recover some parameters: */
@@ -83,8 +86,14 @@
 			/*call rotational feedback  module: */
 			Sgo_rot = new Vector<IssmDouble>(gsize); Sgo_rot->Assemble();
-			femmodel->SealevelriseRotationalFeedback(Sgo_rot,Sg_old,latitude,longitude,radius); 
+			femmodel->SealevelriseRotationalFeedback(Sgo_rot,Sg_old,&Ixz,&Iyz,&Izz,latitude,longitude,radius); 
 			Sgo_rot->Assemble(); 
 
+			/*save changes in inertia tensor as results: */
+			femmodel->results->AddResult(new GenericExternalResult<IssmDouble>(femmodel->results->Size()+1,SealevelInertiaTensorXZEnum,Ixz));
+			femmodel->results->AddResult(new GenericExternalResult<IssmDouble>(femmodel->results->Size()+1,SealevelInertiaTensorYZEnum,Iyz));
+			femmodel->results->AddResult(new GenericExternalResult<IssmDouble>(femmodel->results->Size()+1,SealevelInertiaTensorZZEnum,Izz));
+		
 			Sgo->AXPY(Sgo_rot,1); 
+			delete Sgo_rot; 
 		}
 		
@@ -93,5 +102,5 @@
 	
 		/*Sg is the sum of the eustatic term, and the ocean terms: */
-		Sg_eustatic->Copy(Sg); Sg->AXPY(Sgo,1); 
+		Sg_eustatic->Copy(Sg); Sg->AXPY(Sgo,1); delete Sgo; 
 		Sg->Shift(-Sgo_oceanaverage);
 
@@ -112,5 +121,4 @@
 		/*some minor verbosing adjustment:*/
 		if(count>1)verboseconvolution=false;
-		
 	}
 	if(VerboseConvergence()) _printf0_("\n   total number of iterations: " << count-1 << "\n");
Index: /issm/trunk/src/c/cores/stressbalance_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/stressbalance_core.cpp	(revision 22757)
+++ /issm/trunk/src/c/cores/stressbalance_core.cpp	(revision 22758)
@@ -14,5 +14,5 @@
 
 	/*parameters: */
-	bool       dakota_analysis;
+	bool       dakota_analysis,control_analysis;
 	int        domaintype;
 	bool       isSIA,isSSA,isL1L2,isHO,isFS;
@@ -34,4 +34,5 @@
 	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
 	femmodel->parameters->FindParam(&numoutputs,StressbalanceNumRequestedOutputsEnum);
+	femmodel->parameters->FindParam(&control_analysis,InversionIscontrolEnum);
 	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,StressbalanceRequestedOutputsEnum);
 	
@@ -79,6 +80,6 @@
 		femmodel->RequestedOutputsx(&femmodel->results,requested_outputs,numoutputs);
 	}
-
-	if(solution_type==StressbalanceSolutionEnum)femmodel->RequestedDependentsx();
+	
+	if(solution_type==StressbalanceSolutionEnum && !control_analysis)femmodel->RequestedDependentsx();
 
 	/*Free ressources:*/	
Index: /issm/trunk/src/c/cores/transient_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/transient_core.cpp	(revision 22757)
+++ /issm/trunk/src/c/cores/transient_core.cpp	(revision 22758)
@@ -20,11 +20,11 @@
 
 	/*parameters: */
-	IssmDouble finaltime,dt,yts;
-	bool       isstressbalance,ismasstransport,issmb,isFS,isthermal,isgroundingline,isgia,isslr,iscoupler,ismovingfront,isdamageevolution,ishydrology;
+	IssmDouble finaltime,dt,yts,starttime;
+	bool       isstressbalance,ismasstransport,issmb,isFS,isthermal,isgroundingline,isgia,isslr,iscoupler,ismovingfront,isdamageevolution,ishydrology,isoceancoupling,iscontrol,isautodiff;
 	bool       save_results,dakota_analysis;
-	bool       time_adapt;
+	int        timestepping;
 	int        output_frequency;
 	int        recording_frequency;
-	int        domaintype,groundingline_migration,smb_model,amr_frequency;
+	int        domaintype,groundingline_migration,smb_model,amr_frequency,amr_restart;
 	int        numoutputs;
 	Analysis  *analysis          = NULL;
@@ -44,9 +44,9 @@
 	femmodel->parameters->FindParam(&time,TimeEnum);
 	femmodel->parameters->FindParam(&finaltime,TimesteppingFinalTimeEnum);
-	femmodel->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	femmodel->parameters->FindParam(&starttime,TimesteppingStartTimeEnum);
 	femmodel->parameters->FindParam(&yts,ConstantsYtsEnum);
 	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
 	femmodel->parameters->FindParam(&output_frequency,SettingsOutputFrequencyEnum);
-	femmodel->parameters->FindParam(&time_adapt,TimesteppingTimeAdaptEnum);
+	femmodel->parameters->FindParam(&timestepping,TimesteppingTypeEnum);
 	femmodel->parameters->FindParam(&isstressbalance,TransientIsstressbalanceEnum);
 	femmodel->parameters->FindParam(&ismasstransport,TransientIsmasstransportEnum);
@@ -58,23 +58,95 @@
 	femmodel->parameters->FindParam(&isgroundingline,TransientIsgroundinglineEnum);
 	femmodel->parameters->FindParam(&ismovingfront,TransientIsmovingfrontEnum);
+	femmodel->parameters->FindParam(&isoceancoupling,TransientIsoceancouplingEnum);
 	femmodel->parameters->FindParam(&isdamageevolution,TransientIsdamageevolutionEnum);
 	femmodel->parameters->FindParam(&ishydrology,TransientIshydrologyEnum);
 	femmodel->parameters->FindParam(&amr_frequency,TransientAmrFrequencyEnum);
 	femmodel->parameters->FindParam(&isFS,FlowequationIsFSEnum);
+	femmodel->parameters->FindParam(&iscontrol,InversionIscontrolEnum);
+	femmodel->parameters->FindParam(&isautodiff,AutodiffIsautodiffEnum);
 	if(isgroundingline) femmodel->parameters->FindParam(&groundingline_migration,GroundinglineMigrationEnum);
 	femmodel->parameters->FindParam(&numoutputs,TransientNumRequestedOutputsEnum);
 	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,TransientRequestedOutputsEnum);
 
-	#ifdef _HAVE_NEOPZ_
-	bool ismismip = false;//itapopo testing restart 
-	if(ismismip) femmodel->ReMesh();
+	#if defined(_HAVE_BAMG_) && !defined(_HAVE_ADOLC_)
+	if(amr_frequency){
+		femmodel->parameters->FindParam(&amr_restart,AmrRestartEnum);
+		if(amr_restart) femmodel->ReMesh();
+	}
 	#endif
 
+	if(isoceancoupling){ {{{
+		if(VerboseSolution()) _printf0_("   ocean coupling: initialization \n");
+		int my_rank;
+		int oceangridnxsize,oceangridnysize;
+		IssmDouble *oceangridx;
+		IssmDouble *oceangridy;
+		IssmDouble *icebase;
+		IssmDouble coupling_time,oceantime;
+		ISSM_MPI_Comm tomitgcmcomm;
+		ISSM_MPI_Status status;
+
+		my_rank=IssmComm::GetRank();
+		femmodel->parameters->FindParam(&coupling_time,TimesteppingCouplingTimeEnum);
+		GenericParam<ISSM_MPI_Comm>* parcom = dynamic_cast<GenericParam<ISSM_MPI_Comm>*>(femmodel->parameters->FindParamObject(ToMITgcmCommEnum));
+		if(!parcom)_error_("TransferForcing error message: could not find ToMITgcmCommEnum communicator");
+		tomitgcmcomm=parcom->GetParameterValue();
+		if(my_rank==0){
+			ISSM_MPI_Send(&coupling_time,1,ISSM_MPI_DOUBLE,0,10001000,tomitgcmcomm);
+			ISSM_MPI_Recv(&oceangridnxsize,1,ISSM_MPI_INT,0,10001003,tomitgcmcomm,&status);
+			ISSM_MPI_Recv(&oceangridnysize,1,ISSM_MPI_INT,0,10001004,tomitgcmcomm,&status);
+			femmodel->parameters->SetParam(oceangridnxsize,OceanGridNxEnum);
+			femmodel->parameters->SetParam(oceangridnysize,OceanGridNyEnum);
+			oceangridx = xNew<IssmDouble>(oceangridnxsize*oceangridnysize);
+			ISSM_MPI_Recv(oceangridx,oceangridnxsize*oceangridnysize,ISSM_MPI_DOUBLE,0,10001005,tomitgcmcomm,&status);
+			oceangridy = xNew<IssmDouble>(oceangridnxsize*oceangridnysize);
+			ISSM_MPI_Recv(oceangridy,oceangridnxsize*oceangridnysize,ISSM_MPI_DOUBLE,0,10001006,tomitgcmcomm,&status);
+
+			ISSM_MPI_Send(&time,1,ISSM_MPI_DOUBLE,0,10001001,tomitgcmcomm);
+			ISSM_MPI_Recv(&oceantime,1,ISSM_MPI_DOUBLE,0,10001002,tomitgcmcomm,&status);
+			icebase = xNew<IssmDouble>(oceangridnxsize*oceangridnysize);
+			for(int i=0;i<oceangridnxsize;i++){
+				for(int j=0;j<oceangridnysize;j++){
+					icebase[i*oceangridnysize+j]=2*oceangridx[i*oceangridnysize+j];
+				}
+			}
+			ISSM_MPI_Send(icebase,oceangridnxsize*oceangridnysize,ISSM_MPI_DOUBLE,0,10001008,tomitgcmcomm);
+			xDelete<IssmDouble>(icebase);
+			xDelete<IssmDouble>(oceangridx);
+			xDelete<IssmDouble>(oceangridy);
+		}
+	}
+	}}}
+
+		IssmDouble  output_value;
+		int         num_dependents;
+		IssmPDouble *dependents;
+		DataSet*    dependent_objects=NULL;
+		IssmDouble  J=0.;
+
+	if(iscontrol && isautodiff){
+
+		femmodel->parameters->SetParam(starttime,TimeEnum);
+		femmodel->parameters->FindParam(&num_dependents,AutodiffNumDependentsEnum);
+		femmodel->parameters->FindParam(&dependent_objects,AutodiffDependentObjectsEnum);
+
+		/*Go through our dependent variables, and compute the response:*/
+		dependents=xNew<IssmPDouble>(num_dependents);
+	}
+
 	while(time < finaltime - (yts*DBL_EPSILON)){ //make sure we run up to finaltime.
-		/*Increment*/
-		if(time_adapt){
-			femmodel->TimeAdaptx(&dt);
-			if(time+dt>finaltime) dt=finaltime-time;
-			femmodel->parameters->SetParam(dt,TimesteppingTimeStepEnum);
+
+		/*Time Increment*/
+		switch(timestepping){
+			case AdaptiveTimesteppingEnum:
+				femmodel->TimeAdaptx(&dt);
+				if(time+dt>finaltime) dt=finaltime-time;
+				femmodel->parameters->SetParam(dt,TimesteppingTimeStepEnum);
+				break;
+			case FixedTimesteppingEnum:
+				femmodel->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+				break;
+			default:
+				_error_("Time stepping \""<<EnumToStringx(timestepping)<<"\" not supported yet");
 		}
 		step+=1;
@@ -83,5 +155,5 @@
 		femmodel->parameters->SetParam(step,StepEnum);
 
-		if(VerboseSolution()) _printf0_("iteration " << step << "/" << floor((finaltime-time)/dt)+step << "  time [yr]: " << setprecision(4) << time/yts << " (time step: " << dt/yts << ")\n");
+		if(VerboseSolution()) _printf0_("iteration " << step << "/" << ceil((finaltime-time)/dt)+step << "  time [yr]: " << setprecision(4) << time/yts << " (time step: " << dt/yts << ")\n");
 		if(step%output_frequency==0 || (time >= finaltime - (yts*DBL_EPSILON)) || step==1)
 		 save_results=true;
@@ -89,4 +161,39 @@
 		 save_results=false;
 		femmodel->parameters->SetParam(save_results,SaveResultsEnum);
+
+		if(isoceancoupling){ {{{
+			if(VerboseSolution()) _printf0_("   ocean coupling: exchanging information\n");
+			int my_rank;
+			int oceangridnxsize,oceangridnysize;
+			IssmDouble *oceanmelt;
+			IssmDouble *icebase;
+			IssmDouble oceantime;
+			ISSM_MPI_Comm tomitgcmcomm;
+			ISSM_MPI_Status status;
+
+			my_rank=IssmComm::GetRank();
+			GenericParam<ISSM_MPI_Comm>* parcom = dynamic_cast<GenericParam<ISSM_MPI_Comm>*>(femmodel->parameters->FindParamObject(ToMITgcmCommEnum));
+			if(!parcom)_error_("TransferForcing error message: could not find ToMITgcmCommEnum communicator");
+			tomitgcmcomm=parcom->GetParameterValue();
+			if(my_rank==0){
+				ISSM_MPI_Send(&time,1,ISSM_MPI_DOUBLE,0,10001001,tomitgcmcomm);
+				ISSM_MPI_Recv(&oceantime,1,ISSM_MPI_DOUBLE,0,10001002,tomitgcmcomm,&status);
+				if((oceantime - time > 0.1*yts) & (oceantime - time < -0.1*yts)) _error_("Ocean and ice time are starting to diverge");
+				femmodel->parameters->FindParam(&oceangridnxsize,OceanGridNxEnum);
+				femmodel->parameters->FindParam(&oceangridnysize,OceanGridNyEnum);
+				oceanmelt = xNew<IssmDouble>(oceangridnxsize*oceangridnysize);
+				ISSM_MPI_Recv(oceanmelt,oceangridnxsize*oceangridnysize,ISSM_MPI_DOUBLE,0,10001007,tomitgcmcomm,&status);
+                                icebase = xNew<IssmDouble>(oceangridnxsize*oceangridnysize);
+				for(int i=0;i<oceangridnxsize;i++){
+					for(int j=0;j<oceangridnysize;j++){
+						icebase[i*oceangridnysize+j]=9999.;
+					}
+				}
+				ISSM_MPI_Send(icebase,oceangridnxsize*oceangridnysize,ISSM_MPI_DOUBLE,0,10001008,tomitgcmcomm);
+				xDelete<IssmDouble>(oceanmelt);
+				xDelete<IssmDouble>(icebase);
+			}
+		}
+		}}}
 
 		if(isthermal && domaintype==Domain3DEnum){ 
@@ -104,5 +211,4 @@
 				}
 			}
-			if(VerboseSolution()) _printf0_("   computing thermal regime\n");
 			thermal_core(femmodel);
 		}
@@ -117,5 +223,7 @@
 
 		/* from here on, prepare geometry for next time step*/
-		if(issmb)smb_core(femmodel);
+
+		if(issmb)           smb_core(femmodel);
+		if(ismasstransport) FloatingiceMeltingRatex(femmodel);
 
 		if(ismasstransport){
@@ -141,7 +249,4 @@
 		}
 
-		/*Calculate new basal melting on floating ice*/
-		FloatingiceMeltingRatex(femmodel);
-		
 		if(isgia){
 			if(VerboseSolution()) _printf0_("   computing glacial isostatic adjustment\n");
@@ -175,14 +280,30 @@
 
 		/*Adaptive mesh refinement*/
-		#ifdef _HAVE_NEOPZ_
 		if(amr_frequency){
+
+			#if !defined(_HAVE_ADOLC_)
 			if(save_results) femmodel->WriteMeshInResults();
-			if(step%amr_frequency==0 && time<finaltime) femmodel->ReMesh();//Do not refine the last step
-		}
-		#endif
-	
+			if(step%amr_frequency==0 && time<finaltime){
+				if(VerboseSolution()) _printf0_("   refining mesh\n");
+				femmodel->ReMesh();//Do not refine the last step
+			}
+
+			#else
+			_error_("AMR not suppored with ADOLC");
+			#endif
+		}
+
+		if (iscontrol && isautodiff) {
+			/*Go through our dependent variables, and compute the response:*/
+			for(int i=0;i<dependent_objects->Size();i++){
+				DependentObject* dep=(DependentObject*)dependent_objects->GetObjectByOffset(i);
+				 dep->Responsex(&output_value,femmodel);
+				 dep->AddValue(output_value);
+				}
+			}
 	}
 	
-	femmodel->RequestedDependentsx();
+	if(!iscontrol || !isautodiff) femmodel->RequestedDependentsx();
+	if(iscontrol && isautodiff) femmodel->parameters->SetParam(dependent_objects,AutodiffDependentObjectsEnum);
 
 	/*Free ressources:*/	
Index: /issm/trunk/src/c/main/globals.h
===================================================================
--- /issm/trunk/src/c/main/globals.h	(revision 22757)
+++ /issm/trunk/src/c/main/globals.h	(revision 22758)
@@ -16,4 +16,5 @@
  * database if we use Petsc. Can also be used to characterize the ISSM toolkit,
  * often used when Petsc is not allowed*/
+char* ToolkitOptions::toolkittype;
 char* ToolkitOptions::toolkitoptions;
 #endif
Index: /issm/trunk/src/c/main/issm.js
===================================================================
--- /issm/trunk/src/c/main/issm.js	(revision 22757)
+++ /issm/trunk/src/c/main/issm.js	(revision 22758)
@@ -11,5 +11,5 @@
 	binHeap.set(new Uint8Array(dbinary.buffer)); var binary=binHeap.byteOffset;
 
-	//Declare TriMesh module: 
+	//Declare module: 
 	issm= Module.cwrap('main','number',['number','number']);
 	
Index: /issm/trunk/src/c/main/issm_dakota.cpp
===================================================================
--- /issm/trunk/src/c/main/issm_dakota.cpp	(revision 22757)
+++ /issm/trunk/src/c/main/issm_dakota.cpp	(revision 22758)
@@ -84,4 +84,8 @@
 	env.execute();
 
+	xDelete<char>(dakota_input_file);
+	xDelete<char>(dakota_output_file);
+	xDelete<char>(dakota_error_file);
+
 	/*Return unix success: */
 	return 0; 
@@ -90,3 +94,4 @@
 	return 1;
 	#endif
+
 }
Index: /issm/trunk/src/c/main/issm_ocean.cpp
===================================================================
--- /issm/trunk/src/c/main/issm_ocean.cpp	(revision 22757)
+++ /issm/trunk/src/c/main/issm_ocean.cpp	(revision 22758)
@@ -4,99 +4,43 @@
 
 #include "./issm.h"
+#include <stdlib.h>
 
 int main(int argc,char **argv){
 
-//	/*diverse:*/
-//	int    nummodels = 2;
-//	int*   commsizes=xNew<int>(nummodels);
-//	int*   rankzeros=xNew<int>(nummodels);
-//	char** modelnames=xNew<char*>(nummodels);
-//	char** dirnames=xNew<char*>(nummodels);
-//	int    iceid=0; 
-//	int    oceanid=1; 
-//	int    modelid;
-//	int    my_rank;
-//	int    count=0;
-//	ISSM_MPI_Comm worldcomm;
-//	ISSM_MPI_Comm modelcomm;
-//	ISSM_MPI_Comm toonceancomm;
-//	ISSM_MPI_Comm fromicecomms;
+	/*diverse:*/
+	int    icecommsize;
+	int    my_rank,my_local_rank,my_size,my_local_size;
+	ISSM_MPI_Comm worldcomm;
+	ISSM_MPI_Comm modelcomm;
+	ISSM_MPI_Comm frommitgcm;
+	ISSM_MPI_Comm tomitgcmcomm;
+	ISSM_MPI_Status status;
 
 	/*Initialize exception trapping: */
 	ExceptionTrapBegin();
 
-//	/*Initialize environment (MPI, PETSC, MUMPS, etc ...)*/
-//	worldcomm=EnvironmentInit(argc,argv);
-//	
-//	/*What is my rank?:*/
-//	ISSM_MPI_Comm_rank(worldcomm,&my_rank);
-//
-//	/*First model is ice, second is ocean*/
-//	for(int i=0;i<nummodels;i++){
-//		char* string=NULL;
-//		
-//		string=xNew<char>(strlen(argv[5+3*i])+1);
-//		xMemCpy<char>(string,argv[5+3*i],strlen(argv[5+3*i])+1);
-//		dirnames[i]=string;
-//		
-//		string=xNew<char>(strlen(argv[5+3*i+1])+1);
-//		xMemCpy<char>(string,argv[5+3*i+1],strlen(argv[5+3*i+1])+1);
-//		modelnames[i]=string;
-//
-//		commsizes[i]=(int) strtol(argv[5+3*i+2], (char **)NULL, 10);
-//	}
-//
-//	/*Figure out which model each cpu will belong to: */
-//	count=0;
-//	for(int i=0;i<nummodels;i++){
-//		if(my_rank>=count && my_rank<(count+commsizes[i])){
-//			modelid=i;
-//			break;
-//		}
-//		count+=commsizes[i];
-//	} 
-//	/*Buil array of who is rank 0 of their own group:*/
-//	count=0;
-//	for(int i=0;i<nummodels;i++){
-//		rankzeros[i]=count;
-//		count+=commsizes[i];
-//	}
-//	/*}}}*/
-//
-//	/*Split world into sub-communicators for each and every model:*/
-//	ISSM_MPI_Comm_split(worldcomm,modelid, my_rank, &modelcomm);
-//
-//	/*Build inter communicators:*/ // change to Dimitris solution
-//	if(modelid==iceid){
-//		ISSM_MPI_Intercomm_create( modelcomm, 0, worldcomm, rankzeros[oceanid], iceid, fromicecomms+i); //communicate from local erth comm 9rank 0) to ice comm (rank 0) using modelid tag.
-//	}
-//	else{
-//		ISSM_MPI_Intercomm_create( modelcomm, 0, worldcomm, rankzeros[iceid], oceanid, &toearthcomm); //communicate from local ice comm (rank 0) to earth comm (rank 0) using modelid tag.
-//	}
+	/*Initialize environment (MPI, PETSC, MUMPS, etc ...)*/
+	worldcomm=EnvironmentInit(argc,argv);
+	
+	/*What is my rank?:*/
+	ISSM_MPI_Comm_rank(worldcomm,&my_rank);
+	ISSM_MPI_Comm_size(worldcomm,&my_size);
 
-//	/*Supply specific argc and argv for each sub-communicator (corresponding to each  model specificatiions):{{{*/
-//	char** arguments=xNew<char*>(4);
-//	arguments[0]=xNew<char>(strlen(argv[0])+1); xMemCpy<char>(arguments[0],argv[0],strlen(argv[0])+1); //executable name
-//	arguments[1]=xNew<char>(strlen(argv[1])+1); xMemCpy<char>(arguments[1],argv[1],strlen(argv[1])+1); //solution name
-//	arguments[2]=xNew<char>(strlen(argv[5+3*modelid])+1); xMemCpy<char>(arguments[2],argv[5+3*modelid],strlen(argv[5+3*modelid])+1); //directory name
-//	arguments[3]=xNew<char>(strlen(argv[5+3*modelid+1])+1); xMemCpy<char>(arguments[3],argv[5+3*modelid+1],strlen(argv[5+3*modelid+1])+1); //model name
-//	/*}}}*/
-//
+	/*First model is ice, second is ocean*/
+	/*ice comm size: */
+	icecommsize=(int) strtol(argv[2], (char **)NULL, 10);
 
-	//REMOVE
-	/*Initialize environment (MPI, PETSC, MUMPS, etc ...)*/
-	ISSM_MPI_Comm comm_init=EnvironmentInit(argc,argv);
-	/*Initialize femmodel from arguments provided command line: */
-	FemModel *femmodel = new FemModel(argc,argv,comm_init);
-	///*Initialize femmodel from arguments provided command line: */
-	//FemModel *femmodel = new FemModel(1,arguments,modelcomm);
+	/*Split world into sub-communicators for each and every model:*/
+	ISSM_MPI_Comm_split(worldcomm,0, my_rank, &modelcomm);
+	ISSM_MPI_Comm_rank(modelcomm,&my_local_rank);
+	ISSM_MPI_Comm_size(modelcomm,&my_local_size);
+
+	ISSM_MPI_Intercomm_create( modelcomm, 0, worldcomm, my_local_size, 0, &tomitgcmcomm); 
+
+	FemModel *femmodel = new FemModel(argc,argv,modelcomm);
 	
-//	/*Now that the models are initialized, keep communicator information in the parameters datasets of each model: */
-//	femmodel->parameters->AddObject(new GenericParam<ISSM_MPI_Comm>(worldcomm,WorldCommEnum));
-//	femmodel->parameters->AddObject(new IntParam(NumModelsEnum,nummodels));
-//	femmodel->parameters->AddObject(new IntParam(ModelIdEnum,oceanid));
-//	femmodel->parameters->AddObject(new IntParam(EarthIdEnum,iceid));
-//	if(modelid==earthid) femmodel->parameters->AddObject(new GenericParam<ISSM_MPI_Comm*>(fromicecomms,IcecapToEarthCommEnum));
-//	else femmodel->parameters->AddObject(new GenericParam<ISSM_MPI_Comm>(toearthcomm,IcecapToEarthCommEnum));
+	/*Now that the models are initialized, keep communicator information in the parameters datasets of each model: */
+	femmodel->parameters->AddObject(new GenericParam<ISSM_MPI_Comm>(worldcomm,WorldCommEnum));
+	femmodel->parameters->AddObject(new GenericParam<ISSM_MPI_Comm>(tomitgcmcomm,ToMITgcmCommEnum));
 
 	/*Solve: */
@@ -118,13 +62,5 @@
 	ExceptionTrapEnd();
 
-//	/*Free ressources:*/
-//	xDelete<int>(commsizes);
-//	for(int i=0;i<nummodels;i++){
-//		char* string=NULL;
-//		string=dirnames[i]; xDelete<char>(string);
-//		string=modelnames[i]; xDelete<char>(string);
-//	}
-//	xDelete<char*>(dirnames);
-//	xDelete<char*>(modelnames);
+	/*Free ressources:*/
 
 	/*Return unix success: */
Index: /issm/trunk/src/c/main/issm_slr.cpp
===================================================================
--- /issm/trunk/src/c/main/issm_slr.cpp	(revision 22757)
+++ /issm/trunk/src/c/main/issm_slr.cpp	(revision 22758)
@@ -4,4 +4,5 @@
 
 #include "./issm.h"
+#include <stdlib.h>
 
 int main(int argc,char **argv){
Index: /issm/trunk/src/c/modules/AllocateSystemMatricesx/AllocateSystemMatricesx.cpp
===================================================================
--- /issm/trunk/src/c/modules/AllocateSystemMatricesx/AllocateSystemMatricesx.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/AllocateSystemMatricesx/AllocateSystemMatricesx.cpp	(revision 22758)
@@ -195,5 +195,5 @@
 			/*Reinitialize flags to false*/
 			j=0;
-			while(true){
+			while(j<localnumnodes){
 				if(flagsindices[j]>=0){
 					flags[flagsindices[j]] = false;
Index: /issm/trunk/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.cpp
===================================================================
--- /issm/trunk/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.cpp	(revision 22758)
@@ -17,5 +17,5 @@
 
 	/*read mesh*/
-	Mesh Th(index,x,y,nods,nels); 
+	Mesh Th(index,x,y,nods,nels,bamgopts); 
 
 	/*write mesh and geometry*/
Index: /issm/trunk/src/c/modules/BamgTriangulatex/BamgTriangulatex.cpp
===================================================================
--- /issm/trunk/src/c/modules/BamgTriangulatex/BamgTriangulatex.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/BamgTriangulatex/BamgTriangulatex.cpp	(revision 22758)
@@ -14,8 +14,9 @@
 int BamgTriangulatex(int** pindex,int* pnels,double* x,double* y,int nods){
 
-	Mesh Th(x,y,nods);
+	BamgOpts* bamgopts=new BamgOpts();//use bamgopts->verbose>5 to debug bamg::Mesh()
+	Mesh Th(x,y,nods,bamgopts);
 	Th.WriteIndex(pindex,pnels);
+	delete bamgopts;
 	//delete &Th;
 	return 0;
-
 }
Index: /issm/trunk/src/c/modules/Bamgx/Bamgx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Bamgx/Bamgx.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/Bamgx/Bamgx.cpp	(revision 22758)
@@ -149,15 +149,12 @@
 		}
 
-		//Add geometry metric if provided
-		if(bamgopts->geometricalmetric) BTh.AddGeometryMetric(bamgopts);
-
 		//Smoothe metric
-		BTh.SmoothMetric(bamgopts->gradation);
+		BTh.SmoothMetric(bamgopts,bamgopts->gradation);
 
 		//Control element subdivision
-		BTh.MaxSubDivision(bamgopts->maxsubdiv);
+		BTh.MaxSubDivision(bamgopts,bamgopts->maxsubdiv);
 
 		//Bound anisotropy
-		BTh.BoundAnisotropy(bamgopts->anisomax,hminaniso);
+		BTh.BoundAnisotropy(bamgopts,bamgopts->anisomax,hminaniso);
 
 		//Build new mesh
@@ -174,5 +171,5 @@
 
 		//Smooth vertices
-		if(nbsmooth>0) Th.SmoothingVertex(nbsmooth,bamgopts->omega);
+		if(nbsmooth>0) Th.SmoothingVertex(bamgopts,nbsmooth,bamgopts->omega);
 
 		//display info
Index: /issm/trunk/src/c/modules/Calvingx/Calvingx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Calvingx/Calvingx.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/Calvingx/Calvingx.cpp	(revision 22758)
@@ -18,4 +18,12 @@
 		case CalvingMinthicknessEnum:
 			break;
+		case CalvingHabEnum:
+			break;
+		case CalvingCrevasseDepthEnum:
+			femmodel->StrainRateparallelx();
+			femmodel->StrainRateeffectivex();
+			femmodel->DeviatoricStressx();
+			femmodel->ElementOperationx(&Element::CalvingCrevasseDepth);
+			break;
 		case CalvingLevermannEnum:
 			if(VerboseModule()) _printf0_("   computing Levermann's calving rate\n");
@@ -24,7 +32,8 @@
 			femmodel->CalvingRateLevermannx();
 			break;
-		case CalvingDevEnum:
-			femmodel->CalvingRateDevx();
-			femmodel->ElementOperationx(&Element::CalvingRateDev);
+		case CalvingVonmisesEnum:
+		case CalvingDev2Enum:
+			femmodel->CalvingRateVonmisesx();
+			femmodel->ElementOperationx(&Element::CalvingRateVonmises);
 			break;
 		default:
Index: /issm/trunk/src/c/modules/Chacox/user_params.cpp
===================================================================
--- /issm/trunk/src/c/modules/Chacox/user_params.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/Chacox/user_params.cpp	(revision 22758)
@@ -119,5 +119,5 @@
 int       MAKE_VWGTS = FALSE;	/* Make vtx weights degrees+1? (TRUE/FALSE) */
 int       FREE_GRAPH = FALSE;	/* Free input graph data? (TRUE/FALSE) */
-char     *PARAMS_FILENAME = "User_Params";	/* File of parameter changes */
+const char  *PARAMS_FILENAME = "User_Params";	/* File of parameter changes */
 
 /* Parameters that control debugging output */
Index: /issm/trunk/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.cpp	(revision 22758)
@@ -9,21 +9,50 @@
 void ControlInputSetGradientx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,IssmDouble* gradient){
 
-	/*Intermediaries*/
-	int  num_controls;
-	int *control_type = NULL;
+	bool isautodiff;
+	parameters->FindParam(&isautodiff,AutodiffIsautodiffEnum);
+	if(isautodiff){
+		/*Intermediaries*/
+		int  num_controls;
+		int *control_type = NULL;
+		int* M_all = NULL;
+		int* N_all = NULL;
 
-	/*Retrieve some parameters*/
-	parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
-	parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+		/*Retrieve some parameters*/
+		parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+		parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+		parameters->FindParam(&M_all,NULL,ControlInputSizeMEnum);
+		parameters->FindParam(&N_all,NULL,ControlInputSizeNEnum);
 
-	for(int i=0;i<num_controls;i++){
-		for(int j=0;j<elements->Size();j++){
-			Element* element=(Element*)elements->GetObjectByOffset(j);
-			element->ControlInputSetGradient(gradient,control_type[i],i);
+		int offset = 0;
+		for(int i=0;i<num_controls;i++){
+			for(int j=0;j<elements->Size();j++){
+				Element* element=(Element*)elements->GetObjectByOffset(j);
+				element->ControlInputSetGradient(gradient,control_type[i],i,offset,N_all[i],M_all[i]);
+			}
+			offset+=M_all[i]*N_all[i];
 		}
+
+		/*Clean up and return*/
+		xDelete<int>(control_type);
 	}
+	else{
+		int  num_controls;
+		int *control_type = NULL;
 
-	/*Clean up and return*/
-	xDelete<int>(control_type);
+		/*Retrieve some parameters*/
+		parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+		parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+
+		int offset = 0;
+		for(int i=0;i<num_controls;i++){
+			for(int j=0;j<elements->Size();j++){
+				Element* element=(Element*)elements->GetObjectByOffset(j);
+				element->ControlInputSetGradient(gradient,control_type[i],i);
+			}
+		}
+
+		/*Clean up and return*/
+		xDelete<int>(control_type);
+	}
 
 }
Index: /issm/trunk/src/c/modules/CoordinateSystemTransformx/CoordinateSystemTransformx.cpp
===================================================================
--- /issm/trunk/src/c/modules/CoordinateSystemTransformx/CoordinateSystemTransformx.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/CoordinateSystemTransformx/CoordinateSystemTransformx.cpp	(revision 22758)
@@ -1,4 +1,4 @@
-/*!\file TriMeshx
- * \brief: x code for TriMesh mesher
+/*!\file CoordinateSystemTransformx
+ * \brief: x code for CoordinateSystemTransformx
  */
 
Index: /issm/trunk/src/c/modules/DistanceToMaskBoundaryx/DistanceToMaskBoundaryx.cpp
===================================================================
--- /issm/trunk/src/c/modules/DistanceToMaskBoundaryx/DistanceToMaskBoundaryx.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/DistanceToMaskBoundaryx/DistanceToMaskBoundaryx.cpp	(revision 22758)
@@ -20,9 +20,9 @@
 	/*initialize thread parameters: */
 	DistanceToMaskBoundaryxThreadStruct gate;
-	gate.distance    = distance;
-	gate.x         = x;
-	gate.y         = y;
-	gate.mask         = mask;
-	gate.nods      = nods;
+	gate.distance = distance;
+	gate.x        = x;
+	gate.y        = y;
+	gate.mask     = mask;
+	gate.nods     = nods;
 
 	/*launch the thread manager with DistanceToMaskBoundaryxt as a core: */
Index: /issm/trunk/src/c/modules/DistanceToMaskBoundaryx/DistanceToMaskBoundaryxt.cpp
===================================================================
--- /issm/trunk/src/c/modules/DistanceToMaskBoundaryx/DistanceToMaskBoundaryxt.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/DistanceToMaskBoundaryx/DistanceToMaskBoundaryxt.cpp	(revision 22758)
@@ -37,6 +37,5 @@
 	for(i=i0;i<i1;i++){
 
-		IssmDouble d0=pow(10.,10);
-
+		IssmDouble d0=1.e+10;
 		IssmDouble xi,yi;
 		
Index: /issm/trunk/src/c/modules/ExpToLevelSetx/ExpToLevelSetx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ExpToLevelSetx/ExpToLevelSetx.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/ExpToLevelSetx/ExpToLevelSetx.cpp	(revision 22758)
@@ -12,10 +12,6 @@
 int ExpToLevelSetx(double** pdistance,double* x, double* y, int nods, Contours* contours){
 
-	/*Contour:*/
-	double value;
-
 	/*output: */
-	double*  distance;
-	distance = xNew<double>(nods);
+	double* distance = xNew<double>(nods);
 	for(int i=0;i<nods;i++) distance[i]=1e50;
 
Index: /issm/trunk/src/c/modules/ExpToLevelSetx/ExpToLevelSetxt.cpp
===================================================================
--- /issm/trunk/src/c/modules/ExpToLevelSetx/ExpToLevelSetxt.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/ExpToLevelSetx/ExpToLevelSetxt.cpp	(revision 22758)
@@ -9,9 +9,8 @@
 #endif
 
-/*Include files: {{{*/
+/*Include files*/
 #include "./ExpToLevelSetx.h"
 double minimum_distance(double x1, double y1, double x2, double y2, double x0, double y0);
-void ContourToLevelSet(double* distance,double* contourx, double* contoury, int contournods, double* x, double* y, int i0, int i10);
-/*}}}*/
+void   ContourToLevelSet(double* distance,double* contourx, double* contoury, int contournods, double* x, double* y, int i0, int i10);
 
 void* ExpToLevelSetxt(void* vpthread_handle){
@@ -29,9 +28,9 @@
 
 	/*recover parameters :*/
-	Contours* contours  = gate->contours;
-	int       nods      = gate->nods;
-	double   *distance    = gate->distance;
-	double   *x         = gate->x;
-	double   *y         = gate->y;
+	Contours* contours = gate->contours;
+	int       nods     = gate->nods;
+	double   *distance = gate->distance;
+	double   *x        = gate->x;
+	double   *y        = gate->y;
 
 	/*distribute indices across threads :*/
@@ -39,5 +38,5 @@
 
 	/*Loop through all contours: */
-	for (i=0;i<contours->Size();i++){
+	for(i=0;i<contours->Size();i++){
 		Contour<double>* contour=(Contour<double>*)contours->GetObjectByOffset(i);
 		ContourToLevelSet(distance,contour->x,contour->y,contour->nods,x,y,i0,i1);
@@ -48,5 +47,5 @@
 
 void ContourToLevelSet(double* dist,double* contourx, double* contoury, int contournods, double* x, double* y, int i0, int i1){/*{{{*/
-	int i,j;
+
 	double x0,y0;
 	double x1,y1;
@@ -54,11 +53,14 @@
 	double mind;
 	
-	for(i=i0;i<i1;i++){
+	for(int i=i0;i<i1;i++){
+
+      /*Get current point*/
 		x0=x[i]; y0=y[i];
 
 		/*Figure out distance from (x0,y0) to contour: */
 		mind=1e+50;
-		for (j=0;j<contournods-1;j++){
-			x1=contourx[j]; y1=contoury[j];
+		for(int j=0;j<contournods-1;j++){
+         /*Get distance from current segment*/
+			x1=contourx[j];   y1=contoury[j];
 			x2=contourx[j+1]; y2=contoury[j+1];
 			mind=min(mind,minimum_distance(x1,y1,x2,y2,x0,y0));
@@ -66,39 +68,34 @@
 		dist[i]=min(dist[i],mind);
 	}
+}
+double minimum_distance(double x1, double y1, double x2, double y2, double x0, double y0){
+	/* Return minimum distance between line segment [(x1,y1) (x2,y2)] and point (x0,y0)
+	 * We use the following notations:
+	 * segment: v=(x1,y1), w=(x2,y2)
+	 * point:   p=(x0,y0) 
+	 */
 
-}
-double ddistance(double x1,double y1,double x2,double y2){
-	return sqrt(pow(x2-x1,2)+pow(y2-y1,2));
-}
-double ddot(double x1, double y1, double x2, double y2){
-	return x1*x2+y1*y2;
-}
+   /*Get segment length square (avoid sqrt) |w-v|^2*/
+	double l2 = pow(x2-x1,2)+pow(y2-y1,2); 
 
-bool isPointLeftOfRay(double x, double y, double raySx, double raySy, double rayEx, double rayEy) {
-	  return (y-raySy)*(rayEx-raySx)
-		    >      (x-raySx)*(rayEy-raySy); 
-}
+   /*segment is single point: v == w*/
+	if(l2 == 0.) return sqrt(pow(x1-x0,2)+pow(y1-y0,2));
 
-double minimum_distance(double x1, double y1, double x2, double y2, double x0, double y0){
+	/*Consider the line extending the segment, parameterized as v + t (w - v).
+	We find projection of point p onto the line.  It falls where t = [(p-v) . (w-v)] / |w-v|^2*/
+	double t = ((x0-x1)*(x2-x1) + (y0-y1)*(y2-y1)) / l2;
+	if(t < 0.){
+      /*Beyond the 'v' end of the segment*/
+      return sqrt(pow(x1-x0,2)+pow(y1-y0,2));
+   }
+	else if(t > 1.){
+      /*Beyond the 'w' end of the segment*/
+      return sqrt(pow(x2-x0,2)+pow(y2-y0,2));
+   }
 	
-	// Return minimum distance between line segment [(x1,y1) (x2,y2)] and point (x0,y0) (v=(x1,y1), w=(x2,y2) and p=(x0,y0)
-	double projectionx; 
-	double projectiony; 
-	double l2;
-	double t;
-
-	l2 = pow(x2-x1,2)+pow(y2-y1,2); // i.e. |w-v|^2 -  avoid a sqrt
-
-	if (l2 == 0.0) return ddistance(x0,y0, x1,y1); // v == w case
-	// Consider the line extending the segment, parameterized as v + t (w - v).
-	//         // We find projection of point p onto the line. 
-	//           // It falls where t = [(p-v) . (w-v)] / |w-v|^2
-	t = ddot(x0-x1,y0-y1, x2-x1, y2-y1) / l2;
-	if (t < 0.0) return ddistance(x0,y0, x1, y1);       // Beyond the 'v' end of the segment
-	else if (t > 1.0) return ddistance(x0,y0, x2,y2);  // Beyond the 'w' end of the segment
-	
-	projectionx= x1 + t* (x2-x1);  // Projection falls on the segment
-	projectiony= y1 + t* (y2-y1);
-	return ddistance(x0, y0, projectionx, projectiony);
+   /*Projection falls on segment*/
+	double projx= x1 + t* (x2-x1);
+	double projy= y1 + t* (y2-y1);
+	return sqrt(pow(projx-x0,2)+pow(projy-y0,2));
 }
 /*}}}*/
Index: /issm/trunk/src/c/modules/FloatingiceMeltingRatePicox/FloatingiceMeltingRatePicox.cpp
===================================================================
--- /issm/trunk/src/c/modules/FloatingiceMeltingRatePicox/FloatingiceMeltingRatePicox.cpp	(revision 22758)
+++ /issm/trunk/src/c/modules/FloatingiceMeltingRatePicox/FloatingiceMeltingRatePicox.cpp	(revision 22758)
@@ -0,0 +1,223 @@
+/*!\file FloatingiceMeltingRatePicox
+ * \brief: calculates Floating ice melting rate following the PICO model (Reese et al., 2017)
+ */
+
+#include "./FloatingiceMeltingRatePicox.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void FloatingiceMeltingRatePicox(FemModel* femmodel){/*{{{*/
+
+	int maxbox;
+
+   /*First, reset all melt to 0 */
+   for(int i=0;i<femmodel->elements->Size();i++){
+	      Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
+	      int numvertices = element->GetNumberOfVertices();
+	      IssmDouble* values = xNewZeroInit<IssmDouble>(numvertices);
+	      element->AddInput(BasalforcingsFloatingiceMeltingRateEnum,values,P1Enum);
+	      xDelete<IssmDouble>(values);
+	   }
+
+   femmodel->parameters->FindParam(&maxbox,BasalforcingsPicoMaxboxcountEnum);
+   UpdateBoxIdsPico(femmodel);
+   ComputeBoxAreasPico(femmodel);
+   for(int i=0;i<maxbox;i++){
+	      UpdateBoxPico(femmodel,i);
+	      ComputeAverageOceanvarsPico(femmodel,i);
+	}
+}/*}}}*/
+
+void UpdateBoxIdsPico(FemModel* femmodel){/*{{{*/
+
+	int         numvertices,num_basins,maxbox,basinid;
+	IssmDouble  dist_max;
+	IssmDouble* dmax_basin_cpu=NULL;
+	IssmDouble* distances=NULL;
+
+	femmodel->parameters->FindParam(&num_basins,BasalforcingsPicoNumBasinsEnum);
+	femmodel->parameters->FindParam(&maxbox,BasalforcingsPicoMaxboxcountEnum);
+	dmax_basin_cpu=xNew<IssmDouble>(num_basins);
+
+	femmodel->elements->InputDuplicate(MaskGroundediceLevelsetEnum,DistanceToGroundinglineEnum);
+	femmodel->DistanceToFieldValue(MaskGroundediceLevelsetEnum,0.,DistanceToGroundinglineEnum);
+	
+	femmodel->elements->InputDuplicate(MaskIceLevelsetEnum,DistanceToCalvingfrontEnum);
+	femmodel->DistanceToFieldValue(MaskIceLevelsetEnum,0.,DistanceToCalvingfrontEnum);
+
+	/*find maximum distance to grounding line per domain and per basin*/
+	IssmDouble maxdist_cpu=-1.;
+	for(int i=0;i<num_basins;i++){dmax_basin_cpu[i]=-1;}
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		if(!element->IsIceInElement() || !element->IsFloating()) continue;
+		numvertices = element->GetNumberOfVertices();
+		distances=xNew<IssmDouble>(numvertices);
+		element->GetInputListOnVertices(&distances[0],DistanceToGroundinglineEnum);
+		element->inputs->GetInputValue(&basinid,BasalforcingsPicoBasinIdEnum);
+		for(int k=0; k<numvertices; k++){
+			if(fabs(distances[k])>maxdist_cpu){maxdist_cpu=fabs(distances[k]);}
+			if(fabs(distances[k])>dmax_basin_cpu[basinid]){dmax_basin_cpu[basinid]=fabs(distances[k]);}
+		}
+		xDelete<IssmDouble>(distances);
+	}
+
+	/*Synchronize across cpus*/
+	IssmDouble* dmax_basin=xNew<IssmDouble>(num_basins);
+	ISSM_MPI_Allreduce((void*)&maxdist_cpu,(void*)&dist_max,1,ISSM_MPI_DOUBLE,ISSM_MPI_MAX,IssmComm::GetComm());
+	ISSM_MPI_Allreduce(dmax_basin_cpu,dmax_basin,num_basins,ISSM_MPI_DOUBLE,ISSM_MPI_MAX,IssmComm::GetComm());
+
+	/*Define maximum number of boxes per basin*/
+	int* nd=xNew<int>(num_basins);
+	for(int i=0; i<num_basins;i++){
+		IssmDouble val=sqrt(dmax_basin[i]/dist_max)*(maxbox-1);
+
+		#ifdef _HAVE_ADOLC_
+		/*Do not use floor when AD is on*/
+		int k=0; while(k<val+.5){k++;}
+		nd[i]=k;
+
+		#else
+		nd[i]= reCast<int>(floor(val));
+		#endif
+	} 
+
+	/*Assign box numbers*/
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element->PicoUpdateBoxid(nd);
+	}
+
+	/*Cleanup and return */
+	xDelete<int>(nd);
+	xDelete<IssmDouble>(dmax_basin);
+
+}/*}}}*/
+void ComputeBoxAreasPico(FemModel* femmodel){/*{{{*/
+
+	int num_basins,maxbox,basinid,boxid;
+	IssmDouble dist_max,area;
+
+	femmodel->parameters->FindParam(&num_basins,BasalforcingsPicoNumBasinsEnum);
+	femmodel->parameters->FindParam(&maxbox,BasalforcingsPicoMaxboxcountEnum);
+	
+	IssmDouble* boxareas=xNewZeroInit<IssmDouble>(num_basins*maxbox);
+
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		if(!element->IsIceInElement() || !element->IsFloating()) continue;
+		element->inputs->GetInputValue(&boxid,BasalforcingsPicoBoxIdEnum);
+		element->inputs->GetInputValue(&basinid,BasalforcingsPicoBasinIdEnum);
+		boxareas[basinid*maxbox+boxid]+=element->GetHorizontalSurfaceArea();
+	}
+
+	/*Synchronize across cpus*/
+	IssmDouble* sumareas =xNew<IssmDouble>(num_basins*maxbox);
+	ISSM_MPI_Allreduce(boxareas,sumareas,num_basins*maxbox,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
+	if(sumareas[0]==0){_error_("No elements in box 0, basal meltrates will be 0. Consider decreasing md.basalforcings.maxboxcount or refining your mesh!");}
+	
+	/*Update parameters to keep track of the new areas in future calculations*/
+	femmodel->parameters->AddObject(new DoubleVecParam(BasalforcingsPicoBoxAreaEnum,sumareas,maxbox*num_basins));
+
+	/*Cleanup and return */
+	xDelete<IssmDouble>(boxareas);
+	xDelete<IssmDouble>(sumareas);
+
+}/*}}}*/
+void UpdateBoxPico(FemModel* femmodel, int loopboxid){/*{{{*/
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element->PicoUpdateBox(loopboxid);
+	}
+}/*}}}*/
+void ComputeAverageOceanvarsPico(FemModel* femmodel, int boxid){/*{{{*/
+
+	int num_basins, basinid, maxbox, M;
+	IssmDouble area, toc, soc, overturning;
+	IssmDouble* boxareas=NULL;
+	IssmDouble* overturning_weighted_avg=NULL;
+
+	femmodel->parameters->FindParam(&num_basins,BasalforcingsPicoNumBasinsEnum);
+	femmodel->parameters->FindParam(&maxbox,BasalforcingsPicoMaxboxcountEnum);
+	femmodel->parameters->FindParam(&boxareas,&M, BasalforcingsPicoBoxAreaEnum);
+	IssmDouble* toc_weighted_avg           = xNewZeroInit<IssmDouble>(num_basins);
+	IssmDouble* soc_weighted_avg           = xNewZeroInit<IssmDouble>(num_basins);
+	IssmDouble* toc_sumweightedavg         = xNewZeroInit<IssmDouble>(num_basins);
+	IssmDouble* soc_sumweightedavg         = xNewZeroInit<IssmDouble>(num_basins);
+	IssmDouble* overturning_sumweightedavg = xNewZeroInit<IssmDouble>(num_basins);
+
+	/* Compute Toc and Soc weighted avg (boxes 0 to n-1) */
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		if(!element->IsIceInElement() || !element->IsFloating()) continue;
+		int el_boxid;
+		element->inputs->GetInputValue(&el_boxid,BasalforcingsPicoBoxIdEnum);
+		if(el_boxid!=boxid) continue;
+
+		Input* tocs_input=element->GetInput(BasalforcingsPicoSubShelfOceanTempEnum); _assert_(tocs_input); 
+		Input* socs_input=element->GetInput(BasalforcingsPicoSubShelfOceanSalinityEnum); _assert_(socs_input);
+
+		element->inputs->GetInputValue(&basinid,BasalforcingsPicoBasinIdEnum);
+		Gauss* gauss=element->NewGauss(1); gauss->GaussPoint(0);
+		tocs_input->GetInputValue(&toc,gauss);
+		socs_input->GetInputValue(&soc,gauss);
+		delete gauss;
+		area=element->GetHorizontalSurfaceArea();
+		toc_weighted_avg[basinid]+=toc*area;
+		soc_weighted_avg[basinid]+=soc*area;
+	}
+
+	/*Syncronize across cpus*/
+	ISSM_MPI_Allreduce(toc_weighted_avg,toc_sumweightedavg,num_basins,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
+	ISSM_MPI_Allreduce(soc_weighted_avg,soc_sumweightedavg,num_basins,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
+
+	for(int k=0;k<num_basins;k++){
+		int p=k*maxbox+boxid; 
+		if(boxareas[p]==0) continue;	
+		toc_sumweightedavg[k] = toc_sumweightedavg[k]/boxareas[p];
+		soc_sumweightedavg[k] = soc_sumweightedavg[k]/boxareas[p];
+	}
+
+	femmodel->parameters->AddObject(new DoubleVecParam(BasalforcingsPicoAverageTemperatureEnum,toc_sumweightedavg,num_basins));
+	femmodel->parameters->AddObject(new DoubleVecParam(BasalforcingsPicoAverageSalinityEnum,soc_sumweightedavg,num_basins));
+
+	/* Compute overturning weighted avg (box 0 only) */
+	if(boxid==0){ 
+		overturning_weighted_avg=xNewZeroInit<IssmDouble>(num_basins);
+		for(int i=0;i<femmodel->elements->Size();i++){
+			Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
+			if(!element->IsIceInElement() || !element->IsFloating()) continue;
+			int el_boxid;
+			element->inputs->GetInputValue(&el_boxid,BasalforcingsPicoBoxIdEnum);
+			if(el_boxid!=boxid) continue;
+
+	     	Input* overturnings_input=element->GetInput(BasalforcingsPicoSubShelfOceanOverturningEnum); _assert_(overturnings_input);
+
+			element->inputs->GetInputValue(&basinid,BasalforcingsPicoBasinIdEnum);
+			Gauss* gauss=element->NewGauss(1); gauss->GaussPoint(0);
+			overturnings_input->GetInputValue(&overturning,gauss);
+			delete gauss;
+			area=element->GetHorizontalSurfaceArea();
+			overturning_weighted_avg[basinid]+=overturning*area;
+		}
+
+		/*Syncronize across cpus*/
+		ISSM_MPI_Allreduce(overturning_weighted_avg,overturning_sumweightedavg,num_basins,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
+
+		for(int k=0;k<num_basins;k++){
+			int p=k*maxbox+boxid;
+			if(boxareas[p]==0.) continue;
+			overturning_sumweightedavg[k] = overturning_sumweightedavg[k]/boxareas[p];
+		}
+		femmodel->parameters->AddObject(new DoubleVecParam(BasalforcingsPicoAverageOverturningEnum,overturning_sumweightedavg,num_basins));
+	}
+
+	/*Cleanup and return */
+	xDelete<IssmDouble>(overturning_sumweightedavg);
+	xDelete<IssmDouble>(toc_sumweightedavg);
+	xDelete<IssmDouble>(soc_sumweightedavg);
+	xDelete<IssmDouble>(overturning_weighted_avg);
+	xDelete<IssmDouble>(toc_weighted_avg);
+	xDelete<IssmDouble>(soc_weighted_avg);
+	xDelete<IssmDouble>(boxareas);
+}/*}}}*/
Index: /issm/trunk/src/c/modules/FloatingiceMeltingRatePicox/FloatingiceMeltingRatePicox.h
===================================================================
--- /issm/trunk/src/c/modules/FloatingiceMeltingRatePicox/FloatingiceMeltingRatePicox.h	(revision 22758)
+++ /issm/trunk/src/c/modules/FloatingiceMeltingRatePicox/FloatingiceMeltingRatePicox.h	(revision 22758)
@@ -0,0 +1,18 @@
+/*!\file:  FloatingiceMeltingRatePicox.h
+ * \brief header file for Floatingice melting rate
+ */ 
+
+#ifndef _FloatingiceMeltingRatePicox_H
+#define _FloatingiceMeltingRatePicox_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void FloatingiceMeltingRatePicox(FemModel* femmodel);
+
+void UpdateBoxIdsPico(FemModel* femmodel);
+void ComputeBoxAreasPico(FemModel* femmodel);
+void UpdateBoxPico(FemModel* femmodel, int loopboxid);
+void ComputeAverageOceanvarsPico(FemModel* femmodel, int boxid);
+
+#endif  /* _FloatingiceMeltingRatePicox_H*/
Index: /issm/trunk/src/c/modules/FloatingiceMeltingRatex/FloatingiceMeltingRatex.cpp
===================================================================
--- /issm/trunk/src/c/modules/FloatingiceMeltingRatex/FloatingiceMeltingRatex.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/FloatingiceMeltingRatex/FloatingiceMeltingRatex.cpp	(revision 22758)
@@ -29,4 +29,8 @@
 			MismipFloatingiceMeltingRatex(femmodel);
 			break;
+		case BasalforcingsPicoEnum:
+			if(VerboseSolution())_printf0_(" call Pico Floating melting rate module\n");
+			FloatingiceMeltingRatePicox(femmodel);
+			break;
 		default:
 			_error_("Basal forcing model "<<EnumToStringx(basalforcing_model)<<" not supported yet");
@@ -49,4 +53,5 @@
 		element->MismipFloatingiceMeltingRate();
 	}
+}
+/*}}}*/
 
-}/*}}}*/
Index: /issm/trunk/src/c/modules/FloatingiceMeltingRatex/FloatingiceMeltingRatex.h
===================================================================
--- /issm/trunk/src/c/modules/FloatingiceMeltingRatex/FloatingiceMeltingRatex.h	(revision 22757)
+++ /issm/trunk/src/c/modules/FloatingiceMeltingRatex/FloatingiceMeltingRatex.h	(revision 22758)
@@ -7,4 +7,5 @@
 
 #include "../../classes/classes.h"
+#include "../FloatingiceMeltingRatePicox/FloatingiceMeltingRatePicox.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/FourierLoveCorex/FourierLoveCorex.cpp
===================================================================
--- /issm/trunk/src/c/modules/FourierLoveCorex/FourierLoveCorex.cpp	(revision 22758)
+++ /issm/trunk/src/c/modules/FourierLoveCorex/FourierLoveCorex.cpp	(revision 22758)
@@ -0,0 +1,35 @@
+/*!\file FourierLoveCorex
+ * \brief: core solution module for love analysis. Based on Caron's fortran core. 
+ */
+
+#include "./FourierLoveCorex.h"
+
+#include "../../classes/classes.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+#include "../InputUpdateFromConstantx/InputUpdateFromConstantx.h"
+
+extern "C" { 
+	int lnb_setup_( IssmDouble* LoveKr, IssmDouble* LoveKi, IssmDouble* LoveHr, IssmDouble* LoveHi, IssmDouble* LoveLr, 
+		IssmDouble* LoveLi, IssmDouble* LoveKernelsReal, IssmDouble* LoveKernelsImag, 
+		int* pnfreq, IssmDouble* frequencies, int* psh_nmax, int* psh_nmin, IssmDouble* pg0, 
+		IssmDouble* pr0, IssmDouble* pmu0,bool* pallow_layer_deletion, int* pforcing_type, bool* pverbosemod,
+		int* pnumlayers, IssmDouble* radius, IssmDouble* viscosity, IssmDouble* lame_lambda, IssmDouble* lame_mu, 
+		IssmDouble* burgers_viscosity, IssmDouble* burgers_mu, IssmDouble* density, IssmDouble* isburgers, IssmDouble* issolid);
+}
+
+void FourierLoveCorex( IssmDouble* LoveKr, IssmDouble* LoveKi, IssmDouble* LoveHr, IssmDouble* LoveHi, IssmDouble* LoveLr, 
+		IssmDouble* LoveLi, IssmDouble* LoveKernelsReal, IssmDouble* LoveKernelsImag, 
+		int nfreq, IssmDouble* frequencies, int sh_nmax, int sh_nmin, IssmDouble g0, 
+		IssmDouble r0, IssmDouble mu0,bool allow_layer_deletion, int forcing_type, bool verbosemod,
+		int numlayers, IssmDouble* radius, IssmDouble* viscosity, IssmDouble* lame_lambda, IssmDouble* lame_mu, 
+		IssmDouble* burgers_viscosity, IssmDouble* burgers_mu, IssmDouble* density, IssmDouble* isburgers, IssmDouble* issolid){
+
+	/*Call fortran driver: */
+	lnb_setup_(  LoveKr,  LoveKi,  LoveHr,  LoveHi,  LoveLr, 
+		 LoveLi, LoveKernelsReal, LoveKernelsImag, 
+		 &nfreq,  frequencies,  &sh_nmax,  &sh_nmin, &g0,  
+		 &r0,  &mu0, &allow_layer_deletion, &forcing_type, &verbosemod,
+		 &numlayers,  radius,  viscosity,  lame_lambda,  lame_mu, 
+		 burgers_viscosity,  burgers_mu,  density,  isburgers,  issolid);
+}
Index: /issm/trunk/src/c/modules/FourierLoveCorex/FourierLoveCorex.h
===================================================================
--- /issm/trunk/src/c/modules/FourierLoveCorex/FourierLoveCorex.h	(revision 22758)
+++ /issm/trunk/src/c/modules/FourierLoveCorex/FourierLoveCorex.h	(revision 22758)
@@ -0,0 +1,18 @@
+/*!\file:  FourierLoveCorex.h
+ * \brief header file for ...
+ */ 
+
+#ifndef _FOURIERLOVECOREX_H
+#define _FOURIERLOVECOREX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void FourierLoveCorex( IssmDouble* LoveKr, IssmDouble* LoveKi, IssmDouble* LoveHr, IssmDouble* LoveHi, IssmDouble* LoveLr, 
+		IssmDouble* LoveLi, IssmDouble* LoveKernelsReal, IssmDouble* LoveKernelsImag, 
+		int nfreq, IssmDouble* frequencies, int sh_nmax, int sh_nmin, IssmDouble g0, 
+		IssmDouble r0, IssmDouble mu0,bool allow_layer_deletion, int forcing_type, bool verbosemod, 
+		int numlayers, IssmDouble* radius, IssmDouble* viscosity,IssmDouble* lame_lambda, IssmDouble* lame_mu, 
+		IssmDouble* burgers_viscosity, IssmDouble* burgers_mu, IssmDouble* density,IssmDouble* isburgers, IssmDouble* issolid);
+
+#endif  /* _FOURIERLOVECOREX_H */
Index: /issm/trunk/src/c/modules/FourierLoveCorex/Makefile
===================================================================
--- /issm/trunk/src/c/modules/FourierLoveCorex/Makefile	(revision 22758)
+++ /issm/trunk/src/c/modules/FourierLoveCorex/Makefile	(revision 22758)
@@ -0,0 +1,50 @@
+PROG =	lnb_calc.exe
+
+### Modules du programme 
+SRCS =  lnb_param.f90 lovenb_sub.f90 love_numbers.f90 model.f90 util.f90
+
+OBJS =  lnb_param.o model.o util.o lovenb_sub.o love_numbers.o
+
+MOD = lnb_param.mod model.mod util.mod lovenb_sub.mod
+
+SHTOOLSPATH = /home/caronlam/Codes/SHTOOLS-3.4
+
+LIBS =  -m64 -fPIC -O2 -ffast-math -L/usr/lib64 -lfftw3 -lm -llapack -lblas  
+#	LIBS =  -L$(SHTOOLSPATH)/lib -lSHTOOLS2.8 -llapack -lfftw3  -lm
+
+INCLUDE = -mcmodel=medium -I/usr/include 
+
+CC = cc
+CFLAGS = -O
+
+#F90 = gfortran -mcmodel=medium -O2
+F90= gfortran -O2
+#F90 = gfortran
+#F90 = g95
+#F90 = ifort
+
+F90FLAGS = 
+LDFLAGS =
+
+all: 	$(PROG)
+
+$(PROG): $(OBJS)
+	$(F90) $(LDFLAGS)  -o $@ $(OBJS) $(LIBS)
+
+clean:
+	rm -f $(PROG) $(OBJS) *.M *.mod *.T *.lst 
+
+.SUFFIXES: $(SUFFIXES) .f90
+
+.f90.o:
+	$(F90) $(F90FLAGS)  -c $< $(INCLUDE)
+
+#------------------------
+#Dependances
+#------------------------
+
+#invGIA.o: nblove.o, parameters.o
+love_numbers.o: lnb_param.o model.o lovenb_sub.o 
+model.o: lnb_param.o
+util.o: lnb_param.o model.o
+lovenb_sub.o: lnb_param.o model.o util.o
Index: /issm/trunk/src/c/modules/FourierLoveCorex/lnb_param.f90
===================================================================
--- /issm/trunk/src/c/modules/FourierLoveCorex/lnb_param.f90	(revision 22758)
+++ /issm/trunk/src/c/modules/FourierLoveCorex/lnb_param.f90	(revision 22758)
@@ -0,0 +1,35 @@
+module lnb_param
+
+ implicit none
+ 
+ public 
+
+ !Physical Constants
+ double precision, parameter :: GG = 6.67259e-11! gravitational constant
+ double precision :: ra,rb,rc ! radii of the surface, CMB and ICB
+ double precision :: pi,ro_mean,go_surf,go_icb,go_cmb !some constants
+ ! GG --> gravitational constant
+ ! ra, rb, rc --> Surface, CMB and ICB radius
+ ! ro_mean --> mean density of the planet 
+ ! go_surf --> mean surface gravity
+ ! go_icb/cmb --> gravity at the Inner Core/Core-Mantle Boundary
+ double precision   :: mu0,go0,r0 !3 normalization constants
+
+!Numerical Constants
+ double precision :: epsdb, layerrap !used in detecting underflows in the lovenb integration
+ double complex     :: valini,freq ! integration constant and angular frequency being processed
+ logical :: allow_layer_del,display, benchmark_spada !do we allow deletion of layers in case of underflow, enable some prints in terminal
+
+!GIA problem setup
+ integer :: deg,ifmin,ifmax ! deg=SH degree, ifmin/ifmax=which kind of forcing is applied (usually we want loading)
+ logical :: incompressible !choose which mode of calculation is activated
+
+!Earth Model 
+ integer :: nfreq, degmax, degmin
+ integer :: nlayer! number of layers
+ double precision, dimension(:), pointer :: roc,lac,muc,vic,vic2,muc2 ! Earth layers parameters
+ double precision, dimension(:), pointer :: radius ! Earth layers parameters
+ double precision :: vicratio,mucratio !2 Burgers long-term to short-term ratios
+ logical, dimension(:), pointer :: soliddim,radbc,burgers ! is this layer solid (if not it's liquid), does it have specific boundary conditions and does it have a Burgers rheology (if not, it uses Maxwell)
+ 
+end module lnb_param
Index: /issm/trunk/src/c/modules/FourierLoveCorex/lnb_param.mod
===================================================================
--- /issm/trunk/src/c/modules/FourierLoveCorex/lnb_param.mod	(revision 22758)
+++ /issm/trunk/src/c/modules/FourierLoveCorex/lnb_param.mod	(revision 22758)
@@ -0,0 +1,141 @@
+GFORTRAN module version '10' created from lnb_param.f90
+MD5:07349d97d2b98213e660e1a97b540f41 -- If you edit this, you'll get what you deserve.
+
+(() () () () () () () () () () () () () () () () () () () () () () () ()
+() () ())
+
+()
+
+()
+
+()
+
+()
+
+()
+
+(2 '__convert_r4_r8' '(intrinsic)' '' 1 ((PROCEDURE UNKNOWN-INTENT
+UNKNOWN-PROC UNKNOWN UNKNOWN 0 0 FUNCTION ELEMENTAL PURE) (REAL 8 0 0 0
+REAL ()) 0 0 () () 2 () () () 0 0)
+3 'allow_layer_del' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT
+UNKNOWN-PROC UNKNOWN IMPLICIT-SAVE 0 0) (LOGICAL 4 0 0 0 LOGICAL ()) 0 0
+() () 0 () () () 0 0)
+4 'benchmark_spada' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT
+UNKNOWN-PROC UNKNOWN IMPLICIT-SAVE 0 0) (LOGICAL 4 0 0 0 LOGICAL ()) 0 0
+() () 0 () () () 0 0)
+5 'burgers' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0 DIMENSION POINTER) (LOGICAL 4 0 0 0 LOGICAL ())
+0 0 () (1 0 DEFERRED () ()) 0 () () () 0 0)
+6 'deg' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+7 'degmax' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () ()
+() 0 0)
+8 'degmin' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () ()
+() 0 0)
+9 'display' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (LOGICAL 4 0 0 0 LOGICAL ()) 0 0 () () 0 () ()
+() 0 0)
+10 'epsdb' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0
+0)
+11 'freq' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (COMPLEX 8 0 0 0 COMPLEX ()) 0 0 () () 0 () ()
+() 0 0)
+12 'gg' 'lnb_param' '' 1 ((PARAMETER UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () (CONSTANT (REAL 8 0 0 0
+REAL ()) 0 '0.495dac00000000@-8') () 0 () () () 0 0)
+13 'go0' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+14 'go_cmb' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0
+0)
+15 'go_icb' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0
+0)
+16 'go_surf' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0
+0)
+17 'ifmax' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () ()
+() 0 0)
+18 'ifmin' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () ()
+() 0 0)
+19 'incompressible' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT
+UNKNOWN-PROC UNKNOWN IMPLICIT-SAVE 0 0) (LOGICAL 4 0 0 0 LOGICAL ()) 0 0
+() () 0 () () () 0 0)
+20 'lac' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0 DIMENSION POINTER) (REAL 8 0 0 0 REAL ()) 0 0 () (1 0
+DEFERRED () ()) 0 () () () 0 0)
+21 'layerrap' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0
+0)
+22 'lnb_param' 'lnb_param' '' 1 ((MODULE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN UNKNOWN 0 0) (UNKNOWN 0 0 0 0 UNKNOWN ()) 0 0 () () 0 () () () 0
+0)
+23 'mu0' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+24 'muc' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0 DIMENSION POINTER) (REAL 8 0 0 0 REAL ()) 0 0 () (1 0
+DEFERRED () ()) 0 () () () 0 0)
+25 'muc2' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0 DIMENSION POINTER) (REAL 8 0 0 0 REAL ()) 0 0
+() (1 0 DEFERRED () ()) 0 () () () 0 0)
+26 'mucratio' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0
+0)
+27 'nfreq' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () ()
+() 0 0)
+28 'nlayer' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () ()
+() 0 0)
+29 'pi' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+30 'r0' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+31 'ra' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+32 'radbc' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0 DIMENSION POINTER) (LOGICAL 4 0 0 0 LOGICAL ())
+0 0 () (1 0 DEFERRED () ()) 0 () () () 0 0)
+33 'radius' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0 DIMENSION POINTER) (REAL 8 0 0 0 REAL ()) 0 0
+() (1 0 DEFERRED () ()) 0 () () () 0 0)
+34 'rb' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+35 'rc' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+36 'ro_mean' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0
+0)
+37 'roc' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0 DIMENSION POINTER) (REAL 8 0 0 0 REAL ()) 0 0 () (1 0
+DEFERRED () ()) 0 () () () 0 0)
+38 'soliddim' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0 DIMENSION POINTER) (LOGICAL 4 0 0 0 LOGICAL ())
+0 0 () (1 0 DEFERRED () ()) 0 () () () 0 0)
+39 'valini' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (COMPLEX 8 0 0 0 COMPLEX ()) 0 0 () () 0 () ()
+() 0 0)
+40 'vic' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0 DIMENSION POINTER) (REAL 8 0 0 0 REAL ()) 0 0 () (1 0
+DEFERRED () ()) 0 () () () 0 0)
+41 'vic2' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0 DIMENSION POINTER) (REAL 8 0 0 0 REAL ()) 0 0
+() (1 0 DEFERRED () ()) 0 () () () 0 0)
+42 'vicratio' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0
+0)
+)
+
+('__convert_r4_r8' 0 2 'allow_layer_del' 0 3 'benchmark_spada' 0 4
+'burgers' 0 5 'deg' 0 6 'degmax' 0 7 'degmin' 0 8 'display' 0 9 'epsdb'
+0 10 'freq' 0 11 'gg' 0 12 'go0' 0 13 'go_cmb' 0 14 'go_icb' 0 15
+'go_surf' 0 16 'ifmax' 0 17 'ifmin' 0 18 'incompressible' 0 19 'lac' 0
+20 'layerrap' 0 21 'lnb_param' 0 22 'mu0' 0 23 'muc' 0 24 'muc2' 0 25
+'mucratio' 0 26 'nfreq' 0 27 'nlayer' 0 28 'pi' 0 29 'r0' 0 30 'ra' 0 31
+'radbc' 0 32 'radius' 0 33 'rb' 0 34 'rc' 0 35 'ro_mean' 0 36 'roc' 0 37
+'soliddim' 0 38 'valini' 0 39 'vic' 0 40 'vic2' 0 41 'vicratio' 0 42)
Index: /issm/trunk/src/c/modules/FourierLoveCorex/love_numbers.f90
===================================================================
--- /issm/trunk/src/c/modules/FourierLoveCorex/love_numbers.f90	(revision 22758)
+++ /issm/trunk/src/c/modules/FourierLoveCorex/love_numbers.f90	(revision 22758)
@@ -0,0 +1,385 @@
+ 
+ !subroutine lnb_setup {{{
+ subroutine lnb_setup(  ksr, ksi, hsr, hsi, lsr, lsi, lksr, lksi, dnfreq,  frequencies,  ddegmax, ddegmin, &
+          dgo0,  dr0,  dmu0, dallow_layer_del, source_type, ddisplay, dnlayer,  dradius,    &
+          dvic,  dlac,  dmuc, dvic2,  dmuc2,  droc, dburgers,  dsoliddim)
+
+ use lnb_param
+ use util
+ implicit none
+
+ integer :: dnfreq, ddegmax, ddegmin
+ integer :: dnlayer
+ integer :: source_type, fr, i, IERR
+ double precision :: T,cst, fluid_tscale,g
+ double precision, dimension(dnfreq,ddegmax+1) :: hsr,hsi,lsr,lsi,ksr,ksi
+ double complex, dimension(dnfreq,ddegmax+1) :: hs,ls,ks
+ double precision, dimension(dnfreq) :: frequencies
+
+ double complex :: lks(dnfreq,(ddegmax+1)*(dnlayer+1)*6) 
+ double precision, dimension(dnfreq,(ddegmax+1)*(dnlayer+1)*6) :: lksr, lksi 
+ 
+ double precision   :: dmu0,dgo0,dr0
+ logical :: dallow_layer_del, ddisplay
+
+ double precision, dimension(dnlayer) :: droc,dlac,dmuc,dvic,dvic2,dmuc2 
+ double precision, dimension(dnlayer+1) :: dradius 
+ double precision, dimension(dnlayer) :: dsoliddim,dburgers 
+
+ !assign local variables to public variables
+ mu0=dmu0; go0=dgo0; r0=dr0; allow_layer_del=dallow_layer_del; 
+ nfreq=dnfreq;degmax=ddegmax;degmin=ddegmin;nlayer=dnlayer; 
+ allocate(roc(nlayer),lac(nlayer),muc(nlayer),vic(nlayer),vic2(nlayer),muc2(nlayer))
+ roc=droc; lac=dlac; muc=dmuc; vic=dvic; vic2=dvic2; muc2=dmuc2; 
+ allocate(radius(nlayer+1),soliddim(nlayer),burgers(nlayer),radbc(nlayer+1))
+ radius=dradius; 
+
+	display=ddisplay
+	!print*,display
+	do i=1,nlayer
+	if (NINT(dsoliddim(i))==1) then
+		soliddim(i)=.true.
+	else
+		soliddim(i)=.false.
+	endif 
+	if (NINT(dburgers(i))==1) then
+		burgers(i)=.true.
+	else
+		burgers(i)=.false.
+	endif 
+	enddo
+
+ pi=dacos(-1.d0)
+
+ ra=radius(nlayer+1)
+ rb = 3480.d3
+ rc = 1221.5d3
+ r0=ra
+ cst = 365.25d0*24.d0*3600.d0*1000.d0 
+
+ benchmark_spada=.false.
+ !frequencies=1E-5/cst*2*pi
+
+	hs(:,:)=(0.d0,0.d0)
+	ks=hs
+	ls=hs
+ 
+ call love_numbers(frequencies,source_type,hs,ls,ks,lks)
+
+ hsr=dble(hs)
+ hsi=dimag(hs)
+ ksr=dble(ks)
+ ksi=dimag(ks)
+ lsr=dble(ls)
+ lsi=dimag(ls)
+ !!! love kernels 
+ lksr=dble(lks)
+ lksi=dimag(lks)
+
+end subroutine
+! }}}
+
+!subroutine love_numbers {{{
+ subroutine love_numbers(frequencies,source_type,hs,ls,ks,lks)
+
+ use model
+ use lovenb_sub
+
+ double complex, dimension(:,:), pointer :: bc
+ double complex, dimension(:,:), pointer :: f
+ character*40,     dimension(:),   pointer :: sourcs
+ integer,          dimension(:),   pointer :: indx,indx2
+ integer :: nbc,nfext,ifreq,ntheta2,nphi2
+ double precision :: cst,prec, delta!,h1,h2,k1,k2,l1,l2,dh1,dh2,dk1,dk2,dl1,dl2
+ double precision :: he,ke,le
+ double precision :: frequencies(nfreq), fluid_tscale
+ double complex :: loveh,lovel,lovek
+ logical :: logi
+ integer :: i,j,k,n, fr,m,l, source_type
+ double complex :: hs(nfreq,degmax+1), ls(nfreq,degmax+1), ks(nfreq,degmax+1)
+ 
+ double complex, dimension((nlayer+1)*6,1) :: lovekernels
+ double complex :: lks(nfreq,(degmax+1)*(nlayer+1)*6) 
+
+ double precision :: cpu_time1(100)
+ integer :: cpu_count
+
+ pi=dacos(-1.d0)
+
+
+  open(unit=101, file='lastrun_log')
+ cpu_count=0
+ cpu_count=cpu_count+1;call cpu_time(cpu_time1(cpu_count))
+ !write(101,*), 'Done !', cpu_time1(cpu_count), 's'
+ !write(101,*),''
+
+
+ !double precision, dimension(:), pointer :: vech,vecl,veck,vecd,vec
+
+ radbc(:)=.false.
+ radbc(1)=.true.
+ radbc(nlayer+1)=.true.
+ do i=2,nlayer
+  if ((.not.soliddim(i)).or.(.not.soliddim(i-1))) then
+   radbc(i)=.true.
+  end if
+ end do
+ 
+
+ ! Test number of interfaces and of boundary conditions
+  nbc = 0
+  !!! >>> SA: 01/27/2018 => following changes are made to retrieve love numbers at depth 
+  !do i=1,nlayer+1 
+ !if (radbc(i)) nbc=nbc+6
+  !enddo
+  nbc = (nlayer+1)*6
+  !!! >>> SA 
+
+ ifmin=source_type
+ ifmax=source_type
+ 
+
+  if (display) then
+	 print*,'model init'
+ endif
+
+
+ call model_init2(nbc)  
+
+
+  if (display) then
+	 print*, 'done'
+ endif
+
+ nfext = 13 ! Number of potential excitation sources
+ allocate( bc(nbc,nbc), indx(nbc) )
+ allocate( f(nfext,nbc), sourcs(nfext) )
+
+ sourcs(1)='ICB --Volumetric Potential' 
+ sourcs(2)='ICB --Pressure'
+ sourcs(3)='ICB --Loading'
+ sourcs(4)='ICB --Tangential Traction'
+ sourcs(5)='CMB --Volumetric Potential'
+ sourcs(6)='CMB --Pressure'
+ sourcs(7)='CMB --Loading'
+ sourcs(8)='CMB --Tangential Traction'
+ sourcs(9)='SURF--Volumetric Potential'
+ sourcs(10)='SURF--Pressure'
+ sourcs(11)='SURF--Loading'
+ sourcs(12)='SURF--Tangential Traction'
+
+ 
+ if (display)  print*, 'source_type =', source_type, ', ', sourcs(source_type)
+ if (source_type<9) then
+  print*,'Error: Internal loading not supported yet, please input source_type between 9 and 12'
+  print*,'Reference:'
+  do i=1,12
+   print*,i,sourcs(i)
+  enddo
+ return
+ endif
+
+
+! Print/write control
+ !display=.false. ! Printing on the terminal
+ 
+ ! Calculation optimization (avoids underflows at high degree)
+ !allow_layer_del = .true.     ! Do we allow deletion of the central layers in the calculation if necessary?
+ layerrap = 1.d0  ! Max absolute ratio between love numbers at the top and bottom of the last layer
+ 
+ ! Mode search parameters
+ freq0 = -1.d10
+ logi = .true.
+ cst = 365.25d0*24.d0*3600.d0*1000.d0 
+ prec = 1.d-8
+ firstmode = 0.d0
+
+ 
+ cpu_count=cpu_count+1;call cpu_time(cpu_time1(cpu_count))
+ !write(101,*), 'Earth model initialization :', cpu_time1(cpu_count) -cpu_time1(cpu_count-1), 's'
+ !write(101,*),''
+ if (display) then
+ write(*,*), 'Earth model initialization :', cpu_time1(cpu_count) -cpu_time1(cpu_count-1), 's'
+ write(*,*),''
+ endif
+
+! Spherical Harmonics initialization
+
+
+
+! -- SH degree loop
+
+
+ bc(:,:)=0.d0
+ 
+ 
+  !write(101,*), 'Calculating impulse response'
+ if (display) then
+ write(*,*), 'Calculating impulse response'
+ endif
+ 	if (maxval(frequencies).ne.0 .and. display) then
+		print*, 'Frequency ranging from ', minval(dabs(frequencies)), &
+		' to ', maxval(frequencies),' s^-1'
+	endif 
+
+	if (frequencies(1)==0 .and. display) then
+		print*,'Elastic calculation'
+	endif
+ deg=degmin-1
+
+
+
+
+ do l = degmin,degmax 
+ deg=deg+1
+ !write(*,*)
+  !write(*,*)
+  !write(101,fmt='(A19, 10X,A2,I3,A1,I3)',ADVANCE='NO'), repeat(char(8),19),'l=',deg,'/',degmax
+  if (display) then
+  write(*,fmt='(A10,A2,I5,A1,I5)',ADVANCE='NO'),repeat(char(32),10),'l=',deg,'/',degmax
+  endif
+
+  !write(*,*)
+  !!write(101,*), fr, T
+
+
+
+
+ do fr=1,nfreq
+
+  !!write(101,*),fr
+
+
+  !the way Fourier Transform algorithms works : they calculate for fmin=0 to fmax=1/dt
+  !by aliasing for this algo, f=1/(2*dt) to f=1/dt is the same as f=-1/(2*dt) to f=0
+  !but physics-wise, the Earth response at high frequency is not what we are looking for
+  !the [0 ; 1/(2*dt)] interval and its negative counterpart are what we are looking for
+  !therefore in our love number calculation the frenquency set must be [0 ; 1/(2*dt) ] U [-1/(2*dt) 0[
+
+  !if (fr==1) then ! the variable freq is, in fact, the pulsation = 2*pi*frequency
+  ! fluid_tscale=-575.502 / (deg+91.1765) -0.176471 ! this formula sets fluid time scale = 1e6 kyr at degree 2, 1e5 kyr at degree 20 and 1e3 kyr at degree 90, which allows no error growth and still the fluid number as the benchmark at all degree (tested up to degmax=147)
+   !print*,fluid_tscale
+  ! freq=complex(0.d0,1.d0)*2.d0*pi*(10.d0**(fluid_tscale)/cst) ! empiric time period that changes according to harmonic degree to ensure getting fluid response without crazy error growing for high degree
+! it is meant to approximate the theoretical freq=0.d0 that should be assessed for fft
+  !elseif (fr <= nfreq/2+1) then
+  ! freq=complex(0.d0,1.d0)*(dble(fr-1)/T)*2.d0*pi
+  !else 
+  ! freq=complex(0.d0,1.d0)*(-dble(nfreq+1-fr)/T)*2.d0*pi
+  !end if
+  
+  freq=dcmplx(0.d0,frequencies(fr))
+  !print*,fr,freq
+
+  !if (deg==degmin) write(31,*),fr,real(freq)*cst,aimag(freq)*cst,time(fr)
+  !freq=dble(fr)/T
+  !--  Elastic Love number calculation
+  !freq=2.d0*pi/(1e4*cst)*complex(0.d0,1.d0)
+
+   !if (deg==2) then ! for rotationnal feedback
+   !ifmin=9;ifmax=9 ! Sets tidal calculation
+   !bc(:,:)=0.d0
+   !call boundary_conditions_matrix(bc,indx,nbc)
+   !call external_forcing(deg,f,sourcs,nfext,nbc) 
+   !call solution(deg,bc,indx,f,sourcs,nfext,nbc,loveh,lovel,lovek,delta)
+   !k2tidal(fr)=lovek-1.d0
+   !h2tidal(fr)=loveh
+   !l2tidal(fr)=lovel
+   !ifmin=11;ifmax=11 ! Sets back loading calculation
+   !endif
+   !print*,(deg)
+   bc(:,:)=0.d0
+   call boundary_conditions_matrix(bc,indx,nbc)
+	!print*,'bc ok', layerrap
+   call external_forcing(deg,f,sourcs,nfext,nbc) 
+	!print*,'forcing ok', layerrap
+   call solution(deg,bc,indx,f,sourcs,nfext,nbc,loveh,lovel,lovek,delta,lovekernels)
+
+	!print*,'first_sol', layerrap, epsdb
+
+   ! Automatic reduction of the number of layers when the attenuation with depth becomes too strong
+   if (allow_layer_del.eqv..true.) then
+
+     do while ((layerrap<=epsdb).and.(nbc>12).or.(isnan(layerrap)) )
+ !		print*,'trying to delete layer', layerrap, epsdb, nbc
+     !write(101,*)
+     !write(101,*) 'Rapport Nombre de Love surface/profondeur faible : ', layerrap 
+     !write(101,*) ' Changement d''interface de debut d''integration' 
+
+     if (display) then
+     write(*,*)
+     write(*,*) 'Surface/Depth Love number ratio small: ', layerrap 
+     write(*,*) ' Changing the interface where the integration starts'
+     endif
+
+     nbc = nbc-6
+     n = 1
+     do while (.not.radbc(n))
+      n = n+1
+     end do
+     radbc(n) =.false.
+     !write(101,*) ' New start interface: ', radius(n+1)/1.d3,' km'
+     if (display) then
+     write(*,*) ' New start interface: ', radius(n+1)/1.d3,' km'
+     endif
+        
+     deallocate( bc, indx, f, sourcs )
+     allocate( bc(nbc,nbc), indx(nbc) )
+     allocate( f(nfext,nbc), sourcs(nfext) )
+  
+
+     bc(:,:)=0.d0
+     call boundary_conditions_matrix(bc,indx,nbc)
+     call external_forcing(deg,f,sourcs,nfext,nbc) 
+     call solution(deg,bc,indx,f,sourcs,nfext,nbc,loveh,lovel,lovek,delta,lovekernels)
+
+    end do
+   end if
+
+   !-- Saving Love numbers
+    hs(fr,deg+1) = loveh
+    ks(fr,deg+1) = lovek - 1.d0
+    ls(fr,deg+1) = lovel
+    
+    !!! and love kernels 
+    do i=1,nbc
+      lks(fr,deg*nbc+i) = lovekernels(i,1)
+    end do
+    !!! for ks... 6th variable is y5 => love_k
+    do i = 1,nbc/6
+      lks(fr,deg*nbc+6*i) = lks(fr,deg*nbc+6*i) - (radius(i)/ra)**deg
+    end do 
+
+	!print*,dble(hs(fr,deg+1)), dimag(hs(fr,deg+1)),dble(ks(fr,deg+1)), dimag(ks(fr,deg+1))
+
+    !if (fr==1) then ! if this is supposed to be fluid response
+    !  ! then cut off the imaginary part, which is inherited from approximating t=infinity to a few million years (see above the setting of freq)
+    ! hs(fr,deg+1)=real(hs(fr,deg+1))
+    ! ks(fr,deg+1)=real(ks(fr,deg+1))
+    ! ls(fr,deg+1)=real(ls(fr,deg+1))
+    !endif
+!~~~~~~~~~~~~~~TEST ZONE~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ if (benchmark_spada) then
+ write(17,*), deg,fr,dble(hs(fr,deg+1)), dimag(hs(fr,deg+1)),dble(ks(fr,deg+1)), dimag(ks(fr,deg+1))
+ endif
+!~~~~~~~~~~~~~~END TEST ZONE~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+
+  !write(*,*) 'Elastic Love Numbers:  ',ke,he,le 
+  !write(ifile1,*) deg,ke,he,le
+ end do
+ 
+ end do
+
+
+ cpu_count=cpu_count+1;call cpu_time(cpu_time1(cpu_count))
+ !write(101,*), 'Earth model initialization :', cpu_time1(cpu_count) -cpu_time1(cpu_count-1), 's'
+ !write(101,*),''
+ if (display) then
+ write(*,*), 'Love number calc done :', cpu_time1(cpu_count) -cpu_time1(cpu_count-1), 's'
+ write(*,*),''
+ endif
+
+ deallocate( bc, indx, f, sourcs )
+end subroutine
+! }}} 
+
Index: /issm/trunk/src/c/modules/FourierLoveCorex/lovenb_sub.f90
===================================================================
--- /issm/trunk/src/c/modules/FourierLoveCorex/lovenb_sub.f90	(revision 22758)
+++ /issm/trunk/src/c/modules/FourierLoveCorex/lovenb_sub.f90	(revision 22758)
@@ -0,0 +1,647 @@
+module lovenb_sub
+
+ use util
+ use lnb_param
+
+ implicit none
+ 
+ contains
+ 
+ ! subroutine boundary_conditions_matrix {{{ 
+ subroutine boundary_conditions_matrix(bc,indx,nbc)
+
+  implicit none
+  double complex :: la, mu
+  double precision :: xmin,xmax,eps,hini,hmin
+  double precision :: x,ro1,ro2,g,d,one
+  double complex, dimension (:,:), pointer :: bc
+  integer, dimension(:), pointer   :: indx
+  double complex, dimension(6)   :: ystart,dydx
+  double complex, dimension(6,6) :: ystep
+  integer :: ny,i,j,k,ii,jj,kk,nok,nbad,is,nbc,ibc,ifirst,nstep
+  logical :: solid,vali
+  
+  !-- Initialisation of boundary condition matrix
+
+  indx(:) = 0
+  
+  !-- Integration 
+
+  eps= 1.d-10
+  hini=1.d-10
+  hmin=0.d0
+
+  ! Underflows risk tests in the numerical integration
+  ! The starting ystart are chosen to be different than 1 to limit under and overflows in the Runge-Kutta
+  if (-300.d0<dlog10(tiny(ra))) then 
+	write(*,*) 'Warning problem in the dimensioning of the starting values in Runge-Kutta'
+	write(*,*) 'log tiny(ra) = ', dlog(tiny(ra))
+	stop
+  endif
+
+	
+   if ((dlog10(1.d0/ra**dint(dble(deg)/10.d0)))<-250.d0) then
+	valini=1.d-300!*complex(1.d0,1.d0)
+   else
+	valini= 1.d0!*complex(1.d0,1.d0)
+   endif
+
+  
+  ! Which among the model interfaces is the first to display boundary conditions
+  ifirst = 0
+  i = 0
+  do while (ifirst==0)
+	i = i+1
+	if (radbc(i)) ifirst = i
+  end do
+  
+  
+  !-- Layer iteration for the solutions propagation 
+  !    and typing the matrix boundary conditions 
+  ibc = 0   ! Counter of interfaces with boundary conditions 
+
+  do i = ifirst,nlayer 
+  
+   xmin= radius(i)/ra
+   xmax= radius(i+1)/ra - epsdb
+   nstep=100
+  
+   if (soliddim(i)) then
+   		ny = 6
+   		is = 0
+   		one= 1.d0
+   else	
+   		ny = 2
+   		is = 4
+   		one= -1.d0
+   end if 	
+   
+   do j = 1,ny
+		! Typing ystart 
+      !!! >>> SA: 01/27/2018 => changes made to retrieve love numbers at depth 
+		!!!if (radbc(i)) then
+   		ystart(:)=0.d0
+			ystart(j)= valini
+ 			k=ibc+1
+ 		!!!else
+ 		!!!	ystart(:)=ystep(j,:)
+ 		!!!end if
+ 		
+		! Numerical Integration 
+		!print*,j
+		call propagFDS(ystart,xmin,xmax,nstep)
+ 		!call odeint(ystart,ny,xmin,xmax,eps,hini,hmin,nok,nbad)
+		!print*,j
+ 		
+ 		! Boundary Condition matrix - propagation part 
+		!!!if (radbc(i+1)) then
+ 			ii = 6*k+is
+ 			jj = 6*k+j+is-3
+ 			do kk=1,ny
+				bc(ii+kk,jj) = ystart(kk)*one
+			end do
+		!!!else
+		!!!	ystep(j,:)=ystart(:) 
+ 		!!!end if
+   end do
+	
+	
+   !!!if (radbc(i)) then
+   
+	! Boundary Condition matrix - solid regions
+	if (soliddim(i)) then
+		one = -1.d0
+		if (i>1)then 
+			if (.not.soliddim(i-1)) one = 1.d0
+		end if
+		do  j=1,6
+			bc(j+6*ibc,j+6*ibc+3) = one
+		end do
+		
+	! Boundary Condition matrix - liquid regions
+	else
+		x = radius(i)/ra
+		call earth_nlayers_viscoelas(x,ro2,la,mu,g,solid)
+		ii = 6*ibc+1
+		bc(ii,ii+3) = -1.d0
+		bc(ii,ii+4+3) = -go0/g
+		bc( ii+1,ii+3)=-ro2*g*ra/mu0
+		bc( ii+2,ii+1+3)=-1.d0
+		bc(ii+5,ii+3)= 4.d0*pi*GG*ro2*ra/go0
+		bc(ii+4,ii+4+3)=-1.d0
+		bc(ii+5,ii+5+3)=-1.d0
+		x = radius(i+1)/ra
+		call earth_nlayers_viscoelas(x-epsdb,ro1,la,mu,g,solid)
+		call earth_nlayers_viscoelas(x,ro2,la,mu,g,solid)
+		ii = 6*(ibc+1)+1
+		bc(ii,ii-1)=-1.d0
+		bc(ii,ii+1)=bc(ii+4,ii+1)*go0/g ! b(17,14) solution integration 1 of z5 CMB
+		bc(ii,ii+2)=bc(ii+4,ii+2)*go0/g ! b(17,15) solution integration 2 of z5 CMB
+		 					  ! b(13,..) y1 CMB
+		bc(ii+1,ii-1)=-ro1*g*ra/mu0
+		bc(ii+2,ii)=-1.d0
+		bc(ii+5,ii-1)= 4.d0*pi*GG*ro1*ra/go0
+	end if	
+	ibc = ibc+1
+	
+   !! end if
+	
+  end do
+
+
+  !-- Internal sphere
+
+  call sphere(ifirst,deg,bc)
+
+  !-- Surface conditions
+	bc(nbc-5,nbc-2)=-1.d0
+	bc(nbc-3,nbc-1)=-1.d0
+	bc(nbc-1,nbc)=-1.d0
+	bc(nbc,nbc)=dble(deg+1)
+
+  !-- Degree 1 special case
+	if(deg==1) then
+		  bc(nbc,:)=0.d0
+		  bc(nbc,nbc)=1.d0
+	end if
+	
+
+	!print*, bc, imag_eval
+ end subroutine boundary_conditions_matrix
+  ! }}} 
+ 
+ ! subroutine sphere {{{
+ subroutine sphere(i,n,bc)
+!------------------------
+
+	implicit none
+	double complex :: la,mu
+	integer :: n,i
+	double precision :: x,e,r,ro,g,cst,xsen,eps
+	double complex, dimension(:,:),pointer :: bc
+
+	logical :: solid
+	
+
+	eps= 1.d-10
+	x = radius(i)/ra
+	e = x
+	call earth_nlayers_viscoelas(x-eps,ro,la,mu,g,solid)
+	
+	xsen=(x/e)**n
+	r=x*ra
+	cst = 4.d0*pi*GG*ro
+
+	!write(89,*),xsen,r,ra,cst,mu0,mu,n	
+
+
+	bc(1,1)=xsen*r/ra
+	bc(1,2)=xsen/(r*ra)
+	bc(1,3)=0.d0
+
+	bc(2,1)=(2.d0*mu*dble(n*n-n-3)/dble(n) + cst/3.d0*ro*r**2)*xsen/mu0
+	bc(2,2)=(2.d0*mu*dble(n-1)/r**2 + cst/3.d0*ro)*xsen/mu0
+	bc(2,3)=-ro*xsen/mu0
+
+	bc(3,1)=dble(n+3)/dble(n*(n+1))*xsen*r/ra
+	bc(3,2)=1.d0/dble(n)*xsen/(r*ra)
+	bc(3,3)=0.d0
+
+	bc(4,1)=2.d0*mu*dble(n+2)/dble(n+1)*xsen/mu0
+	bc(4,2)=2.d0*mu*dble(n-1)/dble(n)*xsen/(r**2*mu0)
+	bc(4,3)=0.d0
+
+	bc(5,1)=0.d0
+	bc(5,2)=0.d0
+	bc(5,3)=xsen/(go0*ra)
+
+	bc(6,1)=-cst*xsen*r/go0
+	bc(6,2)=-cst*xsen/(r*go0)
+	bc(6,3)=dble(n)*xsen/(r*go0)
+
+
+ end subroutine sphere
+ ! }}} 
+ 
+ ! subroutine external_forcing {{{
+ subroutine external_forcing(n,source,sourcs,nfext,nbc)
+!-----------------------------------
+
+   implicit none
+   integer :: n
+   integer :: nfext,nbc
+   character*40,     dimension(:),   pointer :: sourcs
+   double complex, dimension(:,:), pointer :: source
+   
+   source(:,:)=0.d0
+   sourcs(:)=' '
+	  
+   ! In Case of a Inner Core - Outer Core - Mantle planet and Boundary conditions on these 3 interfaces
+   if (nbc == 24) then 
+   
+	!-- Sources at the ICB
+   
+	sourcs(1)='ICB --Volumetric Potential'
+	source(1,12)=dble(n)/(rc*go0)
+	source(1,11)=1.d0/(ra*go0)
+	
+	sourcs(2)='ICB --Pressure'
+	source(2, 8)=-ro_mean/mu0
+
+	sourcs(3)='ICB --Loading'
+	source(3, 8)=-ro_mean*dble(2*n+1)/(3.d0*mu0)*ra/rc
+	source(3,12)= dble(2*n+1)/(rc*go0)
+
+	sourcs(4)='ICB --Tangential Traction'
+	source(4,10)= ro_mean/mu0
+
+	!--Sources at the CMB
+
+	sourcs(5)='CMB --Volumetric Potential'
+	source(5,14)=-ro_mean/mu0*ra/rb
+	source(5,18)= dble(2*n+1)/(rb*go0)
+
+	sourcs(6)='CMB --Pressure'
+	source(6,14)=-ro_mean/mu0
+
+	sourcs(7)='CMB --Loading'
+	source(7,14)=-ro_mean*dble(2*n+1)/(3.d0*mu0)*ra/rb
+	source(7,18)= dble(2*n+1)/(rb*go0)
+
+	sourcs(8)='CMB --Tangential Traction'
+	source(8,16)=-ro_mean/mu0
+	
+    endif
+
+    !--Sources at the surface
+
+	sourcs(9)='SURF--Volumetric Potential'
+	source(9,nbc)=dble(2*n+1)/(ra*go0)
+
+	sourcs(10)='SURF--Pressure'
+	source(10,nbc-4)=-ro_mean/mu0
+
+	sourcs(11)='SURF--Loading'
+	source(11,nbc-4)=-ro_mean*dble(2*n+1)/(3.d0*mu0)
+	source(11,nbc)= dble(2*n+1)/(ra*go0)
+
+	sourcs(12)='SURF--Tangential Traction'
+	source(12,nbc-2)= ro_mean/mu0
+
+	!--Special case n=1
+
+	if (n.eq.1) then
+	  source(11,nbc)=0.d0
+	  source(9,nbc)=0.d0
+	end if
+	
+ 
+ end subroutine external_forcing
+ ! }}} 
+ 
+ ! subroutine solution {{{ 
+ subroutine solution(n,bc,indx,f,sourcs,nfext,nbc,loveh,lovel,lovek,delta,love_kernels)
+!-------------------------------------------------
+
+  integer :: n,nfext,nbc,i,j,ic,ibc,ii,jj,icmin,ifirst,info,lda,ldb
+  double complex, dimension(:,:), pointer :: bc,f
+  integer,      dimension(:), pointer :: indx
+  character*40, dimension(:), pointer :: sourcs	
+  double complex, dimension(nbc,1) :: sc, love_kernels
+  double complex :: loveh,lovel,lovek,loveh1,lovel1,lovek1,loveh1s,lovel1s,lovek1s
+  double complex :: sumh,suml,sumk,d,val,sumy2,sumy4,sumy6,rads
+  double precision :: delta
+  double complex, dimension(6) :: icbh,icbl,icbk,y2srf,y4srf,y6srf
+  double complex, dimension(nbc,nbc) :: bcsav
+  integer :: ipiv(nbc)
+  logical :: ok
+
+
+  bcsav(:,:) = bc(:,:)
+  rads=0.d0
+  lda=nbc
+  ldb=nbc
+
+
+  ifirst = 0
+  i = 0
+  do while (ifirst==0)
+	i = i+1
+	if (radbc(i)) ifirst = i
+  end do
+! do i = 1,nbc 
+!	do j = 1,nbc
+!	if (bc(i,j)/=0.d0) print*, i,j,bc(i,j)
+!	enddo
+! enddo
+! write(*,*)
+  
+  !-- LU decomposition and determinant
+    ok = .true.
+   
+  !call ludcmp(bc,nbc,nbc,indx,d)
+  !do i=1,nbc
+  !   d=d*bc(i,i)
+  !end do
+  !if (display) write(*,*)
+  !write(*,*),dlog(freq),'   Matrix det = ',d/dabs(d)*dlog(dabs(d))
+  !if (display) write(*,*),dlog10(freq*365.25d0*24.d0*3600.d0*1000.d0),'   Matrix det = ',d
+  !write(ifile5,*) freq,d
+
+!-- Resolution
+
+  if (ok) then
+  do i = ifmin,ifmax
+  	
+	do j=1,nbc
+	  sc(j,1)=f(i,j)
+	end do
+
+	!if (display) write(*,*) 'Source: ',sourcs(i)
+	!call lubksb(bc,nbc,nbc,indx,sc)
+	call ZGESV(nbc,1,bc,lda,ipiv,sc,ldb,info)
+
+	if (info.ne.0) then 
+		print*, 'Error in ZGESV : LAPACK linear equation solver couldn''t resolve the system'
+	end if
+   !!! >>> y1, y3, y5 at surface (by default) 
+	loveh = sc(nbc-2,1)*ra*go_surf
+	lovel = sc(nbc-1,1)*ra*go_surf
+	lovek = sc(nbc,1)*ra*go0
+	delta = (1.d0-dble(n+1)/dble(n)*(lovek-1.d0)+2.d0/dble(n)*loveh)
+
+   !!! >>> at depth [by SA on 1/31/2018] 
+   !!! sc outputs as follows (so scale it accordingly) 
+   !!!      y4 y2 y6 y1 y3 y5 
+   !!!      at center of mass of the earth (top row) => at surface (bottom row) 
+   !print *, nbc 
+   do j = 1,nbc/6
+      !!! y4, y2, y6 are not scaled yet =>>> ask lambert ==>>> 
+      !love_kernels((j-1)*6+1,1) = sc((j-1)*6+1,1)               ! y4 NOT SCALED YET 
+      !love_kernels((j-1)*6+2,1) = sc((j-1)*6+2,1)               ! y2 NOT SCALED YET 
+      !love_kernels((j-1)*6+3,1) = sc((j-1)*6+3,1)               ! y6 NOT SCALED YET 
+      love_kernels((j-1)*6+4,1) = sc((j-1)*6+4,1)*ra*go_surf    ! y1 => love_h 
+      love_kernels((j-1)*6+5,1) = sc((j-1)*6+5,1)*ra*go_surf    ! y3 => love_l 
+      love_kernels((j-1)*6+6,1) = sc((j-1)*6+6,1)*ra*go0        ! y5 => love_k
+      !if (deg==2) then 
+      !   print *, real(love_kernels((j-1)*6+1,1)), real(love_kernels((j-1)*6+4,1))
+      !end if 
+   end do
+   ! some reshuffling is needed for y4, y2, y6...
+   do j = 2,nbc/6
+      !!! y4, y2, y6 are not scaled yet =>>> ask lambert ==>>> 
+      love_kernels((j-2)*6+1,1) = sc((j-1)*6+1,1)               ! y4 NOT SCALED YET 
+      love_kernels((j-2)*6+2,1) = sc((j-1)*6+2,1)               ! y2 NOT SCALED YET 
+      love_kernels((j-2)*6+3,1) = sc((j-1)*6+3,1)               ! y6 NOT SCALED YET 
+   end do
+   !!! these are surface values... 
+   love_kernels(nbc-5,1) = sc(1,1)               ! y4 NOT SCALED YET 
+   love_kernels(nbc-4,1) = sc(2,1)               ! y4 NOT SCALED YET 
+   love_kernels(nbc-3,1) = sc(3,1)               ! y4 NOT SCALED YET 
+ 
+   !print *, ' ************* ' 
+   !if (deg==2) then
+   !  do ibc=1,nbc/6
+         !print *, real(sc( (ibc-1)*6+1:(ibc-1)*6+6 , 1))
+   !      print *, real(love_kernels( (ibc-1)*6+1:(ibc-1)*6+6 , 1))
+    !  end do 
+      !print *, ' ************* ' 
+      !do ibc=1,nbc/6
+      !   print *, real(love_kernels( (ibc-1)*6+1:(ibc-1)*6+6 , 1))
+      !end do 
+      !print *, ' ************* ' 
+      !print*, ra*go_surf, ra*go0, mu0
+   !end if 
+   !!! >>> SA 
+
+	sumy2=0.d0
+	sumy4=0.d0
+	sumy6=0.d0
+
+	do ic=1,6
+	  sumy2 = sumy2+bcsav(nbc-4,ic+nbc-9)*sc(ic+nbc-9,1)
+	  sumy4 = sumy4+bcsav(nbc-2,ic+nbc-9)*sc(ic+nbc-9,1)
+	  sumy6 = sumy6+bcsav(nbc,ic+nbc-9)*sc(ic+nbc-9,1)
+	end do
+
+
+	ibc = 0
+	do  j = nlayer,1,-1
+		if (radbc(j)) then 
+			ibc=ibc+1
+			if (soliddim(j)) then
+
+				loveh1 = sc(nbc - ibc*6 -3 +1,1)*ra*go_surf*valini
+				lovel1 = sc(nbc -ibc*6 -3 +3,1)*ra*go_surf*valini
+				lovek1 = sc(nbc -ibc*6 -3 +5,1)*ra*go0*valini
+			else 
+
+				sumh=0.d0
+				suml=0.d0
+				sumk=0.d0
+				ii = nbc - (ibc+1)*6
+				jj = nbc - (ibc+1)*6 -3
+				if (j==ifirst) then 
+					icmin = 4
+				else
+					icmin = 1
+				end if
+				do ic=icmin,6
+					sumh = sumh+bcsav(ii+1,jj+ic)*sc(jj+ic,1)
+					suml = suml+bcsav(ii+3,jj+ic)*sc(jj+ic,1)
+					sumk = sumk+bcsav(ii+5,jj+ic)*sc(jj+ic,1)
+				end do
+				loveh1 = sumh*ra*go_surf*valini
+				lovel1 = suml*ra*go_surf*valini
+				lovek1 = sumk*ra*go0*valini
+
+			end if			
+			if (j==ifirst) then
+
+				layerrap = zabs(loveh1s/loveh)
+				if (layerrap > zabs(lovel1s/lovel)) layerrap = zabs(lovel1s/lovel)
+				if (layerrap > zabs((lovek1s-(rads/ra)**deg)/(lovek-1.d0))) &
+				layerrap = zabs((lovek1s-(rads/ra)**deg)/(lovek-1.d0)) 
+			endif
+
+			loveh1s = loveh1
+			lovel1s = lovel1
+			lovek1s = lovek1
+			rads = radius(j)
+			!if (radius(j)==rb) then 
+			!	 write(*,*) 'CMB ',n,loveh1,lovel1,lovek1-(rb/ra)**deg
+			!else if (radius(j)==rc) then
+			!	 write(*,*) 'ICB ',n,loveh1,lovel1,lovek1-(rc/ra)**deg
+			!else
+			!	if (j<10) then
+			!		 write(*,*) 'ITF-',j,n,loveh1,lovel1,lovek1-(radius(j)/ra)**deg
+			!	else
+			!		 write(*,*) 'ITF-',j,n,loveh1,lovel1,lovek1-(radius(j)/ra)**deg
+			!	end if
+			!endif
+		end if
+	end do
+
+  end do
+  end if
+  
+
+ !301 format(a4,5x,'n=',i3,5x,'h=',f14.10,5x,'l=',f14.10,5x,'k=',f14.10)
+ 301 format(a4,5x,'n=',i5,5x,'h=',d14.7,5x,'l=',d14.7,5x,'k=',d14.7)
+ 305 format(a4,i1,4x,'n=',i5,5x,'h=',d14.7,5x,'l=',d14.7,5x,'k=',d14.7)
+ 306 format(a4,i2,3x,'n=',i5,5x,'h=',d14.7,5x,'l=',d14.7,5x,'k=',d14.7)
+ 302 format(i5,5x,f14.10,5x,f14.10,5x,f14.10)
+ 303 format(i5,5x,f14.10,5x,f14.10,5x,f14.10,5x,f14.10)
+ 304 format(i5,5x,d20.10,5x,d20.10,5x,d20.10)
+
+ end subroutine solution 
+ ! }}}
+ 
+  ! subroutine solution_nbloutput {{{ 
+  subroutine solution_nbloutput(n,bc,indx,f,sourcs,nfext,nbc,loveh,lovel,lovek,delta)
+!-------------------------------------------------
+
+  integer :: n,nfext,nbc,i,j,ic,ibc,ii,jj,icmin,ifirst
+  double precision, dimension(:,:), pointer :: bc,f
+  integer,      dimension(:), pointer :: indx
+  character*40, dimension(:), pointer :: sourcs	
+  double precision, dimension(nbc) :: sc
+  double precision :: loveh,lovel,lovek,loveh1,lovel1,lovek1,loveh1s,lovel1s,lovek1s
+  double precision :: sumh,suml,sumk,d,val,delta,sumy2,sumy4,sumy6,rads
+  double precision, dimension(6) :: icbh,icbl,icbk,y2srf,y4srf,y6srf
+  double precision, dimension(nbc,nbc) :: bcsav
+  logical :: ok
+
+  
+  !do ic=1,6
+!	if (nbc==18) then 
+!		icbh(ic) = bc(1,ic)
+!		icbl(ic) = bc(3,ic)
+!		icbk(ic) = bc(5,ic)
+!!	elseif (nbc==24) then 
+!		icbh(ic) = bc(7,ic+3)
+!		icbl(ic) = bc(9,ic+3)
+!		icbk(ic) = bc(11,ic+3)
+!	end if
+!	y2srf(ic) = bc(nbc-4,ic+nbc-9)
+!	y4srf(ic) = bc(nbc-2,ic+nbc-9)
+!	y6srf(ic) = bc(nbc,ic+nbc-9)
+ ! end do
+  
+  bcsav(:,:) = bc(:,:)
+  rads=0
+  ifirst = 0
+  i = 0
+  do while (ifirst==0)
+	i = i+1
+	if (radbc(i)) ifirst = i
+  end do
+ !do i = 1,nbc 
+!	do j = 1,nbc
+!	if (bc(i,j)/=0.d0) print*, i,j,bc(i,j)
+!	enddo
+ !enddo
+ !write(*,*)
+  
+  !-- LU decomposition and determinant
+    ok = .true.
+   
+  call ludcmp(bc,nbc,nbc,indx,d)
+  do i=1,nbc
+     d=d*bc(i,i)
+  end do
+  write(*,*)
+  !write(*,*),dlog(freq),'   Matrix det = ',d/dabs(d)*dlog(dabs(d))
+ 
+!-- Resolution
+ 
+  if (ok) then
+  do i = ifmin,ifmax
+  	
+	do j=1,nbc
+	  sc(j)=f(i,j)
+	end do
+
+	write(*,*) 'Source: ',sourcs(i)
+	call lubksb(bc,nbc,nbc,indx,sc)
+
+	loveh = sc(nbc-2)*ra*go_surf
+	lovel = sc(nbc-1)*ra*go_surf
+	lovek = sc(nbc)*ra*go0
+	delta = 1.d0-dble(n+1)/dble(n)*(lovek-1.d0)+2.d0/dble(n)*loveh
+	
+	sumy2=0.d0
+	sumy4=0.d0
+	sumy6=0.d0
+
+	do ic=1,6
+	  sumy2 = sumy2+bcsav(nbc-4,ic+nbc-9)*sc(ic+nbc-9)
+	  sumy4 = sumy4+bcsav(nbc-2,ic+nbc-9)*sc(ic+nbc-9)
+	  sumy6 = sumy6+bcsav(nbc,ic+nbc-9)*sc(ic+nbc-9)
+	end do
+	
+	!write(*,*) 'SURF',n,loveh,lovel,lovek-1.d0
+	
+	ibc = 0
+	do  j = nlayer,1,-1
+		if (radbc(j)) then 
+			ibc=ibc+1
+			if (soliddim(j)) then
+				loveh1 = sc(nbc - ibc*6 -3 +1)*ra*go_surf*valini
+				lovel1 = sc(nbc -ibc*6 -3 +3)*ra*go_surf*valini
+				lovek1 = sc(nbc -ibc*6 -3 +5)*ra*go0*valini
+			else 
+				sumh=0.d0
+				suml=0.d0
+				sumk=0.d0
+				ii = nbc - (ibc+1)*6
+				jj = nbc - (ibc+1)*6 -3
+				if (j==ifirst) then 
+					icmin = 4
+				else
+					icmin = 1
+				end if
+				do ic=icmin,6
+					!print*, ii+1,jj+ic
+					sumh = sumh+bcsav(ii+1,jj+ic)*sc(jj+ic)
+					suml = suml+bcsav(ii+3,jj+ic)*sc(jj+ic)
+					sumk = sumk+bcsav(ii+5,jj+ic)*sc(jj+ic)
+				end do
+				loveh1 = sumh*ra*go_surf*valini
+				lovel1 = suml*ra*go_surf*valini
+				lovek1 = sumk*ra*go0*valini
+			end if			
+			if (j==ifirst) then
+				layerrap = dabs(loveh1s/loveh)
+				if (layerrap > dabs(lovel1s/lovel)) layerrap = dabs(lovel1s/lovel)
+				if (layerrap > dabs((lovek1s-(rads/ra)**deg)/(lovek-1.d0))) &
+				layerrap = dabs((lovek1s-(rads/ra)**deg)/(lovek-1.d0)) 
+			endif
+
+			loveh1s = loveh1
+			lovel1s = lovel1
+			lovek1s = lovek1
+			rads = radius(j)
+			!if (radius(j)==rb) then 
+			!	write(*,301) 'CMB ',n,loveh1,lovel1,lovek1-(rb/ra)**deg
+			!else if (radius(j)==rc) then
+			!	write(*,301) 'ICB ',n,loveh1,lovel1,lovek1-(rc/ra)**deg
+			!else
+			!	if (j<10) then
+			!		write(*,305) 'ITF-',j,n,loveh1,lovel1,lovek1-(radius(j)/ra)**deg
+			!	else
+			!		write(*,306) 'ITF-',j,n,loveh1,lovel1,lovek1-(radius(j)/ra)**deg
+			!	end if
+			!endif
+		end if
+	end do
+			
+  end do
+  end if
+  
+   !write(*,*),dlog10(aimag(freq)*365.d0*24.d0*3600.d0*1000.d0),'   Matrix det = ',d, lovek
+  
+ end subroutine solution_nbloutput 
+ ! }}}
+
+end module lovenb_sub
Index: /issm/trunk/src/c/modules/FourierLoveCorex/lovenb_sub.mod
===================================================================
--- /issm/trunk/src/c/modules/FourierLoveCorex/lovenb_sub.mod	(revision 22758)
+++ /issm/trunk/src/c/modules/FourierLoveCorex/lovenb_sub.mod	(revision 22758)
@@ -0,0 +1,373 @@
+GFORTRAN module version '10' created from lovenb_sub.f90
+MD5:abd34956a6ed4ca3faf89b83c227ea8d -- If you edit this, you'll get what you deserve.
+
+(() () () () () () () () () () () () () () () () () () () () () () ()
+() () () ())
+
+()
+
+()
+
+()
+
+()
+
+()
+
+(2 '__convert_r4_r8' '(intrinsic)' '' 1 ((PROCEDURE UNKNOWN-INTENT
+UNKNOWN-PROC UNKNOWN UNKNOWN 0 0 FUNCTION ELEMENTAL PURE) (REAL 8 0 0 0
+REAL ()) 0 0 () () 2 () () () 0 0)
+3 'allow_layer_del' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT
+UNKNOWN-PROC UNKNOWN IMPLICIT-SAVE 0 0) (LOGICAL 4 0 0 0 LOGICAL ()) 0 0
+() () 0 () () () 0 0)
+4 'benchmark_spada' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT
+UNKNOWN-PROC UNKNOWN IMPLICIT-SAVE 0 0) (LOGICAL 4 0 0 0 LOGICAL ()) 0 0
+() () 0 () () () 0 0)
+5 'boundary_conditions_matrix' 'lovenb_sub' '' 1 ((PROCEDURE
+UNKNOWN-INTENT MODULE-PROC DECL UNKNOWN 0 0 SUBROUTINE ALWAYS_EXPLICIT)
+(UNKNOWN 0 0 0 0 UNKNOWN ()) 6 0 (7 8 9) () 0 () () () 0 0)
+10 'burgers' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0 DIMENSION POINTER) (LOGICAL 4 0 0 0 LOGICAL ())
+0 0 () (1 0 DEFERRED () ()) 0 () () () 0 0)
+11 'deg' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+12 'degmax' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () ()
+() 0 0)
+13 'degmin' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () ()
+() 0 0)
+14 'derivs' 'util' '' 1 ((PROCEDURE UNKNOWN-INTENT MODULE-PROC DECL
+UNKNOWN 0 0 SUBROUTINE) (UNKNOWN 0 0 0 0 UNKNOWN ()) 15 0 (16 17 18) ()
+0 () () () 0 0)
+19 'display' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (LOGICAL 4 0 0 0 LOGICAL ()) 0 0 () () 0 () ()
+() 0 0)
+20 'earth_homogeneous_layers_prembased' 'model' '' 1 ((PROCEDURE
+UNKNOWN-INTENT MODULE-PROC DECL UNKNOWN 0 0 SUBROUTINE ALWAYS_EXPLICIT)
+(UNKNOWN 0 0 0 0 UNKNOWN ()) 21 0 (22 23 24 25 26 27 28) () 0 () () () 0
+0)
+29 'earth_nlayers' 'model' '' 1 ((PROCEDURE UNKNOWN-INTENT MODULE-PROC
+DECL UNKNOWN 0 0 SUBROUTINE) (UNKNOWN 0 0 0 0 UNKNOWN ()) 30 0 (31 32 33
+34 35 36) () 0 () () () 0 0)
+37 'earth_nlayers_viscoelas' 'model' '' 1 ((PROCEDURE UNKNOWN-INTENT
+MODULE-PROC DECL UNKNOWN 0 0 SUBROUTINE) (UNKNOWN 0 0 0 0 UNKNOWN ()) 38
+0 (39 40 41 42 43 44) () 0 () () () 0 0)
+45 'epsdb' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0
+0)
+46 'external_forcing' 'lovenb_sub' '' 1 ((PROCEDURE UNKNOWN-INTENT
+MODULE-PROC DECL UNKNOWN 0 0 SUBROUTINE ALWAYS_EXPLICIT) (UNKNOWN 0 0 0
+0 UNKNOWN ()) 47 0 (48 49 50 51 52) () 0 () () () 0 0)
+53 'freq' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (COMPLEX 8 0 0 0 COMPLEX ()) 0 0 () () 0 () ()
+() 0 0)
+54 'gg' 'lnb_param' '' 1 ((PARAMETER UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () (CONSTANT (REAL 8 0 0 0
+REAL ()) 0 '0.495dac00000000@-8') () 0 () () () 0 0)
+55 'go0' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+56 'go_cmb' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0
+0)
+57 'go_icb' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0
+0)
+58 'go_surf' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0
+0)
+59 'ifmax' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () ()
+() 0 0)
+60 'ifmin' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () ()
+() 0 0)
+61 'incompressible' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT
+UNKNOWN-PROC UNKNOWN IMPLICIT-SAVE 0 0) (LOGICAL 4 0 0 0 LOGICAL ()) 0 0
+() () 0 () () () 0 0)
+62 'lac' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0 DIMENSION POINTER) (REAL 8 0 0 0 REAL ()) 0 0 () (1 0
+DEFERRED () ()) 0 () () () 0 0)
+63 'layerrap' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0
+0)
+64 'lnb_param' 'lnb_param' '' 1 ((MODULE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN UNKNOWN 0 0) (UNKNOWN 0 0 0 0 UNKNOWN ()) 0 0 () () 0 () () () 0
+0)
+65 'lovenb_sub' 'lovenb_sub' '' 1 ((MODULE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN UNKNOWN 0 0) (UNKNOWN 0 0 0 0 UNKNOWN ()) 0 0 () () 0 () () () 0
+0)
+66 'lubksb' 'util' '' 1 ((PROCEDURE UNKNOWN-INTENT MODULE-PROC DECL
+UNKNOWN 0 0 SUBROUTINE) (UNKNOWN 0 0 0 0 UNKNOWN ()) 67 0 (68 69 70 71
+72) () 0 () () () 0 0)
+73 'ludcmp' 'util' '' 1 ((PROCEDURE UNKNOWN-INTENT MODULE-PROC DECL
+UNKNOWN 0 0 SUBROUTINE) (UNKNOWN 0 0 0 0 UNKNOWN ()) 74 0 (75 76 77 78
+79) () 0 () () () 0 0)
+80 'model' 'model' '' 1 ((MODULE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0) (UNKNOWN 0 0 0 0 UNKNOWN ()) 0 0 () () 0 () () () 0 0)
+81 'model_init2' 'model' '' 1 ((PROCEDURE UNKNOWN-INTENT MODULE-PROC
+DECL UNKNOWN 0 0 SUBROUTINE) (UNKNOWN 0 0 0 0 UNKNOWN ()) 82 0 (83) () 0
+() () () 0 0)
+84 'mu0' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+85 'muc' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0 DIMENSION POINTER) (REAL 8 0 0 0 REAL ()) 0 0 () (1 0
+DEFERRED () ()) 0 () () () 0 0)
+86 'muc2' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0 DIMENSION POINTER) (REAL 8 0 0 0 REAL ()) 0 0
+() (1 0 DEFERRED () ()) 0 () () () 0 0)
+87 'mucratio' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0
+0)
+88 'nfreq' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () ()
+() 0 0)
+89 'nlayer' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () ()
+() 0 0)
+90 'pi' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+91 'propagfds' 'util' '' 1 ((PROCEDURE UNKNOWN-INTENT MODULE-PROC DECL
+UNKNOWN 0 0 SUBROUTINE) (UNKNOWN 0 0 0 0 UNKNOWN ()) 92 0 (93 94 95 96)
+() 0 () () () 0 0)
+97 'r0' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+98 'ra' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+99 'radbc' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0 DIMENSION POINTER) (LOGICAL 4 0 0 0 LOGICAL ())
+0 0 () (1 0 DEFERRED () ()) 0 () () () 0 0)
+100 'radius' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0 DIMENSION POINTER) (REAL 8 0 0 0 REAL ()) 0 0
+() (1 0 DEFERRED () ()) 0 () () () 0 0)
+101 'rb' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+102 'rc' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+103 'ro_mean' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0
+0)
+104 'roc' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0 DIMENSION POINTER) (REAL 8 0 0 0 REAL ()) 0 0
+() (1 0 DEFERRED () ()) 0 () () () 0 0)
+105 'soliddim' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0 DIMENSION POINTER) (LOGICAL 4 0 0 0 LOGICAL ())
+0 0 () (1 0 DEFERRED () ()) 0 () () () 0 0)
+106 'solution' 'lovenb_sub' '' 1 ((PROCEDURE UNKNOWN-INTENT MODULE-PROC
+DECL UNKNOWN 0 0 SUBROUTINE ALWAYS_EXPLICIT) (UNKNOWN 0 0 0 0 UNKNOWN ())
+107 0 (108 109 110 111 112 113 114 115 116 117 118) () 0 () () () 0 0)
+119 'solution_nbloutput' 'lovenb_sub' '' 1 ((PROCEDURE UNKNOWN-INTENT
+MODULE-PROC DECL UNKNOWN 0 0 SUBROUTINE ALWAYS_EXPLICIT) (UNKNOWN 0 0 0
+0 UNKNOWN ()) 120 0 (121 122 123 124 125 126 127 128 129 130 131) () 0 ()
+() () 0 0)
+132 'sphere' 'lovenb_sub' '' 1 ((PROCEDURE UNKNOWN-INTENT MODULE-PROC
+DECL UNKNOWN 0 0 SUBROUTINE ALWAYS_EXPLICIT) (UNKNOWN 0 0 0 0 UNKNOWN ())
+133 0 (134 135 136) () 0 () () () 0 0)
+137 'util' 'util' '' 1 ((MODULE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0) (UNKNOWN 0 0 0 0 UNKNOWN ()) 0 0 () () 0 () () () 0 0)
+138 'valini' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (COMPLEX 8 0 0 0 COMPLEX ()) 0 0 () () 0 () ()
+() 0 0)
+139 'vic' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0 DIMENSION POINTER) (REAL 8 0 0 0 REAL ()) 0 0
+() (1 0 DEFERRED () ()) 0 () () () 0 0)
+140 'vic2' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0 DIMENSION POINTER) (REAL 8 0 0 0 REAL ()) 0 0
+() (1 0 DEFERRED () ()) 0 () () () 0 0)
+141 'vicratio' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0
+0)
+7 'bc' '' '' 6 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN 0
+0 DIMENSION POINTER DUMMY) (COMPLEX 8 0 0 0 COMPLEX ()) 0 0 () (2 0
+DEFERRED () () () ()) 0 () () () 0 0)
+8 'indx' '' '' 6 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DIMENSION POINTER DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () (1 0
+DEFERRED () ()) 0 () () () 0 0)
+9 'nbc' '' '' 6 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN 0
+0 DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+16 'x' '' '' 15 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN 0
+0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+17 'y' '' '' 15 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN 0
+0 DIMENSION DUMMY) (COMPLEX 8 0 0 0 COMPLEX ()) 0 0 () (1 0 EXPLICIT (
+CONSTANT (INTEGER 4 0 0 0 INTEGER ()) 0 '1') (CONSTANT (INTEGER 4 0 0 0
+INTEGER ()) 0 '6')) 0 () () () 0 0)
+18 'dydx' '' '' 15 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DIMENSION DUMMY) (COMPLEX 8 0 0 0 COMPLEX ()) 0 0 () (1 0
+EXPLICIT (CONSTANT (INTEGER 4 0 0 0 INTEGER ()) 0 '1') (CONSTANT (
+INTEGER 4 0 0 0 INTEGER ()) 0 '6')) 0 () () () 0 0)
+22 'radin' '' '' 21 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DIMENSION POINTER DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () (1 0
+DEFERRED () ()) 0 () () () 0 0)
+23 'nl' '' '' 21 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+24 'rot' '' '' 21 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DIMENSION POINTER DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () (1 0 DEFERRED
+() ()) 0 () () () 0 0)
+25 'lat' '' '' 21 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DIMENSION POINTER DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () (1 0 DEFERRED
+() ()) 0 () () () 0 0)
+26 'mut' '' '' 21 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DIMENSION POINTER DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () (1 0 DEFERRED
+() ()) 0 () () () 0 0)
+27 'gr' '' '' 21 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+28 'solid' '' '' 21 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DUMMY) (LOGICAL 4 0 0 0 LOGICAL ()) 0 0 () () 0 () () () 0 0)
+31 'x0' '' '' 30 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+32 'ro' '' '' 30 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+33 'la' '' '' 30 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+34 'mu' '' '' 30 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+35 'gr' '' '' 30 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+36 'solid' '' '' 30 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DUMMY) (LOGICAL 4 0 0 0 LOGICAL ()) 0 0 () () 0 () () () 0 0)
+39 'x0' '' '' 38 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+40 'ro' '' '' 38 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+41 'la' '' '' 38 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (COMPLEX 8 0 0 0 COMPLEX ()) 0 0 () () 0 () () () 0 0)
+42 'mu' '' '' 38 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (COMPLEX 8 0 0 0 COMPLEX ()) 0 0 () () 0 () () () 0 0)
+43 'gr' '' '' 38 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+44 'solid' '' '' 38 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DUMMY) (LOGICAL 4 0 0 0 LOGICAL ()) 0 0 () () 0 () () () 0 0)
+48 'n' '' '' 47 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN 0
+0 DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+49 'source' '' '' 47 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DIMENSION POINTER DUMMY) (COMPLEX 8 0 0 0 COMPLEX ()) 0 0 ()
+(2 0 DEFERRED () () () ()) 0 () () () 0 0)
+50 'sourcs' '' '' 47 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DIMENSION POINTER DUMMY) (CHARACTER 1 0 0 0 CHARACTER ((
+CONSTANT (INTEGER 4 0 0 0 INTEGER ()) 0 '40'))) 0 0 () (1 0 DEFERRED ()
+()) 0 () () () 0 0)
+51 'nfext' '' '' 47 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+52 'nbc' '' '' 47 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+68 'a' '' '' 67 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN 0
+0 DIMENSION DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () (2 0 EXPLICIT (
+CONSTANT (INTEGER 4 0 0 0 INTEGER ()) 0 '1') (VARIABLE (INTEGER 4 0 0 0
+INTEGER ()) 0 70 ()) (CONSTANT (INTEGER 4 0 0 0 INTEGER ()) 0 '1') (
+VARIABLE (INTEGER 4 0 0 0 INTEGER ()) 0 70 ())) 0 () () () 0 0)
+69 'n' '' '' 67 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN 0
+0 DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+70 'np' '' '' 67 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+71 'indx' '' '' 67 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DIMENSION DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () (1 0
+EXPLICIT (CONSTANT (INTEGER 4 0 0 0 INTEGER ()) 0 '1') (VARIABLE (
+INTEGER 4 0 0 0 INTEGER ()) 0 69 ())) 0 () () () 0 0)
+72 'b' '' '' 67 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN 0
+0 DIMENSION DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () (1 0 EXPLICIT (
+CONSTANT (INTEGER 4 0 0 0 INTEGER ()) 0 '1') (VARIABLE (INTEGER 4 0 0 0
+INTEGER ()) 0 70 ())) 0 () () () 0 0)
+75 'a' '' '' 74 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN 0
+0 DIMENSION DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () (2 0 EXPLICIT (
+CONSTANT (INTEGER 4 0 0 0 INTEGER ()) 0 '1') (VARIABLE (INTEGER 4 0 0 0
+INTEGER ()) 0 77 ()) (CONSTANT (INTEGER 4 0 0 0 INTEGER ()) 0 '1') (
+VARIABLE (INTEGER 4 0 0 0 INTEGER ()) 0 77 ())) 0 () () () 0 0)
+76 'n' '' '' 74 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN 0
+0 DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+77 'np' '' '' 74 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+78 'indx' '' '' 74 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DIMENSION DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () (1 0
+EXPLICIT (CONSTANT (INTEGER 4 0 0 0 INTEGER ()) 0 '1') (VARIABLE (
+INTEGER 4 0 0 0 INTEGER ()) 0 76 ())) 0 () () () 0 0)
+79 'd' '' '' 74 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN 0
+0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+83 'nbc' '' '' 82 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+93 'ystart' '' '' 92 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DIMENSION DUMMY) (COMPLEX 8 0 0 0 COMPLEX ()) 0 0 () (1 0
+EXPLICIT (CONSTANT (INTEGER 4 0 0 0 INTEGER ()) 0 '1') (CONSTANT (
+INTEGER 4 0 0 0 INTEGER ()) 0 '6')) 0 () () () 0 0)
+94 'xmin' '' '' 92 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+95 'xmax' '' '' 92 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+96 'nstep' '' '' 92 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+108 'n' '' '' 107 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+109 'bc' '' '' 107 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DIMENSION POINTER DUMMY) (COMPLEX 8 0 0 0 COMPLEX ()) 0 0 ()
+(2 0 DEFERRED () () () ()) 0 () () () 0 0)
+110 'indx' '' '' 107 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DIMENSION POINTER DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 ()
+(1 0 DEFERRED () ()) 0 () () () 0 0)
+111 'f' '' '' 107 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DIMENSION POINTER DUMMY) (COMPLEX 8 0 0 0 COMPLEX ()) 0 0 () (2 0
+DEFERRED () () () ()) 0 () () () 0 0)
+112 'sourcs' '' '' 107 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DIMENSION POINTER DUMMY) (CHARACTER 1 0 0 0 CHARACTER ((
+CONSTANT (INTEGER 4 0 0 0 INTEGER ()) 0 '40'))) 0 0 () (1 0 DEFERRED ()
+()) 0 () () () 0 0)
+113 'nfext' '' '' 107 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+114 'nbc' '' '' 107 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+115 'loveh' '' '' 107 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DUMMY) (COMPLEX 8 0 0 0 COMPLEX ()) 0 0 () () 0 () () () 0 0)
+116 'lovel' '' '' 107 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DUMMY) (COMPLEX 8 0 0 0 COMPLEX ()) 0 0 () () 0 () () () 0 0)
+117 'lovek' '' '' 107 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DUMMY) (COMPLEX 8 0 0 0 COMPLEX ()) 0 0 () () 0 () () () 0 0)
+118 'delta' '' '' 107 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+121 'n' '' '' 120 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+122 'bc' '' '' 120 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DIMENSION POINTER DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () (2 0
+DEFERRED () () () ()) 0 () () () 0 0)
+123 'indx' '' '' 120 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DIMENSION POINTER DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 ()
+(1 0 DEFERRED () ()) 0 () () () 0 0)
+124 'f' '' '' 120 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DIMENSION POINTER DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () (2 0 DEFERRED
+() () () ()) 0 () () () 0 0)
+125 'sourcs' '' '' 120 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DIMENSION POINTER DUMMY) (CHARACTER 1 0 0 0 CHARACTER ((
+CONSTANT (INTEGER 4 0 0 0 INTEGER ()) 0 '40'))) 0 0 () (1 0 DEFERRED ()
+()) 0 () () () 0 0)
+126 'nfext' '' '' 120 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+127 'nbc' '' '' 120 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+128 'loveh' '' '' 120 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+129 'lovel' '' '' 120 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+130 'lovek' '' '' 120 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+131 'delta' '' '' 120 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+134 'i' '' '' 133 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+135 'n' '' '' 133 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+136 'bc' '' '' 133 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DIMENSION POINTER DUMMY) (COMPLEX 8 0 0 0 COMPLEX ()) 0 0 ()
+(2 0 DEFERRED () () () ()) 0 () () () 0 0)
+)
+
+('__convert_r4_r8' 0 2 'allow_layer_del' 0 3 'benchmark_spada' 0 4
+'boundary_conditions_matrix' 0 5 'burgers' 0 10 'deg' 0 11 'degmax' 0 12
+'degmin' 0 13 'derivs' 0 14 'display' 0 19
+'earth_homogeneous_layers_prembased' 0 20 'earth_nlayers' 0 29
+'earth_nlayers_viscoelas' 0 37 'epsdb' 0 45 'external_forcing' 0 46 'freq'
+0 53 'gg' 0 54 'go0' 0 55 'go_cmb' 0 56 'go_icb' 0 57 'go_surf' 0 58
+'ifmax' 0 59 'ifmin' 0 60 'incompressible' 0 61 'lac' 0 62 'layerrap' 0
+63 'lnb_param' 0 64 'lovenb_sub' 0 65 'lubksb' 0 66 'ludcmp' 0 73 'model'
+0 80 'model_init2' 0 81 'mu0' 0 84 'muc' 0 85 'muc2' 0 86 'mucratio' 0
+87 'nfreq' 0 88 'nlayer' 0 89 'pi' 0 90 'propagfds' 0 91 'r0' 0 97 'ra'
+0 98 'radbc' 0 99 'radius' 0 100 'rb' 0 101 'rc' 0 102 'ro_mean' 0 103
+'roc' 0 104 'soliddim' 0 105 'solution' 0 106 'solution_nbloutput' 0 119
+'sphere' 0 132 'util' 0 137 'valini' 0 138 'vic' 0 139 'vic2' 0 140
+'vicratio' 0 141)
Index: /issm/trunk/src/c/modules/FourierLoveCorex/model.f90
===================================================================
--- /issm/trunk/src/c/modules/FourierLoveCorex/model.f90	(revision 22758)
+++ /issm/trunk/src/c/modules/FourierLoveCorex/model.f90	(revision 22758)
@@ -0,0 +1,425 @@
+module model
+ 
+ implicit none
+
+ contains
+
+  subroutine model_init2(nbc)
+!--------------------- 
+ use lnb_param
+
+  double precision :: ro,g,drad,la,mu,ro1,ro2,x
+  logical :: solid,test
+  integer :: nbc,i,n,j
+
+
+
+  !- Calculus parameters    
+  pi=dacos(-1.d0)
+  epsdb=epsilon(1.d0)
+  
+  !write(101,*), 'Epsilon machine = ',epsdb
+  !write(101,*), 'Constants:'
+  !write(101,*), ' pi = ',pi
+  !write(101,*), ' G  = ',GG 
+  !write(101,*), 'Dimensioned scales:'
+  !write(101,*), ' rigidity mu0 = ',mu0
+  !write(101,*), ' gravity  go0 = ',go0
+  !write(101,*), ' distance r0  = ',r0
+  
+ 
+
+ 
+ !call earth_homogeneous_layers_prembased(radius,nlayer,roc,lac,muc,g,solid) !yields the Earth layers radii, density, lamé parameters, gravity and solid/liquid state boolean identifier
+ 
+ !if (benchmark_spada) then
+ ! muc(1) = 1.d6; muc(2) = 0.d0; muc(3) = 2.28340d11 
+ ! muc(4) = 1.05490d11; muc(5) = 0.70363d11; muc(6) = 0.50605d11
+ ! roc(1) = 10751.d0; roc(2) = 10750.d0; roc(3) = 4978.d0 
+ ! roc(6)=3300.d0
+ !else
+  !muc(1) = 1.d6; muc(2) = 0.d0; muc(3) = 2.20425d11 
+  !muc(4) = 0.870257d11; muc(5) = 0.870257d11; muc(6) = 0.510268d11
+  !roc(1) = 10987.9d0; roc(2) = 10986.9d0; roc(3) = 4903.58d0 
+  !roc(4) = 3628.29d0; roc(5) = 3628.29d0; roc(6) = 3113.94d0
+ !endif
+
+ !vic2=vic/vicratio
+ !muc2=muc/mucratio
+
+ if (display) then
+	print*, '  Layer top boundary        rho                       la                        mu                        eta' 
+ do i = 1,nlayer
+  ! print*, radius(i+1),roc(i),lac(i),muc(i),vic(i)
+  if (burgers(i)) then
+  print*, radius(i+1),roc(i),lac(i),muc(i),vic(i),muc2(i),vic2(i), 'B'
+  else
+  print*, radius(i+1),roc(i),lac(i),muc(i),vic(i)
+  endif
+ end do
+
+ endif
+ !write(101,*),
+
+
+ call earth_nlayers(1.d0,ro,la,mu,g,solid)
+   go_surf = g
+   ro_mean = 3.d0/4.d0*go_surf/(pi*GG*ra)
+	if (display) then
+		print*, 'Surface Gravity: ', go_surf, ' m.s^-2, mean density: ', ro_mean, ' kg.m^-3'
+		print*, 'Center of the Earth approximated at r=', radius(1)/1e3, ' km'
+	endif 
+  
+  ! Test number of interfaces and of boundary conditions
+  n = 0
+  !!! >>> SA: 01/27/2018 => following changes made to retrieve love numbers at depth 
+  !do i=1,nlayer+1 
+ !if (radbc(i)) n=n+1
+  !enddo
+  n = nlayer+1 
+  !!! >>> SA 
+  if (nbc/=(6*n)) then
+ !write(101,*),
+ print*, 'Error nbc should be ',6*n,' instead of ',nbc
+ stop
+  endif
+  
+  ! Test solid-liquid boundaries
+ test = .false.
+  do i = 1,nlayer
+ if (radbc(i)) test = .true.
+ if (test) then
+ if ((.not.soliddim(i)).and.((.not.radbc(i)).or.(.not.radbc(i+1)))) then
+  print*, 'Error in model definition: one fluid layer is not set with correct boundary conditions'
+  stop
+ endif
+ endif
+  enddo
+  
+  !-- Display a few quantities
+  !write(101,*), ' surface radius = ',ra
+  !write(101,*), ' CMB radius = ',rb
+  !write(101,*), ' ICB radius = ',rc
+  !write(101,*), ' go surface = ',go_surf
+  !write(101,*), ' mean density = ',ro_mean 
+  
+  !-- Diplsay ICB conditions
+  !x=rc/ra
+  !write(101,*), 
+  !call earth_nlayers_viscoelas(x-epsdb,ro1,complex(la,0.d0),complex(mu,0d0),g,solid)
+  !write(101,*), 'ICB, g = ',g
+  !write(101,*), 'ICB, ro(Inner Core) = ', ro1
+  !call earth_nlayers_viscoelas(x,ro2,complex(la,0.d0),complex(mu,0d0),g,solid)
+  !write(101,*), 'ICB, g = ',g
+  !write(101,*), 'ICB, ro(Outer Core) = ', ro2
+  !go_icb = g
+  
+  !-- Display CMB conditions
+  !x=rb/ra
+  !write(101,*),
+  !call earth_nlayers_viscoelas(x-epsdb,ro1,complex(la,0.d0),complex(mu,0d0),g,solid)
+  !write(101,*), 'CMB, g = ',g
+  !write(101,*), 'CMB, ro(Outer Core) = ', ro1
+  !call earth_nlayers_viscoelas(x,ro2,complex(la,0.d0),complex(mu,0d0),g,solid)
+  !write(101,*), 'CMB, g = ',g
+  !write(101,*), 'CMB, ro(Mantle) = ', ro2
+  !go_cmb = g
+ 
+ end subroutine model_init2
+
+
+ subroutine earth_homogeneous_layers_prembased(radin,nl,rot,lat,mut,GR,solid)
+ use lnb_param
+   
+   double precision :: x0,GR
+   logical :: solid
+   integer                 :: i,j,nl
+   doubleprecision      :: la,mu,ro,vp,vs,RT
+   doubleprecision      :: t1,t2,t3,t4,r1,r2
+   doubleprecision, dimension(14) :: r
+   doubleprecision, dimension(13,4) :: d,p,s
+   doubleprecision, dimension(:), pointer :: radin
+   doubleprecision, dimension(:), pointer :: rot,lat,mut
+    doubleprecision, dimension(nl+1) :: rad
+   
+   
+   RT = ra
+   r(1) = 0.d0;     r(2) = 1221.5d0; r(3) = 3480.d0; r(4) = 3630.d0
+   r(5) = 5600.d0;  r(6) = 5701.d0;  r(7) = 5771.d0; r(8) = 5971.d0
+   r(9) = 6151.d0; r(10) = 6291.d0; r(11) = 6346.6d0
+   r(12) = 6356.d0; r(13) = 6368.d0; r(14) = ra
+  
+!   if ((r(14)*1.d3) /= ra) stop'Problem in prem: Earth radius /= ra !' 
+!
+  d(:,:) = 0.d0
+  d(1,1) = 13.0885d0;               d(1,3) = -8.8381d0 
+  d(2,1) = 12.5815d0; d(2,2) = -1.2638d0; d(2,3) = -3.6426d0; d(2,4) = -5.5281d0
+  d(3,1) = 7.9565d0 ; d(3,2) = -6.4761;   d(3,3) = 5.5283d0;  d(3,4) = -3.0807d0
+  d(4,1) = 7.9565d0 ; d(4,2) = -6.4761;   d(4,3) = 5.5283d0;  d(4,4) = -3.0807d0
+  d(5,1) = 7.9565d0 ; d(5,2) = -6.4761;   d(5,3) = 5.5283d0;  d(5,4) = -3.0807d0
+  d(6,1) = 5.3197d0 ; d(6,2) = -1.4836d0
+  d(7,1) = 11.2494d0; d(7,2) = -8.0298d0
+  d(8,1) = 7.1089d0 ; d(8,2) = -3.8045d0
+  d(9,1) = 2.6910d0 ; d(9,2) = 0.6924d0
+  d(10,1) = 2.6910d0; d(10,2) = 0.6924d0
+  d(11,1) = 2.9d0  
+  d(12,1) = 2.6d0  
+
+! ocean
+  if (soliddim(13).eqv..false.) then
+   d(13,1) = 1.02d0 
+
+! continental
+  else
+  d(13,1) = d(12,1)
+  end if
+
+  p(:,:) = 0.d0
+  p(1,1) = 11.2622d0 ; p(1,3) = -6.3640d0
+  p(2,1) = 11.0487d0 ; p(2,2) = -4.0362d0; p(2,3)  = 4.8023d0; p(2,4) = -13.5732d0
+  p(3,1) = 15.3891d0 ; p(3,2) = -5.3181d0; p(3,3)  = 5.5242d0; p(3,4) = -2.5514d0
+  p(4,1) = 24.952d0 ; p(4,2)  = -40.4673d0; p(4,3) = 51.4832d0; p(4,4) = -26.6419d0
+  p(5,1) = 29.2766d0 ; p(5,2) = -23.6027d0; p(5,3) = 5.5242d0; p(5,4) = -2.5514d0
+  p(6,1) = 19.0957d0 ; p(6,2)  = -9.8672d0
+  p(7,1) = 39.7027d0 ; p(7,2)  = -32.6166d0
+  p(8,1) = 20.3926d0 ; p(8,2)  = -12.2569d0
+  p(9,1) = 4.1875d0 ; p(9,2)  = 3.9382d0
+  p(10,1) = 4.1875d0 ; p(10,2) = 3.9382d0
+  p(11,1) = 6.8d0 
+  p(12,1) = 5.8d0
+!
+! ocean
+  if (soliddim(13).eqv..false.) then
+  p(13,1) = 1.45d0 
+!
+! continental
+  else
+  p(13,1) = p(12,1)
+  end if
+!----
+!
+  s(:,:) = 0.d0
+!
+  s(1,1) = 3.6678d0; s(1,3) = -4.4475d0
+
+  s(3,1) = 6.9254d0; s(3,2) = 1.4672d0; s(3,3) = -2.0834d0; s(3,4) = 0.9783d0
+  s(4,1) = 11.1671d0; s(4,2) = -13.7818d0; s(4,3) = 17.4575d0; s(4,4) = -9.2777d0
+  s(5,1) = 22.3459d0; s(5,2) = -17.2473d0; s(5,3) = -2.0834d0; s(5,4) = 0.9783d0
+  s(6,1) = 9.9839d0; s(6,2) = -4.9324
+  s(7,1) = 22.3512d0; s(7,2) = -18.5856d0 
+  s(8,1) = 8.9496d0; s(8,2) = -4.4597
+  s(9,1) = 2.1519d0; s(9,2) = 2.3481d0
+  s(10,1) = 2.1519d0; s(10,2) = 2.3481d0
+  s(11,1) = 3.9d0 
+  s(12,1) = 3.2d0 
+!
+! ocean (please don't modify)
+  if (soliddim(13).eqv..false.) then
+!
+! continental
+  else
+  s(13,1) = s(12,1)
+  end if
+!
+!
+  r(:) = r(:)*1.d3
+  
+  !- handling the first layer : central sphere
+  rad = radin
+  rad(1) = 0.d0
+  
+  do j = 1,nl
+  
+ ro = 0.d0
+ vp = 0.d0
+ vs = 0.d0
+
+ do i = 1,13
+
+  r1 = 0.d0
+  r2 = 0.d0
+  if ((rad(j) > r(i)).and.(rad(j) <= r(i+1))) then
+   if (rad(j+1) <= r(i+1)) then
+    r2 = rad(j+1)
+    r1 = rad(j)
+   else
+    r2 = r(i+1)
+    r1 = rad(j)
+   end if
+  else if (rad(j) <= r(i)) then
+   if ((rad(j+1) > r(i)).and.(rad(j+1) <= r(i+1))) then
+    r2 = rad(j+1)
+    r1 = r(i)
+   else if (rad(j+1) > r(i+1)) then
+    r2 = r(i+1)
+    r1 = r(i)
+   end if
+  end if
+
+  t1 = d(i,1)/3.d0
+  t2 = d(i,2)/(Rt*4.d0)
+  t3 = d(i,3)/((Rt**2)*5.d0)
+  t4 = d(i,4)/((Rt**3)*6.d0)
+  ro =  ro + t1*(r2**3) + t2*(r2**4) + t3*(r2**5) + t4*(r2**6) - &
+   ( t1*(r1**3) + t2*(r1**4) + t3*(r1**5) + t4*(r1**6) )
+     
+  t1 = p(i,1)/3.d0
+  t2 = p(i,2)/(Rt*4.d0)
+  t3 = p(i,3)/((Rt**2)*5.d0)
+  t4 = p(i,4)/((Rt**3)*6.d0)
+  vp =  vp + t1*(r2**3) + t2*(r2**4) + t3*(r2**5) + t4*(r2**6) - &
+   ( t1*(r1**3) + t2*(r1**4) + t3*(r1**5) + t4*(r1**6) )
+     
+  t1 = s(i,1)/3.d0
+  t2 = s(i,2)/(Rt*4.d0)
+  t3 = s(i,3)/((Rt**2)*5.d0)
+  t4 = s(i,4)/((Rt**3)*6.d0)
+  vs =  vs + t1*(r2**3) + t2*(r2**4) + t3*(r2**5) + t4*(r2**6) - &
+   ( t1*(r1**3) + t2*(r1**4) + t3*(r1**5) + t4*(r1**6) )
+
+ end do
+ ro = ro*3 / (rad(j+1)**3-rad(j)**3)
+ vp = vp*3 /(rad(j+1)**3-rad(j)**3)
+ vs = vs*3 / (rad(j+1)**3-rad(j)**3)
+ mu = ro*vs**2
+ la = ro*vp**2 - 2.d0*mu
+ ro = ro*1.d3
+ la = la*1.d9
+ mu = mu*1.d9
+
+ !print*, rad(j+1), ro, la , mu
+ rot(j) = ro
+ lat(j) = la
+ mut(j) = mu
+  end do
+   
+   
+ end subroutine earth_homogeneous_layers_prembased
+
+
+ subroutine earth_nlayers(x0,ro,la,mu,GR,solid)
+ use lnb_param
+!---------------------------------------
+! Gets planet properties at non-dimentionalized radius x0:
+!ro: density
+!la: Lame lambda constant
+!mu: Lame mu constant (shear modulus)
+!GR: gravity
+!solid: boolean, true if solid, otherwise liquid
+    integer                 :: i,j
+    doubleprecision      :: la,mu,CST,GR
+    doubleprecision      :: x,x0,xx0,ro
+    doubleprecision      ::r1,r2
+    logical       :: solid
+    double precision, dimension(nlayer+1) :: r
+    
+
+
+    solid = .true.
+
+    r(:) = radius(:)
+    r(1) = 0.d0
+    x    = x0   * ra
+    CST = 4.d0*pi*GG/3.d0
+    if ( x > r(nlayer+1) ) x = r(nlayer+1)
+    
+    GR = 0.d0
+    
+    do i = 1,nlayer
+
+ if (x > r(i)) then 
+
+  r2 = r(i+1)
+  r1 = r(i)
+  ro = roc(i)
+
+  if (x <= r(i+1)) then
+
+   GR = GR + ro*(x**3-r1**3)
+   if (x > epsdb) GR = GR*CST/(x**2)
+
+  else
+   GR = GR + ro*(r2**3-r1**3)
+  end if
+ end if
+
+ if ((x >= r(i)).and.(x < r(i+1))) then    
+  la = lac(i)
+  mu = muc(i)
+  ro = roc(i)
+  if ( soliddim(i).eqv..false. ) solid = .false.
+
+ end if
+
+    end do
+
+    if (x>=r(nlayer+1)) then
+ la = lac(nlayer)
+ mu = muc(nlayer)
+ ro = roc(nlayer)
+  if ( soliddim(nlayer).eqv..false. ) solid = .false.
+
+     end if
+
+ end subroutine earth_nlayers
+ 
+ subroutine earth_nlayers_viscoelas(x0,ro,la,mu,GR,solid)
+ use lnb_param
+!---------------------------------------
+! Defines the earth rheology at non-dimensionalized radius x0 and angular frequency freq (global/public variable)
+
+    integer                 :: i
+    double complex   :: la, mu, cst
+    double precision      :: GR,la0,mu00,ka,mu1,mu2,vi2
+    double precision      :: x,x0,xx0,ro,vi
+    logical       :: notfound,solid,burg
+
+
+
+  call earth_nlayers(x0,ro,la0,mu00,GR,solid)
+  
+  x    = x0 * ra
+ do i = 1,nlayer
+ if ((x >= radius(i)).and.(x < radius(i+1))) then
+ vi = vic(i) 
+ vi2 = vic2(i)
+ mu2=muc2(i)
+ burg=burgers(i)
+ end if
+ end do
+
+  if (burg.eqv..true.) then
+ mu1=mu00
+
+ if ((vi*freq) /= 0.d0) then
+  ka=la0 + 2.d0/3.d0*mu00
+  !print*,mu1,mu2,vi,vi2
+   mu=mu1*freq*(freq+mu2/vi2)/((freq+mu2/vi2)*(freq+mu1/vi)+mu1/vi2*freq)
+  !la=4*la0*mu**2/(2*mu*(3*la0+2*mu)-3*la0*mu)
+  la=ka-2.d0/3.d0*mu
+  !print*,freq,mu,la
+ else
+  mu = mu00
+  la = la0
+ endif
+  else
+   ka = la0 + 2.d0/3.d0*mu00
+   cst = vi*freq
+   if (cst /= 0.d0) then
+  mu = mu00/(1.d0+mu00/cst)
+  la = (la0 + mu00*ka/cst)/(1.d0 + mu00/cst)
+   else
+  mu = mu00
+  la = la0
+   endif
+  endif
+   
+  !
+  !!write(101,*), freq,cst,la0,la,mu00,mu,vi
+
+ end subroutine earth_nlayers_viscoelas
+ 
+ 
+
+
+end module model
Index: /issm/trunk/src/c/modules/FourierLoveCorex/model.mod
===================================================================
--- /issm/trunk/src/c/modules/FourierLoveCorex/model.mod	(revision 22758)
+++ /issm/trunk/src/c/modules/FourierLoveCorex/model.mod	(revision 22758)
@@ -0,0 +1,78 @@
+GFORTRAN module version '10' created from model.f90
+MD5:a258024f3edabbd9d8f912615daabf3f -- If you edit this, you'll get what you deserve.
+
+(() () () () () () () () () () () () () () () () () () () () () () ()
+() () () ())
+
+()
+
+()
+
+()
+
+()
+
+()
+
+(2 'earth_homogeneous_layers_prembased' 'model' '' 1 ((PROCEDURE
+UNKNOWN-INTENT MODULE-PROC DECL UNKNOWN 0 0 SUBROUTINE ALWAYS_EXPLICIT)
+(UNKNOWN 0 0 0 0 UNKNOWN ()) 3 0 (4 5 6 7 8 9 10) () 0 () () () 0 0)
+11 'earth_nlayers' 'model' '' 1 ((PROCEDURE UNKNOWN-INTENT MODULE-PROC
+DECL UNKNOWN 0 0 SUBROUTINE) (UNKNOWN 0 0 0 0 UNKNOWN ()) 12 0 (13 14 15
+16 17 18) () 0 () () () 0 0)
+19 'earth_nlayers_viscoelas' 'model' '' 1 ((PROCEDURE UNKNOWN-INTENT
+MODULE-PROC DECL UNKNOWN 0 0 SUBROUTINE) (UNKNOWN 0 0 0 0 UNKNOWN ()) 20
+0 (21 22 23 24 25 26) () 0 () () () 0 0)
+27 'model' 'model' '' 1 ((MODULE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0) (UNKNOWN 0 0 0 0 UNKNOWN ()) 0 0 () () 0 () () () 0 0)
+28 'model_init2' 'model' '' 1 ((PROCEDURE UNKNOWN-INTENT MODULE-PROC
+DECL UNKNOWN 0 0 SUBROUTINE) (UNKNOWN 0 0 0 0 UNKNOWN ()) 29 0 (30) () 0
+() () () 0 0)
+4 'radin' '' '' 3 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DIMENSION POINTER DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () (1 0 DEFERRED
+() ()) 0 () () () 0 0)
+5 'nl' '' '' 3 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN 0
+0 DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+6 'rot' '' '' 3 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN 0
+0 DIMENSION POINTER DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () (1 0 DEFERRED ()
+()) 0 () () () 0 0)
+7 'lat' '' '' 3 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN 0
+0 DIMENSION POINTER DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () (1 0 DEFERRED ()
+()) 0 () () () 0 0)
+8 'mut' '' '' 3 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN 0
+0 DIMENSION POINTER DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () (1 0 DEFERRED ()
+()) 0 () () () 0 0)
+9 'gr' '' '' 3 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN 0
+0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+10 'solid' '' '' 3 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DUMMY) (LOGICAL 4 0 0 0 LOGICAL ()) 0 0 () () 0 () () () 0 0)
+13 'x0' '' '' 12 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+14 'ro' '' '' 12 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+15 'la' '' '' 12 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+16 'mu' '' '' 12 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+17 'gr' '' '' 12 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+18 'solid' '' '' 12 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DUMMY) (LOGICAL 4 0 0 0 LOGICAL ()) 0 0 () () 0 () () () 0 0)
+21 'x0' '' '' 20 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+22 'ro' '' '' 20 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+23 'la' '' '' 20 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (COMPLEX 8 0 0 0 COMPLEX ()) 0 0 () () 0 () () () 0 0)
+24 'mu' '' '' 20 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (COMPLEX 8 0 0 0 COMPLEX ()) 0 0 () () 0 () () () 0 0)
+25 'gr' '' '' 20 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+26 'solid' '' '' 20 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DUMMY) (LOGICAL 4 0 0 0 LOGICAL ()) 0 0 () () 0 () () () 0 0)
+30 'nbc' '' '' 29 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+)
+
+('earth_homogeneous_layers_prembased' 0 2 'earth_nlayers' 0 11
+'earth_nlayers_viscoelas' 0 19 'model' 0 27 'model_init2' 0 28)
Index: /issm/trunk/src/c/modules/FourierLoveCorex/util.f90
===================================================================
--- /issm/trunk/src/c/modules/FourierLoveCorex/util.f90	(revision 22758)
+++ /issm/trunk/src/c/modules/FourierLoveCorex/util.f90	(revision 22758)
@@ -0,0 +1,226 @@
+module util
+ 
+ use model
+ use lnb_param
+
+ contains
+
+!
+!_______DERIVS_________________________________________________________________
+!
+ subroutine derivs(x,y,dydx)
+ 
+ implicit none
+ double complex  :: la, mu
+ double precision :: x,ro,g
+ double complex :: flm,rlm,rm0,rg0,frh,fgr,fn
+ logical :: solid
+ integer :: iy,id,n2,ny
+ double complex, dimension(6)   :: y,dydx,f
+ double complex, dimension(6,6) :: dy
+
+ call earth_nlayers_viscoelas(x,ro,la,mu,g,solid)
+ !print*,la,mu
+!
+!_______Expressions
+!
+ flm=(la+2.d0*mu)
+ rlm=(3.d0*la+2.d0*mu)/(la+2.d0*mu)
+ rm0=mu/mu0
+ rg0=g/go0
+ frh=ro*g*ra/mu0
+ fgr=4.d0*Pi*GG*ro*ra/go0
+ fn=dble(deg*(deg+1))
+ 
+!
+!_______Systeme differentiel yi dans un solide
+!
+ if(solid) then
+ 
+ ny = 6
+
+ dy(1,1)= (-2.d0*la/flm)/x
+ dy(1,2)= mu0/flm
+ dy(1,3)= (la*fn/flm)/x
+ dy(1,4)= 0.d0
+ dy(1,5)= 0.d0
+ dy(1,6)= 0.d0
+
+ dy(2,1)=  4.d0*(-frh+rm0*rlm/x)/x + ro*freq**2*ra/mu0
+ dy(2,2)=(-4.d0*mu/flm)/x
+ dy(2,3)= fn*(frh-2.d0*rm0*rlm/x)/x
+ dy(2,4)= fn/x
+ dy(2,5)= 0.d0
+ dy(2,6)= -frh/rg0
+
+ dy(3,1)= -1.d0/x
+ dy(3,2)= 0.d0
+ dy(3,3)= 1.d0/x
+ dy(3,4)= 1.d0/rm0
+ dy(3,5)= 0.d0
+ dy(3,6)= 0.d0
+
+ dy(4,1)= (frh-2.d0*rm0*rlm/x)/x
+ dy(4,2)= ( -la/flm)/x
+ dy(4,3)= (2.d0*rm0*(la*(2.d0*fn-1.d0)+2.d0*mu*(fn-1.d0))/flm)/(x*x) + ro*freq**2*ra/mu0
+ dy(4,4)= -3.d0/x
+ dy(4,5)= -(frh/rg0)/x
+ dy(4,6)= 0.d0
+
+ dy(5,1)= fgr
+ dy(5,2)= 0.d0
+ dy(5,3)= 0.d0
+ dy(5,4)= 0.d0
+ dy(5,5)= 0.d0
+ dy(5,6)= 1.d0
+
+ dy(6,1)= 0.d0
+ dy(6,2)= 0.d0
+ dy(6,3)= -(fgr*fn)/x
+ dy(6,4)= 0.d0
+ dy(6,5)= fn/(x*x)
+ dy(6,6)= -2.d0/x
+  
+ else
+ 
+ ny = 2
+
+ dy(:,:)= 0.d0
+
+ dy(1,1)= fgr/rg0
+ dy(1,2)= 1.d0
+ dy(2,1)= (-4.d0*(fgr/rg0)+fn/x)/x
+ dy(2,2)= -2.d0/x-fgr/rg0
+ 
+ end if
+!
+!_______Derivees des yi
+! 
+ dydx(:)=0.d0 
+ do id=1,ny
+  do iy=1,ny
+     dydx(id)=dydx(id)+dy(id,iy)*y(iy)
+  end do
+ end do
+
+    end subroutine derivs
+
+
+    subroutine propagFDS(ystart,xmin,xmax,nstep)
+     implicit none
+     double precision :: xmin,xmax,dr,x
+     integer :: nstep,i
+     double complex, dimension(6)   :: ystart,dydx,y,y1
+
+     dr = (xmax -xmin)/nstep
+     y = ystart
+     x = xmin
+
+     do i = 1,nstep
+
+  call derivs(x,y,dydx)
+  y1 = y + dr*dydx
+  x = x + dr
+  y = y1
+
+     end do
+
+     ystart = y
+
+ end subroutine propagFDS
+
+!_____LUDCMP___________________________________________________________________
+!
+      SUBROUTINE ludcmp(a,n,np,indx,d)
+      IMPLICIT DOUBLE PRECISION (a-h,o-z)
+      INTEGER n,np,indx(n),NMAX
+      REAL*8 d,a(np,np),TINY
+      PARAMETER (NMAX=500,TINY=1.0D-30)
+      INTEGER i,imax,j,k
+      REAL*8 aamax,dum,sum,vv(NMAX)
+      d=1d0
+      do 12 i=1,n
+        aamax=0d0
+        do 11 j=1,n
+          if (dabs(a(i,j)).gt.aamax) aamax=dabs(a(i,j))
+11      continue
+        if (aamax.eq.0d0) stop 'singular matrix in ludcmp'
+        vv(i)=1./aamax
+12    continue
+      do 19 j=1,n
+        do 14 i=1,j-1
+          sum=a(i,j)
+          do 13 k=1,i-1
+            sum=sum-a(i,k)*a(k,j)
+13        continue
+          a(i,j)=sum
+14      continue
+        aamax=0d0
+        do 16 i=j,n
+          sum=a(i,j)
+          do 15 k=1,j-1
+            sum=sum-a(i,k)*a(k,j)
+15        continue
+          a(i,j)=sum
+          dum=vv(i)*dabs(sum)
+          if (dum.ge.aamax) then
+            imax=i
+            aamax=dum
+          endif
+16      continue
+        if (j.ne.imax)then
+          do 17 k=1,n
+            dum=a(imax,k)
+            a(imax,k)=a(j,k)
+            a(j,k)=dum
+17        continue
+          d=-d
+          vv(imax)=vv(j)
+        endif
+        indx(j)=imax
+        if(a(j,j).eq.0d0)a(j,j)=TINY
+        if(j.ne.n)then
+          dum=1d0/a(j,j)
+          do 18 i=j+1,n
+            a(i,j)=a(i,j)*dum
+18        continue
+        endif
+19    continue
+      return
+      END SUBROUTINE ludcmp
+!
+!_____LUBKSB___________________________________________________________________
+!
+      SUBROUTINE lubksb(a,n,np,indx,b)
+      IMPLICIT DOUBLE PRECISION (a-h,o-z)
+      INTEGER n,np,indx(n)
+      REAL*8 a(np,np),b(np)
+      INTEGER i,ii,j,ll
+      REAL*8 sum
+      ii=0
+      do 12 i=1,n
+        ll=indx(i)
+        sum=b(ll)
+        b(ll)=b(i)
+        if (ii.ne.0)then
+          do 11 j=ii,i-1
+            sum=sum-a(i,j)*b(j)
+11        continue
+        else if (sum.ne.0d0) then
+          ii=i
+        endif
+        b(i)=sum
+12    continue
+      do 14 i=n,1,-1
+        sum=b(i)
+        do 13 j=i+1,n
+          sum=sum-a(i,j)*b(j)
+13      continue
+        b(i)=sum/a(i,i)
+14    continue
+      return
+      END SUBROUTINE lubksb
+
+
+
+end module util
Index: /issm/trunk/src/c/modules/FourierLoveCorex/util.mod
===================================================================
--- /issm/trunk/src/c/modules/FourierLoveCorex/util.mod	(revision 22758)
+++ /issm/trunk/src/c/modules/FourierLoveCorex/util.mod	(revision 22758)
@@ -0,0 +1,269 @@
+GFORTRAN module version '10' created from util.f90
+MD5:6b427639b8981256d3e19f33c3e9956b -- If you edit this, you'll get what you deserve.
+
+(() () () () () () () () () () () () () () () () () () () () () () ()
+() () () ())
+
+()
+
+()
+
+()
+
+()
+
+()
+
+(2 '__convert_r4_r8' '(intrinsic)' '' 1 ((PROCEDURE UNKNOWN-INTENT
+UNKNOWN-PROC UNKNOWN UNKNOWN 0 0 FUNCTION ELEMENTAL PURE) (REAL 8 0 0 0
+REAL ()) 0 0 () () 2 () () () 0 0)
+3 'allow_layer_del' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT
+UNKNOWN-PROC UNKNOWN IMPLICIT-SAVE 0 0) (LOGICAL 4 0 0 0 LOGICAL ()) 0 0
+() () 0 () () () 0 0)
+4 'benchmark_spada' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT
+UNKNOWN-PROC UNKNOWN IMPLICIT-SAVE 0 0) (LOGICAL 4 0 0 0 LOGICAL ()) 0 0
+() () 0 () () () 0 0)
+5 'burgers' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0 DIMENSION POINTER) (LOGICAL 4 0 0 0 LOGICAL ())
+0 0 () (1 0 DEFERRED () ()) 0 () () () 0 0)
+6 'deg' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+7 'degmax' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () ()
+() 0 0)
+8 'degmin' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () ()
+() 0 0)
+9 'derivs' 'util' '' 1 ((PROCEDURE UNKNOWN-INTENT MODULE-PROC DECL
+UNKNOWN 0 0 SUBROUTINE) (UNKNOWN 0 0 0 0 UNKNOWN ()) 10 0 (11 12 13) ()
+0 () () () 0 0)
+14 'display' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (LOGICAL 4 0 0 0 LOGICAL ()) 0 0 () () 0 () ()
+() 0 0)
+15 'earth_homogeneous_layers_prembased' 'model' '' 1 ((PROCEDURE
+UNKNOWN-INTENT MODULE-PROC DECL UNKNOWN 0 0 SUBROUTINE ALWAYS_EXPLICIT)
+(UNKNOWN 0 0 0 0 UNKNOWN ()) 16 0 (17 18 19 20 21 22 23) () 0 () () () 0
+0)
+24 'earth_nlayers' 'model' '' 1 ((PROCEDURE UNKNOWN-INTENT MODULE-PROC
+DECL UNKNOWN 0 0 SUBROUTINE) (UNKNOWN 0 0 0 0 UNKNOWN ()) 25 0 (26 27 28
+29 30 31) () 0 () () () 0 0)
+32 'earth_nlayers_viscoelas' 'model' '' 1 ((PROCEDURE UNKNOWN-INTENT
+MODULE-PROC DECL UNKNOWN 0 0 SUBROUTINE) (UNKNOWN 0 0 0 0 UNKNOWN ()) 33
+0 (34 35 36 37 38 39) () 0 () () () 0 0)
+40 'epsdb' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0
+0)
+41 'freq' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (COMPLEX 8 0 0 0 COMPLEX ()) 0 0 () () 0 () ()
+() 0 0)
+42 'gg' 'lnb_param' '' 1 ((PARAMETER UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () (CONSTANT (REAL 8 0 0 0
+REAL ()) 0 '0.495dac00000000@-8') () 0 () () () 0 0)
+43 'go0' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+44 'go_cmb' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0
+0)
+45 'go_icb' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0
+0)
+46 'go_surf' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0
+0)
+47 'ifmax' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () ()
+() 0 0)
+48 'ifmin' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () ()
+() 0 0)
+49 'incompressible' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT
+UNKNOWN-PROC UNKNOWN IMPLICIT-SAVE 0 0) (LOGICAL 4 0 0 0 LOGICAL ()) 0 0
+() () 0 () () () 0 0)
+50 'lac' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0 DIMENSION POINTER) (REAL 8 0 0 0 REAL ()) 0 0 () (1 0
+DEFERRED () ()) 0 () () () 0 0)
+51 'layerrap' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0
+0)
+52 'lnb_param' 'lnb_param' '' 1 ((MODULE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN UNKNOWN 0 0) (UNKNOWN 0 0 0 0 UNKNOWN ()) 0 0 () () 0 () () () 0
+0)
+53 'lubksb' 'util' '' 1 ((PROCEDURE UNKNOWN-INTENT MODULE-PROC DECL
+UNKNOWN 0 0 SUBROUTINE) (UNKNOWN 0 0 0 0 UNKNOWN ()) 54 0 (55 56 57 58
+59) () 0 () () () 0 0)
+60 'ludcmp' 'util' '' 1 ((PROCEDURE UNKNOWN-INTENT MODULE-PROC DECL
+UNKNOWN 0 0 SUBROUTINE) (UNKNOWN 0 0 0 0 UNKNOWN ()) 61 0 (62 63 64 65
+66) () 0 () () () 0 0)
+67 'model' 'model' '' 1 ((MODULE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0) (UNKNOWN 0 0 0 0 UNKNOWN ()) 0 0 () () 0 () () () 0 0)
+68 'model_init2' 'model' '' 1 ((PROCEDURE UNKNOWN-INTENT MODULE-PROC
+DECL UNKNOWN 0 0 SUBROUTINE) (UNKNOWN 0 0 0 0 UNKNOWN ()) 69 0 (70) () 0
+() () () 0 0)
+71 'mu0' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+72 'muc' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0 DIMENSION POINTER) (REAL 8 0 0 0 REAL ()) 0 0 () (1 0
+DEFERRED () ()) 0 () () () 0 0)
+73 'muc2' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0 DIMENSION POINTER) (REAL 8 0 0 0 REAL ()) 0 0
+() (1 0 DEFERRED () ()) 0 () () () 0 0)
+74 'mucratio' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0
+0)
+75 'nfreq' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () ()
+() 0 0)
+76 'nlayer' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () ()
+() 0 0)
+77 'pi' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+78 'propagfds' 'util' '' 1 ((PROCEDURE UNKNOWN-INTENT MODULE-PROC DECL
+UNKNOWN 0 0 SUBROUTINE) (UNKNOWN 0 0 0 0 UNKNOWN ()) 79 0 (80 81 82 83)
+() 0 () () () 0 0)
+84 'r0' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+85 'ra' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+86 'radbc' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0 DIMENSION POINTER) (LOGICAL 4 0 0 0 LOGICAL ())
+0 0 () (1 0 DEFERRED () ()) 0 () () () 0 0)
+87 'radius' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0 DIMENSION POINTER) (REAL 8 0 0 0 REAL ()) 0 0
+() (1 0 DEFERRED () ()) 0 () () () 0 0)
+88 'rb' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+89 'rc' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+90 'ro_mean' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0
+0)
+91 'roc' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0 DIMENSION POINTER) (REAL 8 0 0 0 REAL ()) 0 0 () (1 0
+DEFERRED () ()) 0 () () () 0 0)
+92 'soliddim' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0 DIMENSION POINTER) (LOGICAL 4 0 0 0 LOGICAL ())
+0 0 () (1 0 DEFERRED () ()) 0 () () () 0 0)
+93 'util' 'util' '' 1 ((MODULE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0) (UNKNOWN 0 0 0 0 UNKNOWN ()) 0 0 () () 0 () () () 0 0)
+94 'valini' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (COMPLEX 8 0 0 0 COMPLEX ()) 0 0 () () 0 () ()
+() 0 0)
+95 'vic' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+IMPLICIT-SAVE 0 0 DIMENSION POINTER) (REAL 8 0 0 0 REAL ()) 0 0 () (1 0
+DEFERRED () ()) 0 () () () 0 0)
+96 'vic2' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0 DIMENSION POINTER) (REAL 8 0 0 0 REAL ()) 0 0
+() (1 0 DEFERRED () ()) 0 () () () 0 0)
+97 'vicratio' 'lnb_param' '' 1 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC
+UNKNOWN IMPLICIT-SAVE 0 0) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0
+0)
+11 'x' '' '' 10 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN 0
+0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+12 'y' '' '' 10 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN 0
+0 DIMENSION DUMMY) (COMPLEX 8 0 0 0 COMPLEX ()) 0 0 () (1 0 EXPLICIT (
+CONSTANT (INTEGER 4 0 0 0 INTEGER ()) 0 '1') (CONSTANT (INTEGER 4 0 0 0
+INTEGER ()) 0 '6')) 0 () () () 0 0)
+13 'dydx' '' '' 10 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DIMENSION DUMMY) (COMPLEX 8 0 0 0 COMPLEX ()) 0 0 () (1 0
+EXPLICIT (CONSTANT (INTEGER 4 0 0 0 INTEGER ()) 0 '1') (CONSTANT (
+INTEGER 4 0 0 0 INTEGER ()) 0 '6')) 0 () () () 0 0)
+17 'radin' '' '' 16 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DIMENSION POINTER DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () (1 0
+DEFERRED () ()) 0 () () () 0 0)
+18 'nl' '' '' 16 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+19 'rot' '' '' 16 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DIMENSION POINTER DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () (1 0 DEFERRED
+() ()) 0 () () () 0 0)
+20 'lat' '' '' 16 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DIMENSION POINTER DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () (1 0 DEFERRED
+() ()) 0 () () () 0 0)
+21 'mut' '' '' 16 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DIMENSION POINTER DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () (1 0 DEFERRED
+() ()) 0 () () () 0 0)
+22 'gr' '' '' 16 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+23 'solid' '' '' 16 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DUMMY) (LOGICAL 4 0 0 0 LOGICAL ()) 0 0 () () 0 () () () 0 0)
+26 'x0' '' '' 25 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+27 'ro' '' '' 25 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+28 'la' '' '' 25 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+29 'mu' '' '' 25 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+30 'gr' '' '' 25 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+31 'solid' '' '' 25 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DUMMY) (LOGICAL 4 0 0 0 LOGICAL ()) 0 0 () () 0 () () () 0 0)
+34 'x0' '' '' 33 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+35 'ro' '' '' 33 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+36 'la' '' '' 33 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (COMPLEX 8 0 0 0 COMPLEX ()) 0 0 () () 0 () () () 0 0)
+37 'mu' '' '' 33 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (COMPLEX 8 0 0 0 COMPLEX ()) 0 0 () () 0 () () () 0 0)
+38 'gr' '' '' 33 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+39 'solid' '' '' 33 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DUMMY) (LOGICAL 4 0 0 0 LOGICAL ()) 0 0 () () 0 () () () 0 0)
+55 'a' '' '' 54 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN 0
+0 DIMENSION DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () (2 0 EXPLICIT (
+CONSTANT (INTEGER 4 0 0 0 INTEGER ()) 0 '1') (VARIABLE (INTEGER 4 0 0 0
+INTEGER ()) 0 57 ()) (CONSTANT (INTEGER 4 0 0 0 INTEGER ()) 0 '1') (
+VARIABLE (INTEGER 4 0 0 0 INTEGER ()) 0 57 ())) 0 () () () 0 0)
+56 'n' '' '' 54 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN 0
+0 DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+57 'np' '' '' 54 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+58 'indx' '' '' 54 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DIMENSION DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () (1 0
+EXPLICIT (CONSTANT (INTEGER 4 0 0 0 INTEGER ()) 0 '1') (VARIABLE (
+INTEGER 4 0 0 0 INTEGER ()) 0 56 ())) 0 () () () 0 0)
+59 'b' '' '' 54 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN 0
+0 DIMENSION DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () (1 0 EXPLICIT (
+CONSTANT (INTEGER 4 0 0 0 INTEGER ()) 0 '1') (VARIABLE (INTEGER 4 0 0 0
+INTEGER ()) 0 57 ())) 0 () () () 0 0)
+62 'a' '' '' 61 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN 0
+0 DIMENSION DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () (2 0 EXPLICIT (
+CONSTANT (INTEGER 4 0 0 0 INTEGER ()) 0 '1') (VARIABLE (INTEGER 4 0 0 0
+INTEGER ()) 0 64 ()) (CONSTANT (INTEGER 4 0 0 0 INTEGER ()) 0 '1') (
+VARIABLE (INTEGER 4 0 0 0 INTEGER ()) 0 64 ())) 0 () () () 0 0)
+63 'n' '' '' 61 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN 0
+0 DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+64 'np' '' '' 61 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+65 'indx' '' '' 61 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DIMENSION DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () (1 0
+EXPLICIT (CONSTANT (INTEGER 4 0 0 0 INTEGER ()) 0 '1') (VARIABLE (
+INTEGER 4 0 0 0 INTEGER ()) 0 63 ())) 0 () () () 0 0)
+66 'd' '' '' 61 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN 0
+0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+70 'nbc' '' '' 69 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN UNKNOWN
+0 0 DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+80 'ystart' '' '' 79 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DIMENSION DUMMY) (COMPLEX 8 0 0 0 COMPLEX ()) 0 0 () (1 0
+EXPLICIT (CONSTANT (INTEGER 4 0 0 0 INTEGER ()) 0 '1') (CONSTANT (
+INTEGER 4 0 0 0 INTEGER ()) 0 '6')) 0 () () () 0 0)
+81 'xmin' '' '' 79 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+82 'xmax' '' '' 79 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DUMMY) (REAL 8 0 0 0 REAL ()) 0 0 () () 0 () () () 0 0)
+83 'nstep' '' '' 79 ((VARIABLE UNKNOWN-INTENT UNKNOWN-PROC UNKNOWN
+UNKNOWN 0 0 DUMMY) (INTEGER 4 0 0 0 INTEGER ()) 0 0 () () 0 () () () 0 0)
+)
+
+('__convert_r4_r8' 0 2 'allow_layer_del' 0 3 'benchmark_spada' 0 4
+'burgers' 0 5 'deg' 0 6 'degmax' 0 7 'degmin' 0 8 'derivs' 0 9 'display'
+0 14 'earth_homogeneous_layers_prembased' 0 15 'earth_nlayers' 0 24
+'earth_nlayers_viscoelas' 0 32 'epsdb' 0 40 'freq' 0 41 'gg' 0 42 'go0'
+0 43 'go_cmb' 0 44 'go_icb' 0 45 'go_surf' 0 46 'ifmax' 0 47 'ifmin' 0
+48 'incompressible' 0 49 'lac' 0 50 'layerrap' 0 51 'lnb_param' 0 52
+'lubksb' 0 53 'ludcmp' 0 60 'model' 0 67 'model_init2' 0 68 'mu0' 0 71
+'muc' 0 72 'muc2' 0 73 'mucratio' 0 74 'nfreq' 0 75 'nlayer' 0 76 'pi' 0
+77 'propagfds' 0 78 'r0' 0 84 'ra' 0 85 'radbc' 0 86 'radius' 0 87 'rb'
+0 88 'rc' 0 89 'ro_mean' 0 90 'roc' 0 91 'soliddim' 0 92 'util' 0 93
+'valini' 0 94 'vic' 0 95 'vic2' 0 96 'vicratio' 0 97)
Index: /issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp	(revision 22758)
@@ -7,35 +7,78 @@
 #include "../../toolkits/toolkits.h"
 
-void GetVectorFromControlInputsx(Vector<IssmDouble>** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,const char* data,bool onsid){
+void GetVectorFromControlInputsx(Vector<IssmDouble>** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,const char* data,bool onsid){/*{{{*/
 
-	int  num_controls;
-	int *control_type = NULL;
-	Vector<IssmDouble>*  vector=NULL;
+	bool isautodiff;
+	parameters->FindParam(&isautodiff,AutodiffIsautodiffEnum);
+	if(isautodiff){
+		int*  N = NULL;
+		int*  M = NULL;
+		int  num_controls;
+		int* control_type = NULL;
+		Vector<IssmDouble>*  vector=NULL;
 
-	/*Retrieve some parameters*/
-	parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
-	parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+		/*Retrieve some parameters*/
+		parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+		parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+		parameters->FindParam(&N,NULL,ControlInputSizeNEnum);
+		parameters->FindParam(&M,NULL,ControlInputSizeMEnum);
 
-	/*Allocate and populate gradient*/
-	vector=new Vector<IssmDouble>(num_controls*vertices->NumberOfVertices());
+		/*1. Get vector size*/
+		int size = 0;
+		for(int i=0;i<num_controls;i++) size+=M[i]*N[i];
 
-	for(int i=0;i<num_controls;i++){
-		for(int j=0;j<elements->Size();j++){
-			Element* element=(Element*)elements->GetObjectByOffset(j);
-			element->GetVectorFromControlInputs(vector,control_type[i],i,data,onsid);
+
+		/*2. Allocate vector*/
+		vector=new Vector<IssmDouble>(size);
+
+		/*3. Populate vector*/
+		int offset = 0;
+		for(int i=0;i<num_controls;i++){
+			for(int j=0;j<elements->Size();j++){
+				Element* element=(Element*)elements->GetObjectByOffset(j);
+				element->GetVectorFromControlInputs(vector,control_type[i],i,data,offset,onsid);
+			}
+			offset += M[i]*N[i];
 		}
+
+		vector->Assemble();
+
+		/*Assign output pointers:*/
+		xDelete<int>(control_type);
+		xDelete<int>(M);
+		xDelete<int>(N);
+
+		*pvector=vector;
+	}
+	else{
+		int  num_controls;
+		int* control_type = NULL;
+		Vector<IssmDouble>*  vector=NULL;
+
+		/*Retrieve some parameters*/
+		parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+		parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+
+
+		/*2. Allocate vector*/
+		vector=new Vector<IssmDouble>(num_controls*vertices->NumberOfVertices());
+
+		/*3. Populate vector*/
+		int offset = 0;
+		for(int i=0;i<num_controls;i++){
+			for(int j=0;j<elements->Size();j++){
+				Element* element=(Element*)elements->GetObjectByOffset(j);
+				element->GetVectorFromControlInputs(vector,control_type[i],i,data,onsid);
+			}
+		}
+		vector->Assemble();
+
+		/*Assign output pointers:*/
+		xDelete<int>(control_type);
+		*pvector=vector;
 	}
 
-	vector->Assemble();
-
-	/*Assign output pointers:*/
-	xDelete<int>(control_type);
-	*pvector=vector;
-}
-
-void GetVectorFromControlInputsx( IssmDouble** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, const char* data,bool onsid){
-
-	/*output: */
-	IssmDouble* vector=NULL;
+}/*}}}*/
+void GetVectorFromControlInputsx( IssmDouble** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, const char* data,bool onsid){/*{{{*/
 
 	/*intermediary: */
@@ -43,5 +86,5 @@
 
 	GetVectorFromControlInputsx( &vec_vector, elements,nodes, vertices, loads, materials, parameters,data,onsid);
-	vector=vec_vector->ToMPISerial();
+	IssmDouble* vector=vec_vector->ToMPISerial();
 
 	/*Free ressources:*/
@@ -50,3 +93,68 @@
 	/*Assign output pointers:*/
 	*pvector=vector;
-}
+}/*}}}*/
+
+/*For autodiff, we sometimes need to cast our vectors to passive*/
+#ifdef _HAVE_ADOLC_
+void GetPassiveVectorFromControlInputsx(Vector<IssmPDouble>** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,const char* data,bool onsid){/*{{{*/
+
+	/*Get active vector first*/
+	Vector<IssmDouble>*   activevector=NULL;
+	Vector<IssmPDouble>*  vector=NULL;
+	int                   size;
+
+	/*Retrieve some parameters*/
+	GetVectorFromControlInputsx(&activevector, elements,nodes, vertices, loads, materials, parameters,data,onsid);
+
+	/*Serialize vector*/
+	activevector->GetSize(&size);
+	IssmDouble* dactivevector=activevector->ToMPISerial();
+
+	/*Cast to passive*/
+	vector=new Vector<IssmPDouble>(size);
+	for(int i=0;i<size;i++){
+		vector->SetValue(i,reCast<IssmPDouble>(dactivevector[i]),INS_VAL);
+	}
+	vector->Assemble();
+
+	/*Assign output pointers:*/
+	delete activevector;
+	xDelete<IssmDouble>(dactivevector);
+	*pvector=vector;
+
+}/*}}}*/
+void GetPassiveVectorFromControlInputsx(IssmPDouble** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, const char* data,bool onsid){/*{{{*/
+
+	/*Get active vector first*/
+	Vector<IssmDouble>*   activevector=NULL;
+	IssmPDouble*          vector=NULL;
+	int                   size;
+
+	/*Retrieve some parameters*/
+	GetVectorFromControlInputsx(&activevector, elements,nodes, vertices, loads, materials, parameters,data,onsid);
+
+	/*Serialize vector*/
+	activevector->GetSize(&size);
+	IssmDouble* dactivevector=activevector->ToMPISerial();
+
+	/*Cast to passive*/
+	vector=xNew<IssmPDouble>(size);
+	for(int i=0;i<size;i++) vector[i] = reCast<IssmPDouble>(dactivevector[i]);
+
+	/*Assign output pointers:*/
+	delete activevector;
+	xDelete<IssmDouble>(dactivevector);
+	*pvector=vector;
+
+}/*}}}*/
+#else
+void GetPassiveVectorFromControlInputsx(Vector<IssmPDouble>** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,const char* data,bool onsid){/*{{{*/
+
+	GetVectorFromControlInputsx(pvector, elements,nodes, vertices, loads, materials, parameters,data,onsid);
+
+}/*}}}*/
+void GetPassiveVectorFromControlInputsx(IssmPDouble** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, const char* data,bool onsid){/*{{{*/
+
+	GetVectorFromControlInputsx(pvector, elements,nodes, vertices, loads, materials, parameters,data,onsid);
+}/*}}}*/
+#endif
Index: /issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h
===================================================================
--- /issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h	(revision 22757)
+++ /issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h	(revision 22758)
@@ -11,3 +11,6 @@
 void	GetVectorFromControlInputsx( IssmDouble** pvector, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,const char* data="value",bool onsid=false);
 
+void	GetPassiveVectorFromControlInputsx(Vector<double>** pvector, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,const char* data="value",bool onsid=false);
+void	GetPassiveVectorFromControlInputsx(double** pvector, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,const char* data="value",bool onsid=false);
+
 #endif  /* _GETVECTORFROMCONTROLINPUTSXX_H */
Index: /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp	(revision 22758)
@@ -7,5 +7,5 @@
 #include "../../toolkits/toolkits.h"
 
-void GetVectorFromInputsx(Vector<IssmDouble>** pvector,FemModel* femmodel,int name,int type){
+void GetVectorFromInputsx(Vector<IssmDouble>** pvector,FemModel* femmodel,int name,int type){/*{{{*/
 
 	int i;
@@ -35,7 +35,6 @@
 	/*Assign output pointers:*/
 	*pvector=vector;
-}
-
-void GetVectorFromInputsx(IssmDouble** pvector,FemModel* femmodel,int name, int type){
+}/*}}}*/
+void GetVectorFromInputsx(IssmDouble** pvector,FemModel* femmodel,int name, int type){/*{{{*/
 
 	/*output: */
@@ -53,3 +52,25 @@
 	/*Assign output pointers:*/
 	*pvector=vector;
-}
+}/*}}}*/
+void GetVectorFromInputsx(IssmDouble** pvector,int* pvector_size, FemModel* femmodel,int name){/*{{{*/
+
+	int interpolation_type;
+	/*this one is special: we don't specify the type, but let the nature of the inputs dictace. 
+	 * P0 -> ElementSIdEnum, P1 ->VertexSIdEnum: */
+	
+	/*We go find the input of the first element, and query its interpolation type: */
+	Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(0));
+	Input* input=element->GetInput(name); 
+	if (!input) _error_("could not find input: " << name);
+
+	interpolation_type=input->GetInputInterpolationType(); 
+	if(interpolation_type==P0Enum){
+		*pvector_size=femmodel->elements->NumberOfElements();
+		GetVectorFromInputsx(pvector,femmodel,name, ElementSIdEnum);
+	}
+	else if(interpolation_type==P1Enum){
+		*pvector_size=femmodel->vertices->NumberOfVertices();
+		GetVectorFromInputsx(pvector,femmodel,name, VertexSIdEnum);
+	}
+	else _error_("interpolation type : " << interpolation_type << " not supported yet!");
+}/*}}}*/
Index: /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.h
===================================================================
--- /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.h	(revision 22757)
+++ /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.h	(revision 22758)
@@ -10,4 +10,5 @@
 void	GetVectorFromInputsx( Vector<IssmDouble>** pvector,FemModel* femmodel,int name,int type);
 void	GetVectorFromInputsx( IssmDouble** pvector,FemModel* femmodel,int name,int type);
+void  GetVectorFromInputsx(IssmDouble** pvector,int* pvector_size, FemModel* femmodel,int name);
 
 #endif  /* _GETVECTORFROMINPUTSXX_H */
Index: /issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp	(revision 22758)
@@ -54,5 +54,5 @@
 
 			/*Now, pick up the parameter corresponding to root: */
-			femmodel->parameters->FindParam(&parameter,&nrows,&ncols,StringToEnumx(root));
+			femmodel->parameters->FindParamInDataset(&parameter,&nrows,&ncols,QmuVariableDescriptorsEnum,StringToEnumx(root));
 
 			/*We've got the parameter, we need to update it using qmu_part (a partitioning vector), 
Index: /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp	(revision 22758)
@@ -18,18 +18,20 @@
 void InputUpdateFromVectorDakotax(FemModel* femmodel,IssmDouble* vector, int name, int type){
 
-	int i;
-
 	/*Update elements, nodes, loads and materials from inputs: */
-	for(i=0;i<femmodel->elements->Size();i++){
+	for(int i=0;i<femmodel->elements->Size();i++){
 		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		element->InputUpdateFromVectorDakota(vector,name,type);
 	}
-	for(i=0;i<femmodel->loads->Size();i++){
+	for(int i=0;i<femmodel->loads->Size();i++){
 		Load* load=(Load*)femmodel->loads->GetObjectByOffset(i);
 		load->InputUpdateFromVectorDakota(vector,name,type);
 	}
-	for(i=0;i<femmodel->materials->Size();i++){
+	for(int i=0;i<femmodel->materials->Size();i++){
 		Material* material=(Material*)femmodel->materials->GetObjectByOffset(i);
 		material->InputUpdateFromVectorDakota(vector,name,type);
 	}
+	for(int i=0;i<femmodel->constraints->Size();i++){
+		Constraint* constraint=(Constraint*)femmodel->constraints->GetObjectByOffset(i);
+		constraint->InputUpdateFromVectorDakota(vector,femmodel->nodes,name,type);
+	}
 }
Index: /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp	(revision 22758)
@@ -10,5 +10,5 @@
 
 int InterpFromMesh2dx(IssmSeqVec<IssmPDouble>** pdata_prime,
-			double* index_data, double* x_data, double* y_data, int nods_data,int nels_data, double* data, int data_length,
+			int* index_data, double* x_data, double* y_data, int nods_data,int nels_data, double* data, int data_length,
 			double* x_prime, double* y_prime, int nods_prime,
 			double* default_values,int num_default_values,Contour<IssmPDouble>** contours,int numcontours){
Index: /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.h
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.h	(revision 22757)
+++ /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.h	(revision 22758)
@@ -15,5 +15,5 @@
 	bool                debug;
 	int                 nels_data;
-	double              *index_data;
+	int                *index_data;
 	double              *x_data;
 	double              *y_data;
@@ -31,5 +31,5 @@
 } InterpFromMesh2dxThreadStruct;
 
-int InterpFromMesh2dx(IssmSeqVec<IssmPDouble>** pdata_prime,double* index_data, double* x_data, double* y_data, int nods_data,int nels_data, double* data, int data_length, double* x_prime, double* y_prime, int nods_prime,
+int InterpFromMesh2dx(IssmSeqVec<IssmPDouble>** pdata_prime,int* index_data, double* x_data, double* y_data, int nods_data,int nels_data, double* data, int data_length, double* x_prime, double* y_prime, int nods_prime,
 		double* default_values,int num_default_values,Contour<IssmPDouble>** contours,int numcontours);
 
Index: /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dxt.cpp
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dxt.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dxt.cpp	(revision 22758)
@@ -23,5 +23,5 @@
 	bool    debug                   = gate->debug;
 	int     nels_data               = gate->nels_data;
-	double *index_data              = gate->index_data;
+	int    *index_data              = gate->index_data;
 	double *x_data                  = gate->x_data;
 	double *y_data                  = gate->y_data;
@@ -50,14 +50,14 @@
 
 		/*if there is no point inside the domain, go to next iteration*/
-		if ( (x_data[(int)index_data[3*i+0]-1]<xmin) && (x_data[(int)index_data[3*i+1]-1]<xmin) && (x_data[(int)index_data[3*i+2]-1]<xmin)) continue;
-		if ( (x_data[(int)index_data[3*i+0]-1]>xmax) && (x_data[(int)index_data[3*i+1]-1]>xmax) && (x_data[(int)index_data[3*i+2]-1]>xmax)) continue;
-		if ( (y_data[(int)index_data[3*i+0]-1]<ymin) && (y_data[(int)index_data[3*i+1]-1]<ymin) && (y_data[(int)index_data[3*i+2]-1]<ymin)) continue;
-		if ( (y_data[(int)index_data[3*i+0]-1]>ymax) && (y_data[(int)index_data[3*i+1]-1]>ymax) && (y_data[(int)index_data[3*i+2]-1]>ymax)) continue;
+		if ( (x_data[index_data[3*i+0]-1]<xmin) && (x_data[index_data[3*i+1]-1]<xmin) && (x_data[index_data[3*i+2]-1]<xmin)) continue;
+		if ( (x_data[index_data[3*i+0]-1]>xmax) && (x_data[index_data[3*i+1]-1]>xmax) && (x_data[index_data[3*i+2]-1]>xmax)) continue;
+		if ( (y_data[index_data[3*i+0]-1]<ymin) && (y_data[index_data[3*i+1]-1]<ymin) && (y_data[index_data[3*i+2]-1]<ymin)) continue;
+		if ( (y_data[index_data[3*i+0]-1]>ymax) && (y_data[index_data[3*i+1]-1]>ymax) && (y_data[index_data[3*i+2]-1]>ymax)) continue;
 
 		/*get area of the current element (Jacobian = 2 * area)*/
 		//area =x2 * y3 - y2*x3 + x1 * y2 - y1 * x2 + x3 * y1 - y3 * x1;
-		area=x_data[(int)index_data[3*i+1]-1]*y_data[(int)index_data[3*i+2]-1]-y_data[(int)index_data[3*i+1]-1]*x_data[(int)index_data[3*i+2]-1]
-		  +  x_data[(int)index_data[3*i+0]-1]*y_data[(int)index_data[3*i+1]-1]-y_data[(int)index_data[3*i+0]-1]*x_data[(int)index_data[3*i+1]-1]
-		  +  x_data[(int)index_data[3*i+2]-1]*y_data[(int)index_data[3*i+0]-1]-y_data[(int)index_data[3*i+2]-1]*x_data[(int)index_data[3*i+0]-1];
+		area=x_data[index_data[3*i+1]-1]*y_data[index_data[3*i+2]-1]-y_data[index_data[3*i+1]-1]*x_data[index_data[3*i+2]-1]
+		  +  x_data[index_data[3*i+0]-1]*y_data[index_data[3*i+1]-1]-y_data[index_data[3*i+0]-1]*x_data[index_data[3*i+1]-1]
+		  +  x_data[index_data[3*i+2]-1]*y_data[index_data[3*i+0]-1]-y_data[index_data[3*i+2]-1]*x_data[index_data[3*i+0]-1];
 
 		/*loop over the prime nodes*/
@@ -67,9 +67,9 @@
 
 				/*Get first area coordinate = det(x-x3  x2-x3 ; y-y3   y2-y3)/area*/
-				area_1=((x_prime[j]-x_data[(int)index_data[3*i+2]-1])*(y_data[(int)index_data[3*i+1]-1]-y_data[(int)index_data[3*i+2]-1]) 
-						-  (y_prime[j]-y_data[(int)index_data[3*i+2]-1])*(x_data[(int)index_data[3*i+1]-1]-x_data[(int)index_data[3*i+2]-1]))/area;
+				area_1=((x_prime[j]-x_data[index_data[3*i+2]-1])*(y_data[index_data[3*i+1]-1]-y_data[index_data[3*i+2]-1]) 
+						-  (y_prime[j]-y_data[index_data[3*i+2]-1])*(x_data[index_data[3*i+1]-1]-x_data[index_data[3*i+2]-1]))/area;
 				/*Get second area coordinate =det(x1-x3  x-x3 ; y1-y3   y-y3)/area*/
-				area_2=((x_data[(int)index_data[3*i+0]-1]-x_data[(int)index_data[3*i+2]-1])*(y_prime[j]-y_data[(int)index_data[3*i+2]-1]) 
-						- (y_data[(int)index_data[3*i+0]-1]-y_data[(int)index_data[3*i+2]-1])*(x_prime[j]-x_data[(int)index_data[3*i+2]-1]))/area;
+				area_2=((x_data[index_data[3*i+0]-1]-x_data[index_data[3*i+2]-1])*(y_prime[j]-y_data[index_data[3*i+2]-1]) 
+						- (y_data[index_data[3*i+0]-1]-y_data[index_data[3*i+2]-1])*(x_prime[j]-x_data[index_data[3*i+2]-1]))/area;
 				/*Get third area coordinate = 1-area1-area2*/
 				area_3=1-area_1-area_2;
@@ -81,5 +81,5 @@
 					if (interpolation_type==1){
 						/*nodal interpolation*/
-						data_value=area_1*data[(int)index_data[3*i+0]-1]+area_2*data[(int)index_data[3*i+1]-1]+area_3*data[(int)index_data[3*i+2]-1];
+						data_value=area_1*data[index_data[3*i+0]-1]+area_2*data[index_data[3*i+1]-1]+area_3*data[index_data[3*i+2]-1];
 					}
 					else{
Index: /issm/trunk/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp	(revision 22758)
@@ -6,17 +6,9 @@
 #include "../../shared/shared.h"
 
-void InterpFromMeshToGridx(double** px_m,double** py_m,double** pgriddata,double* index_mesh, double* x_mesh, double* y_mesh, int nods,int nels, double* data_mesh, int data_length, double xmin,double ymax,double xposting,double yposting,int nlines,int ncols,double default_value) {
-
-	/*Output*/
-	double* griddata=NULL;
-	double* x_grid=NULL;
-	double* y_grid=NULL;
+void InterpFromMeshToGridx(double** pgriddata,int* index_mesh, double* x_mesh, double* y_mesh, int nods,int nels, double* data_mesh,int data_length,double* x_grid,double* y_grid,int nlines,int ncols,double default_value){
 
 	/*Intermediary*/
-	int    i,j,n;
 	int    i1,i2,j1,j2;
 	int    interpolation_type;
-	bool   debug;
-	int    xflip,yflip;
 	double area;
 	double area_1,area_2,area_3;
@@ -28,57 +20,40 @@
 
 	/*some checks*/
-	if (nels<1 || nods<3 || nlines<1 || ncols<1 || xposting==0 || yposting==0){
-		_error_("nothing to be done according to the mesh given in input");
-	}
+	if(nels<1 || nods<3 || nlines<2 || ncols<2) _error_("nothing to be done according to the mesh given in input");
 
 	/*figure out what kind of interpolation is needed*/
-	if (data_length==nods){
-		interpolation_type=1;
-	}
-	else if (data_length==nels){
-		interpolation_type=2;
-	}
-	else{
-		_error_("length of vector data not supported yet. It should be of length (number of nodes) or (number of elements)!");
-	}
+	if(data_length==nods)      interpolation_type=1;
+	else if(data_length==nels) interpolation_type=2;
+	else _error_("length of vector data not supported yet. It should be of length (number of nodes) or (number of elements)!");
 
-	/*First, allocate pointers: */
-	griddata=xNewZeroInit<double>(nlines*ncols);
-	x_grid=xNewZeroInit<double>(ncols);
-	y_grid=xNewZeroInit<double>(nlines);
+	/*First, prepare output*/
+	double* griddata=xNew<double>(nlines*ncols);
+	for(int i=0;i<nlines;i++) for(int j=0;j<ncols; j++) griddata[i*ncols+j]=default_value;
 
-	/*Set debug to 1 if there are lots of elements*/
-	debug=(bool)((double)ncols*nlines*nels >= 5*pow(10.,10.));
+	/*Set debug to "true" if there are lots of elements*/
+	bool debug=(bool)((double)ncols*nlines*nels >= 5.e10);
 
-	/*Initialize coordintes and griddata*/
-	for(i=0;i<nlines;i++){
-		for(j=0;j<ncols; j++){
-			griddata[i*ncols+j]=default_value;
-		}
-	}
 	/*figure out if x or y are flipped*/
-	if (xposting<0) xflip=1;
-	else xflip=0;
-	if (yposting<0) yflip=1;
-	else yflip=0;
+	bool xflip = false;
+	bool yflip = false;
+	if(x_grid[1]-x_grid[0]<0) xflip=true;
+	if(y_grid[1]-y_grid[0]<0) yflip=true;
 
-	/*Get extreme coordinates of the grid*/
-	if (xflip){
-		for(i=0;i<ncols; i++) x_grid[ncols-1-i] = xmin - xposting*i;
+	/*Get min/max coordinates of the grid*/
+	double xposting = x_grid[1]-x_grid[0];
+	double yposting = y_grid[1]-y_grid[0];
+	if(xflip){
 		x_grid_min=x_grid[ncols-1];
 		x_grid_max=x_grid[0];
 	}
 	else{
-		for(i=0;i<ncols; i++) x_grid[i]= xmin + xposting*i;
 		x_grid_min=x_grid[0];
 		x_grid_max=x_grid[ncols-1];
 	}
-	if (yflip){
-		for(i=0;i<nlines;i++) y_grid[i] = ymax + yposting*i;
+	if(yflip){
 		y_grid_min=y_grid[nlines-1];
 		y_grid_max=y_grid[0];
 	}
 	else{
-		for(i=0;i<nlines;i++) y_grid[nlines-1-i]= ymax - yposting*i;
 		y_grid_min=y_grid[0];
 		y_grid_max=y_grid[nlines-1];
@@ -86,25 +61,25 @@
 
 	/*Loop over the elements*/
-	for (n=0;n<nels;n++){
+	for(int n=0;n<nels;n++){
 
 		/*display current iteration*/
-		if (debug && fmod((double)n,(double)100)==0)
+		if(debug && n%10000==0)
 		 _printf_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(n)/double(nels)*100<<"%   ");
 
 		/*Get extrema coordinates of current elements*/
-		x_tria_min=x_mesh[(int)index_mesh[3*n+0]-1]; x_tria_max=x_tria_min;
-		y_tria_min=y_mesh[(int)index_mesh[3*n+0]-1]; y_tria_max=y_tria_min;
-		for (i=1;i<3;i++){
-			if(x_mesh[(int)index_mesh[3*n+i]-1]<x_tria_min) x_tria_min=x_mesh[(int)index_mesh[3*n+i]-1];
-			if(x_mesh[(int)index_mesh[3*n+i]-1]>x_tria_max) x_tria_max=x_mesh[(int)index_mesh[3*n+i]-1];
-			if(y_mesh[(int)index_mesh[3*n+i]-1]<y_tria_min) y_tria_min=y_mesh[(int)index_mesh[3*n+i]-1];
-			if(y_mesh[(int)index_mesh[3*n+i]-1]>y_tria_max) y_tria_max=y_mesh[(int)index_mesh[3*n+i]-1];
+		x_tria_min=x_mesh[index_mesh[3*n+0]-1]; x_tria_max=x_tria_min;
+		y_tria_min=y_mesh[index_mesh[3*n+0]-1]; y_tria_max=y_tria_min;
+		for(int i=1;i<3;i++){
+			if(x_mesh[index_mesh[3*n+i]-1]<x_tria_min) x_tria_min=x_mesh[index_mesh[3*n+i]-1];
+			if(x_mesh[index_mesh[3*n+i]-1]>x_tria_max) x_tria_max=x_mesh[index_mesh[3*n+i]-1];
+			if(y_mesh[index_mesh[3*n+i]-1]<y_tria_min) y_tria_min=y_mesh[index_mesh[3*n+i]-1];
+			if(y_mesh[index_mesh[3*n+i]-1]>y_tria_max) y_tria_max=y_mesh[index_mesh[3*n+i]-1];
 		}
 
 		/*if the current triangle is not in the grid, continue*/
-		if ( (x_tria_min>x_grid_max) || (x_tria_max<x_grid_min) || (y_tria_min>y_grid_max) || (y_tria_max<y_grid_min) ) continue;
+		if( (x_tria_min>x_grid_max) || (x_tria_max<x_grid_min) || (y_tria_min>y_grid_max) || (y_tria_max<y_grid_min) ) continue;
 
-		/*Get indices i and j that form a square around the currant triangle*/
-		if (yflip){
+		/*Get indices i and j that form a square around the current triangle*/
+		if(yflip){
 			i1=max(0,       (int)floor((y_tria_max-y_grid_max)/yposting)-1);
 			i2=min(nlines-1,(int)ceil((y_tria_min-y_grid_max)/yposting));
@@ -114,5 +89,5 @@
 			i2=min(nlines-1,(int)ceil((y_tria_max-y_grid_min)/yposting));
 		}
-		if (xflip){
+		if(xflip){
 			j1=max(0,      (int)floor((x_tria_max-x_grid_max)/xposting)-1);
 			j2=min(ncols-1,(int)ceil((x_tria_min-x_grid_max)/xposting));
@@ -125,15 +100,15 @@
 		/*get area of the current element (Jacobian = 2 * area)*/
 		//area =x2 * y3 - y2*x3 + x1 * y2 - y1 * x2 + x3 * y1 - y3 * x1;
-		area=x_mesh[(int)index_mesh[3*n+1]-1]*y_mesh[(int)index_mesh[3*n+2]-1]-y_mesh[(int)index_mesh[3*n+1]-1]*x_mesh[(int)index_mesh[3*n+2]-1]
-		  +  x_mesh[(int)index_mesh[3*n+0]-1]*y_mesh[(int)index_mesh[3*n+1]-1]-y_mesh[(int)index_mesh[3*n+0]-1]*x_mesh[(int)index_mesh[3*n+1]-1]
-		  +  x_mesh[(int)index_mesh[3*n+2]-1]*y_mesh[(int)index_mesh[3*n+0]-1]-y_mesh[(int)index_mesh[3*n+2]-1]*x_mesh[(int)index_mesh[3*n+0]-1];
+		area=x_mesh[index_mesh[3*n+1]-1]*y_mesh[index_mesh[3*n+2]-1]-y_mesh[index_mesh[3*n+1]-1]*x_mesh[index_mesh[3*n+2]-1]
+		  +  x_mesh[index_mesh[3*n+0]-1]*y_mesh[index_mesh[3*n+1]-1]-y_mesh[index_mesh[3*n+0]-1]*x_mesh[index_mesh[3*n+1]-1]
+		  +  x_mesh[index_mesh[3*n+2]-1]*y_mesh[index_mesh[3*n+0]-1]-y_mesh[index_mesh[3*n+2]-1]*x_mesh[index_mesh[3*n+0]-1];
 
 		/*Go through x_grid and y_grid and interpolate if necessary*/
-		for (i=i1;i<=i2;i++){
+		for(int i=i1;i<=i2;i++){
 
 			//exit if y not between y_tria_min and y_tria_max
 			if((y_grid[i]>y_tria_max) || (y_grid[i]<y_tria_min)) continue;
 
-			for(j=j1;j<=j2; j++){
+			for(int j=j1;j<=j2; j++){
 
 				//exit if x not between x_tria_min and x_tria_max
@@ -141,19 +116,19 @@
 
 				/*Get first area coordinate = det(x-x3  x2-x3 ; y-y3   y2-y3)/area*/
-				area_1=((x_grid[j]-x_mesh[(int)index_mesh[3*n+2]-1])*(y_mesh[(int)index_mesh[3*n+1]-1]-y_mesh[(int)index_mesh[3*n+2]-1]) 
-							-  (y_grid[i]-y_mesh[(int)index_mesh[3*n+2]-1])*(x_mesh[(int)index_mesh[3*n+1]-1]-x_mesh[(int)index_mesh[3*n+2]-1]))/area;
+				area_1=((x_grid[j]-x_mesh[index_mesh[3*n+2]-1])*(y_mesh[index_mesh[3*n+1]-1]-y_mesh[index_mesh[3*n+2]-1]) 
+							-  (y_grid[i]-y_mesh[index_mesh[3*n+2]-1])*(x_mesh[index_mesh[3*n+1]-1]-x_mesh[index_mesh[3*n+2]-1]))/area;
 				/*Get second area coordinate =det(x1-x3  x-x3 ; y1-y3   y-y3)/area*/
-				area_2=((x_mesh[(int)index_mesh[3*n+0]-1]-x_mesh[(int)index_mesh[3*n+2]-1])*(y_grid[i]-y_mesh[(int)index_mesh[3*n+2]-1]) 
-							- (y_mesh[(int)index_mesh[3*n+0]-1]-y_mesh[(int)index_mesh[3*n+2]-1])*(x_grid[j]-x_mesh[(int)index_mesh[3*n+2]-1]))/area;
+				area_2=((x_mesh[index_mesh[3*n+0]-1]-x_mesh[index_mesh[3*n+2]-1])*(y_grid[i]-y_mesh[index_mesh[3*n+2]-1]) 
+							- (y_mesh[index_mesh[3*n+0]-1]-y_mesh[index_mesh[3*n+2]-1])*(x_grid[j]-x_mesh[index_mesh[3*n+2]-1]))/area;
 				/*Get third area coordinate = 1-area1-area2*/
-				area_3=1-area_1-area_2;
+				area_3=1.-area_1-area_2;
 
 				/*is the current point in the current element?*/
-				if (area_1>-10e-12 && area_2>-10e-12 && area_3>-10e-12){
+				if(area_1>-1e-12 && area_2>-1e-12 && area_3>-1e-12){
 
 					/*Yes ! compute the value on the point*/
-					if (interpolation_type==1){
+					if(interpolation_type==1){
 						/*nodal interpolation*/
-						data_value=area_1*data_mesh[(int)index_mesh[3*n+0]-1]+area_2*data_mesh[(int)index_mesh[3*n+1]-1]+area_3*data_mesh[(int)index_mesh[3*n+2]-1];
+						data_value=area_1*data_mesh[index_mesh[3*n+0]-1]+area_2*data_mesh[index_mesh[3*n+1]-1]+area_3*data_mesh[index_mesh[3*n+2]-1];
 					}
 					else{
@@ -169,10 +144,7 @@
 		}
 	}
-	if (debug)
-	 _printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%  \n");
+	if(debug) _printf_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<fixed<<100.<<"%   \n");
 
 	/*Assign output pointers:*/
 	*pgriddata=griddata;
-	*px_m=x_grid;
-	*py_m=y_grid;
 }
Index: /issm/trunk/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.h
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.h	(revision 22757)
+++ /issm/trunk/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.h	(revision 22758)
@@ -8,5 +8,5 @@
 #include "../../toolkits/toolkits.h"
 
-void InterpFromMeshToGridx(double** px_m,double** py_m,double** pgriddata,double* index_mesh, double* x_mesh, double* y_mesh, int nods,int nels, double* data_mesh, int data_length, double xmin,double ymax,double xposting,double yposting,int nlines,int ncols,double default_value);
+void InterpFromMeshToGridx(double** pgriddata,int* index_mesh, double* x_mesh, double* y_mesh, int nods,int nels, double* data_mesh,int data_length,double* x_grid,double* y_grid,int nlines,int ncols,double default_value);
 
 #endif /* _INTERPFROMMESHTOGRIDX_H */
Index: /issm/trunk/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp	(revision 22758)
@@ -7,11 +7,15 @@
 #include "../../toolkits/toolkits.h"
 #include "../../classes/classes.h"
+
+#ifdef _HAVE_BAMG_
 #include "../../bamg/bamgobjects.h"
-
 using namespace bamg;
 using namespace std;
+#endif
 
 int InterpFromMeshToMesh2dx(double** pdata_interp,int* index_data,double* x_data,double* y_data,int nods_data,int nels_data,
 			double* data,int M_data,int N_data,double* x_interp,double* y_interp,int N_interp,Options* options){
+
+	#ifdef _HAVE_BAMG_
 
 	/*Output*/
@@ -24,10 +28,11 @@
 	R2     r;
 	I2     I;
-	int    i,j;
+	int    i,j,k;
 	int    it;
 	int    i0,i1,i2;
 	double areacoord[3];
 	double aa,bb;
-	Icoor2 dete[3];
+	long long dete[3];
+	BamgOpts* bamgopts=new BamgOpts();//if necessary debug bamg::Mesh, set bamgopts->verbose>5
 
 	/*Checks*/
@@ -49,5 +54,6 @@
 
 	/*read background mesh*/
-	Mesh* Th=new Mesh(index_data,x_data,y_data,nods_data,nels_data); 
+	bamgopts->verbose=0;
+	Mesh* Th=new Mesh(index_data,x_data,y_data,nods_data,nels_data,bamgopts); 
 
 	/*Get reference number (for subdomains)*/
@@ -64,4 +70,14 @@
 		if(y_data[i]<ymin) ymin=y_data[i];
 		if(y_data[i]>ymax) ymax=y_data[i];
+	}
+
+	/*Create Single vertex to element connectivity*/
+	int* connectivity = xNew<int>(nods_data);
+	for(i=0;i<nels_data;i++){
+		for(j=0;j<3;j++){
+			k = index_data[i*3+j]-1;
+			_assert_(k>=0 & k<nods_data);
+			connectivity[k]=i;
+		}
 	}
 
@@ -88,7 +104,7 @@
 
 			/*Area coordinates*/
-			areacoord[0]= (double) dete[0]/tb.det;
-			areacoord[1]= (double) dete[1]/tb.det;
-			areacoord[2]= (double) dete[2]/tb.det;
+			areacoord[0]= reCast<double>(dete[0])/reCast<double>(tb.det);
+			areacoord[1]= reCast<double>(dete[1])/reCast<double>(tb.det);
+			areacoord[2]= reCast<double>(dete[2])/reCast<double>(tb.det);
 			/*3 vertices of the triangle*/
 			i0=Th->GetId(tb[0]);
@@ -137,17 +153,16 @@
 			/*If we fall outside of the convex or outside of the mesh, return NaN*/
 			if(tb.det<0 || reft[it]<0){
-				for (j=0;j<N_data;j++){
-					data_interp[i*N_data+j]=NAN;
-				}
+				_assert_(i0>=0 & i0<nods_data);
+				it=connectivity[i0]; //or i1 or i2
+				_assert_(it>=0 && it<nels_data);
+				for(j=0;j<N_data;j++) data_interp[i*N_data+j]=data[N_data*it+j];
 			}
 			else{
+				/*Inside the mesh!*/
 				if(it<0 || it>=nels_data){
 					_error_("Triangle number " << it << " not in [0 " << nels_data
 								<< "], report bug to developers (interpolation point: " <<x_interp[i]<<" "<<y_interp[i]<<")");
 				}
-				for (j=0;j<N_data;j++){
-
-					data_interp[i*N_data+j]=data[N_data*it+j];
-				}
+				for (j=0;j<N_data;j++) data_interp[i*N_data+j]=data[N_data*it+j];
 			}
 		}
@@ -157,6 +172,12 @@
 	/*clean-up and return*/
 	delete Th;
+	delete bamgopts;
 	xDelete<long>(reft);
+	xDelete<int>(connectivity);
 	*pdata_interp=data_interp;
+
+	#else
+	_error_("Cannot interpolate without bamg support");
+	#endif
 	return 1;
 }
Index: /issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp	(revision 22758)
@@ -82,7 +82,6 @@
 			break;
 		case P1xP2Enum:
-			EdgesPartitioning(&my_edges,iomodel);
-			break;
 		case P1xP3Enum:
+		case P1xP4Enum:
 			EdgesPartitioning(&my_edges,iomodel);
 			break;
@@ -370,4 +369,31 @@
 				}
 				break;
+			case P1xP4Enum:
+				for(i=0;i<iomodel->numberofvertices;i++){
+					if((iomodel->my_vertices[i])){
+						if (!xIsNan<IssmDouble>(spcdata[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,dof,spcdata[i],analysis_type));
+							count++;
+						}
+					}
+				}
+				for(i=0;i<iomodel->numberofedges;i++){
+					if(iomodel->edges[i*3+2]==2){/*Vertical edges*/
+						if(my_edges[i]){
+							v1 = iomodel->edges[3*i+0]-1;
+							v2 = iomodel->edges[3*i+1]-1;
+							if(!xIsNan<IssmDouble>(spcdata[v1]) && !xIsNan<IssmDouble>(spcdata[v2])){
+								constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+iomodel->numberofvertices+3*i+1,
+												dof,1./2.*spcdata[v1]+1./2.*spcdata[v2],analysis_type));
+								constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+2,iomodel->nodecounter+iomodel->numberofvertices+3*i+2,
+												dof,1./2.*spcdata[v1]+1./2.*spcdata[v2],analysis_type));
+								constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+3,iomodel->nodecounter+iomodel->numberofvertices+3*i+3,
+												dof,1./2.*spcdata[v1]+1./2.*spcdata[v2],analysis_type));
+								count=count+3;
+							}
+						}
+					}
+				}
+				break;
 			case P2xP1Enum:
 				for(i=0;i<iomodel->numberofvertices;i++){
@@ -601,4 +627,7 @@
 		_error_("Size of spc field not supported");
 	}
+
+	/*Update counter now since we have added some constraints*/
+	iomodel->constraintcounter = constraints->NumberOfConstraints();
 
 	/*Free ressources:*/
@@ -745,4 +774,7 @@
 	}
 
+	/*Update counter now since we have added some constraints*/
+	iomodel->constraintcounter = constraints->NumberOfConstraints();
+
 	/*Free ressources:*/
 	xDelete<IssmDouble>(times);
Index: /issm/trunk/src/c/modules/Krigingx/Krigingx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Krigingx/Krigingx.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/Krigingx/Krigingx.cpp	(revision 22758)
@@ -71,4 +71,6 @@
 	}
 	else if(strcmp(output,"delaunay")==0){
+
+		#ifdef _HAVE_BAMG_
 		int nobs,nel;
 		double *x     = NULL;
@@ -89,4 +91,7 @@
 		xDelete<double>(data);
 		xDelete<int>(index);
+		#else
+		_error_("you did not compile ISSM with bamg");
+		#endif
 	}
 	else if(strcmp(output,"nearestneighbor")==0){
Index: /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp
===================================================================
--- /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp	(revision 22758)
@@ -149,5 +149,6 @@
 
 	double xel[2],yel[2];
-	double coord1,coord2;
+	double coord1 = 0.;
+	double coord2 = 0.;
 	double xfinal[2],yfinal[2];
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp	(revision 22758)
@@ -21,4 +21,5 @@
 	int         num_indices;
 	char* options=NULL;
+	char* toolkit=NULL;
 
 	IssmDouble* xp=NULL;
@@ -35,6 +36,6 @@
 
 		/*Solver pointers depend on what type of solver we are implementing: */
-		options=OptionsFromAnalysis(parameters,DefaultAnalysisEnum); //options database is not filled in yet, use default.
-		ToolkitOptions::Init(options);
+		options=OptionsFromAnalysis(&toolkit,parameters,DefaultAnalysisEnum);
+		ToolkitOptions::Init(toolkit,options);
 
 		switch(IssmSolverTypeFromToolkitOptions()){
@@ -74,5 +75,4 @@
 	if(isautodiff){
 		/*Copy some parameters from IoModel to parameters dataset: {{{*/
-		parameters->AddObject(iomodel->CopyConstantObject("md.autodiff.keep",AutodiffKeepEnum));
 		parameters->AddObject(iomodel->CopyConstantObject("md.autodiff.obufsize",AutodiffObufsizeEnum));
 		parameters->AddObject(iomodel->CopyConstantObject("md.autodiff.cbufsize",AutodiffCbufsizeEnum));
Index: /issm/trunk/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp	(revision 22758)
@@ -8,5 +8,5 @@
 #include "../ModelProcessorx.h"
 
-void CreateParametersControl(Parameters* parameters,IoModel* iomodel,int solution_type){/*{{{*/
+void CreateParametersControl(Parameters* parameters,IoModel* iomodel,int solution_type){
 
 	bool        control_analysis;
@@ -28,39 +28,88 @@
 	if(control_analysis){
 
-		/*How many controls and how many responses?*/
-		parameters->AddObject(iomodel->CopyConstantObject("md.inversion.num_control_parameters",InversionNumControlParametersEnum));
-		parameters->AddObject(iomodel->CopyConstantObject("md.inversion.num_cost_functions",InversionNumCostFunctionsEnum));
+		switch(inversiontype){
+			  {
+			case 0:/*Brent Search*/
+			case 1:/*TAO*/
+			case 2:/*M1QN3*/
+			case 3:/*Validation*/
+				/*How many controls and how many responses?*/
+				parameters->AddObject(iomodel->CopyConstantObject("md.inversion.num_control_parameters",InversionNumControlParametersEnum));
+				parameters->AddObject(iomodel->CopyConstantObject("md.inversion.num_cost_functions",InversionNumCostFunctionsEnum));
 
-		/*What solution type?*/
-		if(solution_type==SteadystateSolutionEnum){
-			parameters->AddObject(new BoolParam(ControlSteadyEnum,true));
+				/*recover controls and convert to Enums*/
+				iomodel->FindConstant(&controls,&num_controls,"md.inversion.control_parameters");
+				if(num_controls<1) _error_("no controls found");
+				int* control_enums=xNew<int>(num_controls);
+				for(int i=0;i<num_controls;i++){
+					control_enums[i]=StringToEnumx(controls[i]);
+					xDelete<char>(controls[i]);
+				}
+				xDelete<char*>(controls);
+				parameters->AddObject(new IntVecParam(InversionControlParametersEnum,control_enums,num_controls));
+
+				iomodel->FindConstant(&cm_responses,&num_costfunc,"md.inversion.cost_functions");
+				if(num_costfunc<1) _error_ ("no cost functions found");
+				int* costfunc_enums=xNew<int>(num_costfunc);
+				for(int i=0;i<num_costfunc;i++){
+					costfunc_enums[i]=StringToEnumx(cm_responses[i]);
+					xDelete<char>(cm_responses[i]);
+				}
+				xDelete<char*>(cm_responses);
+				parameters->AddObject(new IntVecParam(InversionCostFunctionsEnum,costfunc_enums,num_costfunc));
+
+				xDelete<int>(control_enums);
+				xDelete<int>(costfunc_enums);
+
+				break;
 		}
-		else{
-			parameters->AddObject(new BoolParam(ControlSteadyEnum,false));
+			case 4:/*AD M1QN3*/
+			{
+			/*Intermediaries*/
+			int            num_independent_objects,M;
+			char**         names                   = NULL;
+				
+				/*this is done somewhere else*/
+				parameters->AddObject(iomodel->CopyConstantObject("md.autodiff.num_independent_objects",InversionNumControlParametersEnum));
+			   parameters->AddObject(iomodel->CopyConstantObject("md.autodiff.num_dependent_objects",InversionNumCostFunctionsEnum));
+				
+				/*Step1: create controls (independents)*/
+				iomodel->FetchData(&num_independent_objects,"md.autodiff.num_independent_objects");
+				_assert_(num_independent_objects>0);
+				iomodel->FetchData(&names,&M,"md.autodiff.independent_object_names");
+				_assert_(M==num_independent_objects);
+				int* ind_enums=xNew<int>(num_independent_objects);
+				for(int i=0;i<num_independent_objects;i++){
+					ind_enums[i]=StringToEnumx(names[i]);
+					xDelete<char>(names[i]);
+				}
+
+				parameters->AddObject(new IntVecParam(InversionControlParametersEnum,ind_enums,num_independent_objects));
+				iomodel->FindConstant(&cm_responses,&num_costfunc,"md.autodiff.dependent_object_names");
+				      _assert_(num_costfunc>0);
+				if(num_costfunc<1) _error_ ("no cost functions found");
+				int* costfunc_enums=xNew<int>(num_costfunc);
+				for(int i=0;i<num_costfunc;i++){
+					costfunc_enums[i]=StringToEnumx(cm_responses[i]);
+					xDelete<char>(cm_responses[i]);
+				}
+				xDelete<char*>(cm_responses);
+				parameters->AddObject(new IntVecParam(InversionCostFunctionsEnum,costfunc_enums,num_costfunc));
+				
+				iomodel->FetchData(&control_scaling_factors,NULL,NULL,"md.autodiff.independent_scaling_factors");
+				parameters->AddObject(new DoubleVecParam(InversionControlScalingFactorsEnum,control_scaling_factors,num_independent_objects));
+	
+				/*cleanup*/
+				for(int i=0;i<num_independent_objects;i++){
+					xDelete<char>(names[i]);
+				}
+				xDelete<char*>(names);
+				xDelete<int>(ind_enums);	
+				xDelete<int>(costfunc_enums);
+				break;
+			}
+			default:
+				_error_("not supported");
 		}
-
-		/*recover controls and convert to Enums*/
-		iomodel->FindConstant(&controls,&num_controls,"md.inversion.control_parameters");
-		if(num_controls<1) _error_("no controls found");
-		int* control_enums=xNew<int>(num_controls);
-		for(int i=0;i<num_controls;i++){
-			control_enums[i]=StringToEnumx(controls[i]);
-			xDelete<char>(controls[i]);
-		}
-		xDelete<char*>(controls);
-		parameters->AddObject(new IntVecParam(InversionControlParametersEnum,control_enums,num_controls));
-
-		iomodel->FindConstant(&cm_responses,&num_costfunc,"md.inversion.cost_functions");
-		if(num_costfunc<1) _error_ ("no cost functions found");
-		int* costfunc_enums=xNew<int>(num_costfunc);
-		for(int i=0;i<num_costfunc;i++){
-			costfunc_enums[i]=StringToEnumx(cm_responses[i]);
-			xDelete<char>(cm_responses[i]);
-		}
-		xDelete<char*>(cm_responses);
-		parameters->AddObject(new IntVecParam(InversionCostFunctionsEnum,costfunc_enums,num_costfunc));
-		
-		xDelete<int>(control_enums);
-		xDelete<int>(costfunc_enums);
 
 		/*Inversion type specifics*/
@@ -69,5 +118,4 @@
 				parameters->AddObject(iomodel->CopyConstantObject("md.inversion.incomplete_adjoint",InversionIncompleteAdjointEnum));
 				parameters->AddObject(iomodel->CopyConstantObject("md.inversion.nsteps",InversionNstepsEnum));
-				parameters->AddObject(iomodel->CopyConstantObject("md.inversion.cost_function_threshold",InversionCostFunctionThresholdEnum));
 				iomodel->FetchData(&cm_jump,&nsteps,NULL,"md.inversion.step_threshold");
 				iomodel->FetchData(&optscal,NULL,NULL,"md.inversion.gradient_scaling");
@@ -79,6 +127,4 @@
 			case 1:/*TAO*/
 				parameters->AddObject(iomodel->CopyConstantObject("md.inversion.incomplete_adjoint",InversionIncompleteAdjointEnum));
-				parameters->AddObject(iomodel->CopyConstantObject("md.inversion.fatol",InversionFatolEnum));
-				parameters->AddObject(iomodel->CopyConstantObject("md.inversion.frtol",InversionFrtolEnum));
 				parameters->AddObject(iomodel->CopyConstantObject("md.inversion.gatol",InversionGatolEnum));
 				parameters->AddObject(iomodel->CopyConstantObject("md.inversion.grtol",InversionGrtolEnum));
@@ -102,17 +148,14 @@
 				parameters->AddObject(new DoubleVecParam(InversionControlScalingFactorsEnum,control_scaling_factors,num_controls));
 				break;
-			case 4:/*M1QN3 AD*/
+			case 4:/*AD M1QN3*/
 				parameters->AddObject(iomodel->CopyConstantObject("md.inversion.dxmin",InversionDxminEnum));
 				parameters->AddObject(iomodel->CopyConstantObject("md.inversion.gttol",InversionGttolEnum));
 				parameters->AddObject(iomodel->CopyConstantObject("md.inversion.maxsteps",InversionMaxstepsEnum));
 				parameters->AddObject(iomodel->CopyConstantObject("md.inversion.maxiter",InversionMaxiterEnum));
-				iomodel->FetchData(&control_scaling_factors,NULL,NULL,"md.inversion.control_scaling_factors");
-				parameters->AddObject(new DoubleVecParam(InversionControlScalingFactorsEnum,control_scaling_factors,num_controls));
-				break;
+			break;
 			default:
 				_error_("not supported");
 		}
 
-		xDelete<int>(control_enums);
 		xDelete<int>(maxiter);
 		xDelete<IssmDouble>(control_scaling_factors);
@@ -120,3 +163,3 @@
 		iomodel->DeleteData(optscal,"md.inversion.gradient_scaling");
 	}
-}/*}}}*/
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp	(revision 22758)
@@ -9,6 +9,7 @@
 #include "../ModelProcessorx.h"
 
-void	UpdateElementsAndMaterialsControl(Elements* elements,Materials* materials, IoModel* iomodel){
-
+
+#if !defined(_HAVE_ADOLC_)
+void	UpdateElementsAndMaterialsControl(Elements* elements,Parameters* parameters,Materials* materials, IoModel* iomodel){
 	/*Intermediary*/
 	bool       control_analysis;
@@ -21,4 +22,5 @@
 	char     **cost_functions   = NULL;
 
+
 	/*Fetch parameters: */
 	iomodel->FindConstant(&control_analysis,"md.inversion.iscontrol");
@@ -27,5 +29,5 @@
 	/*Now, return if no control*/
 	if(!control_analysis) return;
-
+	
 	/*Process controls and convert from string to enums*/
 	iomodel->FindConstant(&controls,&num_controls,"md.inversion.control_parameters");
@@ -62,4 +64,5 @@
 		}
 	}
+	parameters->AddObject(new IntParam(ControlInputSizeMEnum,iomodel->numberofvertices));
 
 	for(int i=0;i<num_controls;i++){
@@ -68,4 +71,5 @@
 			/*List of supported controls*/
 			case BalancethicknessThickeningRateEnum:      iomodel->FetchData(1,"md.balancethickness.thickening_rate"); break;
+			case BalancethicknessSpcthicknessEnum:        iomodel->FetchData(1,"md.balancethickness.spcthickness"); break;
 			case VxEnum:                                  iomodel->FetchData(1,"md.initialization.vx"); break;
 			case VyEnum:                                  iomodel->FetchData(1,"md.initialization.vy"); break;
@@ -99,4 +103,5 @@
 			/*List of supported controls*/
 			case BalancethicknessThickeningRateEnum:      iomodel->DeleteData(1,"md.balancethickness.thickening_rate"); break;
+			case BalancethicknessSpcthicknessEnum:        iomodel->DeleteData(1,"md.balancethickness.spcthickness"); break;
 			case VxEnum:                                  iomodel->DeleteData(1,"md.initialization.vx"); break;
 			case VyEnum:                                  iomodel->DeleteData(1,"md.initialization.vy"); break;
@@ -123,2 +128,104 @@
 	xDelete<char*>(controls);
 }
+#else 
+void UpdateElementsAndMaterialsControl(Elements* elements,Parameters* parameters,Materials* materials, IoModel* iomodel){
+
+	/*Intermediaries*/
+	int				num_independent_objects,M,N,M_par,N_par;
+	char**			names                   = NULL;
+	int*				types							= NULL;
+	int*				control_sizes				= NULL;
+	int*				M_all							= NULL;
+	IssmDouble*		independent					= NULL;
+	IssmDouble*		independents_fullmin    = NULL;
+	IssmDouble*		independents_fullmax		= NULL;
+	bool				control_analysis			=false;
+
+	iomodel->FindConstant(&control_analysis,"md.inversion.iscontrol");
+
+	/*Now, return if no control*/
+	if(!control_analysis) return;
+
+	/*Step1: create controls (independents)*/
+	iomodel->FetchData(&num_independent_objects,"md.autodiff.num_independent_objects");
+	_assert_(num_independent_objects>0); 
+	iomodel->FetchData(&names,&M,"md.autodiff.independent_object_names");
+	_assert_(M==num_independent_objects);
+	iomodel->FetchData(&types,NULL,NULL,"md.autodiff.independent_object_types");
+
+		
+	M_all = xNew<int>(num_independent_objects);
+
+	/*create independent objects, and at the same time, fetch the corresponding independent variables, 
+	 *and declare them as such in ADOLC: */
+	iomodel->FetchData(&independents_fullmin,&M_par,&N_par,"md.autodiff.independent_min_parameters");
+	iomodel->FetchData(&independents_fullmax,&M_par,&N_par,"md.autodiff.independent_max_parameters");
+	iomodel->FetchData(&control_sizes,NULL,NULL,"md.autodiff.independent_control_sizes");
+	
+	int* start_point = NULL;
+	start_point = xNew<int>(num_independent_objects);
+	int counter = 0;
+	for(int i=0;i<num_independent_objects;i++){
+		start_point[i]=counter; 
+		counter+=control_sizes[i];
+	}
+
+	for(int i=0;i<num_independent_objects;i++){
+
+		if(types[i]==1){ /* vector:*/
+
+			/*Get field name and input Enum from independent name*/
+			char* iofieldname  = NULL;
+			int   input_enum;
+			IssmDouble*  	independents_min			= NULL;
+			IssmDouble*	   independents_max			= NULL;
+	
+			FieldAndEnumFromCode(&input_enum,&iofieldname,names[i]);
+
+			/*Fetch required data*/
+			iomodel->FetchData(&independent,&M,&N,iofieldname);
+			_assert_(independent);
+			_assert_(N==control_sizes[i]);
+		
+			independents_min = NULL; independents_min = xNew<IssmDouble>(M*N);
+			independents_max = NULL; independents_max = xNew<IssmDouble>(M*N);
+			for(int m=0;m<M;m++){
+				for(int n=0;n<N;n++){
+					independents_min[N*m+n]=independents_fullmin[N_par*m+start_point[i]+n];
+					independents_max[N*m+n]=independents_fullmax[N_par*m+start_point[i]+n];
+				}
+			}
+			if(N!=1) M_all[i]=M-1;
+			else M_all[i]=M;
+
+			for(int j=0;j<elements->Size();j++){
+				Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(j));
+				element->ControlInputCreate(independent,independents_min,independents_max,iomodel,M,N,input_enum,i+1);
+			}
+			xDelete<IssmDouble>(independent);
+			xDelete<IssmDouble>(independents_min);
+			xDelete<IssmDouble>(independents_max);
+	
+		}
+		else{
+			_error_("Independent cannot be of size " << types[i]);
+		}
+	}
+	parameters->AddObject(new IntVecParam(ControlInputSizeNEnum,control_sizes,num_independent_objects));
+	parameters->AddObject(new IntVecParam(ControlInputSizeMEnum,M_all,num_independent_objects));
+
+	/*cleanup*/
+	for(int i=0;i<num_independent_objects;i++){
+		xDelete<char>(names[i]);
+	}
+	xDelete<char*>(names);
+	xDelete<int>(types);
+	xDelete<int>(M_all);
+	xDelete<IssmDouble>(independents_fullmin);
+	xDelete<IssmDouble>(independents_fullmax);
+	xDelete<int>(start_point);
+	/*Step2: create cost functions (dependents)*/
+
+	return;
+}
+#endif
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp	(revision 22758)
@@ -8,5 +8,5 @@
 #include "./ModelProcessorx.h"
 
-void CreateElementsVerticesAndMaterials(Elements* elements,Vertices* vertices,Materials* materials,IoModel* iomodel,const int nummodels){
+void CreateElementsVerticesAndMaterials(Elements* elements,Vertices* vertices,Materials* materials,IoModel* iomodel,const int nummodels,int solution_type){
 
 	/*Intermediary*/
@@ -15,4 +15,7 @@
 	bool control_analysis;
 	bool dakota_analysis;
+	bool adolc_analysis;
+	int nnat,dummy;
+	int* nature=NULL;
 
 	/*Fetch parameters: */
@@ -20,19 +23,24 @@
 	iomodel->FindConstant(&dakota_analysis,"md.qmu.isdakota");
 	iomodel->FindConstant(&materials_type,"md.materials.type");
+	iomodel->FindConstant(&adolc_analysis,"md.autodiff.isautodiff");
 
 	/*Did we already create the elements? : */
 	_assert_(elements->Size()==0);
 
+	/*Setup matpar counter in iomodel before we call on element constructors: */
+	iomodel->matparcounter=iomodel->numberofelements+1;
+
 	/*Create elements*/
-	if(control_analysis)iomodel->FetchData(2,"md.inversion.min_parameters","md.inversion.max_parameters");
+	if(control_analysis && !adolc_analysis)iomodel->FetchData(2,"md.inversion.min_parameters","md.inversion.max_parameters");
+	
 	switch(iomodel->meshelementtype){
 		case TriaEnum:
 			for(i=0;i<iomodel->numberofelements;i++){
-				if(iomodel->my_elements[i]) elements->AddObject(new Tria(i+1,i,i,iomodel,nummodels));
+				if(iomodel->my_elements[i]) elements->AddObject(new Tria(i+1,i,iomodel,nummodels));
 			}
 			break;
 		case TetraEnum:
 			for(i=0;i<iomodel->numberofelements;i++){
-				if(iomodel->my_elements[i]) elements->AddObject(new Tetra(i+1,i,i,iomodel,nummodels));
+				if(iomodel->my_elements[i]) elements->AddObject(new Tetra(i+1,i,iomodel,nummodels));
 			}
 			break;
@@ -40,5 +48,5 @@
 			iomodel->FetchData(2,"md.mesh.upperelements","md.mesh.lowerelements");
 			for(i=0;i<iomodel->numberofelements;i++){
-				if(iomodel->my_elements[i]) elements->AddObject(new Penta(i+1,i,i,iomodel,nummodels));
+				if(iomodel->my_elements[i]) elements->AddObject(new Penta(i+1,i,iomodel,nummodels));
 			}
 			break;
@@ -112,4 +120,100 @@
 			}
 			break;
+		case MaterialsEnum: 
+	
+			//we have several types of materials. Retrieve this info first: 
+			iomodel->FetchData(&nature,&nnat,&dummy,"md.materials.nature");
+
+			//make sure materials that are not tied to elements come last:  for now, only Matlitho qualifies.
+			for(int i=0;i<nnat;i++){ 
+				if (IoCodeToEnumMaterials(nature[i])==MatlithoEnum){
+					int temp=nature[nnat-1];
+					nature[nnat-1]=nature[i];
+					nature[i]=temp;
+				}
+			}
+
+			//go through list of materials, and create them: 
+			for(int i=0;i<nnat;i++){ 
+				switch(IoCodeToEnumMaterials(nature[i])){ //{{{
+					case MaticeEnum:
+						iomodel->FetchDataToInput(elements,"md.materials.rheology_B",MaterialsRheologyBEnum);
+						iomodel->FetchDataToInput(elements,"md.materials.rheology_n",MaterialsRheologyNEnum);
+						for (i=0;i<iomodel->numberofelements;i++) if(iomodel->my_elements[i]) materials->AddObject(new Matice(i+1,i,iomodel));
+						switch(iomodel->domaindim){
+							case 2:
+								elements->InputDuplicate(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum);
+								break;
+							case 3:
+								break;
+							default:
+								_error_("Mesh not supported yet");
+						}
+						break;
+					case MatlithoEnum:
+						iomodel->FetchData(9,"md.materials.radius","md.materials.viscosity","md.materials.lame_lambda","md.materials.lame_mu","md.materials.burgers_viscosity","md.materials.burgers_mu","md.materials.isburgers","md.materials.issolid","md.materials.density");
+						materials->AddObject(new Matlitho(materials->Size()+1,iomodel));
+						iomodel->DeleteData(9,"md.materials.radius","md.materials.viscosity","md.materials.lame_lambda","md.materials.lame_mu","md.materials.burgers_viscosity","md.materials.burgers_mu","md.materials.isburgers","md.materials.issolid","md.materials.density");
+						break;
+
+					case MatenhancediceEnum:
+						iomodel->FetchDataToInput(elements,"md.materials.rheology_B",MaterialsRheologyBEnum);
+						iomodel->FetchDataToInput(elements,"md.materials.rheology_n",MaterialsRheologyNEnum);
+						iomodel->FetchDataToInput(elements,"md.materials.rheology_E",MaterialsRheologyEEnum);
+						for (i=0;i<iomodel->numberofelements;i++) if(iomodel->my_elements[i]) materials->AddObject(new Matice(i+1,i,iomodel));
+						switch(iomodel->domaindim){
+							case 2:
+								elements->InputDuplicate(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum);
+								elements->InputDuplicate(MaterialsRheologyEEnum,MaterialsRheologyEbarEnum);
+								break;
+							case 3:
+								break;
+							default:
+								_error_("Mesh not supported yet");
+						}
+						break;
+					case MatdamageiceEnum:
+						iomodel->FetchDataToInput(elements,"md.materials.rheology_B",MaterialsRheologyBEnum);
+						iomodel->FetchDataToInput(elements,"md.materials.rheology_n",MaterialsRheologyNEnum);
+						iomodel->FetchDataToInput(elements,"md.damage.D",DamageDEnum);
+						for (i=0;i<iomodel->numberofelements;i++) if(iomodel->my_elements[i]) materials->AddObject(new Matice(i+1,i,iomodel));
+						switch(iomodel->domaindim){
+							case 2:
+								elements->InputDuplicate(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum);
+								elements->InputDuplicate(DamageDEnum,DamageDbarEnum);
+								break;
+							case 3:
+								break;
+							default:
+								_error_("Mesh not supported yet");
+						}
+						break;
+					case MatestarEnum:
+						iomodel->FetchDataToInput(elements,"md.materials.rheology_B",MaterialsRheologyBEnum);
+						iomodel->FetchDataToInput(elements,"md.materials.rheology_Ec",MaterialsRheologyEcEnum);
+						iomodel->FetchDataToInput(elements,"md.materials.rheology_Es",MaterialsRheologyEsEnum);
+						for(i=0;i<iomodel->numberofelements;i++) if(iomodel->my_elements[i]) materials->AddObject(new Matestar(i+1,i,iomodel));
+						switch(iomodel->domaindim){
+							case 2:
+								elements->InputDuplicate(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum);
+								elements->InputDuplicate(MaterialsRheologyEcEnum,MaterialsRheologyEcbarEnum);
+								elements->InputDuplicate(MaterialsRheologyEsEnum,MaterialsRheologyEsbarEnum);
+								break;
+							case 3:
+								break;
+							default:
+								_error_("Mesh not supported yet");
+						}
+						break;
+
+					default:
+						_error_("Materials "<<EnumToStringx(IoCodeToEnumMaterials(nature[i]))<<" not supported");
+
+				} //}}}
+			}
+			//Free ressources:
+			xDelete<int>(nature);
+			break;
+
 		default:
 			_error_("Materials "<<EnumToStringx(materials_type)<<" not supported");
@@ -117,9 +221,8 @@
 
 	/*Free data: */
-	iomodel->DeleteData(7,"md.mesh.upperelements","md.mesh.lowerelements","md.material.rheology_B",
-				"md.material.rheology_n","md.damage.D","md.inversion.min_parameters","md.inversion.max_parameters");
+	iomodel->DeleteData(7,"md.mesh.upperelements","md.mesh.lowerelements","md.material.rheology_B","md.material.rheology_n","md.damage.D","md.inversion.min_parameters","md.inversion.max_parameters");
 
 	/*Add new constant material property to materials, at the end: */
-	materials->AddObject(new Matpar(iomodel->numberofelements+1,iomodel));//put it at the end of the materials
+	materials->AddObject(new Matpar(iomodel));//put it at the end of the materials
 
 	/*Create vertices: */
@@ -128,6 +231,7 @@
 	iomodel->FetchData(6,"md.mesh.x","md.mesh.y","md.mesh.z","md.geometry.base","md.geometry.thickness","md.mask.ice_levelset");
 	if (iomodel->domaintype == Domain3DsurfaceEnum) iomodel->FetchData(3,"md.mesh.lat","md.mesh.long","md.mesh.r");
+	else iomodel->FetchDataToInput(elements,"md.mesh.scale_factor",MeshScaleFactorEnum,1.);
 	
-	CreateNumberNodeToElementConnectivity(iomodel);
+	CreateNumberNodeToElementConnectivity(iomodel,solution_type);
 
 	for(i=0;i<iomodel->numberofvertices;i++){
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateNodes.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateNodes.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateNodes.cpp	(revision 22758)
@@ -107,4 +107,26 @@
 					}
 					counter=counter+2;
+				}
+			}
+			break;
+		case P1xP4Enum:
+			EdgesPartitioning(&my_edges,iomodel);
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(id0+i+1,i,lid++,i,iomodel,analysis,approximation));
+				}
+			}
+			counter = iomodel->numberofvertices;
+			for(i=0;i<iomodel->numberofedges;i++){
+				if(iomodel->edges[i*3+2]==2){/*Vertical edges*/
+					if(my_edges[i]){
+						node = new Node(id0+iomodel->numberofvertices+3*i+1,counter+1,lid++,0,iomodel,analysis,approximation);
+						nodes->AddObject(node);
+						node = new Node(id0+iomodel->numberofvertices+3*i+2,counter+2,lid++,0,iomodel,analysis,approximation);
+						nodes->AddObject(node);
+						node = new Node(id0+iomodel->numberofvertices+3*i+3,counter+3,lid++,0,iomodel,analysis,approximation);
+						nodes->AddObject(node);
+					}
+					counter=counter+3;
 				}
 			}
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp	(revision 22758)
@@ -14,5 +14,5 @@
 #include "./ModelProcessorx.h"
 
-void CreateNumberNodeToElementConnectivity(IoModel* iomodel){
+void CreateNumberNodeToElementConnectivity(IoModel* iomodel,int solution_type){
 
 	/*Intermediary*/
@@ -28,25 +28,32 @@
 
 	/*Some checks if debugging*/
-	_assert_(iomodel->numberofvertices);
-	_assert_(iomodel->numberofelements);
-	_assert_(iomodel->elements);
+	if (solution_type==LoveSolutionEnum){
+		/*do nothing, we don't have a mesh. Just initialize to NULL*/
+	}
+	else{
 
-	/*Allocate ouput*/
-	connectivity=xNewZeroInit<int>(iomodel->numberofvertices);
+		/*Some checks if debugging*/
+		_assert_(iomodel->numberofvertices);
+		_assert_(iomodel->numberofelements);
+		_assert_(iomodel->elements);
 
-	/*Get element width*/
-	switch(iomodel->meshelementtype){
-		case TriaEnum:  elementswidth=3; break;
-		case TetraEnum: elementswidth=4; break;
-		case PentaEnum: elementswidth=6; break;
-		default:                   _error_("mesh not supported yet");
-	}
+		/*Allocate ouput*/
+		connectivity=xNewZeroInit<int>(iomodel->numberofvertices);
 
-	/*Create connectivity table*/
-	for (i=0;i<iomodel->numberofelements;i++){
-		for (j=0;j<elementswidth;j++){
-			vertexid=iomodel->elements[elementswidth*i+j];
-			_assert_(vertexid>0 && vertexid-1<iomodel->numberofvertices);
-			connectivity[vertexid-1]+=1;
+		/*Get element width*/
+		switch(iomodel->meshelementtype){
+			case TriaEnum:  elementswidth=3; break;
+			case TetraEnum: elementswidth=4; break;
+			case PentaEnum: elementswidth=6; break;
+			default:                   _error_("mesh not supported yet");
+		}
+
+		/*Create connectivity table*/
+		for (i=0;i<iomodel->numberofelements;i++){
+			for (j=0;j<elementswidth;j++){
+				vertexid=iomodel->elements[elementswidth*i+j];
+				_assert_(vertexid>0 && vertexid-1<iomodel->numberofvertices);
+				connectivity[vertexid-1]+=1;
+			}
 		}
 	}
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateOutputDefinitions.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateOutputDefinitions.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateOutputDefinitions.cpp	(revision 22758)
@@ -46,5 +46,5 @@
 				iomodel->FetchMultipleData(&gatenames,&numgates,                     "md.massfluxatgate.name");
 				iomodel->FetchMultipleData(&gatedefinitionstrings,&temp,             "md.massfluxatgate.definitionstring"); _assert_(temp==numgates);
-				iomodel->FetchMultipleData(&gatesegments,&gatesegments_M,NULL,&temp, "md.massfluxatgate.segments");       _assert_(temp==numgates);
+				iomodel->FetchMultipleData(&gatesegments,&gatesegments_M,NULL,&temp, "md.massfluxatgate.segments");         _assert_(temp==numgates);
 
 				for(j=0;j<numgates;j++){
@@ -65,5 +65,5 @@
 			else if (output_definition_enums[i]==MisfitEnum){
 				/*Deal with misfits: {{{*/
-				
+			
 				/*misfit variables: */
 				int          nummisfits;
@@ -95,12 +95,33 @@
 				for(j=0;j<nummisfits;j++){
 
+					int obs_vector_type=0;
+					if ((misfit_observation_M_s[j]==iomodel->numberofvertices) || (misfit_observation_M_s[j]==iomodel->numberofvertices+1)){
+						obs_vector_type=1;
+					}
+					else if ((misfit_observation_M_s[j]==iomodel->numberofelements) || (misfit_observation_M_s[j]==iomodel->numberofelements+1)){
+						obs_vector_type=2;
+					}
+					else
+					 _error_("misfit observation size not supported yet");
+
+					int weight_vector_type=0;
+					if ((misfit_weights_M_s[j]==iomodel->numberofvertices) || (misfit_weights_M_s[j]==iomodel->numberofvertices+1)){
+						weight_vector_type=1;
+					}
+					else if ((misfit_weights_M_s[j]==iomodel->numberofelements) || (misfit_weights_M_s[j]==iomodel->numberofelements+1)){
+						weight_vector_type=2;
+					}
+					else
+					 _error_("misfit weight size not supported yet");
+
+
 					/*First create a misfit object for that specific string (misfit_model_string_s[j]):*/
-					output_definitions->AddObject(new Misfit(misfit_name_s[j],StringToEnumx(misfit_definitionstring_s[j]),StringToEnumx(misfit_model_string_s[j]),StringToEnumx(misfit_observation_string_s[j]),misfit_timeinterpolation_s[j],(bool)misfit_local_s[j],StringToEnumx(misfit_weights_string_s[j])));
+					output_definitions->AddObject(new Misfit(misfit_name_s[j],StringToEnumx(misfit_definitionstring_s[j]),StringToEnumx(misfit_model_string_s[j]),StringToEnumx(misfit_observation_string_s[j]),misfit_timeinterpolation_s[j],misfit_local_s[j],StringToEnumx(misfit_weights_string_s[j])));
 
 					/*Now, for this particular misfit object, make sure we plug into the elements: the observation, and the weights.*/
 					for(int k=0;k<elements->Size();k++){
 						Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(k));
-						element->InputCreate(misfit_observation_s[j], iomodel,misfit_observation_M_s[j],misfit_observation_N_s[j],1,StringToEnumx(misfit_observation_string_s[j]),7);
-						element->InputCreate(misfit_weights_s[j], iomodel,misfit_weights_M_s[j],misfit_weights_N_s[j],1,StringToEnumx(misfit_weights_string_s[j]),7);
+						element->InputCreate(misfit_observation_s[j], iomodel,misfit_observation_M_s[j],misfit_observation_N_s[j],obs_vector_type,StringToEnumx(misfit_observation_string_s[j]),7);
+						element->InputCreate(misfit_weights_s[j], iomodel,misfit_weights_M_s[j],misfit_weights_N_s[j],weight_vector_type,StringToEnumx(misfit_weights_string_s[j]),7);
 					}
 
@@ -136,4 +157,258 @@
 				/*}}}*/
 			}
+			else if (output_definition_enums[i]==CfsurfacesquareEnum){
+				/*Deal with cfsurfacesquare: {{{*/
+				
+				/*cfsurfacesquare variables: */
+				int          num_cfsurfacesquares;
+				char**       cfsurfacesquare_name_s						= NULL;    
+				char**		 cfsurfacesquare_definitionstring_s		= NULL;    
+				char**       cfsurfacesquare_model_string_s			= NULL;
+				IssmDouble** cfsurfacesquare_observation_s			= NULL;
+				char**		 cfsurfacesquare_observation_string_s	= NULL;
+				int*         cfsurfacesquare_observation_M_s			= NULL;
+				int*         cfsurfacesquare_observation_N_s			= NULL;
+				IssmDouble** cfsurfacesquare_weights_s					= NULL;
+				int*         cfsurfacesquare_weights_M_s				= NULL;
+				int*         cfsurfacesquare_weights_N_s				= NULL;
+				char**       cfsurfacesquare_weights_string_s		= NULL;
+				int*	 cfsurfacesquare_datatime_s				= NULL;
+
+				/*Fetch name, model_string, observation, observation_string, etc ... (see src/m/classes/cfsurfacesquare.m): */
+				iomodel->FetchMultipleData(&cfsurfacesquare_name_s,&num_cfsurfacesquares,                                                        "md.cfsurfacesquare.name");
+				iomodel->FetchMultipleData(&cfsurfacesquare_definitionstring_s,&num_cfsurfacesquares,                                            "md.cfsurfacesquare.definitionstring");
+				iomodel->FetchMultipleData(&cfsurfacesquare_model_string_s,&num_cfsurfacesquares,                                                "md.cfsurfacesquare.model_string");
+				iomodel->FetchMultipleData(&cfsurfacesquare_observation_s,&cfsurfacesquare_observation_M_s,&cfsurfacesquare_observation_N_s,&num_cfsurfacesquares, "md.cfsurfacesquare.observation");
+				iomodel->FetchMultipleData(&cfsurfacesquare_observation_string_s,&num_cfsurfacesquares,                                          "md.cfsurfacesquare.observation_string");
+				iomodel->FetchMultipleData(&cfsurfacesquare_weights_s,&cfsurfacesquare_weights_M_s,&cfsurfacesquare_weights_N_s,&num_cfsurfacesquares,             "md.cfsurfacesquare.weights");
+				iomodel->FetchMultipleData(&cfsurfacesquare_weights_string_s,&num_cfsurfacesquares,                                              "md.cfsurfacesquare.weights_string");
+				iomodel->FetchMultipleData(&cfsurfacesquare_datatime_s,&num_cfsurfacesquares,																	 "md.cfsurfacesquare.datatime");
+
+				for(j=0;j<num_cfsurfacesquares;j++){
+
+					int obs_vector_type=0;
+					if ((cfsurfacesquare_observation_M_s[j]==iomodel->numberofvertices) || (cfsurfacesquare_observation_M_s[j]==iomodel->numberofvertices+1)){
+						obs_vector_type=1;
+					}
+					else if ((cfsurfacesquare_observation_M_s[j]==iomodel->numberofelements) || (cfsurfacesquare_observation_M_s[j]==iomodel->numberofelements+1)){
+						obs_vector_type=2;
+					}
+					else
+					 _error_("cfsurfacesquare observation size not supported yet");
+
+					int weight_vector_type=0;
+					if ((cfsurfacesquare_weights_M_s[j]==iomodel->numberofvertices) || (cfsurfacesquare_weights_M_s[j]==iomodel->numberofvertices+1)){
+						weight_vector_type=1;
+					}
+					else if ((cfsurfacesquare_weights_M_s[j]==iomodel->numberofelements) || (cfsurfacesquare_weights_M_s[j]==iomodel->numberofelements+1)){
+						weight_vector_type=2;
+					}
+					else
+					 _error_("cfsurfacesquare weight size not supported yet");
+
+					/*First create a cfsurfacesquare object for that specific string (cfsurfacesquare_model_string_s[j]):*/
+					output_definitions->AddObject(new Cfsurfacesquare(cfsurfacesquare_name_s[j],StringToEnumx(cfsurfacesquare_definitionstring_s[j]),StringToEnumx(cfsurfacesquare_model_string_s[j]),StringToEnumx(cfsurfacesquare_observation_string_s[j]),StringToEnumx(cfsurfacesquare_weights_string_s[j]),cfsurfacesquare_datatime_s[j],false));
+
+					/*Now, for this particular cfsurfacesquare object, make sure we plug into the elements: the observation, and the weights.*/
+					for(int k=0;k<elements->Size();k++){
+
+						Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(k));
+						
+						element->DatasetInputAdd(StringToEnumx(cfsurfacesquare_definitionstring_s[j]),cfsurfacesquare_observation_s[j], iomodel,cfsurfacesquare_observation_M_s[j],cfsurfacesquare_observation_N_s[j],obs_vector_type,StringToEnumx(cfsurfacesquare_observation_string_s[j]),7,SurfaceObservationEnum);
+						element->DatasetInputAdd(StringToEnumx(cfsurfacesquare_definitionstring_s[j]),cfsurfacesquare_weights_s[j], iomodel,cfsurfacesquare_weights_M_s[j],cfsurfacesquare_weights_N_s[j],weight_vector_type,StringToEnumx(cfsurfacesquare_weights_string_s[j]),7,WeightsSurfaceObservationEnum);
+
+					}
+
+				}
+
+				/*Free ressources:*/
+				for(j=0;j<num_cfsurfacesquares;j++){
+					char* string=NULL;
+					IssmDouble* matrix = NULL;
+
+					string = cfsurfacesquare_definitionstring_s[j];		xDelete<char>(string);
+					string = cfsurfacesquare_observation_string_s[j];	xDelete<char>(string);
+					string = cfsurfacesquare_model_string_s[j];			xDelete<char>(string);
+					string = cfsurfacesquare_weights_string_s[j];		xDelete<char>(string);
+					string = cfsurfacesquare_name_s[j];    xDelete<char>(string);
+					matrix = cfsurfacesquare_observation_s[j]; xDelete<IssmDouble>(matrix);
+					matrix = cfsurfacesquare_weights_s[j]; xDelete<IssmDouble>(matrix);
+				}
+				xDelete<char*>(cfsurfacesquare_name_s);
+				xDelete<char*>(cfsurfacesquare_model_string_s);
+				xDelete<char*>(cfsurfacesquare_definitionstring_s);
+				xDelete<IssmDouble*>(cfsurfacesquare_observation_s);
+				xDelete<char*>(cfsurfacesquare_observation_string_s);
+				xDelete<int>(cfsurfacesquare_observation_M_s);
+				xDelete<int>(cfsurfacesquare_observation_N_s);
+				xDelete<IssmDouble*>(cfsurfacesquare_weights_s);
+				xDelete<int>(cfsurfacesquare_weights_M_s);
+				xDelete<int>(cfsurfacesquare_weights_N_s);
+				xDelete<char*>(cfsurfacesquare_weights_string_s);
+				xDelete<int>(cfsurfacesquare_datatime_s);
+				/*}}}*/
+			}
+			else if (output_definition_enums[i]==CfdragcoeffabsgradEnum){
+				/*Deal with cfdragcoeffabsgrad: {{{*/
+				
+				/*cfdragcoeffabsgrad variables: */
+				int          num_cfdragcoeffabsgrads;
+				char**       cfdragcoeffabsgrad_name_s						= NULL;    
+				char**		 cfdragcoeffabsgrad_definitionstring_s		= NULL;    
+				IssmDouble** cfdragcoeffabsgrad_weights_s					= NULL;
+				int*         cfdragcoeffabsgrad_weights_M_s				= NULL;
+				int*         cfdragcoeffabsgrad_weights_N_s				= NULL;
+				char**       cfdragcoeffabsgrad_weights_string_s		= NULL;
+				int*			 cfdragcoeffabsgrad_datatime_s				= NULL;
+
+				/*Fetch name, model_string, observation, observation_string, etc ... (see src/m/classes/cfdragcoeffabsgrad.m): */
+				iomodel->FetchMultipleData(&cfdragcoeffabsgrad_name_s,&num_cfdragcoeffabsgrads,                                                        "md.cfdragcoeffabsgrad.name");
+				iomodel->FetchMultipleData(&cfdragcoeffabsgrad_definitionstring_s,&num_cfdragcoeffabsgrads,                                            "md.cfdragcoeffabsgrad.definitionstring");
+				iomodel->FetchMultipleData(&cfdragcoeffabsgrad_weights_s,&cfdragcoeffabsgrad_weights_M_s,&cfdragcoeffabsgrad_weights_N_s,&num_cfdragcoeffabsgrads,             "md.cfdragcoeffabsgrad.weights");
+				iomodel->FetchMultipleData(&cfdragcoeffabsgrad_weights_string_s,&num_cfdragcoeffabsgrads,                                              "md.cfdragcoeffabsgrad.weights_string");
+				iomodel->FetchMultipleData(&cfdragcoeffabsgrad_datatime_s,&num_cfdragcoeffabsgrads,																	 "md.cfdragcoeffabsgrad.datatime");
+
+				for(j=0;j<num_cfdragcoeffabsgrads;j++){
+
+					int weight_vector_type=0;
+					if ((cfdragcoeffabsgrad_weights_M_s[j]==iomodel->numberofvertices) || (cfdragcoeffabsgrad_weights_M_s[j]==iomodel->numberofvertices+1)){
+						weight_vector_type=1;
+					}
+					else if ((cfdragcoeffabsgrad_weights_M_s[j]==iomodel->numberofelements) || (cfdragcoeffabsgrad_weights_M_s[j]==iomodel->numberofelements+1)){
+						weight_vector_type=2;
+					}
+					else
+					 _error_("cfdragcoeffabsgrad weight size not supported yet");
+
+					/*First create a cfdragcoeffabsgrad object for that specific string (cfdragcoeffabsgrad_model_string_s[j]):*/
+					output_definitions->AddObject(new Cfdragcoeffabsgrad(cfdragcoeffabsgrad_name_s[j],StringToEnumx(cfdragcoeffabsgrad_definitionstring_s[j]),StringToEnumx(cfdragcoeffabsgrad_weights_string_s[j]),cfdragcoeffabsgrad_datatime_s[j],false));
+
+					/*Now, for this particular cfdragcoeffabsgrad object, make sure we plug into the elements: the observation, and the weights.*/
+					for(int k=0;k<elements->Size();k++){
+
+						Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(k));
+						
+						element->DatasetInputAdd(StringToEnumx(cfdragcoeffabsgrad_definitionstring_s[j]),cfdragcoeffabsgrad_weights_s[j], iomodel,cfdragcoeffabsgrad_weights_M_s[j],cfdragcoeffabsgrad_weights_N_s[j],weight_vector_type,StringToEnumx(cfdragcoeffabsgrad_weights_string_s[j]),7,WeightsSurfaceObservationEnum);
+
+					}
+
+				}
+
+				/*Free ressources:*/
+				for(j=0;j<num_cfdragcoeffabsgrads;j++){
+					char* string=NULL;
+					IssmDouble* matrix = NULL;
+
+					string = cfdragcoeffabsgrad_definitionstring_s[j];		xDelete<char>(string);
+					string = cfdragcoeffabsgrad_weights_string_s[j];		xDelete<char>(string);
+					string = cfdragcoeffabsgrad_name_s[j];    xDelete<char>(string);
+					matrix = cfdragcoeffabsgrad_weights_s[j]; xDelete<IssmDouble>(matrix);
+				}
+				xDelete<char*>(cfdragcoeffabsgrad_name_s);
+				xDelete<char*>(cfdragcoeffabsgrad_definitionstring_s);
+				xDelete<IssmDouble*>(cfdragcoeffabsgrad_weights_s);
+				xDelete<int>(cfdragcoeffabsgrad_weights_M_s);
+				xDelete<int>(cfdragcoeffabsgrad_weights_N_s);
+				xDelete<char*>(cfdragcoeffabsgrad_weights_string_s);
+				xDelete<int>(cfdragcoeffabsgrad_datatime_s);
+				/*}}}*/
+			}
+			else if (output_definition_enums[i]==CfsurfacelogvelEnum){
+				/*Deal with cfsurfacelogvel: {{{*/
+				
+				/*cfsurfacelogvel variables: */
+				int          num_cfsurfacelogvels;
+				char**       cfsurfacelogvel_name						= NULL;    
+				char**		 cfsurfacelogvel_definitionstring		= NULL;    
+				IssmDouble** cfsurfacelogvel_vxobs			= NULL;
+				IssmDouble** cfsurfacelogvel_vyobs			= NULL;
+				char**		 cfsurfacelogvel_vxobs_string	= NULL;
+				char**		 cfsurfacelogvel_vyobs_string	= NULL;
+				int*         cfsurfacelogvel_observation_M			= NULL;
+				int*         cfsurfacelogvel_observation_N			= NULL;
+				IssmDouble** cfsurfacelogvel_weights					= NULL;
+				int*         cfsurfacelogvel_weights_M				= NULL;
+				int*         cfsurfacelogvel_weights_N				= NULL;
+				char**       cfsurfacelogvel_weightstring		= NULL;
+				int*				cfsurfacelogvel_datatime				= NULL;
+
+				/*Fetch name, modeltring, observation, observationtring, etc ... (see src/m/classes/cfsurfacelogvel.m): */
+				iomodel->FetchMultipleData(&cfsurfacelogvel_name,&num_cfsurfacelogvels,                                                        "md.cfsurfacelogvel.name");
+				iomodel->FetchMultipleData(&cfsurfacelogvel_definitionstring,&num_cfsurfacelogvels,                                            "md.cfsurfacelogvel.definitionstring");
+				iomodel->FetchMultipleData(&cfsurfacelogvel_vxobs,&cfsurfacelogvel_observation_M,&cfsurfacelogvel_observation_N,&num_cfsurfacelogvels, "md.cfsurfacelogvel.vxobs");
+				iomodel->FetchMultipleData(&cfsurfacelogvel_vxobs_string,&num_cfsurfacelogvels,                                          "md.cfsurfacelogvel.vxobs_string");
+				iomodel->FetchMultipleData(&cfsurfacelogvel_vyobs,&cfsurfacelogvel_observation_M,&cfsurfacelogvel_observation_N,&num_cfsurfacelogvels, "md.cfsurfacelogvel.vyobs");
+				iomodel->FetchMultipleData(&cfsurfacelogvel_vyobs_string,&num_cfsurfacelogvels,                                          "md.cfsurfacelogvel.vyobs_string");			iomodel->FetchMultipleData(&cfsurfacelogvel_weights,&cfsurfacelogvel_weights_M,&cfsurfacelogvel_weights_N,&num_cfsurfacelogvels,             "md.cfsurfacelogvel.weights");
+				iomodel->FetchMultipleData(&cfsurfacelogvel_weightstring,&num_cfsurfacelogvels,                                              "md.cfsurfacelogvel.weights_string");
+				_printf_("Num with weight string: "<<num_cfsurfacelogvels<<"\n");
+				iomodel->FetchMultipleData(&cfsurfacelogvel_datatime,&num_cfsurfacelogvels,																	 "md.cfsurfacelogvel.datatime");
+
+				for(j=0;j<num_cfsurfacelogvels;j++){
+
+					int obs_vector_type=0;
+					if ((cfsurfacelogvel_observation_M[j]==iomodel->numberofvertices) || (cfsurfacelogvel_observation_M[j]==iomodel->numberofvertices+1)){
+						obs_vector_type=1;
+					}
+					else if ((cfsurfacelogvel_observation_M[j]==iomodel->numberofelements) || (cfsurfacelogvel_observation_M[j]==iomodel->numberofelements+1)){
+						obs_vector_type=2;
+					}
+					else
+					 _error_("cfsurfacelogvel observation size not supported yet");
+
+					int weight_vector_type=0;
+					if ((cfsurfacelogvel_weights_M[j]==iomodel->numberofvertices) || (cfsurfacelogvel_weights_M[j]==iomodel->numberofvertices+1)){
+						weight_vector_type=1;
+					}
+					else if ((cfsurfacelogvel_weights_M[j]==iomodel->numberofelements) || (cfsurfacelogvel_weights_M[j]==iomodel->numberofelements+1)){
+						weight_vector_type=2;
+					}
+					else
+					 _error_("cfsurfacelogvel weight size not supported yet");
+
+					/*First create a cfsurfacelogvel object for that specific string (cfsurfacelogvel_modeltring[j]):*/
+					output_definitions->AddObject(new Cfsurfacelogvel(cfsurfacelogvel_name[j],StringToEnumx(cfsurfacelogvel_definitionstring[j]),cfsurfacelogvel_datatime[j],false));
+
+					/*Now, for this particular cfsurfacelogvel object, make sure we plug into the elements: the observation, and the weights.*/
+					for(int k=0;k<elements->Size();k++){
+
+						Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(k));
+						
+						element->DatasetInputAdd(StringToEnumx(cfsurfacelogvel_definitionstring[j]),cfsurfacelogvel_vxobs[j], iomodel,cfsurfacelogvel_observation_M[j],cfsurfacelogvel_observation_N[j],obs_vector_type,StringToEnumx(cfsurfacelogvel_vxobs_string[j]),7,VxObsEnum);
+							element->DatasetInputAdd(StringToEnumx(cfsurfacelogvel_definitionstring[j]),cfsurfacelogvel_vyobs[j], iomodel,cfsurfacelogvel_observation_M[j],cfsurfacelogvel_observation_N[j],obs_vector_type,StringToEnumx(cfsurfacelogvel_vyobs_string[j]),7,VyObsEnum);
+						element->DatasetInputAdd(StringToEnumx(cfsurfacelogvel_definitionstring[j]),cfsurfacelogvel_weights[j], iomodel,cfsurfacelogvel_weights_M[j],cfsurfacelogvel_weights_N[j],weight_vector_type,StringToEnumx(cfsurfacelogvel_weightstring[j]),7,WeightsSurfaceObservationEnum);
+
+					}
+
+				}
+
+				/*Free ressources:*/
+				for(j=0;j<num_cfsurfacelogvels;j++){
+					char* string=NULL;
+					IssmDouble* matrix = NULL;
+
+					string = cfsurfacelogvel_definitionstring[j];		xDelete<char>(string);
+					string = cfsurfacelogvel_vxobs_string[j];	xDelete<char>(string);
+					string = cfsurfacelogvel_vyobs_string[j];	xDelete<char>(string);
+					string = cfsurfacelogvel_weightstring[j];		xDelete<char>(string);
+					string = cfsurfacelogvel_name[j];    xDelete<char>(string);
+					matrix = cfsurfacelogvel_weights[j]; xDelete<IssmDouble>(matrix);
+					matrix = cfsurfacelogvel_vxobs[j]; xDelete<IssmDouble>(matrix);
+					matrix = cfsurfacelogvel_vyobs[j]; xDelete<IssmDouble>(matrix);
+				}
+				xDelete<char*>(cfsurfacelogvel_name);
+				xDelete<char*>(cfsurfacelogvel_definitionstring);
+				xDelete<int>(cfsurfacelogvel_observation_M);
+				xDelete<IssmDouble*>(cfsurfacelogvel_vxobs);
+				xDelete<IssmDouble*>(cfsurfacelogvel_vyobs);
+				xDelete<char*>(cfsurfacelogvel_vxobs_string);
+				xDelete<char*>(cfsurfacelogvel_vyobs_string);
+				xDelete<int>(cfsurfacelogvel_observation_N);
+				xDelete<IssmDouble*>(cfsurfacelogvel_weights);
+				xDelete<int>(cfsurfacelogvel_weights_M);
+				xDelete<int>(cfsurfacelogvel_weights_N);
+				xDelete<char*>(cfsurfacelogvel_weightstring);
+				xDelete<int>(cfsurfacelogvel_datatime);
+				/*}}}*/
+			}
 			else if (output_definition_enums[i]==NodalvalueEnum){
 				/*Deal with nodal values: {{{*/
@@ -161,5 +436,4 @@
 				for(j=0;j<numnodalvalues;j++){
 					char* string=NULL;
-					IssmDouble* matrix = NULL;
 					string = nodalvalue_name_s[j];    xDelete<char>(string);
 				}
@@ -175,18 +449,19 @@
 				/*masscon variables: */
 				int          nummasscons;
-				char**       masscon_name_s					= NULL;    
-				int*         masscon_definitionenum_s		= NULL;    
+				char**       masscon_name_s               = NULL;
+				char**       masscon_definitionstring_s   = NULL;
 				IssmDouble** masscon_levelset_s           = NULL;
-				int*         masscon_levelset_M_s			= NULL;
-				int*         masscon_levelset_N_s			= NULL;
+				int*         masscon_levelset_M_s         = NULL;
+				int*         masscon_levelset_N_s         = NULL;
 
 				/*Fetch name and levelset, etc ... (see src/m/classes/masscon.m): */
 				iomodel->FetchMultipleData(&masscon_name_s,&nummasscons,                                                "md.masscon.name");
-				iomodel->FetchMultipleData(&masscon_definitionenum_s,&nummasscons,                                      "md.masscon.definitionenum");
+				iomodel->FetchMultipleData(&masscon_definitionstring_s,&nummasscons,                                    "md.masscon.definitionstring");
 				iomodel->FetchMultipleData(&masscon_levelset_s,&masscon_levelset_M_s,&masscon_levelset_N_s,&nummasscons,"md.masscon.levelset");
+
 				for(j=0;j<nummasscons;j++){
 
 					/*Create a masscon object: */
-					output_definitions->AddObject(new Masscon(masscon_name_s[j],masscon_definitionenum_s[j],masscon_levelset_s[j],masscon_levelset_M_s[j]));
+					output_definitions->AddObject(new Masscon(masscon_name_s[j],StringToEnumx(masscon_definitionstring_s[j]),masscon_levelset_s[j],masscon_levelset_M_s[j]));
 
 				}
@@ -198,4 +473,5 @@
 
 					string = masscon_name_s[j];    xDelete<char>(string);
+					string = masscon_definitionstring_s[j];    xDelete<char>(string);
 					matrix = masscon_levelset_s[j]; xDelete<IssmDouble>(matrix);
 				}
@@ -204,5 +480,6 @@
 				xDelete<int>(masscon_levelset_M_s);
 				xDelete<int>(masscon_levelset_N_s);
-				xDelete<int>(masscon_definitionenum_s);
+				xDelete<char*>(masscon_definitionstring_s);
+
 				/*}}}*/
 			}
@@ -212,5 +489,5 @@
 				/*masscon variables: */
 				char**       masscon_name_s             = NULL;    
-				int*         masscon_definitionenum_s             = NULL;    
+				char**		 masscon_definitionstring_s		= NULL;    
 				char**       masscon_namex_s             = NULL;    
 				char**       masscon_namey_s             = NULL;    
@@ -221,5 +498,5 @@
 				/*Fetch names and multiplicators, etc ... (see src/m/classes/masscon_axpby.m): */
 				iomodel->FetchMultipleData(&masscon_name_s,&num,          "md.massconaxpby.name");
-				iomodel->FetchMultipleData(&masscon_definitionenum_s,&num,"md.massconaxpby.definitionenum");
+				iomodel->FetchMultipleData(&masscon_definitionstring_s,&num,"md.massconaxpby.definitionstring");
 				iomodel->FetchMultipleData(&masscon_namex_s,&num,         "md.massconaxpby.namex");
 				iomodel->FetchMultipleData(&masscon_namey_s,&num,         "md.massconaxpby.namey");
@@ -229,5 +506,5 @@
 
 					/*Create a masscon axpyb object: */
-					output_definitions->AddObject(new Massconaxpby(masscon_name_s[j],masscon_definitionenum_s[j],masscon_namex_s[j],masscon_namey_s[j],masscon_alpha_s[j],masscon_beta_s[j]));
+					output_definitions->AddObject(new Massconaxpby(masscon_name_s[j],StringToEnumx(masscon_definitionstring_s[j]),masscon_namex_s[j],masscon_namey_s[j],masscon_alpha_s[j],masscon_beta_s[j]));
 
 				}
@@ -236,17 +513,133 @@
 				for(j=0;j<num;j++){
 					char* string=NULL;
+					string = masscon_definitionstring_s[j];    xDelete<char>(string);
 					string = masscon_name_s[j];    xDelete<char>(string);
 					string = masscon_namex_s[j];    xDelete<char>(string);
 					string = masscon_namey_s[j];    xDelete<char>(string);
 				}
+				xDelete<char*>(masscon_definitionstring_s);
 				xDelete<char*>(masscon_name_s);
 				xDelete<char*>(masscon_namex_s);
 				xDelete<char*>(masscon_namey_s);
-				xDelete<int>(masscon_definitionenum_s);
 				xDelete<IssmDouble>(masscon_alpha_s);
 				xDelete<IssmDouble>(masscon_beta_s);
 				/*}}}*/
 			}
-			else _error_("output definition enum " << output_definition_enums[i] << " not supported yet!");
+			else if (output_definition_enums[i]==RegionaloutputEnum){
+				/*Deal with regional output: {{{*/
+
+				/*regional output variables: */
+				int          numout;
+				char**       reg_name_s               = NULL;
+				char**       reg_definitionstring_s   = NULL;
+				char**       reg_outputnamestring_s   = NULL;
+				IssmDouble** reg_mask_s               = NULL;
+				int*         reg_mask_M_s             = NULL;
+				int*         reg_mask_N_s             = NULL;
+
+				/*Fetch name and mask, etc ... (see src/m/classes/regionaloutput.m): */
+				iomodel->FetchMultipleData(&reg_name_s,&numout,                                                "md.regionaloutput.name");
+				iomodel->FetchMultipleData(&reg_definitionstring_s,&numout,                                    "md.regionaloutput.definitionstring");
+				iomodel->FetchMultipleData(&reg_outputnamestring_s,&numout,                                    "md.regionaloutput.outputnamestring");
+				iomodel->FetchMultipleData(&reg_mask_s,&reg_mask_M_s,&reg_mask_N_s,&numout,                    "md.regionaloutput.mask");
+				for(j=0;j<numout;j++){
+
+					/*Create a regional output object: */
+					output_definitions->AddObject(new Regionaloutput(reg_name_s[j],StringToEnumx(reg_definitionstring_s[j]),reg_outputnamestring_s[j],reg_mask_s[j],reg_mask_M_s[j]));
+
+				}
+
+				/*Free ressources:*/
+				for(j=0;j<numout;j++){
+					char* string=NULL;
+					IssmDouble* matrix = NULL;
+
+					string = reg_name_s[j];    xDelete<char>(string);
+					string = reg_definitionstring_s[j];    xDelete<char>(string);
+					string = reg_outputnamestring_s[j];    xDelete<char>(string);
+					matrix = reg_mask_s[j]; xDelete<IssmDouble>(matrix);
+				}
+				xDelete<char*>(reg_name_s);
+				xDelete<IssmDouble*>(reg_mask_s);
+				xDelete<int>(reg_mask_M_s);
+				xDelete<int>(reg_mask_N_s);
+				xDelete<char*>(reg_outputnamestring_s);
+				xDelete<char*>(reg_definitionstring_s);
+			/*}}}*/
+			}
+			else if (output_definition_enums[i]==NumberedcostfunctionEnum){
+				/*Deal with numbered cost function: {{{*/
+
+				/*Intermediary*/
+				int          numout,numout2;
+				char       **ncf_name_s             = NULL;
+				char       **ncf_definitionstring_s = NULL;
+				char       **cost_functions         = NULL;
+				IssmDouble **cost_functions_weights = NULL;
+				int*         cost_functions_weights_M = NULL;
+				int*         cost_functions_weights_N = NULL;
+				int          cost_function,domaintype;
+				int          num_cost_functions;
+
+				/*Process cost functions and convert from string to enums*/
+				iomodel->FindConstant(&num_cost_functions,"md.numberedcostfunction.num_cost_functions");
+				iomodel->FindConstant(&cost_functions,&num_cost_functions,"md.numberedcostfunction.cost_functions");
+				if(num_cost_functions<1) _error_("No cost functions found");
+				int* cost_function_enums=xNew<int>(num_cost_functions);
+				for(int i=0;i<num_cost_functions;++i){
+					cost_function_enums[i]=StringToEnumx(cost_functions[i]);
+				}
+
+				iomodel->FetchMultipleData(&ncf_name_s,&numout,"md.numberedcostfunction.name");
+				iomodel->FetchMultipleData(&ncf_definitionstring_s,&numout2,"md.numberedcostfunction.definitionstring"); _assert_(numout2 == numout); 
+				iomodel->FetchMultipleData(&cost_functions_weights,&cost_functions_weights_M,&cost_functions_weights_N,&numout2,"md.numberedcostfunction.cost_functions_coefficients");  _assert_(numout2 == numout);
+				if(numout!=1) _error_("not implemented yet, check code here");
+
+				/*Fetch Observations */
+				iomodel->FindConstant(&domaintype,"md.mesh.domain_type");
+				for(int i=0;i<num_cost_functions;i++){
+					cost_function=cost_function_enums[i];
+					if(     cost_function==ThicknessAbsMisfitEnum) iomodel->FetchDataToInput(elements,"md.numberedcostfunction.thickness_obs",InversionThicknessObsEnum);
+					else if(cost_function==SurfaceAbsMisfitEnum)   iomodel->FetchDataToInput(elements,"md.numberedcostfunction.surface_obs",InversionSurfaceObsEnum);
+					else if(cost_function==SurfaceAbsVelMisfitEnum
+							|| cost_function==SurfaceRelVelMisfitEnum
+							|| cost_function==SurfaceLogVelMisfitEnum
+							|| cost_function==SurfaceLogVxVyMisfitEnum
+							|| cost_function==SurfaceAverageVelMisfitEnum){
+						iomodel->FetchDataToInput(elements,"md.numberedcostfunction.vx_obs",InversionVxObsEnum);
+						if(domaintype!=Domain2DverticalEnum) iomodel->FetchDataToInput(elements,"md.numberedcostfunction.vy_obs",InversionVyObsEnum);
+					}
+				}
+
+				for(j=0;j<numout;j++){
+
+					/*Now, for this particular misfit object, make sure we plug into the elements: the observation, and the weights.*/
+					for(int k=0;k<elements->Size();k++){
+						Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(k));
+						element->DatasetInputCreate(cost_functions_weights[j],cost_functions_weights_M[j],cost_functions_weights_N[j],cost_function_enums,num_cost_functions,iomodel,InversionCostFunctionsCoefficientsEnum);
+					}
+					output_definitions->AddObject(new Numberedcostfunction(ncf_name_s[j],StringToEnumx(ncf_definitionstring_s[j]),num_cost_functions,cost_function_enums));
+				}
+				
+				/*Free data: */
+				iomodel->DeleteData(2,"md.numberedcostfunction.name","md.numberedcostfunction.definitionstring");
+				xDelete<int>(cost_function_enums);
+				for(int i=0;i<num_cost_functions;i++) xDelete<char>(cost_functions[i]);
+				xDelete<char*>(cost_functions);
+
+				/*Free ressources:*/
+				for(j=0;j<numout;j++){
+					xDelete<char>(ncf_name_s[j]);
+					xDelete<char>(ncf_definitionstring_s[j]);
+					xDelete<IssmDouble>(cost_functions_weights[j]);
+				}
+				xDelete<char*>(ncf_name_s);
+				xDelete<char*>(ncf_definitionstring_s);
+				xDelete<int>(cost_functions_weights_M);
+				xDelete<int>(cost_functions_weights_N);
+				xDelete<IssmDouble*>(cost_functions_weights);
+			}
+			/*}}}*/
+		else _error_("output definition enum " << EnumToStringx(output_definition_enums[i]) << " not supported yet!");
 		}
 	}
@@ -256,3 +649,4 @@
 	delete output_definitions;
 	xDelete<int>(output_definition_enums);
+
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateParameters.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateParameters.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateParameters.cpp	(revision 22758)
@@ -19,7 +19,13 @@
 
 	int         i,j,m,k;
-	int         numoutputs,materialtype,smb_model,basalforcing_model;
+	int         numoutputs,materialtype,smb_model,basalforcing_model,timestepping_type;
 	char**      requestedoutputs = NULL;
+	char*       fieldname = NULL;
 	IssmDouble  time;
+	
+	/*love numbers: */
+	IssmDouble* frequencies = NULL;
+	int         nfreq=0;
+	int         dummy;
 
 	/*parameters for mass flux:*/
@@ -28,4 +34,5 @@
 	bool         autodiff_mass_flux_present = false;
 	bool         mass_flux_present          = false;
+	bool         interp;
 	IssmDouble **array                      = NULL;
 	int         *mdims_array                = NULL;
@@ -37,4 +44,5 @@
 
 	IssmDouble *temp = NULL;
+	IssmDouble *transparam = NULL;
 	IssmDouble  yts;
 	int         N,M;
@@ -46,15 +54,7 @@
 	parameters->AddObject(iomodel->CopyConstantObject("md.settings.recording_frequency",SettingsRecordingFrequencyEnum));
 	parameters->AddObject(iomodel->CopyConstantObject("md.constants.yts",ConstantsYtsEnum));
-	parameters->AddObject(iomodel->CopyConstantObject("md.timestepping.start_time",TimesteppingStartTimeEnum));
-	parameters->AddObject(iomodel->CopyConstantObject("md.timestepping.final_time",TimesteppingFinalTimeEnum));
-	parameters->AddObject(iomodel->CopyConstantObject("md.timestepping.time_adapt",TimesteppingTimeAdaptEnum));
-	parameters->AddObject(iomodel->CopyConstantObject("md.timestepping.time_step",TimesteppingTimeStepEnum));
-	parameters->AddObject(iomodel->CopyConstantObject("md.timestepping.cfl_coefficient",TimesteppingCflCoefficientEnum));
-	parameters->AddObject(iomodel->CopyConstantObject("md.timestepping.interp_forcings",TimesteppingInterpForcingsEnum));
-	parameters->AddObject(iomodel->CopyConstantObject("md.settings.lowmem",SettingsLowmemEnum));
 	parameters->AddObject(iomodel->CopyConstantObject("md.debug.profiling",DebugProfilingEnum));
 	parameters->AddObject(iomodel->CopyConstantObject("md.mesh.average_vertex_connectivity",MeshAverageVertexConnectivityEnum));
 	parameters->AddObject(iomodel->CopyConstantObject("md.settings.waitonlock",SettingsWaitonlockEnum));
-	parameters->AddObject(iomodel->CopyConstantObject("md.mesh.numberofelements",MeshNumberofelementsEnum));
 	parameters->AddObject(iomodel->CopyConstantObject("md.mesh.numberofvertices",MeshNumberofverticesEnum));
 	parameters->AddObject(iomodel->CopyConstantObject("md.settings.results_on_nodes",SettingsResultsOnNodesEnum));
@@ -66,9 +66,29 @@
 	parameters->AddObject(iomodel->CopyConstantObject("md.inversion.type",InversionTypeEnum));
 	parameters->AddObject(iomodel->CopyConstantObject("md.calving.law",CalvingLawEnum));
-	{/*This is specific to ice...*/
+	
+	/*gia: */
+	parameters->AddObject(iomodel->CopyConstantObject("md.gia.cross_section_shape",GiaCrossSectionShapeEnum));
+	
+	/*love numbers: */
+	iomodel->FetchData(&nfreq,"md.love.nfreq");
+	parameters->AddObject(new IntParam(LoveNfreqEnum,nfreq));
+
+	iomodel->FetchData(&frequencies,&dummy,&dummy,"md.love.frequencies");
+	parameters->AddObject(new DoubleVecParam(LoveFrequenciesEnum,frequencies,nfreq));
+	xDelete<IssmDouble>(frequencies);
+	
+	parameters->AddObject(iomodel->CopyConstantObject("md.love.sh_nmax",LoveShNmaxEnum));
+	parameters->AddObject(iomodel->CopyConstantObject("md.love.sh_nmin",LoveShNminEnum));
+	parameters->AddObject(iomodel->CopyConstantObject("md.love.g0",LoveG0Enum));
+	parameters->AddObject(iomodel->CopyConstantObject("md.love.r0",LoveR0Enum));
+	parameters->AddObject(iomodel->CopyConstantObject("md.love.mu0",LoveMu0Enum));
+	parameters->AddObject(iomodel->CopyConstantObject("md.love.allow_layer_deletion",LoveAllowLayerDeletionEnum));
+	parameters->AddObject(iomodel->CopyConstantObject("md.love.love_kernels",LoveKernelsEnum));
+	parameters->AddObject(iomodel->CopyConstantObject("md.love.forcing_type",LoveForcingTypeEnum));
+
+	  {/*This is specific to ice...*/
 		parameters->AddObject(iomodel->CopyConstantObject("md.mesh.elementtype",MeshElementtypeEnum));
 		parameters->AddObject(iomodel->CopyConstantObject("md.steadystate.reltol",SteadystateReltolEnum));
 		parameters->AddObject(iomodel->CopyConstantObject("md.steadystate.maxiter",SteadystateMaxiterEnum));
-		parameters->AddObject(iomodel->CopyConstantObject("md.constants.referencetemperature",ConstantsReferencetemperatureEnum));
 		parameters->AddObject(iomodel->CopyConstantObject("md.groundingline.migration",GroundinglineMigrationEnum));
 		parameters->AddObject(iomodel->CopyConstantObject("md.transient.isstressbalance",TransientIsstressbalanceEnum));
@@ -84,11 +104,7 @@
 		parameters->AddObject(iomodel->CopyConstantObject("md.transient.isslr",TransientIsslrEnum));
 		parameters->AddObject(iomodel->CopyConstantObject("md.transient.iscoupler",TransientIscouplerEnum));
+		parameters->AddObject(iomodel->CopyConstantObject("md.transient.isoceancoupling",TransientIsoceancouplingEnum));
 		parameters->AddObject(iomodel->CopyConstantObject("md.transient.amr_frequency",TransientAmrFrequencyEnum));
-		parameters->AddObject(iomodel->CopyConstantObject("md.materials.rheology_law",MaterialsRheologyLawEnum));
 		parameters->AddObject(iomodel->CopyConstantObject("md.gia.cross_section_shape",GiaCrossSectionShapeEnum));
-		/*amr properties*/	
-		parameters->AddObject(iomodel->CopyConstantObject("md.amr.level_max",AmrLevelMaxEnum));
-		parameters->AddObject(iomodel->CopyConstantObject("md.amr.region_level_1",AmrRegionLevel1Enum));
-		parameters->AddObject(iomodel->CopyConstantObject("md.amr.region_level_max",AmrRegionLevelMaxEnum));
 
 		/*For stress balance only*/
@@ -101,7 +117,55 @@
 		if(iomodel->domaintype==Domain3DEnum)
 		 parameters->AddObject(iomodel->CopyConstantObject("md.mesh.numberoflayers",MeshNumberoflayersEnum));
-	}
-
-	
+	  }
+
+	/*amr properties*/	
+	int amrtype,amr_frequency;
+	iomodel->FindConstant(&amr_frequency,"md.transient.amr_frequency");
+	if(solution_type==TransientSolutionEnum && amr_frequency){
+		/*Load common amr parameters*/
+		parameters->AddObject(iomodel->CopyConstantObject("md.amr.type",AmrTypeEnum));
+		parameters->AddObject(iomodel->CopyConstantObject("md.amr.groundingline_distance",AmrGroundingLineDistanceEnum));
+		parameters->AddObject(iomodel->CopyConstantObject("md.amr.icefront_distance",AmrIceFrontDistanceEnum));
+		parameters->AddObject(iomodel->CopyConstantObject("md.amr.thicknesserror_threshold",AmrThicknessErrorThresholdEnum));
+		parameters->AddObject(iomodel->CopyConstantObject("md.amr.thicknesserror_groupthreshold",AmrThicknessErrorGroupThresholdEnum));
+		parameters->AddObject(iomodel->CopyConstantObject("md.amr.thicknesserror_maximum",AmrThicknessErrorMaximumEnum));
+		parameters->AddObject(iomodel->CopyConstantObject("md.amr.deviatoricerror_threshold",AmrDeviatoricErrorThresholdEnum));
+		parameters->AddObject(iomodel->CopyConstantObject("md.amr.deviatoricerror_groupthreshold",AmrDeviatoricErrorGroupThresholdEnum));
+		parameters->AddObject(iomodel->CopyConstantObject("md.amr.deviatoricerror_maximum",AmrDeviatoricErrorMaximumEnum));
+		parameters->AddObject(iomodel->CopyConstantObject("md.amr.restart",AmrRestartEnum));
+		/*Load specific amr parameters*/
+		iomodel->FindConstant(&amrtype,"md.amr.type");
+		switch(amrtype){
+			#ifdef _HAVE_NEOPZ_
+			case AmrNeopzEnum:
+				parameters->AddObject(iomodel->CopyConstantObject("md.amr.level_max",AmrLevelMaxEnum));
+				parameters->AddObject(iomodel->CopyConstantObject("md.amr.gradation",AmrGradationEnum));
+				parameters->AddObject(iomodel->CopyConstantObject("md.amr.lag",AmrLagEnum));
+				break;
+			#endif
+
+			#ifdef _HAVE_BAMG_
+			case AmrBamgEnum:
+				parameters->AddObject(iomodel->CopyConstantObject("md.amr.hmin",AmrHminEnum));
+				parameters->AddObject(iomodel->CopyConstantObject("md.amr.hmax",AmrHmaxEnum));
+				parameters->AddObject(iomodel->CopyConstantObject("md.amr.err",AmrErrEnum));
+				parameters->AddObject(iomodel->CopyConstantObject("md.amr.keepmetric",AmrKeepMetricEnum));
+				parameters->AddObject(iomodel->CopyConstantObject("md.amr.gradation",AmrGradationEnum));
+				parameters->AddObject(iomodel->CopyConstantObject("md.amr.groundingline_resolution",AmrGroundingLineResolutionEnum));
+				parameters->AddObject(iomodel->CopyConstantObject("md.amr.icefront_resolution",AmrIceFrontResolutionEnum));
+				parameters->AddObject(iomodel->CopyConstantObject("md.amr.thicknesserror_resolution",AmrThicknessErrorResolutionEnum));
+				parameters->AddObject(iomodel->CopyConstantObject("md.amr.deviatoricerror_resolution",AmrDeviatoricErrorResolutionEnum));
+				/*Convert fieldname to enum and put it in params*/
+				iomodel->FindConstant(&fieldname,"md.amr.fieldname");
+				parameters->AddObject(new IntParam(AmrFieldEnum,StringToEnumx(fieldname)));
+				xDelete<char>(fieldname);
+				break;
+			#endif
+
+			default:
+				_error_("Adaptive mesh refinement "<<EnumToStringx(amrtype)<<" not implemented yet");
+		}
+	}
+
 	/*Basal forcing parameters*/
 	parameters->AddObject(iomodel->CopyConstantObject("md.basalforcings.model",BasalforcingsEnum));
@@ -112,7 +176,35 @@
 			break;
 		case LinearFloatingMeltRateEnum:
-			parameters->AddObject(iomodel->CopyConstantObject("md.basalforcings.deepwater_melting_rate",BasalforcingsDeepwaterMeltingRateEnum));
-			parameters->AddObject(iomodel->CopyConstantObject("md.basalforcings.deepwater_elevation",BasalforcingsDeepwaterElevationEnum));
-			parameters->AddObject(iomodel->CopyConstantObject("md.basalforcings.upperwater_elevation",BasalforcingsUpperwaterElevationEnum));
+			iomodel->FindConstant(&interp,"md.timestepping.interp_forcings");
+			iomodel->FetchData(&transparam,&N,&M,"md.basalforcings.deepwater_melting_rate"); 
+			if(N==1){
+				_assert_(M==1);
+				parameters->AddObject(new DoubleParam(BasalforcingsDeepwaterMeltingRateEnum,transparam[0]));
+			}
+			else{
+				_assert_(N==2);
+				parameters->AddObject(new TransientParam(BasalforcingsDeepwaterMeltingRateEnum,&transparam[0],&transparam[M],interp,M));
+			}
+			xDelete<IssmDouble>(transparam);
+			iomodel->FetchData(&transparam,&N,&M,"md.basalforcings.deepwater_elevation"); 
+			if(N==1){
+				_assert_(M==1);
+				parameters->AddObject(new DoubleParam(BasalforcingsDeepwaterElevationEnum,transparam[0]));
+			}
+			else{
+				_assert_(N==2);
+				parameters->AddObject(new TransientParam(BasalforcingsDeepwaterElevationEnum,&transparam[0],&transparam[M],interp,M)); 
+			}
+			xDelete<IssmDouble>(transparam);
+			iomodel->FetchData(&transparam,&N,&M,"md.basalforcings.upperwater_elevation"); 
+			if(N==1){
+				_assert_(M==1);
+				parameters->AddObject(new DoubleParam(BasalforcingsUpperwaterElevationEnum,transparam[0]));
+			}
+			else{
+				_assert_(N==2);
+				parameters->AddObject(new TransientParam(BasalforcingsUpperwaterElevationEnum,&transparam[0],&transparam[M],interp,M));
+			}
+			xDelete<IssmDouble>(transparam);
 			break;
 		case MismipFloatingMeltRateEnum:
@@ -135,6 +227,21 @@
 			parameters->AddObject(iomodel->CopyConstantObject("md.basalforcings.lowercrustheat",BasalforcingsLowercrustheatEnum));
 			break;
+		case BasalforcingsPicoEnum:
+				iomodel->FindConstant(&interp,"md.timestepping.interp_forcings");
+				parameters->AddObject(iomodel->CopyConstantObject("md.basalforcings.num_basins",BasalforcingsPicoNumBasinsEnum));
+				parameters->AddObject(iomodel->CopyConstantObject("md.basalforcings.maxboxcount",BasalforcingsPicoMaxboxcountEnum));
+				parameters->AddObject(iomodel->CopyConstantObject("md.basalforcings.overturning_coeff",BasalforcingsPicoOverturningCoeffEnum));
+				parameters->AddObject(iomodel->CopyConstantObject("md.basalforcings.gamma_T",BasalforcingsPicoGammaTEnum));
+				iomodel->FetchData(&transparam,&M,&N,"md.basalforcings.farocean_temperature");
+				_assert_(M>=1 && N>=1); 
+				parameters->AddObject(new TransientArrayParam(BasalforcingsPicoFarOceantemperatureEnum,transparam,&transparam[N*(M-1)],interp,N,M));
+				xDelete<IssmDouble>(transparam);
+				iomodel->FetchData(&transparam,&M,&N,"md.basalforcings.farocean_salinity");
+				_assert_(M>=1 && N>=1); 
+				parameters->AddObject(new TransientArrayParam(BasalforcingsPicoFarOceansalinityEnum,transparam,&transparam[N*(M-1)],interp,N,M));
+				xDelete<IssmDouble>(transparam);
+			break;
 		default:
-			_error_("Basal forcing model "<<EnumToStringx(smb_model)<<" not supported yet");
+			_error_("Basal forcing model "<<EnumToStringx(basalforcing_model)<<" not supported yet");
 	}
 
@@ -142,4 +249,27 @@
 	parameters->AddObject(new IntParam(SolutionTypeEnum,solution_type));
 
+	/*Time stepping*/
+	parameters->AddObject(iomodel->CopyConstantObject("md.timestepping.type",TimesteppingTypeEnum));
+	iomodel->FindConstant(&timestepping_type,"md.timestepping.type");
+	switch(timestepping_type){
+		case FixedTimesteppingEnum:
+			parameters->AddObject(iomodel->CopyConstantObject("md.timestepping.start_time",TimesteppingStartTimeEnum));
+			parameters->AddObject(iomodel->CopyConstantObject("md.timestepping.final_time",TimesteppingFinalTimeEnum));
+			parameters->AddObject(iomodel->CopyConstantObject("md.timestepping.time_step",TimesteppingTimeStepEnum));
+			parameters->AddObject(iomodel->CopyConstantObject("md.timestepping.interp_forcings",TimesteppingInterpForcingsEnum));
+			parameters->AddObject(iomodel->CopyConstantObject("md.timestepping.coupling_time",TimesteppingCouplingTimeEnum));
+			break;
+		case AdaptiveTimesteppingEnum:
+			parameters->AddObject(iomodel->CopyConstantObject("md.timestepping.start_time",TimesteppingStartTimeEnum));
+			parameters->AddObject(iomodel->CopyConstantObject("md.timestepping.final_time",TimesteppingFinalTimeEnum));
+			parameters->AddObject(iomodel->CopyConstantObject("md.timestepping.time_step_min",TimesteppingTimeStepMinEnum));
+			parameters->AddObject(iomodel->CopyConstantObject("md.timestepping.time_step_max",TimesteppingTimeStepMaxEnum));
+			parameters->AddObject(iomodel->CopyConstantObject("md.timestepping.cfl_coefficient",TimesteppingCflCoefficientEnum));
+			parameters->AddObject(iomodel->CopyConstantObject("md.timestepping.interp_forcings",TimesteppingInterpForcingsEnum));
+			parameters->AddObject(iomodel->CopyConstantObject("md.timestepping.coupling_time",TimesteppingCouplingTimeEnum));
+			break;
+		default:
+			_error_("Time stepping \""<<EnumToStringx(timestepping_type)<<"\" not supported yet");
+	}
 	iomodel->FindConstant(&time,"md.timestepping.start_time");
 	parameters->AddObject(new DoubleParam(TimeEnum,time));  
@@ -240,6 +370,9 @@
 	ParseToolkitsOptionsx(parameters,toolkitsoptionsfid);
 
- 	#ifdef _HAVE_ADOLC_
+	#ifdef _HAVE_ADOLC_
+	if(VerboseMProcessor()) _printf0_("   starting autodiff parameters \n");
 	CreateParametersAutodiff(parameters,iomodel);
+	if(VerboseMProcessor()) _printf0_("   ending autodiff parameters \n");
+
 	#endif
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp	(revision 22758)
@@ -59,7 +59,4 @@
 		iomodel->FindConstant(&variabledescriptors,&numvariabledescriptors,"md.qmu.variabledescriptors");
 
-		/*Ok, we have all the variable descriptors. Build a parameter with it: */
-		parameters->AddObject(new StringArrayParam(QmuVariabledescriptorsEnum,variabledescriptors,numvariabledescriptors));
-
 		/*Fetch response descriptors*/
 		iomodel->FindConstant(&responsedescriptors,&numresponsedescriptors,"md.qmu.responsedescriptors");
@@ -67,5 +64,4 @@
 		/*Ok, we have all the response descriptors. Build a parameter with it: */
 		parameters->AddObject(new StringArrayParam(QmuResponsedescriptorsEnum,responsedescriptors,numresponsedescriptors));
-		parameters->AddObject(new    IntParam(QmuNumberofresponsesEnum,numberofresponses));
 
 		/*Deal with partitioning*/
@@ -83,4 +79,5 @@
 
 		/*Deal with data needed because of qmu variables*/
+		DataSet* dataset_variable_descriptors = new DataSet(QmuVariableDescriptorsEnum);
 		for(i=0;i<numvariabledescriptors;i++){
 			if (strncmp(variabledescriptors[i],"scaled_",7)==0){
@@ -96,8 +93,8 @@
 				iomodel->FetchData(&dakota_parameter,&nrows,&ncols,fieldname);
 				if(nrows==iomodel->numberofvertices){
-					parameters->AddObject(new DoubleMatParam(param_enum,dakota_parameter,nrows,ncols));
+					dataset_variable_descriptors->AddObject(new DoubleMatParam(param_enum,dakota_parameter,nrows,ncols));
 				}
 				else{
-					parameters->AddObject(new DoubleTransientMatParam(param_enum,dakota_parameter,nrows,ncols));
+					dataset_variable_descriptors->AddObject(new DoubleTransientMatParam(param_enum,dakota_parameter,nrows,ncols));
 				}
 				xDelete<double>(dakota_parameter);
@@ -105,4 +102,6 @@
 			}
 		}
+		parameters->AddObject(new DataSetParam(QmuVariableDescriptorsEnum,dataset_variable_descriptors));
+		delete dataset_variable_descriptors;
 
 		/*clean-up*/
Index: /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.cpp	(revision 22758)
@@ -36,5 +36,5 @@
 
 	/*Create elements, vertices and materials, independent of analysis_enum: */
-	CreateElementsVerticesAndMaterials(elements,vertices,materials,iomodel,nummodels);
+	CreateElementsVerticesAndMaterials(elements,vertices,materials,iomodel,nummodels,solution_enum);
 
 	/*Create Parameters*/
@@ -68,6 +68,8 @@
 
 	/*Solution specific updates*/
-	UpdateElementsAndMaterialsControl(elements,materials,iomodel);
+	if(VerboseMProcessor()) _printf0_("   updating elements and materials for control parameters" << "\n");
+	UpdateElementsAndMaterialsControl(elements,parameters,materials,iomodel);
 	#ifdef _HAVE_DAKOTA_
+	if(VerboseMProcessor()) _printf0_("   updating elements and materials for uncertainty quantification" << "\n");
 	UpdateElementsAndMaterialsDakota(elements,materials,iomodel);
 	#endif
@@ -77,4 +79,5 @@
 
 	/*Output definitions dataset: */
+	if(VerboseMProcessor()) _printf0_("   creating output definitions" << "\n");
 	CreateOutputDefinitions(elements,parameters,iomodel);
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.h
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.h	(revision 22757)
+++ /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.h	(revision 22758)
@@ -12,5 +12,5 @@
 
 /*Creation of fem datasets: general drivers*/
-void CreateElementsVerticesAndMaterials(Elements* elements,Vertices* vertices,Materials* materials, IoModel* iomodel,const int nummodels);
+void CreateElementsVerticesAndMaterials(Elements* elements,Vertices* vertices,Materials* materials, IoModel* iomodel,const int nummodels,int solution_type);
 void CreateParameters(Parameters*parameters,IoModel* iomodel,char* rootpath,FILE* toolkitfile,const int solution_type);
 void CreateParametersAutodiff(Parameters* parameters,IoModel* iomodel);
@@ -18,5 +18,5 @@
 void CreateParametersDakota(Parameters* parameters,IoModel* iomodel,char* rootpath);
 void CreateOutputDefinitions(Elements* elements, Parameters* parameters,IoModel* iomodel);
-void UpdateElementsAndMaterialsControl(Elements* elements,Materials* materials, IoModel* iomodel);
+void UpdateElementsAndMaterialsControl(Elements* elements,Parameters* parameters,Materials* materials, IoModel* iomodel);
 void UpdateElementsAndMaterialsDakota(Elements* elements,Materials* materials, IoModel* iomodel);
 void UpdateElementsTransient(Elements* elements,Parameters* parameters,IoModel* iomodel,int analysis_type);
@@ -37,4 +37,4 @@
 /*Connectivity*/
 void CreateSingleNodeToElementConnectivity(IoModel* iomodel);
-void CreateNumberNodeToElementConnectivity(IoModel* iomodel);
+void CreateNumberNodeToElementConnectivity(IoModel* iomodel,int solution_type);
 #endif
Index: /issm/trunk/src/c/modules/OutputDefinitionsResponsex/OutputDefinitionsResponsex.cpp
===================================================================
--- /issm/trunk/src/c/modules/OutputDefinitionsResponsex/OutputDefinitionsResponsex.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/OutputDefinitionsResponsex/OutputDefinitionsResponsex.cpp	(revision 22758)
@@ -60,5 +60,7 @@
 	
 	/*If we are here, did not find the definition for this response, not good!: */
-	_error_("Could not find the response for output definition " << output_enum << " because could not find the definition itself!");
+	_error_("Could not find the response for output definition " << EnumToStringx(output_enum) 
+				<<" ("<<output_enum<<")"
+				<< " because could not find the definition itself!");
 
 }
Index: /issm/trunk/src/c/modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.cpp	(revision 22758)
@@ -19,16 +19,20 @@
 void ParseToolkitsOptionsx(Parameters* parameters,FILE* fid){
 
-	char line [1000];
+	char line[1000];
+	char word1[1000];
+	char word2[1000];
 	int my_rank;
 	int i;
 
 	/*intermediary: */
-	IssmDouble* analyses=NULL;
-	char** strings=NULL;
-	int numanalyses;
-	char* string=NULL;
-	char* newstring=NULL;
-	char* catstring=NULL;
-	int   stringlength;
+	int         *analyses     = NULL;
+	char       **strings      = NULL;
+	char        *string       = NULL;
+	char       **toolkits     = NULL;
+	char        *toolkit      = NULL;
+	char        *newstring    = NULL;
+	char        *catstring    = NULL;
+	int          numanalyses;
+	int          stringlength,toolkitlength;
 
 	/*Get my_rank:*/
@@ -39,21 +43,27 @@
 		/*Now, go through lines and figure out how many analyses we have: */
 		numanalyses=0;
-		while ( fgets(line, sizeof line, fid) ){
+		while(fgets(line, sizeof line, fid)){
 			/*skip comments and empty lines: */
-			if ((line[0]=='%') || (line[0]=='\n') || (line[0]==' ') || (line[0]=='\t') || (line[0]=='\r'))continue;
+			if ((line[0]=='%') || (line[0]=='\n') || (line[0]==' ') || (line[0]=='\t') || (line[0]=='\r')) continue;
 			/*ok, first time, we should get an analysis enum, starting with a +: */
-			if (line[0]=='+')numanalyses++;
-			else continue;
+			if (line[0]=='+'){
+				numanalyses++;
+			}
+			else{
+				continue;
+			}
 		}
 
 		/*Now, allocate analyses and strings: */
-		analyses=xNew<IssmDouble>(numanalyses);
-		strings=xNew<char*>(numanalyses);
-		for(i=0;i<numanalyses;i++)strings[i]=NULL; 
+		analyses = xNew<int>(numanalyses);
+		strings  = xNew<char*>(numanalyses);
+		toolkits = xNew<char*>(numanalyses);
+		for(i=0;i<numanalyses;i++) strings[i]  = NULL; 
+		for(i=0;i<numanalyses;i++) toolkits[i] = NULL; 
 
 		/*Go back to beginning of file:*/
 		fseek(fid,0,SEEK_SET);
 		numanalyses=0;
-		while ( fgets(line, sizeof line, fid) ){
+		while( fgets(line, sizeof line, fid)){
 
 			/*skip comments and empty lines: */
@@ -63,10 +73,18 @@
 			line[strlen(line)-1]='\0';
 
-			if (line[0]=='+'){ /*this is the analysis line: */
+			if(line[0]=='+'){ /*this is the analysis line: */
 				analyses[numanalyses]=StringToEnumx(&line[1]);  //skip the '+'
 				numanalyses++;
+				/*Now get toolkit (should be following line)*/
+				if(!fgets(line, sizeof line, fid)) _error_("could not read toolkit for analysis " << &line[1]);
+				sscanf(line,"-%s %s",&word1[0],&word2[0]);
+				if(strcmp(word1,"toolkit")!=0) _error_("toolkit option does not follow analysis");
+				toolkit=xNew<char>((strlen(word2)+1)); 
+				xMemCpy<char>(toolkit,word2,(strlen(word2)+1));
+				toolkits[numanalyses-1]=toolkit;
+				continue;
 			}
-			else{ /*this is an option corresponding to analysis numanalyses-1. Add it 
-			to the already existing options*/
+			else{
+				/*this is an option corresponding to analysis numanalyses-1. Add it to the already existing options*/
 				if(strings[numanalyses-1]==NULL){
 					string=xNew<char>((strlen(line)+1)); 
@@ -97,9 +115,20 @@
 	ISSM_MPI_Bcast(&numanalyses,1,ISSM_MPI_INT,0,IssmComm::GetComm());
 	if(my_rank!=0){
-		analyses=xNew<IssmDouble>(numanalyses);
-		strings=xNew<char*>(numanalyses);
+		analyses  = xNew<int>(numanalyses);
+		toolkits  = xNew<char*>(numanalyses);
+		strings   = xNew<char*>(numanalyses);
 	}
-	ISSM_MPI_Bcast(analyses,numanalyses,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+	ISSM_MPI_Bcast(analyses,numanalyses,ISSM_MPI_INT,0,IssmComm::GetComm());
 	for(i=0;i<numanalyses;i++){
+		char* toolkit=toolkits[i];
+		if(my_rank==0){
+			if(toolkit==NULL) _error_("PETSc options for analysis " << EnumToStringx(reCast<int>(analyses[i])) << " have been declared but were not found");
+		}
+		if(my_rank==0)toolkitlength=(strlen(toolkit)+1)*sizeof(char);
+		ISSM_MPI_Bcast(&toolkitlength,1,ISSM_MPI_INT,0,IssmComm::GetComm());
+		if(my_rank!=0)toolkit=xNew<char>(toolkitlength);
+		ISSM_MPI_Bcast(toolkit,toolkitlength,ISSM_MPI_CHAR,0,IssmComm::GetComm());
+		if(my_rank!=0)toolkits[i]=toolkit;
+
 		char* string=strings[i];
 		if(my_rank==0){
@@ -115,10 +144,13 @@
 	/*Ok, out of strings and analyses and numanalyses, create parameters, and plug them into parameters container: */
 	parameters->AddObject(new StringArrayParam(ToolkitsOptionsStringsEnum,strings,numanalyses));
-	parameters->AddObject(new DoubleVecParam(ToolkitsOptionsAnalysesEnum,analyses,numanalyses));
+	parameters->AddObject(new StringArrayParam(ToolkitsTypesEnum,toolkits,numanalyses));
+	parameters->AddObject(new IntVecParam(ToolkitsOptionsAnalysesEnum,analyses,numanalyses));
 
 	/*Clean up and return*/
 	for(i=0;i<numanalyses;i++) xDelete<char>(strings[i]);
+	for(i=0;i<numanalyses;i++) xDelete<char>(toolkits[i]);
 	xDelete<char*>(strings);
-	xDelete<IssmDouble>(analyses);
+	xDelete<char*>(toolkits);
+	xDelete<int>(analyses);
 	return;
 }
Index: /issm/trunk/src/c/modules/ProcessRiftsx/ProcessRiftsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ProcessRiftsx/ProcessRiftsx.cpp	(revision 22758)
+++ /issm/trunk/src/c/modules/ProcessRiftsx/ProcessRiftsx.cpp	(revision 22758)
@@ -0,0 +1,78 @@
+/*!\file:  ProcessRifts.cpp
+ * \brief split a mesh where a rift (or fault) is present
+ */ 
+
+#include "./ProcessRiftsx.h"
+#include "../../classes/RiftStruct.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void ProcessRiftsx(int** pindex, int* pnel,double** px,double** py,int* pnods,int** psegments,int** psegmentmarkers,int *pnum_seg,RiftStruct **priftstruct){
+
+	/*Output*/
+	int      numrifts,numrifts0;
+	int     *riftsnumsegments     = NULL;
+	int    **riftssegments        = NULL;
+	int     *riftsnumpairs        = NULL;
+	int    **riftspairs           = NULL;
+	int     *riftstips            = NULL;
+	double **riftspenaltypairs    = NULL;
+	int     *riftsnumpenaltypairs = NULL;
+
+	/*Recover initial mesh*/
+	int     nel            = *pnel;
+	int    *index          = *pindex;
+	double *x              = *px;
+	double *y              = *py;
+	int     nods           = *pnods;
+	int    *segments       = *psegments;
+	int    *segmentmarkers = *psegmentmarkers;
+	int     num_seg        = *pnum_seg;
+
+	/*Intermediary*/
+	int     riftflag;
+
+	/*First, do some fixing on the existing mesh: we do not want any element belonging entirely to the segment list (ie: 
+	 *all the nodes of this element belong to the segments (tends to happen when there are corners: */
+	RemoveCornersFromRifts(&index,&nel,&x,&y,&nods,segments,segmentmarkers,num_seg);
+
+	/*Figure out if we have rifts, and how many: */
+	IsRiftPresent(&riftflag,&numrifts0,segmentmarkers,num_seg);
+
+	if(!riftflag) _error_("No rift present in mesh");
+
+	/*Split mesh*/
+	SplitMeshForRifts(&nel,&index,&nods,&x,&y,&num_seg,&segments,&segmentmarkers);
+
+	/*Order segments so that their normals point outside the domain: */
+	OrderSegments(&segments,num_seg, index,nel);
+
+	/*We do not want to output segments mixed with rift segments: wring out the rifts from the segments, using the 
+	 *segmentmarkerlist:*/
+	SplitRiftSegments(&segments,&segmentmarkers,&num_seg,&numrifts,&riftsnumsegments,&riftssegments,numrifts0,nods,nel);
+
+	/*Using rift segments, associate rift faces in pairs, each pair face representing opposite flanks of the rifts facing one another directly: */
+	PairRiftElements(&riftsnumpairs,&riftspairs,numrifts,riftsnumsegments,riftssegments,x,y);
+
+	/*Order rifts so that they start from one tip, go to the other tip, and back: */
+	OrderRifts(&riftstips,riftssegments,riftspairs,numrifts,riftsnumsegments,x,y,nods,nel);
+
+	/*Create penalty pairs, used by Imp: */
+	PenaltyPairs(&riftspenaltypairs,&riftsnumpenaltypairs,numrifts,riftssegments,riftsnumsegments,riftspairs,riftstips,x,y);
+
+	/*Create Riftstruct*/
+	RiftStruct* riftstruct = new RiftStruct(numrifts,riftsnumsegments,riftssegments,riftsnumpairs,riftspairs,riftsnumpenaltypairs,riftspenaltypairs,riftstips);
+
+	/*Assign output pointers for mesh*/
+	*pnel            = nel;
+	*pindex          = index;
+	*px              = x;
+	*py              = y;
+	*pnods           = nods;
+	*psegments       = segments;
+	*psegmentmarkers = segmentmarkers;
+	*pnum_seg        = num_seg;
+
+	/*Assign output pointers for rifts*/
+	*priftstruct = riftstruct;
+}
Index: /issm/trunk/src/c/modules/ProcessRiftsx/ProcessRiftsx.h
===================================================================
--- /issm/trunk/src/c/modules/ProcessRiftsx/ProcessRiftsx.h	(revision 22758)
+++ /issm/trunk/src/c/modules/ProcessRiftsx/ProcessRiftsx.h	(revision 22758)
@@ -0,0 +1,12 @@
+/*!\file:  ProcessRiftsx.h
+ * \brief header file for ProcessRifts module
+ */ 
+
+#ifndef _PROCESSRIFTX_H
+#define _PROCESSRIFTX_H
+
+class RiftStruct;
+
+void ProcessRiftsx(int** pindex,int* pnel,double** px,double** py,int* pnods,int** psegments,int** psegmentmarkers,int *pnum_seg,RiftStruct **priftstruct);
+
+#endif  /* _PROCESSRIFTX_H*/
Index: /issm/trunk/src/c/modules/SetActiveNodesLSMx/SetActiveNodesLSMx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SetActiveNodesLSMx/SetActiveNodesLSMx.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/SetActiveNodesLSMx/SetActiveNodesLSMx.cpp	(revision 22758)
@@ -70,5 +70,5 @@
 
 	/*Initialize vector with number of vertices*/
-	int numvertices=femmodel->vertices->NumberOfVertices();
+	int numvertices=femmodel->vertices->NumberOfVertices(); if (numvertices==0)return;
 	Vector<IssmDouble>* vec_mask_ice=new Vector<IssmDouble>(numvertices); //vertices that have ice at next time step
 	/*Fill vector with values: */
Index: /issm/trunk/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp	(revision 22758)
@@ -9,19 +9,45 @@
 void SetControlInputsFromVectorx(FemModel* femmodel,IssmDouble* vector){
 
-	int  num_controls;
-	int *control_type = NULL;
+	bool isautodiff; 
+	femmodel->parameters->FindParam(&isautodiff,AutodiffIsautodiffEnum);
+	if(isautodiff){
+		int  num_controls;
+		int* control_type = NULL;
+		int* M = NULL;
+		int* N = NULL;
 
-	/*Retrieve some parameters*/
-	femmodel->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
-	femmodel->parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+		/*Retrieve some parameters*/
+		femmodel->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+		femmodel->parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+		femmodel->parameters->FindParam(&M,NULL,ControlInputSizeMEnum);
+		femmodel->parameters->FindParam(&N,NULL,ControlInputSizeNEnum);
 
-	for(int i=0;i<num_controls;i++){
-		for(int j=0;j<femmodel->elements->Size();j++){
-			Element* element=(Element*)femmodel->elements->GetObjectByOffset(j);
-			element->SetControlInputsFromVector(vector,control_type[i],i);
+		int offset = 0;
+		for(int i=0;i<num_controls;i++){
+			for(int j=0;j<femmodel->elements->Size();j++){
+				Element* element=(Element*)femmodel->elements->GetObjectByOffset(j);
+				element->SetControlInputsFromVector(vector,control_type[i],i,offset,N[i],M[i]);
+			}
+		offset += M[i]*N[i]; 
 		}
+
+
+		xDelete<int>(control_type);
 	}
+	else{
 
-	xDelete<int>(control_type);
+		int  num_controls;
+		int* control_type = NULL;
+		femmodel->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+		femmodel->parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+		int offset = 0;
+		for(int i=0;i<num_controls;i++){
+			for(int j=0;j<femmodel->elements->Size();j++){
+				Element* element=(Element*)femmodel->elements->GetObjectByOffset(j);
+				element->SetControlInputsFromVector(vector,control_type[i],i);
+			}
+		}
+		xDelete<int>(control_type);
+	}
 }
 
Index: /issm/trunk/src/c/modules/SurfaceMassBalancex/Gembx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceMassBalancex/Gembx.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/SurfaceMassBalancex/Gembx.cpp	(revision 22758)
@@ -8,4 +8,22 @@
 
 const double Pi = 3.141592653589793;
+const double CtoK = 273.15;             // Kelvin to Celcius conversion/ice melt. point T in K
+const double dts = 86400.0;              // Number of seconds in a day
+
+/* Tolerances have to be defined for if loops involving some specific values
+	like densitiy of ice or melting point temp because values are "rounded"
+	(e.g rho ice = 909.99... instead of 910.0) and we don't always go into the right loop */
+const double Ttol = 1e-10;
+const double Dtol = 1e-11;
+const double Gdntol = 1e-10;
+const double Wtol = 1e-13;
+
+const double CI = 2102.0;                       // heat capacity of snow/ice (J kg-1 k-1)
+const double LF = 0.3345E6;             // latent heat of fusion (J kg-1)
+const double LV = 2.495E6;               // latent heat of vaporization (J kg-1)
+const double LS = 2.8295E6;             // latent heat of sublimation (J kg-1)
+const double SB = 5.67E-8;                // Stefan-Boltzmann constant (W m-2 K-4)
+const double CA = 1005.0;                    // heat capacity of air (J kg-1 k-1)
+const double R = 8.314;                      // gas constant (mol-1 K-1)
 
 void Gembx(FemModel* femmodel){  /*{{{*/
@@ -25,13 +43,14 @@
 
 	/*intermediary:*/
-	IssmDouble dgpTop;
-	int gpTop, gpBottom;
-	int i;
-	IssmDouble gp0,z0;
+	IssmDouble dgpTop=0.0;
+	int gpTop=0;
+	int gpBottom=0;
+	int i=0;
+	IssmDouble gp0=0.0;
+	IssmDouble z0=0.0;
 	IssmDouble* dzT=NULL;
 	IssmDouble* dzB=NULL;
 
 	/*output: */
-	int m;
 	IssmDouble* dz=NULL;
 
@@ -102,12 +121,12 @@
 
 	// initialize
-	IssmDouble F = 0, H=0, G=0;
+	IssmDouble F = 0.0, H=0.0, G=0.0;
 	const IssmDouble E = 0.09;        //[mm d-1] model time growth constant E
 	// convert T from K to ºC
-	T = T - 273.15;
+	T = T - CtoK;
 
 	// temperature coefficient F
 	if(T>-6.0) F =  0.7 + ((T/-6.0) * 0.3);
-	if(T<=-6.0 && T>-22.0) F =  1 - ((T+6.0)/-16.0 * 0.8);
+	if(T<=-6.0 && T>-22.0) F =  1.0 - ((T+6.0)/-16.0 * 0.8);
 	if(T<=-22.0 && T>-40.0) F =  0.2 - ((T+22.0)/-18.0 * 0.2);
 
@@ -115,5 +134,5 @@
 	if(d<150.0) H=1.0;
 
-	if(d>=150.0 & d<400.0) H = 1 - ((d-150.0)/250.0);
+	if(d>=150.0 & d<400.0) H = 1.0 - ((d-150.0)/250.0);
 
 	// temperature gradient coefficient G
@@ -122,5 +141,5 @@
 	if(dT >= 0.4  && dT < 0.5)  G = 0.67 + (((dT - 0.4)/0.1) * 0.23);
 	if(dT >= 0.5  && dT < 0.7)  G = 0.9 + (((dT - 0.5)/0.2) * 0.1);
-	if(dT >= .7              )  G = 1.0;
+	if(dT >= 0.7              )  G = 1.0;
 
 	// grouped coefficient Q
@@ -128,5 +147,5 @@
 
 } /*}}}*/
-void grainGrowth(IssmDouble* re, IssmDouble* gdn, IssmDouble* gsp, IssmDouble* T,IssmDouble* dz,IssmDouble* d, IssmDouble* W,IssmDouble smb_dt,int m,int aIdx,int sid){ /*{{{*/
+void grainGrowth(IssmDouble** pre, IssmDouble** pgdn, IssmDouble** pgsp, IssmDouble* T,IssmDouble* dz,IssmDouble* d, IssmDouble* W,IssmDouble smb_dt,int m,int aIdx,int sid){ /*{{{*/
 
 	/*Created by: Alex S. Gardner, University of Alberta
@@ -165,12 +184,22 @@
 
 	/*intermediary: */
-	IssmDouble  dt;
+	IssmDouble  dt=0.0;
 	IssmDouble* gsz=NULL;
 	IssmDouble* dT=NULL;
 	IssmDouble* zGPC=NULL;
 	IssmDouble* lwc=NULL;
-	IssmDouble  Q=0;
+	IssmDouble  Q=0.0;
+
+	/*output: */
+	IssmDouble* re=NULL;
+	IssmDouble* gdn=NULL;
+	IssmDouble* gsp=NULL;
 
 	if(VerboseSmb() && sid==0 && IssmComm::GetRank()==0)_printf0_("   grain growth module\n");
+
+	/*Recover pointers: */
+	re=*pre;
+	gdn=*pgdn;
+	gsp=*pgsp;
 	
 	/*only when aIdx = 1 or 2 do we run grainGrowth: */
@@ -184,5 +213,5 @@
 
 	/*Convert dt from seconds to day: */
-	dt=smb_dt/86400.0;
+	dt=smb_dt/dts;
 
 	/*Determine liquid-water content in percentage: */
@@ -190,5 +219,5 @@
 
 	//set maximum water content by mass to 9 percent (Brun, 1980)
-	for(int i=0;i<m;i++)if(lwc[i]>9.0) lwc[i]=9.0;
+	for(int i=0;i<m;i++)if(lwc[i]>9.0-Wtol) lwc[i]=9.0;
 
 
@@ -203,5 +232,5 @@
 	for(int i=0;i<m;i++){
 		for (int j=0;j<=i;j++) zGPC[i]+=dz[j];
-		zGPC[i]-=dz[i]/2;
+		zGPC[i]-=(dz[i]/2.0);
 	}
 
@@ -218,10 +247,10 @@
 	/*Snow metamorphism. Depends on value of snow dendricity and wetness of the snowpack: */
 	for(int i=0;i<m;i++){
-		if (gdn[i]>0){
+		if (gdn[i]>0.0+Gdntol){
 
 			//_printf_("Dendritic dry snow metamorphism\n");
 
 			//index for dentricity > 0 and T gradients < 5 degC m-1 and >= 5 degC m-1
-			if(dT[i]<5.0){
+			if(dT[i]<5.0-Ttol){
 				//determine coefficients
 				IssmDouble A = - 2e8 * exp(-6e3 / T[i]) * dt;
@@ -241,5 +270,5 @@
 
 			// wet snow metamorphism
-			if(W[i]>0.0){
+			if(W[i]>0.0+Wtol){
 
 				//_printf_("D}ritic wet snow metamorphism\n");
@@ -254,11 +283,11 @@
 
 			// dendricity and sphericity can not be > 1 or < 0
-			if (gdn[i]<0.0)gdn[i]=0.0;
-			if (gsp[i]<0.0)gsp[i]=0.0;
-			if (gdn[i]>1.0)gdn[i]=1.0;
-			if (gsp[i]>1.0)gsp[i]=1.0;
+			if (gdn[i]<0.0+Wtol)gdn[i]=0.0;
+			if (gsp[i]<0.0+Wtol)gsp[i]=0.0;
+			if (gdn[i]>1.0-Wtol)gdn[i]=1.0;
+			if (gsp[i]>1.0-Wtol)gsp[i]=1.0;
 
 			// determine new grain size (mm)
-			gsz[i] = 0.1 + (1-gdn[i])*0.25 + (0.5-gsp[i])*0.1;
+			gsz[i] = 0.1 + (1.0-gdn[i])*0.25 + (0.5-gsp[i])*0.1;
 
 		}
@@ -272,11 +301,11 @@
 
 			// calculate grain growth
-			gsz[i] += Q* dt;
+			gsz[i] += (Q*dt);
 
 			//Wet snow metamorphism (Brun, 1989)
-			if(W[i]>0.0){
+			if(W[i]>0.0+Wtol){
 				//_printf_("Nond}ritic wet snow metamorphism\n");
 				//wet rate of change coefficient
-				IssmDouble E = 1.28e-8 + (4.22e-10 * pow(lwc[i],3.0))* (dt *86400.0);   // [mm^3 s^-1]
+				IssmDouble E = 1.28e-8 + (4.22e-10 * pow(lwc[i],3.0))* (dt *dts);   // [mm^3 s^-1]
 
 				// calculate change in grain volume and convert to grain size
@@ -286,8 +315,8 @@
 
 			// grains with sphericity == 1 can not have grain sizes > 2 mm (Brun, 1992)
-			if (gsp[i]==1.0 && gsz[i]>2.0) gsz[i]=2.0;
+			if (fabs(gsp[i]-1.0)<Wtol && gsz[i]>2.0-Wtol) gsz[i]=2.0;
 
 			// grains with sphericity == 0 can not have grain sizes > 5 mm (Brun, 1992)
-			if (gsp[i]!=1.0 && gsz[i]>5.0) gsz[i]=5.0;
+			if (fabs(gsp[i]-1.0)>Wtol && gsz[i]>5.0-Wtol) gsz[i]=5.0;
 		}
 
@@ -302,8 +331,14 @@
 	xDelete<IssmDouble>(lwc);
 
+	/*Assign output pointers:*/
+	*pre=re;
+	*pgdn=gdn;
+	*pgsp=gsp;
+
 }  /*}}}*/
-void albedo(IssmDouble* a, int aIdx, IssmDouble* re, IssmDouble* d, IssmDouble cldFrac, IssmDouble aIce, IssmDouble aSnow, IssmDouble* TK, IssmDouble* W, IssmDouble P, IssmDouble EC, IssmDouble t0wet, IssmDouble t0dry, IssmDouble K, IssmDouble dt, int m,int sid) { /*{{{*/
+void albedo(IssmDouble** pa, int aIdx, IssmDouble* re, IssmDouble* d, IssmDouble cldFrac, IssmDouble aIce, IssmDouble aSnow, IssmDouble aValue, IssmDouble adThresh, IssmDouble* TK, IssmDouble* W, IssmDouble P, IssmDouble EC, IssmDouble t0wet, IssmDouble t0dry, IssmDouble K, IssmDouble dt, IssmDouble dIce, int m,int sid) { /*{{{*/
 
 	//// Calculates Snow, firn and ice albedo as a function of:
+	//   0 : direct input from aValue parameter
 	//   1 : effective grain radius (Gardner & Sharp, 2009)
 	//   2 : effective grain radius (Brun et al., 2009)
@@ -313,4 +348,12 @@
 	//// Inputs
 	// aIdx      = albedo method to use
+	
+	// Method 0
+	//  aValue   = direct input value for albedo, override all changes to albedo
+
+	// adThresh
+	//  Apply below method to all areas with densities below this value, 
+	//  or else apply direct input value, allowing albedo to be altered.  
+	//  Default value is rho water (1023 kg m-3).
 
 	// Methods 1 & 2
@@ -347,112 +390,125 @@
 	//   [273 272.5 ... 265], [0 0.001 ... 0], 0, 0.01, 15, 15, 7, 3600)
 
+	/*output: */
+	IssmDouble* a=NULL;
+
 	if(VerboseSmb() && sid==0 && IssmComm::GetRank()==0)_printf0_("   albedo module\n");
+
+	/*Recover pointers: */
+	a=*pa;
         
 	//some constants:
 	const IssmDouble dSnow = 300;   // density of fresh snow [kg m-3]       
-	const IssmDouble dIce = 910;    // density of ice [kg m-3]
-
-	if(aIdx==1){ 
-        //function of effective grain radius
-        
-        //convert effective radius to specific surface area [cm2 g-1]
-        IssmDouble S = 3.0 / (.091 * re[0]);
-        
-        //determine broadband albedo
-        a[0]= 1.48 - pow(S,-.07);
-	}
-	else if(aIdx==2){
-		
-        // Spectral fractions  (Lefebre et al., 2003)
-        // [0.3-0.8um 0.8-1.5um 1.5-2.8um]
-        
-        IssmDouble sF[3] = {0.606, 0.301, 0.093};
-        
-        // convert effective radius to grain size in meters
-        IssmDouble gsz = (re[0] * 2) / 1000.0;
-        
-        // spectral range:
-        // 0.3 - 0.8um
-        IssmDouble a0 = fmin(0.98, 1 - 1.58 *pow(gsz,0.5));
-        // 0.8 - 1.5um
-        IssmDouble a1 = fmax(0, 0.95 - 15.4 *pow(gsz,0.5));
-        // 1.5 - 2.8um
-        IssmDouble a2 = fmax(0.127, 0.88 + 346.3*gsz - 32.31*pow(gsz,0.5));
-        
-        // broadband surface albedo
-        a[0] = sF[0]*a0 + sF[1]*a1 + sF[2]*a2;
-
-	}
-	else if(aIdx==3){
-		
-        // a as a function of density
-        
-        // calculate albedo
-        a[0] = aIce + (d[0] - dIce)*(aSnow - aIce) / (dSnow - dIce) + (0.05 * (cldFrac - 0.5));
-	}
-	else if(aIdx==4){
-		
-        // exponential time decay & wetness
-        
-        // change in albedo with time:
-        //   (d_a) = (a - a_old)/(t0)
-        // where: t0 = timescale for albedo decay
-        
-        dt = dt / 86400;    // convert from [s] to [d]
-        
-        // initialize variables
-        IssmDouble* t0=xNew<IssmDouble>(m);
-        IssmDouble* T=xNew<IssmDouble>(m);
-        IssmDouble* t0warm=xNew<IssmDouble>(m);
-        IssmDouble* d_a=xNew<IssmDouble>(m);
-        
-        // specify constants
-        // a_wet = 0.15;        // water albedo (0.15)
-        // a_new = aSnow        // new snow albedo (0.64 - 0.89)
-        // a_old = aIce;        // old snow/ice albedo (0.27-0.53)
-        // t0_wet = t0wet;      // time scale for wet snow (15-21.9) [d]
-        // t0_dry = t0dry;      // warm snow timescale [15] [d]
-        // K = 7                // time scale temperature coef. (7) [d]
-        // W0 = 300;            // 200 - 600 [mm]
-        const IssmDouble z_snow = 15;            // 16 - 32 [mm]
-        
-        // determine timescale for albedo decay
-        for(int i=0;i<m;i++)if(W[i]>0)t0[i]=t0wet; // wet snow timescale
-        for(int i=0;i<m;i++)T[i]=TK[i] - 273.15; // change T from K to degC
-        for(int i=0;i<m;i++) t0warm[i]= fabs(T[i]) * K + t0dry; //// 'warm' snow timescale
-        for(int i=0;i<m;i++)if(W[i]==0.0 && T[i]>=-10)t0[i]= t0warm[i];
-        for(int i=0;i<m;i++)if(T[i]<-10) t0[i] =  10 * K + t0dry; // 'cold' snow timescale
-        
-        // calculate new albedo
-        for(int i=0;i<m;i++)d_a[i] = (a[i] - aIce) / t0[i] * dt;           // change in albedo
-        for(int i=0;i<m;i++)a[i] -= d_a[i];                            // new albedo
-        
-        // modification of albedo due to thin layer of snow or solid
-        // condensation (deposition) at the surface surface
-        
-        // check if condensation occurs & if it is deposited in solid phase
-        if ( EC > 0 && T[0] < 0) P = P + (EC/dSnow) * 1000;  // add cond to precip [mm]
-        
-        a[0] = aSnow - (aSnow - a[0]) * exp(-P/z_snow);
-        
-        //----------THIS NEEDS TO BE IMPLEMENTED AT A LATER DATE------------
-        // modification of albedo due to thin layer of water on the surface
-        // a_surf = a_wet - (a_wet - a_surf) * exp(-W_surf/W0);
-
-        /*Free ressources:*/
-        xDelete<IssmDouble>(t0);
-        xDelete<IssmDouble>(T);
-        xDelete<IssmDouble>(t0warm);
-        xDelete<IssmDouble>(d_a);
-
-	}
-	else _error_("albedo method switch should range from 1 to 4!");
-	
+
+	if(aIdx==0 || (adThresh - d[0]<Dtol)){
+		a[0] = aValue;
+	}
+	else{
+		if(aIdx==1){ 
+			//function of effective grain radius
+
+			//convert effective radius to specific surface area [cm2 g-1]
+			IssmDouble S = 3.0 / (0.091 * re[0]);
+
+			//determine broadband albedo
+			a[0]= 1.48 - pow(S,-0.07);
+		}
+		else if(aIdx==2){
+
+			// Spectral fractions  (Lefebre et al., 2003)
+			// [0.3-0.8um 0.8-1.5um 1.5-2.8um]
+
+			IssmDouble sF[3] = {0.606, 0.301, 0.093};
+
+			// convert effective radius to grain size in meters
+			IssmDouble gsz = (re[0] * 2.0) / 1000.0;
+
+			// spectral range:
+			// 0.3 - 0.8um
+			IssmDouble a0 = fmin(0.98, 1 - 1.58 *pow(gsz,0.5));
+			// 0.8 - 1.5um
+			IssmDouble a1 = fmax(0, 0.95 - 15.4 *pow(gsz,0.5));
+			// 1.5 - 2.8um
+			IssmDouble a2 = fmax(0.127, 0.88 + 346.3*gsz - 32.31*pow(gsz,0.5));
+
+			// broadband surface albedo
+			a[0] = sF[0]*a0 + sF[1]*a1 + sF[2]*a2;
+		}
+		else if(aIdx==3){
+
+			// a as a function of density
+
+			// calculate albedo
+			a[0] = aIce + (d[0] - dIce)*(aSnow - aIce) / (dSnow - dIce) + (0.05 * (cldFrac - 0.5));
+		}
+		else if(aIdx==4){
+
+			// exponential time decay & wetness
+
+			// change in albedo with time:
+			//   (d_a) = (a - a_old)/(t0)
+			// where: t0 = timescale for albedo decay
+
+			dt = dt / dts;    // convert from [s] to [d]
+
+			// initialize variables
+			IssmDouble* t0=xNew<IssmDouble>(m);
+			IssmDouble* T=xNew<IssmDouble>(m);
+			IssmDouble* t0warm=xNew<IssmDouble>(m);
+			IssmDouble* d_a=xNew<IssmDouble>(m);
+
+			// specify constants
+			// a_wet = 0.15;        // water albedo (0.15)
+			// a_new = aSnow        // new snow albedo (0.64 - 0.89)
+			// a_old = aIce;        // old snow/ice albedo (0.27-0.53)
+			// t0_wet = t0wet;      // time scale for wet snow (15-21.9) [d]
+			// t0_dry = t0dry;      // warm snow timescale [15] [d]
+			// K = 7                // time scale temperature coef. (7) [d]
+			// W0 = 300;            // 200 - 600 [mm]
+			const IssmDouble z_snow = 15.0;            // 16 - 32 [mm]
+
+			// determine timescale for albedo decay
+			for(int i=0;i<m;i++)if(W[i]>0.0+Wtol)t0[i]=t0wet; // wet snow timescale
+			for(int i=0;i<m;i++)T[i]=TK[i] - CtoK; // change T from K to degC
+			for(int i=0;i<m;i++) t0warm[i]= fabs(T[i]) * K + t0dry; //// 'warm' snow timescale
+			for(int i=0;i<m;i++)if(fabs(W[i])<Wtol && T[i]>=-10.0-Ttol)t0[i]= t0warm[i];
+			for(int i=0;i<m;i++)if(T[i]<-10.0-Ttol) t0[i] =  10.0 * K + t0dry; // 'cold' snow timescale
+
+			// calculate new albedo
+			for(int i=0;i<m;i++)d_a[i] = (a[i] - aIce) / t0[i] * dt;           // change in albedo
+			for(int i=0;i<m;i++)a[i] -= d_a[i];                            // new albedo
+
+			// modification of albedo due to thin layer of snow or solid
+			// condensation (deposition) at the surface surface
+
+			// check if condensation occurs & if it is deposited in solid phase
+			if ( EC > 0.0 + Dtol && T[0] < 0.0-Ttol) P = P + (EC/dSnow) * 1000.0;  // add cond to precip [mm]
+
+			a[0] = aSnow - (aSnow - a[0]) * exp(-P/z_snow);
+
+			//----------THIS NEEDS TO BE IMPLEMENTED AT A LATER DATE------------
+			// modification of albedo due to thin layer of water on the surface
+			// a_surf = a_wet - (a_wet - a_surf) * exp(-W_surf/W0);
+
+			/*Free ressources:*/
+			xDelete<IssmDouble>(t0);
+			xDelete<IssmDouble>(T);
+			xDelete<IssmDouble>(t0warm);
+			xDelete<IssmDouble>(d_a);
+
+		}
+		else _error_("albedo method switch should range from 0 to 4!");
+	}
+
 	// Check for erroneous values
 	if (a[0] > 1) _printf_("albedo > 1.0\n");
 	else if (a[0] < 0) _printf_("albedo is negative\n");
 	else if (xIsNan(a[0])) _error_("albedo == NAN\n");
+
+	/*Assign output pointers:*/
+	*pa=a;
+
 }  /*}}}*/
-void thermo(IssmDouble* pEC, IssmDouble* T, IssmDouble* dz, IssmDouble* d, IssmDouble* swf, IssmDouble dlwrf, IssmDouble Ta, IssmDouble V, IssmDouble eAir, IssmDouble pAir, IssmDouble Ws, IssmDouble dt0, int m, IssmDouble Vz, IssmDouble Tz,int sid) { /*{{{*/
+void thermo(IssmDouble* pEC, IssmDouble** pT, IssmDouble* dz, IssmDouble* d, IssmDouble* swf, IssmDouble dlwrf, IssmDouble Ta, IssmDouble V, IssmDouble eAir, IssmDouble pAir, IssmDouble teValue, IssmDouble Ws, IssmDouble dt0, int m, IssmDouble Vz, IssmDouble Tz, IssmDouble thermo_scaling, IssmDouble dIce, int sid) { /*{{{*/
 
 	/* ENGLACIAL THERMODYNAMICS*/
@@ -476,4 +532,5 @@
 	//  Vz: air temperature height above surface [m]
 	//  Tz: wind height above surface [m]
+	//  thermo_scaling: scaling factor to multiply the thermal diffusion timestep (delta t) 
 
 	// OUTPUTS
@@ -496,53 +553,42 @@
 	IssmDouble* sw = NULL;
 	IssmDouble* dT_sw = NULL;
-	IssmDouble* lw = NULL;
 	IssmDouble* T0 = NULL;
 	IssmDouble* Tu = NULL;
 	IssmDouble* Td = NULL;
 
-	IssmDouble  z0;	
-	IssmDouble  dt;
-	IssmDouble max_fdt=0;
-	IssmDouble  Ts=0;
-	IssmDouble  L;
-	IssmDouble  eS;
-	IssmDouble  Ri=0;
-	IssmDouble  coefM;
-	IssmDouble  coefH;
-	IssmDouble An;
-	IssmDouble C;
-	IssmDouble shf;
-	IssmDouble SB;
-	IssmDouble CI; 
-	IssmDouble ds;
-	IssmDouble dAir;
-	IssmDouble TCs;
-	IssmDouble lhf;
-	IssmDouble EC_day;
-	IssmDouble dT_turb;
-	IssmDouble turb;
-	IssmDouble ulw;
-	IssmDouble dT_ulw;
-	IssmDouble dlw;
-	IssmDouble dT_dlw;
+	IssmDouble  z0=0.0;	
+	IssmDouble  dt=0.0;
+	IssmDouble max_fdt=0.0;
+	IssmDouble  Ts=0.0;
+	IssmDouble  L=0.0;
+	IssmDouble  eS=0.0;
+	IssmDouble  Ri=0.0;
+	IssmDouble  coefM=0.0;
+	IssmDouble  coefH=0.0;
+	IssmDouble An=0.0;
+	IssmDouble C=0.0;
+	IssmDouble shf=0.0;
+	IssmDouble ds=0.0;
+	IssmDouble dAir=0.0;
+	IssmDouble TCs=0.0;
+	IssmDouble lhf=0.0;
+	IssmDouble EC_day=0.0;
+	IssmDouble dT_turb=0.0;
+	IssmDouble turb=0.0;
+	IssmDouble ulw=0.0;
+	IssmDouble dT_ulw=0.0;
+	IssmDouble dlw=0.0;
+	IssmDouble dT_dlw=0.0;
 	
 	/*outputs:*/
-	IssmDouble EC;
+	IssmDouble EC=0.0;
+	IssmDouble* T=*pT;
 
 	if(VerboseSmb() && sid==0 && IssmComm::GetRank()==0)_printf0_("   thermal module\n");
 
-	// INITIALIZE
-	CI = 2102;          // heat capacity of snow/ice (J kg-1 k-1)
-	// CA = 1005;                  // heat capacity of air (J kg-1 k-1)
-	// LF = 0.3345E6;              // latent heat of fusion(J kg-1)
-	// LV = 2.495E6;               // latent heat of vaporization(J kg-1)
-	// dIce = 910;                 // density of ice [kg m-3]
-	// dSnow = 300;                // density of snow [kg m-3]
-	SB = 5.67E-8;       // Stefan-Boltzmann constant [W m-2 K-4]
-
 	ds = d[0];      // density of top grid cell
 
 	// calculated air density [kg/m3]
-	dAir = 0.029 * pAir /(8.314 * Ta);
+	dAir = 0.029 * pAir /(R * Ta);
 
 	// thermal capacity of top grid cell [J/k]
@@ -550,5 +596,5 @@
 
 	//initialize Evaporation - Condenstation 
-	EC = 0;
+	EC = 0.0;
 	
 	// check if all SW applied to surface or distributed throught subsurface
@@ -557,10 +603,10 @@
 	// SURFACE ROUGHNESS (Bougamont, 2006)
 	// wind/temperature surface roughness height [m]
-	if (ds < 910 && Ws == 0) z0 = 0.00012;       // 0.12 mm for dry snow
-	else if (ds >= 910) z0 = 0.0032;             // 3.2 mm for ice
+	if (ds < dIce-Dtol && fabs(Ws) < Wtol) z0 = 0.00012;       // 0.12 mm for dry snow
+	else if (ds >= dIce-Dtol) z0 = 0.0032;             // 3.2 mm for ice
 	else z0 = 0.0013;                            // 1.3 mm for wet snow
 
 	// if V = 0 goes to infinity therfore if V = 0 change
-	if(V<.01)V=.01;
+	if(V<0.01-Dtol)V=0.01;
 	
 	// Bulk-transfer coefficient for turbulent fluxes
@@ -575,8 +621,8 @@
 
 	// for snow and firn (density < 910 kg m-3) (Sturn et al, 1997)
-	for(int i=0;i<m;i++) if(d[i]<910) K[i] = 0.138 - 1.01E-3 * d[i] + 3.233E-6 * (pow(d[i],2));
+	for(int i=0;i<m;i++) if(d[i]<dIce-Dtol) K[i] = 0.138 - 1.01E-3 * d[i] + 3.233E-6 * (pow(d[i],2));
 
 	// for ice (density >= 910 kg m-3)
-	for(int i=0;i<m;i++) if(d[i]>=910) K[i] = 9.828 * exp(-5.7E-3*T[i]);
+	for(int i=0;i<m;i++) if(d[i]>=dIce-Dtol) K[i] = 9.828 * exp(-5.7E-3*T[i]);
 
 	// THERMAL DIFFUSION COEFFICIENTS
@@ -620,6 +666,7 @@
 
 	// determine minimum acceptable delta t (diffusion number > 1/2) [s]
+	// NS: 2.16.18 divided dt by scaling factor, default set to 1/11 for stability
 	dt=1e12; 
-	for(int i=0;i<m;i++)dt = fmin(dt,CI * pow(dz[i],2) * d[i]  / (3 * K[i]));
+	for(int i=0;i<m;i++)dt = fmin(dt,CI * pow(dz[i],2) * d[i]  / (3 * K[i]) * thermo_scaling);
 
 	// smallest possible even integer of 60 min where diffusion number > 1/2
@@ -633,8 +680,8 @@
 	max_fdt=f[0];
 	for(int i=0;i<45;i++){
-		if (f[i]<dt)if(f[i]>=max_fdt)max_fdt=f[i];
+		if (f[i]<dt-Dtol)if(f[i]>=max_fdt-Dtol)max_fdt=f[i];
 	}
 	dt=max_fdt;
-	
+
 	// determine mean (harmonic mean) of K/dz for u, d, & p
 	Au = xNew<IssmDouble>(m);
@@ -642,6 +689,6 @@
 	Ap = xNew<IssmDouble>(m);
 	for(int i=0;i<m;i++){
-		Au[i] = pow((dzU[i]/2/KP[i] + dz[i]/2/KU[i]),-1);
-		Ad[i] = pow((dzD[i]/2/KP[i] + dz[i]/2/KD[i]),-1);
+		Au[i] = pow((dzU[i]/2.0/KP[i] + dz[i]/2.0/KU[i]),-1.0);
+		Ad[i] = pow((dzD[i]/2.0/KP[i] + dz[i]/2.0/KD[i]),-1.0);
 		Ap[i] = (d[i]*dz[i]*CI)/dt;
 	}
@@ -654,17 +701,17 @@
 		Nu[i] = Au[i] / Ap[i];
 		Nd[i] = Ad[i] / Ap[i];
-		Np[i]= 1 - Nu[i] - Nd[i];
+		Np[i]= 1.0 - Nu[i] - Nd[i];
 	}
 	
 	// specify boundary conditions: constant flux at bottom
-	Nu[m-1] = 0;
-	Np[m-1] = 1;
+	Nu[m-1] = 0.0;
+	Np[m-1] = 1.0;
 	
 	// zero flux at surface
-	Np[0] = 1 - Nd[0];
+	Np[0] = 1.0 - Nd[0];
 	
 	// Create neighbor arrays for diffusion calculations instead of a tridiagonal matrix
-	Nu[0] = 0;
-	Nd[m-1] = 0;
+	Nu[0] = 0.0;
+	Nd[m-1] = 0.0;
 	
 	/* RADIATIVE FLUXES*/
@@ -705,10 +752,10 @@
 		// calculated.  The estimated enegy balance & melt are significanly
 		// less when Ts is taken as the mean of the x top grid cells.
-		Ts = (T[0] + T[1])/2;
-		Ts = fmin(273.15,Ts);    // don't allow Ts to exceed 273.15 K (0°C)
+		Ts = (T[0] + T[1])/2.0;
+		Ts = fmin(CtoK,Ts);    // don't allow Ts to exceed 273.15 K (0 degC)
 		
 		//TURBULENT HEAT FLUX
     
-		// MoninObukhov Stability Correction
+		// Monin-Obukhov Stability Correction
 		// Reference:
 		// Ohmura, A., 1982: Climate and Energy-Balance on the Arctic Tundra.
@@ -716,7 +763,7 @@
 
 		// calculate the Bulk Richardson Number (Ri)
-		Ri = (2*9.81* (Vz - z0) * (Ta - Ts)) / ((Ta + Ts)* pow(V,2.0));
+		Ri = (2.0*9.81* (Vz - z0) * (Ta - Ts)) / ((Ta + Ts)* pow(V,2.0));
 		
-		// calculate Monin-Obukhov stability factors 'coefM' and 'coefH'
+		// calculate Monin-Obukhov stability factors 'coefM' and 'coefH'
     
 		// do not allow Ri to exceed 0.19
@@ -724,46 +771,48 @@
 
 		// calculate momentum 'coefM' stability factor
-		if (Ri > 0){
+		if (Ri > 0.0+Ttol){
 			// if stable
-			coefM = 1/(1-5.2*Ri);
+			coefM = 1.0/(1.0-5.2*Ri);
 		}
 		else {
-			coefM =pow (1-18*Ri,-0.25);
+			coefM =pow (1.0-18*Ri,-0.25);
 		}
 		
 		// calculate heat/wind 'coef_H' stability factor
-		if (Ri < -0.03) coefH = 1.3 * coefM;
+		if (Ri <= -0.03+Ttol) coefH = coefM/1.3;
 		else coefH = coefM;
 		
 		//// Sensible Heat
 		// calculate the sensible heat flux [W m-2](Patterson, 1998)
-		shf = C * 1005 * (Ta - Ts);
-
-		// adjust using MoninObukhov stability theory
+		shf = C * CA * (Ta - Ts);
+
+		// adjust using Monin-Obukhov stability theory
 		shf = shf / (coefM * coefH);
 
 		//// Latent Heat
 		// determine if snow pack is melting & calcualte surface vapour pressure over ice or liquid water
-		if (Ts >= 273.15){
-			L = 2.495E6;
-
+		if (Ts >= CtoK-Ttol){
+			L = LV; //for liquid water at 273.15 k to vapor
+
+			//for liquid surface (assume liquid on surface when Ts == 0 deg C)
+			// Wright (1997), US Meteorological Handbook from Murphy and Koop, 2005 Appendix A
+			eS = 611.21 * exp(17.502 * (Ts - CtoK) / (240.97 + Ts - CtoK));
+		}
+		else{
+			L = LS; // latent heat of sublimation 
+			
 			// for an ice surface Murphy and Koop, 2005 [Equation 7]
 			eS = exp(9.550426 - 5723.265/Ts + 3.53068 * log(Ts) - 0.00728332 * Ts);
 		}
-		else{
-			L = 2.8295E6; // latent heat of sublimation for liquid surface (assume liquid on surface when Ts == 0 deg C)
-			// Wright (1997), US Meteorological Handbook from Murphy and Koop, 2005 Appendix A
-			eS = 611.21 * exp(17.502 * (Ts - 273.15) / (240.97 + Ts - 273.15));
-		}
-		
+
 		// Latent heat flux [W m-2]
 		lhf = C * L * (eAir - eS) * 0.622 / pAir;
-		
-		// adjust using MoninObukhov stability theory (if lhf '+' then there is energy and mass gained at the surface, 
+
+		// adjust using Monin-Obukhov stability theory (if lhf '+' then there is energy and mass gained at the surface, 
 		// if '-' then there is mass and energy loss at the surface.
 		lhf = lhf / (coefM * coefH);
 
 		//mass loss (-)/acreation(+) due to evaporation/condensation [kg]
-		EC_day = lhf * 86400 / L;
+		EC_day = lhf * dts / L;
 
 		// temperature change due turbulent fluxes
@@ -772,5 +821,5 @@
 
 		// upward longwave contribution
-		ulw = - SB * pow(Ts,4.0) * dt;
+		ulw = - (SB * pow(Ts,4.0)* teValue) * dt ;
 		dT_ulw = ulw / TCs;
 		
@@ -782,5 +831,5 @@
 		
 		// temperature diffusion
-		for(int j=0;j<m;j++)T0[1+j]=T[j];
+		for(int j=0;j<m;j++) T0[1+j]=T[j];
 		for(int j=0;j<m;j++) Tu[j] = T0[j];
 		for(int j=0;j<m;j++) Td[j] = T0[2+j];
@@ -788,6 +837,6 @@
 		
 		// calculate cumulative evaporation (+)/condensation(-)
-		EC = EC + (EC_day/86400)*dt;
-    
+		EC = EC + (EC_day/dts)*dt;
+
 		/* CHECK FOR ENERGY (E) CONSERVATION [UNITS: J]
 		//energy flux across lower boundary (energy supplied by underling ice)
@@ -804,5 +853,5 @@
 		*/
 	}
-	
+
 	/*Free ressources:*/
 	xDelete<IssmDouble>(K);
@@ -820,5 +869,4 @@
 	xDelete<IssmDouble>(sw);
 	xDelete<IssmDouble>(dT_sw);
-	xDelete<IssmDouble>(lw);
 	xDelete<IssmDouble>(T0);
 	xDelete<IssmDouble>(Tu);
@@ -828,7 +876,8 @@
 	/*Assign output pointers:*/
 	*pEC=EC;
+	*pT=T;
 
 }  /*}}}*/
-void shortwave(IssmDouble** pswf, int swIdx, int aIdx, IssmDouble dsw, IssmDouble as, IssmDouble* d, IssmDouble* dz, IssmDouble* re, int m, int sid){ /*{{{*/
+void shortwave(IssmDouble** pswf, int swIdx, int aIdx, IssmDouble dsw, IssmDouble as, IssmDouble* d, IssmDouble* dz, IssmDouble* re, IssmDouble dIce, int m, int sid){ /*{{{*/
 
 	// DISTRIBUTES ABSORBED SHORTWAVE RADIATION WITHIN SNOW/ICE
@@ -866,5 +915,5 @@
         
 		// calculate surface shortwave radiation fluxes [W m-2]
-		swf[0] = (1 - as) * dsw;
+		swf[0] = (1.0 - as) * dsw;
 	}
 	else{ // sw radation is absorbed at depth within the glacier
@@ -885,5 +934,5 @@
 			// convert effective radius [mm] to grain size [m]
 			gsz=xNew<IssmDouble>(m);
-			for(int i=0;i<m;i++) gsz[i]= (re[i] * 2) / 1000;
+			for(int i=0;i<m;i++) gsz[i]= (re[i] * 2.0) / 1000.0;
 
 			// Spectral fractions [0.3-0.8um 0.8-1.5um 1.5-2.8um]
@@ -895,6 +944,6 @@
 			B2_cum=xNew<IssmDouble>(m+1);
 			for(int i=0;i<m+1;i++){
-				B1_cum[i]=1;
-				B2_cum[i]=1;
+				B1_cum[i]=1.0;
+				B2_cum[i]=1.0;
 			}
 
@@ -902,7 +951,7 @@
 			// spectral albedos:
 			// 0.3 - 0.8um
-			IssmDouble a0 = fmin(0.98, 1 - 1.58 *pow(gsz[0],0.5));
+			IssmDouble a0 = fmin(0.98, 1.0 - 1.58 *pow(gsz[0],0.5));
 			// 0.8 - 1.5um
-			IssmDouble a1 = fmax(0, 0.95 - 15.4 *pow(gsz[0],0.5));
+			IssmDouble a1 = fmax(0.0, 0.95 - 15.4 *pow(gsz[0],0.5));
 			// 1.5 - 2.8um
 			IssmDouble a2 = fmax(0.127, 0.88 + 346.3*gsz[0] - 32.31*pow(gsz[0],0.5));
@@ -910,7 +959,7 @@
 			// separate net shortwave radiative flux into spectral ranges
 			IssmDouble swfS[3];
-			swfS[0] = (sF[0] * dsw) * (1 - a0);
-			swfS[1] = (sF[1] * dsw) * (1 - a1);
-			swfS[2] = (sF[2] * dsw) * (1 - a2);
+			swfS[0] = (sF[0] * dsw) * (1.0 - a0);
+			swfS[1] = (sF[1] * dsw) * (1.0 - a1);
+			swfS[2] = (sF[2] * dsw) * (1.0 - a2);
 
 			// absorption coeficient for spectral range:
@@ -919,6 +968,6 @@
 			B2 =xNew<IssmDouble>(m);
 			for(int i=0;i<m;i++) h[i]= d[i] /(pow(gsz[i],0.5));
-			for(int i=0;i<m;i++) B1[i] = .0192 * h[i];                 // 0.3 - 0.8um
-			for(int i=0;i<m;i++) B2[i]= .1098 * h[i];                 // 0.8 - 1.5um
+			for(int i=0;i<m;i++) B1[i] = 0.0192 * h[i];                 // 0.3 - 0.8um
+			for(int i=0;i<m;i++) B2[i]= 0.1098 * h[i];                 // 0.8 - 1.5um
 			// B3 = +inf                     // 1.5 - 2.8um
 
@@ -987,16 +1036,16 @@
 
 			// calculate surface shortwave radiation fluxes [W m-2]
-			IssmDouble swf_s = SWs * (1 - as) * dsw;
+			IssmDouble swf_s = SWs * (1.0 - as) * dsw;
 
 			// calculate surface shortwave radiation fluxes [W m-2]
-			IssmDouble swf_ss = (1-SWs) * (1 - as) * dsw;
+			IssmDouble swf_ss = (1.0-SWs) * (1.0 - as) * dsw;
 
 			// SW allowed to penetrate into snowpack
-			IssmDouble Bs = 10;    // snow SW extinction coefficient [m-1] (Bassford,2006)
+			IssmDouble Bs = 10.0;    // snow SW extinction coefficient [m-1] (Bassford,2006)
 			IssmDouble Bi = 1.3;   // ice SW extinction coefficient [m-1] (Bassford,2006)
 
 			// calculate extinction coefficient B [m-1] vector
 			B=xNew<IssmDouble>(m);
-			for(int i=0;i<m;i++) B[i] = Bs + (300 - d[i]) * ((Bs - Bi)/(910 - 300));
+			for(int i=0;i<m;i++) B[i] = Bs + (300.0 - d[i]) * ((Bs - Bi)/(dIce - 300.0));
 
 			// cumulative extinction factor
@@ -1005,5 +1054,5 @@
 			for(int i=0;i<m;i++)exp_B[i]=exp(-B[i]*dz[i]);
 
-			B_cum[0]=1;
+			B_cum[0]=1.0;
 			for(int i=0;i<m;i++){
 				IssmDouble cum_B=exp_B[0];
@@ -1033,5 +1082,5 @@
 
 } /*}}}*/ 
-void accumulation(IssmDouble** pT, IssmDouble** pdz, IssmDouble** pd, IssmDouble** pW, IssmDouble** pa, IssmDouble** pre, IssmDouble** pgdn, IssmDouble** pgsp, int* pm, IssmDouble T_air, IssmDouble P, IssmDouble dzMin, IssmDouble aSnow, int sid){ /*{{{*/
+void accumulation(IssmDouble** pT, IssmDouble** pdz, IssmDouble** pd, IssmDouble** pW, IssmDouble** pa, IssmDouble** pre, IssmDouble** pgdn, IssmDouble** pgsp, int* pm, int aIdx, IssmDouble T_air, IssmDouble P, IssmDouble dzMin, IssmDouble aSnow, IssmDouble dIce, int sid){ /*{{{*/
 
 	// Adds precipitation and deposition to the model grid
@@ -1052,8 +1101,7 @@
 	// MAIN FUNCTION
 	// specify constants
-	const IssmDouble dIce = 910;     // density of ice [kg m-3]
 	const IssmDouble dSnow = 150;    // density of snow [kg m-3]
 	const IssmDouble reNew = 0.1;    // new snow grain size [mm]
-	const IssmDouble gdnNew = 1;     // new snow dendricity 
+	const IssmDouble gdnNew = 1.0;     // new snow dendricity 
 	const IssmDouble gspNew = 0.5;   // new snow sphericity 
 
@@ -1061,5 +1109,7 @@
 	IssmDouble* mInit=NULL;
 	bool        top=true;
-	IssmDouble  mass, massinit, mass_diff;
+	IssmDouble  mass=0;
+	IssmDouble  massinit=0;
+	IssmDouble  mass_diff=0;
 
 	/*output: */
@@ -1072,5 +1122,5 @@
 	IssmDouble* gdn=NULL;
 	IssmDouble* gsp=NULL;
-	int         m;
+	int         m=0;
 
 	if(VerboseSmb() && sid==0 && IssmComm::GetRank()==0)_printf0_("   accumulation module\n");
@@ -1090,20 +1140,21 @@
 	mInit=xNew<IssmDouble>(m);
 	for(int i=0;i<m;i++) mInit[i]= d[i] * dz[i];
-	massinit=0; for(int i=0;i<m;i++)massinit+=mInit[i];
-
-	if (P > 0){
+	massinit=0.0; 
+	for(int i=0;i<m;i++)massinit+=mInit[i];
+
+	if (P > 0.0+Dtol){
 			
 
-		if (T_air <= 273.15){ // if snow
+		if (T_air <= CtoK+Ttol){ // if snow
 
 			IssmDouble  z_snow = P/dSnow;               // depth of snow
 
 			// if snow depth is greater than specified min dz, new cell created
-			if (z_snow > dzMin){
+			if (z_snow > dzMin+Dtol){
 
 				newcell(&T,T_air,top,m); //new cell T
 				newcell(&dz,z_snow,top,m); //new cell dz
 				newcell(&d,dSnow,top,m); //new cell d
-				newcell(&W,0,top,m); //new cell W
+				newcell(&W,0.0,top,m); //new cell W
 				newcell(&a,aSnow,top,m); //new cell a
 				newcell(&re,reNew,top,m); //new cell grain size
@@ -1124,5 +1175,5 @@
 
 				// adjust a, re, gdn & gsp
-				a[0] = (aSnow * P + a[0] * mInit[0])/mass;
+				if(aIdx>0)a[0] = (aSnow * P + a[0] * mInit[0])/mass;
 				re[0] = (reNew * P + re[0] * mInit[0])/mass;
 				gdn[0] = (gdnNew * P + gdn[0] * mInit[0])/mass;
@@ -1138,7 +1189,4 @@
 			  makes the numerics easier.*/
 
-			IssmDouble LF = 0.3345E6;  // latent heat of fusion(J kg-1)
-			IssmDouble CI = 2102;      // specific heat capacity of snow/ice (J kg-1 k-1)
-
 			// grid cell adjust mass
 			mass = mInit[0] + P;
@@ -1152,5 +1200,5 @@
 
 			// if d > the density of ice, d = dIce
-			if (d[0] > dIce){
+			if (d[0] > dIce+Dtol){
 				d[0] = dIce;           // adjust d
 				dz[0] = mass / d[0];    // dz is adjusted to conserve mass
@@ -1164,5 +1212,5 @@
 		
 		#ifndef _HAVE_ADOLC_  //avoid round operation. only check in forward mode.
-		mass_diff = round(mass_diff * 100)/100;
+		mass_diff = round(mass_diff * 100.0)/100.0;
 		if (mass_diff > 0) _error_("mass not conserved in accumulation function");
 		#endif
@@ -1183,5 +1231,5 @@
 	*pm=m;
 } /*}}}*/
-void melt(IssmDouble* pM, IssmDouble* pR, IssmDouble* pmAdd, IssmDouble* pdz_add, IssmDouble** pT, IssmDouble** pd, IssmDouble** pdz, IssmDouble** pW, IssmDouble** pa, IssmDouble** pre, IssmDouble** pgdn, IssmDouble** pgsp, int* pn, IssmDouble dzMin, IssmDouble zMax, IssmDouble zMin, IssmDouble zTop, int sid){ /*{{{*/
+void melt(IssmDouble* pM, IssmDouble* pR, IssmDouble* pmAdd, IssmDouble* pdz_add, IssmDouble** pT, IssmDouble** pd, IssmDouble** pdz, IssmDouble** pW, IssmDouble** pa, IssmDouble** pre, IssmDouble** pgdn, IssmDouble** pgsp, int* pn, IssmDouble dzMin, IssmDouble zMax, IssmDouble zMin, IssmDouble zTop, IssmDouble dIce, int sid){ /*{{{*/
 
 	//// MELT ROUTINE
@@ -1199,7 +1247,6 @@
 	IssmDouble* surpT=NULL;
 	IssmDouble* surpE=NULL;
-	IssmDouble* F=NULL;
 	IssmDouble* flxDn=NULL;
-	IssmDouble  ER=0;
+	IssmDouble  ER=0.0;
 	IssmDouble* EI=NULL;
 	IssmDouble* EW=NULL;
@@ -1207,26 +1254,28 @@
 	int*       D=NULL;
 	
-	IssmDouble sumM;
-	IssmDouble sumER;
-	IssmDouble addE;
-	IssmDouble mSum0;
-	IssmDouble sumE0;
-	IssmDouble mSum1;
-	IssmDouble sumE1;
-	IssmDouble dE;
-	IssmDouble dm;
-	IssmDouble X;
-	IssmDouble Wi;
+	IssmDouble sumM=0.0;
+	IssmDouble sumER=0.0;
+	IssmDouble addE=0.0;
+	IssmDouble mSum0=0.0;
+	IssmDouble sumE0=0.0;
+	IssmDouble mSum1=0.0;
+	IssmDouble sumE1=0.0;
+	IssmDouble dE=0.0;
+	IssmDouble dm=0.0;
+	IssmDouble X=0.0;
+	IssmDouble Wi=0.0;
     
-	IssmDouble Ztot;
-	IssmDouble T_bot;
-	IssmDouble m_bot;
-	IssmDouble dz_bot;
-	IssmDouble d_bot;
-	IssmDouble W_bot;
-	IssmDouble a_bot;
-	IssmDouble re_bot;
-	IssmDouble gdn_bot;
-	IssmDouble gsp_bot;
+	IssmDouble Ztot=0.0;
+	IssmDouble T_bot=0.0;
+	IssmDouble m_bot=0.0;
+	IssmDouble dz_bot=0.0;
+	IssmDouble d_bot=0.0;
+	IssmDouble W_bot=0.0;
+	IssmDouble a_bot=0.0;
+	IssmDouble re_bot=0.0;
+	IssmDouble gdn_bot=0.0;
+	IssmDouble gsp_bot=0.0;
+	IssmDouble EI_bot=0.0;
+	IssmDouble EW_bot=0.0;
 	bool        top=false;
     
@@ -1234,14 +1283,14 @@
 	IssmDouble* dzMin2=NULL;
 	IssmDouble zY2=1.025;
-	bool lastCellFlag;
+	bool lastCellFlag = false;
 	int X1=0;
 	int X2=0;
     
-	int        D_size;
+	int        D_size = 0;
 
 	/*outputs:*/
-	IssmDouble  mAdd;
-	IssmDouble dz_add;
-	IssmDouble  Rsum;
+	IssmDouble  mAdd = 0.0;
+	IssmDouble dz_add = 0.0;
+	IssmDouble  Rsum = 0.0;
 	IssmDouble* T=*pT;
 	IssmDouble* d=*pd;
@@ -1253,5 +1302,5 @@
 	IssmDouble* gsp=*pgsp;
 	int         n=*pn;
-	IssmDouble* R=0;
+	IssmDouble* R=NULL;
 	
 	if(VerboseSmb() && sid==0 && IssmComm::GetRank()==0)_printf0_("   melt module\n");
@@ -1261,13 +1310,6 @@
 	/*Allocations: */
 	M=xNewZeroInit<IssmDouble>(n); 
-	maxF=xNew<IssmDouble>(n); 
-	dW=xNew<IssmDouble>(n); 
-
-	// specify constants
-	const IssmDouble CtoK = 273.15;  // clecius to Kelvin conversion
-	const IssmDouble CI = 2102;      // specific heat capacity of snow/ice (J kg-1 k-1)
-	const IssmDouble LF = 0.3345E6;  // latent heat of fusion(J kg-1)
-	const IssmDouble dPHC = 830;     // pore hole close off density[kg m-3]
-	const IssmDouble dIce = 910;     // density of ice [kg m-3]
+	maxF=xNewZeroInit<IssmDouble>(n); 
+	dW=xNewZeroInit<IssmDouble>(n); 
 
 	// store initial mass [kg] and energy [J]
@@ -1280,17 +1322,18 @@
 
 	// initialize melt and runoff scalars
-	Rsum = 0;       // runoff [kg]
-	sumM = 0;       // total melt [kg]
-	mAdd = 0;       // mass added/removed to/from base of model [kg]
-	addE = 0;       // energy added/removed to/from base of model [J]
-	dz_add=0;      // thickness of the layer added/removed to/from base of model [m]
+	Rsum = 0.0;       // runoff [kg]
+	sumM = 0.0;       // total melt [kg]
+	mAdd = 0.0;       // mass added/removed to/from base of model [kg]
+	addE = 0.0;       // energy added/removed to/from base of model [J]
+	dz_add=0.0;      // thickness of the layer added/removed to/from base of model [m]
 
 	// calculate temperature excess above 0 deg C
 	exsT=xNewZeroInit<IssmDouble>(n);
-	for(int i=0;i<n;i++) exsT[i]= fmax(0, T[i] - CtoK);        // [K] to [°C]
+	for(int i=0;i<n;i++) exsT[i]= fmax(0.0, T[i] - CtoK);        // [K] to [degC]
 
 	// new grid point center temperature, T [K]
-	for(int i=0;i<n;i++) T[i]-=exsT[i];
-
+	// for(int i=0;i<n;i++) T[i]-=exsT[i];
+	for(int i=0;i<n;i++) T[i]=fmin(T[i],CtoK);
+	
 	// specify irreducible water content saturation [fraction]
 	const IssmDouble Swi = 0.07;                     // assumed constant after Colbeck, 1974
@@ -1298,8 +1341,8 @@
 	//// REFREEZE PORE WATER
 	// check if any pore water
-	if (cellsum(W,n) > 0){
+	if (cellsum(W,n) >0.0+Wtol){
 		if(VerboseSmb() && sid==0 && IssmComm::GetRank()==0)_printf0_("      pore water refreeze\n");
 		// calculate maximum freeze amount, maxF [kg]
-		for(int i=0;i<n;i++) maxF[i] = fmax(0, -((T[i] - CtoK) * m[i] * CI) / LF);
+		for(int i=0;i<n;i++) maxF[i] = fmax(0.0, -((T[i] - CtoK) * m[i] * CI) / LF);
 
 		// freeze pore water and change snow/ice properties
@@ -1311,6 +1354,7 @@
 
 		// if pore water froze in ice then adjust d and dz thickness
-		for(int i=0;i<n;i++)if(d[i]>dIce)d[i]=dIce;
+		for(int i=0;i<n;i++)if(d[i]>dIce-Dtol)d[i]=dIce;
 		for(int i=0;i<n;i++) dz[i]= m[i]/d[i];
+
 	}
 
@@ -1318,6 +1362,6 @@
 	exsW=xNew<IssmDouble>(n); 
 	for(int i=0;i<n;i++){
-		Wi= (910 - d[i]) * Swi * (m[i] / d[i]);        // irreducible water content [kg]
-		exsW[i] = fmax(0, W[i] - Wi);                  // water "squeezed" from snow [kg]
+		Wi= (dIce - d[i]) * Swi * (m[i] / d[i]);        // irreducible water content [kg]
+		exsW[i] = fmax(0.0, W[i] - Wi);                  // water "squeezed" from snow [kg]
 	}
 
@@ -1325,5 +1369,5 @@
 
 	// run melt algorithm if there is melt water or excess pore water
-	if ((cellsum(exsT,n) > 0) || (cellsum(exsW,n) > 0)){
+	if ((cellsum(exsT,n) > 0.0 + Ttol) || (cellsum(exsW,n) > 0.0 + Wtol)){
 		// _printf_(""MELT OCCURS");
 		// check to see if thermal energy exceeds energy to melt entire cell
@@ -1331,25 +1375,25 @@
 		// (maximum T of snow before entire grid cell melts is a constant
 		// LF/CI = 159.1342)
-		surpT=xNew<IssmDouble>(n); for(int i=0;i<n;i++)surpT[i] = fmax(0, exsT [i]- 159.1342);
-        
-		if (cellsum(surpT,n) > 0 ){
+		surpT=xNew<IssmDouble>(n); for(int i=0;i<n;i++)surpT[i] = fmax(0.0, exsT[i]- LF/CI);
+
+		if (cellsum(surpT,n) > 0.0 + Ttol ){
 			// _printf_("T Surplus");
 			// calculate surplus energy
 			surpE=xNew<IssmDouble>(n); for(int i=0;i<n;i++)surpE[i] = surpT[i] * CI * m[i];
-            
+
 			int i = 0;
-			while (cellsum(surpE,n) > 0){
+			while (cellsum(surpE,n) > 0.0 + Ttol){
 				// use surplus energy to increase the temperature of lower cell
 				T[i+1] = surpE[i]/m[i+1]/CI + T[i+1];
-                
-				exsT[i+1] = fmax(0, T[i+1] - CtoK) + exsT[i+1];
+
+				exsT[i+1] = fmax(0.0, T[i+1] - CtoK) + exsT[i+1];
 				T[i+1] = fmin(CtoK, T[i+1]);
-                
-				surpT[i+1] = fmax(0, exsT[i+1] - 159.1342);
+
+				surpT[i+1] = fmax(0.0, exsT[i+1] - LF/CI);
 				surpE[i+1] = surpT[i+1] * CI * m[i+1];
-                
+
 				// adjust current cell properties (again 159.1342 is the max T)
-				exsT[i] = 159.1342;
-				surpE[i] = 0;
+				exsT[i] = LF/CI;
+				surpE[i] = 0.0;
 				i = i + 1;
 			}
@@ -1357,21 +1401,21 @@
 
 		// convert temperature excess to melt [kg]
-		for(int i=0;i<n;i++) M[i] = exsT[i] * d[i] * dz[i] * CI / LF;      // melt
-		sumM = cellsum(M,n);                                               // total melt [kg]
+		for(int i=0;i<n;i++) M[i] = fmin(exsT[i] * d[i] * dz[i] * CI / LF, m[i]);  // melt
+		sumM = cellsum(M,n);                                                       // total melt [kg]
 
 		// calculate maximum refreeze amount, maxF [kg]
-		for(int i=0;i<n;i++)maxF[i] = fmax(0, -((T[i] - CtoK) * d[i] * dz[i] * CI)/ LF);
+		for(int i=0;i<n;i++)maxF[i] = fmax(0.0, -((T[i] - CtoK) * d[i] * dz[i] * CI)/ LF);
 
 		// initialize refreeze, runoff, flxDn and dW vectors [kg]
  		IssmDouble* F = xNewZeroInit<IssmDouble>(n);
-		IssmDouble* R=xNewZeroInit<IssmDouble>(n);
-
-		for(int i=0;i<n;i++)dW[i] = 0;
-		flxDn=xNewZeroInit<IssmDouble>(n+1); for(int i=0;i<n;i++)flxDn[i+1]=F[i];
+		IssmDouble* R = xNewZeroInit<IssmDouble>(n);
+
+		for(int i=0;i<n;i++)dW[i] = 0.0;
+		flxDn=xNewZeroInit<IssmDouble>(n+1);
 
 		// determine the deepest grid cell where melt/pore water is generated
 		X = 0;
 		for(int i=n-1;i>=0;i--){
-			if(M[i]>0 || reCast<int,IssmDouble>(exsW[i])){
+			if(M[i]>0.0+Wtol || exsW[i]>0.0+Wtol){
 				X=i;
 				break;
@@ -1385,10 +1429,10 @@
 
 			// break loop if there is no meltwater and if depth is > mw_depth
-			if (inM == 0 && i > X){
+			if (inM == 0.0 && i > X){
 				break;
 			}
 
 			// if reaches impermeable ice layer all liquid water runs off (R)
-			else if (d[i] >= dIce){  // dPHC = pore hole close off [kg m-3]
+			else if (d[i] >= dIce-Dtol){  // dPHC = pore hole close off [kg m-3]
 				// _printf_("ICE LAYER");
 				// no water freezes in this cell
@@ -1397,10 +1441,11 @@
 
 				m[i] = m[i] - M[i];                     // mass after melt
-				Wi = (910-d[i]) * Swi * (m[i]/d[i]);    // irreducible water 
-				dW[i] = fmin(inM, Wi - W[i]);            // change in pore water
-				R[i] = fmax(0, inM - dW[i]);             // runoff
+				Wi = (dIce-d[i]) * Swi * (m[i]/d[i]);    // irreducible water 
+				dW[i] = fmax(fmin(inM, Wi - W[i]),-1*W[i]);            // change in pore water
+				R[i] = fmax(0.0, inM - dW[i]);             // runoff
+				F[i] = 0.0;
 			}
 			// check if no energy to refreeze meltwater
-			else if (maxF[i] == 0){
+			else if (fabs(maxF[i]) < Dtol){
 				// _printf_("REFREEZE == 0");
 				// no water freezes in this cell
@@ -1408,8 +1453,9 @@
 
 				m[i] = m[i] - M[i];                     // mass after melt
-				Wi = (910-d[i]) * Swi * (m[i]/d[i]);    // irreducible water 
-				dW[i] = fmin(inM, Wi-W[i]);              // change in pore water
-				flxDn[i+1] = fmax(0, inM-dW[i]);         // meltwater out
-				F[i] = 0;                               // no freeze 
+				Wi = (dIce-d[i]) * Swi * (m[i]/d[i]);    // irreducible water 
+				dW[i] = fmax(fmin(inM, Wi - W[i]),-1*W[i]);              // change in pore water
+				flxDn[i+1] = fmax(0.0, inM - dW[i]);         // meltwater out
+				R[i] = 0.0;
+				F[i] = 0.0;                               // no freeze 
 			}
 			// some or all meltwater refreezes
@@ -1418,4 +1464,5 @@
 				// _printf_("MELT REFREEZE");
 				//-----------------------melt water-----------------------------
+				m[i] = m[i] - M[i];
 				IssmDouble dz_0 = m[i]/d[i];          
 				IssmDouble dMax = (dIce - d[i])*dz_0;              // d max = dIce
@@ -1425,30 +1472,33 @@
 
 				//-----------------------pore water-----------------------------
-				Wi = (910-d[i])* Swi * dz_0;            // irreducible water 
+				Wi = (dIce-d[i])* Swi * dz_0;            // irreducible water 
 				dW[i] = fmin(inM - F1, Wi-W[i]);         // change in pore water
-				if (-dW[i]>W[i] ){
-					dW[i]= W[i];
+				if (dW[i] < 0.0-Wtol && -1*dW[i]>W[i]-Wtol ){
+					dW[i]= -1*W[i];
 				}
-				IssmDouble F2 = 0;                                 
-
-				if (dW[i] < 0){                         // excess pore water
+				IssmDouble F2 = 0.0;                                 
+
+				if (dW[i] < 0.0-Wtol){                         // excess pore water
 					dMax = (dIce - d[i])*dz_0;          // maximum refreeze                                             
 					IssmDouble maxF2 = fmin(dMax, maxF[i]-F1);      // maximum refreeze
-					F2 = fmin(-dW[i], maxF2);            // pore water refreeze
+					F2 = fmin(-1*dW[i], maxF2);            // pore water refreeze
 					m[i] = m[i] + F2;                   // mass after refreeze
 					d[i] = m[i]/dz_0;
+					dW[i] = dW[i] - F2;
 				}
 
-				flxDn[i+1] = inM - F1 - dW[i] - F2;     // meltwater out        
+				F[i] = F1 + F2;
+
+				flxDn[i+1] = inM - F1 - dW[i];     // meltwater out        
 				T[i] = T[i] + ((F1+F2)*(LF+(CtoK - T[i])*CI)/(m[i]*CI));// change in temperature
 
 
 				// check if an ice layer forms 
-				if (d[i] == dIce){
+				if (fabs(d[i] - dIce) < Dtol){
 					// _printf_("ICE LAYER FORMS");
 					// excess water runs off
 					R[i] = flxDn[i+1];
 					// no water percolates to lower cell
-					flxDn[i+1] = 0;
+					flxDn[i+1] = 0.0;
 				}
 			}
@@ -1457,5 +1507,5 @@
 
 		//// GRID CELL SPACING AND MODEL DEPTH
-		for(int i=0;i<n;i++)if (W[i] < 0) _error_("negative pore water generated in melt equations");
+		for(int i=0;i<n;i++)if (W[i] < 0.0 - Wtol) _error_("negative pore water generated in melt equations");
 		
 		// delete all cells with zero mass
@@ -1463,8 +1513,12 @@
 		for(int i=0;i<n;i++)W[i] += dW[i];
 
+		//calculate Rsum:
+		Rsum=cellsum(R,n) + flxDn[n];
+
 		// delete all cells with zero mass
-		D_size=0; for(int i=0;i<n;i++)if(m[i]!=0)D_size++; D=xNew<int>(D_size);
-		D_size=0; for(int i=0;i<n;i++)if(m[i]!=0){ D[D_size] = i; D_size++;}
-		
+		D_size=0; for(int i=0;i<n;i++)if(m[i]>0.0)D_size++; 
+		D=xNew<int>(D_size);
+		D_size=0; for(int i=0;i<n;i++)if(m[i]>0.0){ D[D_size] = i; D_size++;}
+
 		celldelete(&m,n,D,D_size);
 		celldelete(&W,n,D,D_size);
@@ -1477,5 +1531,4 @@
 		celldelete(&EI,n,D,D_size);
 		celldelete(&EW,n,D,D_size);
-		celldelete(&R,n,D,D_size);
 		n=D_size;
 		xDelete<int>(D);
@@ -1483,7 +1536,4 @@
 		// calculate new grid lengths
 		for(int i=0;i<n;i++)dz[i] = m[i] / d[i];
-
-		//calculate Rsum:
-		Rsum=cellsum(R,n);
 
 		/*Free ressources:*/
@@ -1491,5 +1541,5 @@
 		xDelete<IssmDouble>(R);
 	}
-    
+
 	//Merging of cells as they are burried under snow.
 	Zcum=xNew<IssmDouble>(n);
@@ -1503,5 +1553,5 @@
     
 	for (int i=0;i<n;i++){
-		if (Zcum[i]<=zTop){
+		if (Zcum[i]<=zTop+Dtol){
 			dzMin2[i]=dzMin;
 		}
@@ -1514,5 +1564,5 @@
 	X = 0;
 	for(int i=n-1;i>=0;i--){
-		if(dz[i]<dzMin2[i]){
+		if(dz[i]<dzMin2[i]-Dtol){
 			X=i;
 			break;
@@ -1530,5 +1580,5 @@
 
 	for (int i = 0; i<=X;i++){
-		if (dz [i] < dzMin2[i]){                              // merge top cells
+		if (dz[i] < dzMin2[i]-Dtol){                              // merge top cells
 			// _printf_("dz > dzMin * 2')
 			// adjust variables as a linearly weighted function of mass
@@ -1541,5 +1591,5 @@
             
 			// merge with underlying grid cell and delete old cell
-			dz [i+1] = dz[i] + dz[i+1];                 // combine cell depths
+			dz[i+1] = dz[i] + dz[i+1];                 // combine cell depths
 			d[i+1] = m_new / dz[i+1];                   // combine top densities
 			W[i+1] = W[i+1] + W[i];                     // combine liquid water
@@ -1547,5 +1597,5 @@
             
 			// set cell to 99999 for deletion
-			m[i] = 99999;
+			m[i] = -99999;
 		}
 	}
@@ -1555,5 +1605,5 @@
          //find closest cell to merge with
 		for(int i=n-2;i>=0;i--){
-			if(m[i]!=99999){
+			if(m[i]!=-99999){
 				X2=i;
 				X1=n-1;
@@ -1571,5 +1621,5 @@
         
 		// merge with underlying grid cell and delete old cell
-  		dz [X1] = dz[X2] + dz[X1];                 // combine cell depths
+  		dz[X1] = dz[X2] + dz[X1];                 // combine cell depths
 		d[X1] = m_new / dz[X1];                   // combine top densities
  		W[X1] = W[X1] + W[X2];                     // combine liquid water
@@ -1577,10 +1627,11 @@
         
 		// set cell to 99999 for deletion
-		m[X2] = 99999;
+		m[X2] = -99999;
 	}
 
 	// delete combined cells
-	D_size=0; for(int i=0;i<n;i++)if(m[i]!=99999)D_size++; D=xNew<int>(D_size); 
-	D_size=0; for(int i=0;i<n;i++)if(m[i]!=99999){ D[D_size] = i; D_size++;}
+	D_size=0; for(int i=0;i<n;i++)if(m[i]!=-99999)D_size++; 
+	D=xNew<int>(D_size); 
+	D_size=0; for(int i=0;i<n;i++)if(m[i]!=-99999){ D[D_size] = i; D_size++;}
 
 	celldelete(&m,n,D,D_size);
@@ -1601,5 +1652,5 @@
 	X=0;
 	for(int i=9;i>=0;i--){
-		if(dz[i]> 2* dzMin){
+		if(dz[i]> 2.0*dzMin+Dtol){
 			X=i;
 			break;
@@ -1607,25 +1658,25 @@
 	}
 	
-	int i=0;
-	while(i<=X){
-		if (dz [i] > dzMin *2){
+	int j=0;
+	while(j<=X){
+		if (dz[j] > dzMin*2.0+Dtol){
 
 				// _printf_("dz > dzMin * 2");
 				// split in two
-				cellsplit(&dz, n, i,.5);
-				cellsplit(&W, n, i,.5);
-				cellsplit(&m, n, i,.5);
-				cellsplit(&T, n, i,1.0);
-				cellsplit(&d, n, i,1.0);
-				cellsplit(&a, n, i,1.0);
-				cellsplit(&EI, n, i,1.0);
-				cellsplit(&EW, n, i,1.0);
-				cellsplit(&re, n, i,1.0);
-				cellsplit(&gdn, n, i,1.0);
-				cellsplit(&gsp, n, i,1.0);
+				cellsplit(&dz, n, j,.5);
+				cellsplit(&W, n, j,.5);
+				cellsplit(&m, n, j,.5);
+				cellsplit(&T, n, j,1.0);
+				cellsplit(&d, n, j,1.0);
+				cellsplit(&a, n, j,1.0);
+				cellsplit(&EI, n, j,.5);
+				cellsplit(&EW, n, j,.5);
+				cellsplit(&re, n, j,1.0);
+				cellsplit(&gdn, n, j,1.0);
+				cellsplit(&gsp, n, j,1.0);
 				n++;
 				X=X+1;
 		}
-		else i++;
+		else j++;
 	}
 
@@ -1633,12 +1684,12 @@
 	// WORKS FINE BUT HAS BEEN DISABLED FOR CONVIENCE OF MODEL OUTPUT
 	// INTERPRETATION
-	// // calculate total model depth
+	// calculate total model depth
 	Ztot = cellsum(dz,n);
     
-	if (Ztot < zMin){
+	if (Ztot < zMin-Dtol){
 		// printf("Total depth < zMin %f \n", Ztot);
 		// mass and energy to be added
 		mAdd = m[n-1]+W[n-1];
-		addE = T[n-1]*m[n-1]*CI;
+		addE = T[n-1]*m[n-1]*CI + W[n-1]*(LF+CtoK*CI);
         
 		// add a grid cell of the same size and temperature to the bottom
@@ -1652,4 +1703,6 @@
 		gdn_bot=gdn[n-1];
 		gsp_bot=gsp[n-1];
+		EI_bot=EI[n-1];
+		EW_bot=EW[n-1];
         
 		dz_add=dz_bot;
@@ -1664,14 +1717,16 @@
 		newcell(&gdn,gdn_bot,top,n);
 		newcell(&gsp,gsp_bot,top,n);
+		newcell(&EI,EI_bot,top,n);
+		newcell(&EW,EW_bot,top,n);
 		n=n+1;
 	}
-	else if (Ztot > zMax){
+	else if (Ztot > zMax+Dtol){
 		// printf("Total depth > zMax %f \n", Ztot);
 		// mass and energy loss
 		mAdd = -(m[n-1]+W[n-1]);
-		addE = -(T[n-1]*m[n-1]*CI);
+		addE = -(T[n-1]*m[n-1]*CI) - (W[n-1]*(LF+CtoK*CI));
 		dz_add=-(dz[n-1]);
         
-		// add a grid cell of the same size and temperature to the bottom
+		// remove a grid cell from the bottom
 		D_size=n-1;
 		D=xNew<int>(D_size);
@@ -1687,7 +1742,8 @@
 		celldelete(&gdn,n,D,D_size);
 		celldelete(&gsp,n,D,D_size);
+		celldelete(&EI,n,D,D_size);
+		celldelete(&EW,n,D,D_size);
 		n=D_size;
 		xDelete<int>(D);
-        
 	}
 
@@ -1703,9 +1759,9 @@
 
 	/*checks: */
-	for(int i=0;i<n;i++) if (W[i]<0) _error_("negative pore water generated in melt equations\n");
-	
+	for(int i=0;i<n;i++) if (W[i]<0.0-Wtol) _error_("negative pore water generated in melt equations\n");
+
 	/*only in forward mode! avoid round in AD mode as it is not differentiable: */
 	#ifndef _HAVE_ADOLC_
-	dm = round(mSum0 - mSum1 + mAdd);
+	dm = round((mSum0 - mSum1 + mAdd)*100.0)/100.0;
 	dE = round(sumE0 - sumE1 - sumER +  addE);
 	if (dm !=0  || dE !=0) _error_("mass or energy are not conserved in melt equations\n"
@@ -1746,7 +1802,7 @@
 
 } /*}}}*/ 
-void densification(IssmDouble* d,IssmDouble* dz, IssmDouble* T, IssmDouble* re, int denIdx, IssmDouble C, IssmDouble dt, IssmDouble Tmean,IssmDouble dIce, int m, int sid){ /*{{{*/
-
-	//// THIS NEEDS TO BE DOUBLE CHECKED AS THERE SEAMS TO BE LITTLE DENSIFICATION IN THE MODEL OUTOUT [MAYBE COMPATION IS COMPNSATED FOR BY TRACES OF SNOW???]
+void densification(IssmDouble** pd,IssmDouble** pdz, IssmDouble* T, IssmDouble* re, int denIdx, IssmDouble C, IssmDouble dt, IssmDouble Tmean, IssmDouble dIce, int m, int sid){ /*{{{*/
+
+	//// THIS NEEDS TO BE DOUBLE CHECKED AS THERE SEAMS TO BE LITTLE DENSIFICATION IN THE MODEL OUTOUT [MAYBE COMPACTION IS COMPENSATED FOR BY TRACES OF SNOW???]
 
 	//// FUNCTION INFO
@@ -1788,5 +1844,5 @@
 	//// MAIN FUNCTION
 	// specify constants
-	dt      = dt / 86400;  // convert from [s] to [d]
+	dt      = dt / dts;  // convert from [s] to [d]
 	// R     = 8.314        // gas constant [mol-1 K-1]
 	// Ec    = 60           // activation energy for self-diffusion of water
@@ -1795,7 +1851,17 @@
 
 	/*intermediary: */
-	IssmDouble c0,c1,H;
+	IssmDouble c0=0.0;
+	IssmDouble c1=0.0;
+	IssmDouble H=0.0;
+
+	/*output: */
+	IssmDouble* dz=NULL;
+	IssmDouble* d=NULL;
 	
 	if(VerboseSmb() && sid==0 && IssmComm::GetRank()==0)_printf0_("   densification module\n");
+
+	/*Recover pointers: */
+	dz=*pdz;
+	d=*pd;
 
 	// initial mass
@@ -1808,5 +1874,5 @@
 
 	IssmDouble* obp = xNew<IssmDouble>(m);
-	obp[0]=0;
+	obp[0]=0.0;
 	for(int i=1;i<m;i++)obp[i]=cumdz[i-1]*d[i-1];
 	
@@ -1819,11 +1885,11 @@
 		switch (denIdx){
 			case 1: // Herron and Langway (1980)
-				c0 = (11 * exp(-10160 / (T[i] * 8.314))) * C/1000;
-				c1 = (575 * exp(-21400 / (T[i]* 8.314))) * pow(C/1000,.5);
+				c0 = (11.0 * exp(-10160.0 / (T[i] * 8.314))) * C/1000.0;
+				c1 = (575.0 * exp(-21400.0 / (T[i]* 8.314))) * pow(C/1000.0,.5);
 				break;
 			case 2: // Arthern et al. (2010) [semi-emperical]
 				// common variable
 				// NOTE: Ec=60000, Eg=42400 (i.e. should be in J not kJ)
-				H = exp((-60000./(T[i] * 8.314)) + (42400./(Tmean * 8.314))) * (C * 9.81);
+				H = exp((-60000.0/(T[i] * 8.314)) + (42400.0/(Tmean * 8.314))) * (C * 9.81);
 				c0 = 0.07 * H;
 				c1 = 0.03 * H;
@@ -1833,5 +1899,5 @@
 
 				// common variable
-				H = exp((-60/(T[i] * 8.314))) * obp[i] / pow(re[i]/1000,2.0);
+				H = exp((-60.0/(T[i] * 8.314))) * obp[i] / pow(re[i]/1000.0,2.0);
 				c0 = 9.2e-9 * H;
 				c1 = 3.7e-9 * H;
@@ -1839,5 +1905,5 @@
 
 			case 4: // Li and Zwally (2004)
-				c0 = (C/dIce) * (139.21 - 0.542*Tmean)*8.36*pow(273.15 - T[i],-2.061);
+				c0 = (C/dIce) * (139.21 - 0.542*Tmean)*8.36*pow(CtoK - T[i],-2.061);
 				c1 = c0;
 				break;
@@ -1845,5 +1911,5 @@
 			case 5: // Helsen et al. (2008)
 				// common variable
-				c0 = (C/dIce) * (76.138 - 0.28965*Tmean)*8.36*pow(273.15 - T[i],-2.061);
+				c0 = (C/dIce) * (76.138 - 0.28965*Tmean)*8.36*pow(CtoK - T[i],-2.061);
 				c1 = c0;
 				break;
@@ -1851,11 +1917,11 @@
 
 		// new snow density
-		if(d[i] <= 550) d[i] = d[i] + (c0 * (dIce - d[i]) / 365 * dt);
-		else            d[i] = d[i] + (c1 * (dIce - d[i]) / 365 * dt);
+		if(d[i] <= 550.0+Dtol) d[i] = d[i] + (c0 * (dIce - d[i]) / 365.0 * dt);
+		else            d[i] = d[i] + (c1 * (dIce - d[i]) / 365.0 * dt);
 
 		//disp((num2str(nanmean(c0 .* (dIce - d(idx)) / 365 * dt))))
 
 		// do not allow densities to exceed the density of ice
-		if(d[i]>dIce)d[i]=dIce;
+		if(d[i] > dIce-Dtol) d[i]=dIce;
 
 		// calculate new grid cell length
@@ -1868,6 +1934,10 @@
 	xDelete<IssmDouble>(obp);
 
+	/*Assign output pointers:*/
+	*pdz=dz;
+	*pd=d;
+
 } /*}}}*/
-void turbulentFlux(IssmDouble* pshf, IssmDouble* plhf, IssmDouble* pEC, IssmDouble Ta, IssmDouble Ts, IssmDouble V, IssmDouble eAir, IssmDouble pAir, IssmDouble ds, IssmDouble Ws, IssmDouble Vz, IssmDouble Tz, int sid){ /*{{{*/
+void turbulentFlux(IssmDouble* pshf, IssmDouble* plhf, IssmDouble* pEC, IssmDouble Ta, IssmDouble Ts, IssmDouble V, IssmDouble eAir, IssmDouble pAir, IssmDouble ds, IssmDouble Ws, IssmDouble Vz, IssmDouble Tz, IssmDouble dIce, int sid){ /*{{{*/
 
 	//// TURBULENT HEAT FLUX
@@ -1892,35 +1962,33 @@
 	//   Tz: height above ground at which temperature (T) was sampled [m]
 
-	//// FUNCTION INITILIZATION 
-
-	// CA = 1005;                    // heat capacity of air (J kg-1 k-1)
-	// LF = 0.3345E6;                // latent heat of fusion(J kg-1)
-	// LV = 2.495E6;                 // latent heat of vaporization(J kg-1)
-	// dIce = 910;                   // density of ice [kg m-3]
-	
 	/*intermediary:*/
-	IssmDouble d_air;
-	IssmDouble Ri;
-	IssmDouble z0;
-	IssmDouble coef_M,coef_H;
-	IssmDouble An, C;
-	IssmDouble L, eS;
+	IssmDouble d_air=0.0;
+	IssmDouble Ri=0.0;
+	IssmDouble z0=0.0;
+	IssmDouble coef_M=0.0;
+	IssmDouble coef_H=0.0;
+	IssmDouble An=0.0;
+	IssmDouble C=0.0;
+	IssmDouble L=0.0;
+	IssmDouble eS=0.0;
 
 	/*output: */
-	IssmDouble shf, lhf, EC;
+	IssmDouble shf=0.0;
+	IssmDouble lhf=0.0;
+	IssmDouble EC=0.0;
 	
 	if(VerboseSmb() && sid==0 && IssmComm::GetRank()==0)_printf0_("   turbulentFlux module\n");
 
 	// calculated air density [kg/m3]
-	d_air = 0.029 * pAir /(8.314 * Ta);
+	d_air = 0.029 * pAir /(R * Ta);
 
 	//// Determine Surface Roughness
 	// Bougamont, 2006
 	// wind/temperature surface roughness height [m]
-	if (ds < 910 && Ws == 0) z0 = 0.00012;               // 0.12 mm for dry snow
-	else if (ds >= 910) z0 = 0.0032;                // 3.2 mm for ice 
+	if (ds < dIce-Dtol && fabs(Ws) < Wtol) z0 = 0.00012;               // 0.12 mm for dry snow
+	else if (ds >= dIce-Dtol) z0 = 0.0032;                // 3.2 mm for ice 
 	else z0 = 0.0013;                // 1.3 mm for wet snow
 
-	//// MoninObukhov Stability Correction
+	//// Monin-Obukhov Stability Correction
 	// Reference:
 	// Ohmura, A., 1982: Climate and Energy-Balance on the Arctic Tundra.
@@ -1928,22 +1996,27 @@
 
 	// if V = 0 goes to infinity therfore if V = 0 change
-	if(V< .01) V=.01;
+	if(V<0.01-Dtol)V=0.01;
 
 	// calculate the Bulk Richardson Number (Ri)
-	Ri = (2*9.81* (Vz - z0) * (Ta - Ts)) / ((Ta + Ts)* pow(V,2));
-
-	// calculate MoninObukhov stability factors 'coef_M' and 'coef_H'
-
+	Ri = (2.0*9.81* (Vz - z0) * (Ta - Ts)) / ((Ta + Ts)* pow(V,2));
+
+	// calculate Monin-Obukhov stability factors 'coef_M' and 'coef_H'
+	
 	// do not allow Ri to exceed 0.19
-	if(Ri>.19)Ri= 0.19;
-
-	// calculate momentum 'coef_M' stability factor
-	if (Ri > 0) coef_M = pow(1-5.2*Ri,-1); // if stable
-	else coef_M = pow(1-18*Ri,-0.25);
+	Ri = fmin(Ri, 0.19);
+
+	// calculate momentum 'coefM' stability factor
+	if (Ri > 0.0+Ttol){
+		// if stable
+		coef_M = 1.0/(1.0-5.2*Ri);
+	}
+	else {
+		coef_M =pow (1.0-18*Ri,-0.25);
+	}
 
 	// calculate heat/wind 'coef_H' stability factor
-	if (Ri < -0.03) coef_H = 1.3 * coef_M;
+	if (Ri <= -0.03+Ttol) coef_H = coef_M/1.3;
 	else coef_H = coef_M;
-		
+
 	//// Bulk-transfer coefficient
 	An =  pow(0.4,2) / pow(log(Tz/z0),2);     // Bulk-transfer coefficient
@@ -1952,30 +2025,30 @@
 	//// Sensible Heat
 	// calculate the sensible heat flux [W m-2](Patterson, 1998)
-	shf = C * 1005 * (Ta - Ts);
-
-	// adjust using MoninObukhov stability theory
+	shf = C * CA * (Ta - Ts);
+
+	// adjust using Monin-Obukhov stability theory
 	shf = shf / (coef_M * coef_H);
 
-	//// Latent Heat
-	// determine if snow pack is melting & calcualte surface vapour pressure
-	// over ice or liquid water
-	if (Ts >= 273.15){
-		L = 2.495E6;
+	// Latent Heat
+	// determine if snow pack is melting & calcualte surface vapour pressure over ice or liquid water
+	if (Ts >= CtoK-Ttol){
+		L = LV; //for liquid water at 273.15 k to vapor
+
+		//for liquid surface (assume liquid on surface when Ts == 0 deg C)
+		// Wright (1997), US Meteorological Handbook from Murphy and Koop, 2005 Appendix A
+		eS = 611.21 * exp(17.502 * (Ts - CtoK) / (240.97 + Ts - CtoK));
+	}
+	else{
+		L = LS; // latent heat of sublimation
 
 		// for an ice surface Murphy and Koop, 2005 [Equation 7]
-		eS = exp(9.550426 - 5723.265/Ts + 3.53068 * log(Ts)- 0.00728332 * Ts);
-	}
-	else{
-		L = 2.8295E6; // latent heat of sublimation
-		// for liquid surface (assume liquid on surface when Ts == 0 deg C)
-		// Wright (1997), US Meteorological Handbook from Murphy and Koop,
-		// 2005 Apendix A
-		eS = 611.21 * exp(17.502 * (Ts - 273.15) / (240.97 + Ts - 273.15));
-	}
+		eS = exp(9.550426 - 5723.265/Ts + 3.53068 * log(Ts) - 0.00728332 * Ts);
+	}
+
 
 	// Latent heat flux [W m-2]
 	lhf = C * L * (eAir - eS) * 0.622 / pAir;
 
-	// adjust using MoninObukhov stability theory (if lhf '+' then there is
+	// adjust using Monin-Obukhov stability theory (if lhf '+' then there is
 	// energy and mass gained at the surface, if '-' then there is mass and 
 	// energy loss at the surface. 
@@ -1983,5 +2056,5 @@
 
 	// mass loss (-)/acreation(+) due to evaporation/condensation [kg]
-	EC = lhf * 86400 / L;
+	EC = lhf * dts / L;
 
 	/*assign output poitners: */
Index: /issm/trunk/src/c/modules/SurfaceMassBalancex/SurfaceMassBalancex.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceMassBalancex/SurfaceMassBalancex.cpp	(revision 22757)
+++ /issm/trunk/src/c/modules/SurfaceMassBalancex/SurfaceMassBalancex.cpp	(revision 22758)
@@ -188,4 +188,5 @@
 
 	bool ismungsm;
+	bool issetpddfac;
 
 	IssmDouble *pdds    = NULL;
@@ -198,4 +199,7 @@
 	// Get ismungsm parameter
 	femmodel->parameters->FindParam(&ismungsm,SmbIsmungsmEnum);
+
+	// Get issetpddfac parameter
+	femmodel->parameters->FindParam(&issetpddfac,SmbIssetpddfacEnum);
 
 	/* initialize PDD (creation of a lookup table)*/
@@ -253,5 +257,5 @@
 	for(i=0;i<femmodel->elements->Size();i++){
 		element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
-		element->PositiveDegreeDay(pdds,pds,signorm,ismungsm);
+		element->PositiveDegreeDay(pdds,pds,signorm,ismungsm,issetpddfac);
 	}
 	/*free ressouces: */
@@ -271,12 +275,12 @@
 	IssmDouble  h = -1.54e-5;
 	IssmDouble  smb,smbref,anomaly,yts,z;
-    
-    /* Get constants */
-    femmodel->parameters->FindParam(&yts,ConstantsYtsEnum);
-    /*iomodel->FindConstant(&yts,"md.constants.yts");*/
-    /*this->parameters->FindParam(&yts,ConstantsYtsEnum);*/
-    /*Mathieu original*/
-    /*IssmDouble  smb,smbref,z;*/
-    
+
+	/* Get constants */
+	femmodel->parameters->FindParam(&yts,ConstantsYtsEnum);
+	/*iomodel->FindConstant(&yts,"md.constants.yts");*/
+	/*this->parameters->FindParam(&yts,ConstantsYtsEnum);*/
+	/*Mathieu original*/
+	/*IssmDouble  smb,smbref,z;*/
+
 	/*Loop over all the elements of this partition*/
 	for(int i=0;i<femmodel->elements->Size();i++){
@@ -298,16 +302,16 @@
 			anomaly = smblistref[v];
 
-            /* Henning edited acc. to Riannes equations*/
-            /* Set SMB maximum elevation, if dz = 0 -> z_critical = 1675 */
-            z_critical = z_critical + dz;
-            
-            /* Calculate smb acc. to the surface elevation z */
-            if(z<z_critical){
+			/* Henning edited acc. to Riannes equations*/
+			/* Set SMB maximum elevation, if dz = 0 -> z_critical = 1675 */
+			z_critical = z_critical + dz;
+
+			/* Calculate smb acc. to the surface elevation z */
+			if(z<z_critical){
 				smb = a + b*z + c;
 			}
 			else{
-			  smb = (a + b*z)*(f + g*(z-z_critical) + h*(z-z_critical)*(z-z_critical)) + c;
-			}
-            
+				smb = (a + b*z)*(f + g*(z-z_critical) + h*(z-z_critical)*(z-z_critical)) + c;
+			}
+
 			/* Compute smb including anomaly,
 				correct for number of seconds in a year [s/yr]*/
Index: /issm/trunk/src/c/modules/SurfaceMassBalancex/SurfaceMassBalancex.h
===================================================================
--- /issm/trunk/src/c/modules/SurfaceMassBalancex/SurfaceMassBalancex.h	(revision 22757)
+++ /issm/trunk/src/c/modules/SurfaceMassBalancex/SurfaceMassBalancex.h	(revision 22758)
@@ -24,11 +24,11 @@
 void       GembgridInitialize(IssmDouble** pdz, int* psize, IssmDouble zTop, IssmDouble dzTop, IssmDouble zMax, IssmDouble zY); 
 IssmDouble Marbouty(IssmDouble T, IssmDouble d, IssmDouble dT);
-void grainGrowth(IssmDouble* pre, IssmDouble* pgdn, IssmDouble* pgsp, IssmDouble* T,IssmDouble* dz,IssmDouble* d, IssmDouble* W,IssmDouble smb_dt,int m,int aIdx, int sid);
-void albedo(IssmDouble* a,int aIdx, IssmDouble* re, IssmDouble* d, IssmDouble cldFrac, IssmDouble aIce, IssmDouble aSnow, IssmDouble* T, IssmDouble* W, IssmDouble P, IssmDouble EC, IssmDouble t0wet, IssmDouble t0dry, IssmDouble K, IssmDouble dt,int m, int sid);
-void shortwave(IssmDouble** pswf, int swIdx, int aIdx, IssmDouble dsw, IssmDouble as, IssmDouble* d, IssmDouble* dz, IssmDouble* re, int m, int sid);
-void thermo(IssmDouble* pEC, IssmDouble* T, IssmDouble* dz, IssmDouble* d, IssmDouble* swf, IssmDouble dlw, IssmDouble Ta, IssmDouble V, IssmDouble eAir, IssmDouble pAir, IssmDouble Ws, IssmDouble dt0, int m, IssmDouble Vz, IssmDouble Tz, int sid);
-void accumulation(IssmDouble** pT, IssmDouble** pdz, IssmDouble** pd, IssmDouble** pW, IssmDouble** pa, IssmDouble** pre, IssmDouble** pgdn, IssmDouble** pgsp, int* pm, IssmDouble Ta, IssmDouble P, IssmDouble dzMin, IssmDouble aSnow, int sid); 
-void melt(IssmDouble* pM, IssmDouble* pR, IssmDouble* pmAdd, IssmDouble* pdz_add, IssmDouble** pT, IssmDouble** pd, IssmDouble** pdz, IssmDouble** pW, IssmDouble** pa, IssmDouble** pre, IssmDouble** pgdn, IssmDouble** pgsp, int* pn, IssmDouble dzMin, IssmDouble zMax, IssmDouble zMin, IssmDouble zTop, int sid);
-void densification(IssmDouble* d,IssmDouble* dz, IssmDouble* T, IssmDouble* re, int denIdx, IssmDouble C, IssmDouble dt, IssmDouble Tmean,IssmDouble rho_ice,int m, int sid);
-void turbulentFlux(IssmDouble* pshf, IssmDouble* plhf, IssmDouble* pEC, IssmDouble Ta, IssmDouble Ts, IssmDouble V, IssmDouble eAir, IssmDouble pAir, IssmDouble ds, IssmDouble Ws, IssmDouble Vz, IssmDouble Tz, int sid);
+void grainGrowth(IssmDouble** pre, IssmDouble** pgdn, IssmDouble** pgsp, IssmDouble* T,IssmDouble* dz,IssmDouble* d, IssmDouble* W,IssmDouble smb_dt,int m,int aIdx, int sid);
+void albedo(IssmDouble** a,int aIdx, IssmDouble* re, IssmDouble* d, IssmDouble cldFrac, IssmDouble aIce, IssmDouble aSnow, IssmDouble aValue, IssmDouble adThresh, IssmDouble* T, IssmDouble* W, IssmDouble P, IssmDouble EC, IssmDouble t0wet, IssmDouble t0dry, IssmDouble K, IssmDouble dt, IssmDouble dIce, int m, int sid);
+void shortwave(IssmDouble** pswf, int swIdx, int aIdx, IssmDouble dsw, IssmDouble as, IssmDouble* d, IssmDouble* dz, IssmDouble* re, IssmDouble dIce, int m, int sid);
+void thermo(IssmDouble* pEC, IssmDouble** T, IssmDouble* dz, IssmDouble* d, IssmDouble* swf, IssmDouble dlw, IssmDouble Ta, IssmDouble V, IssmDouble eAir, IssmDouble pAir, IssmDouble teValue, IssmDouble Ws, IssmDouble dt0, int m, IssmDouble Vz, IssmDouble Tz, IssmDouble thermo_scaling, IssmDouble dIce, int sid);
+void accumulation(IssmDouble** pT, IssmDouble** pdz, IssmDouble** pd, IssmDouble** pW, IssmDouble** pa, IssmDouble** pre, IssmDouble** pgdn, IssmDouble** pgsp, int* pm, int aIdx,IssmDouble Ta, IssmDouble P, IssmDouble dzMin, IssmDouble aSnow, IssmDouble dIce, int sid); 
+void melt(IssmDouble* pM, IssmDouble* pR, IssmDouble* pmAdd, IssmDouble* pdz_add, IssmDouble** pT, IssmDouble** pd, IssmDouble** pdz, IssmDouble** pW, IssmDouble** pa, IssmDouble** pre, IssmDouble** pgdn, IssmDouble** pgsp, int* pn, IssmDouble dzMin, IssmDouble zMax, IssmDouble zMin, IssmDouble zTop, IssmDouble dIce, int sid);
+void densification(IssmDouble** pd,IssmDouble** pdz, IssmDouble* T, IssmDouble* re, int denIdx, IssmDouble C, IssmDouble dt, IssmDouble Tmean, IssmDouble dIce, int m, int sid);
+void turbulentFlux(IssmDouble* pshf, IssmDouble* plhf, IssmDouble* pEC, IssmDouble Ta, IssmDouble Ts, IssmDouble V, IssmDouble eAir, IssmDouble pAir, IssmDouble ds, IssmDouble Ws, IssmDouble Vz, IssmDouble Tz, IssmDouble dIce, int sid);
 #endif  /* _SurfaceMassBalancex_H*/
Index: /issm/trunk/src/c/modules/Trianglex/Trianglex.cpp
===================================================================
--- /issm/trunk/src/c/modules/Trianglex/Trianglex.cpp	(revision 22758)
+++ /issm/trunk/src/c/modules/Trianglex/Trianglex.cpp	(revision 22758)
@@ -0,0 +1,201 @@
+/*!\file Trianglex
+ * \brief: x code for Triangle mesher
+ */
+
+/*Header files: {{{*/
+#include "./Trianglex.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+/*ANSI_DECLARATORS needed to call triangle library: */
+#if defined(_HAVE_TRIANGLE_)
+	#ifndef ANSI_DECLARATORS
+	#define ANSI_DECLARATORS
+	#endif
+	#include "triangle.h"
+	#undef ANSI_DECLARATORS
+#endif
+/*}}}*/
+
+void Trianglex(int** pindex,IssmPDouble** px,IssmPDouble** py,int** psegments,int** psegmentmarkerlist,int* pnels,int* pnods, int* pnsegs,Contours* domain,Contours* rifts,double area){
+
+#if !defined(_HAVE_TRIANGLE_)
+	_error_("triangle has not been installed");
+#else
+	/*indexing: */
+	int i,j;
+
+	/*output: */
+	int    *index             = NULL;
+	double *x                 = NULL;
+	double *y                 = NULL;
+	int    *segments          = NULL;
+	int    *segmentmarkerlist = NULL;
+
+	/*intermediary: */
+	int counter,counter2,backcounter;
+	Contour<IssmPDouble> *contour = NULL;
+
+	/* Triangle structures needed to call Triangle library routines: */
+	struct triangulateio in,out;
+	char   options[256];
+
+	/*Create initial triangulation to call triangulate(). First number of points:*/
+	in.numberofpoints=0;
+	for (i=0;i<domain->Size();i++){
+		contour=(Contour<IssmPDouble>*)domain->GetObjectByOffset(i);
+		in.numberofpoints+=contour->nods-1;
+	}
+	for (i=0;i<rifts->Size();i++){
+		contour=(Contour<IssmPDouble>*)rifts->GetObjectByOffset(i);
+		in.numberofpoints+=contour->nods;
+	}
+
+	/*number of point attributes: */
+	in.numberofpointattributes=1;
+
+	/*fill in the point list: */
+	in.pointlist = xNew<REAL>(in.numberofpoints*2);
+
+	counter=0;
+	for (i=0;i<domain->Size();i++){
+		contour=(Contour<IssmPDouble>*)domain->GetObjectByOffset(i);
+		for (j=0;j<contour->nods-1;j++){
+			in.pointlist[2*counter+0]=contour->x[j];
+			in.pointlist[2*counter+1]=contour->y[j];
+			counter++;
+		}
+	}
+	for (i=0;i<rifts->Size();i++){
+		contour=(Contour<IssmPDouble>*)rifts->GetObjectByOffset(i);
+		for (j=0;j<contour->nods;j++){
+			in.pointlist[2*counter+0]=contour->x[j];
+			in.pointlist[2*counter+1]=contour->y[j];
+			counter++;
+		}
+	}
+
+	/*fill in the point attribute list: */
+	in.pointattributelist = xNew<REAL>(in.numberofpoints*in.numberofpointattributes);
+	for (i=0;i<in.numberofpoints;i++) in.pointattributelist[i] = 0.0;
+
+	/*fill in the point marker list: */
+	in.pointmarkerlist = xNew<int>(in.numberofpoints);
+	for(i=0;i<in.numberofpoints;i++) in.pointmarkerlist[i] = 0;
+
+	/*Build segments. First figure out number of segments: holes and closed outlines have as many segments as vertices: */
+	in.numberofsegments=0;
+	for (i=0;i<domain->Size();i++){
+		contour=(Contour<IssmPDouble>*)domain->GetObjectByOffset(i);
+		in.numberofsegments+=contour->nods-1;
+	}
+	for(i=0;i<rifts->Size();i++){
+		contour=(Contour<IssmPDouble>*)rifts->GetObjectByOffset(i);
+		/*for rifts, we have one less segment as we have vertices*/
+		in.numberofsegments+=contour->nods-1;
+	}
+
+	in.segmentlist = xNew<int>(in.numberofsegments*2);
+	in.segmentmarkerlist = xNewZeroInit<int>(in.numberofsegments);
+	counter=0;
+	backcounter=0;
+	for (i=0;i<domain->Size();i++){
+		contour=(Contour<IssmPDouble>*)domain->GetObjectByOffset(i);
+		for (j=0;j<contour->nods-2;j++){
+			in.segmentlist[2*counter+0]=counter;
+			in.segmentlist[2*counter+1]=counter+1;
+			in.segmentmarkerlist[counter]=0;
+			counter++;
+		}
+		/*Close this profile: */
+		 in.segmentlist[2*counter+0]=counter;
+		 in.segmentlist[2*counter+1]=backcounter;
+		 in.segmentmarkerlist[counter]=0;
+		 counter++;
+		 backcounter=counter;
+	}
+	counter2=counter;
+	for (i=0;i<rifts->Size();i++){
+		contour=(Contour<IssmPDouble>*)rifts->GetObjectByOffset(i);
+		for (j=0;j<(contour->nods-1);j++){
+			in.segmentlist[2*counter2+0]=counter;
+			in.segmentlist[2*counter2+1]=counter+1;
+			in.segmentmarkerlist[counter2]=2+i;
+			counter2++;
+			counter++;
+		}
+		counter++;
+	}
+
+	/*Build regions: */
+	in.numberofregions = 0;
+
+	/*Build holes: */
+	in.numberofholes = domain->Size()-1; /*everything is a hole, but for the first profile.*/
+	if(in.numberofholes){
+		in.holelist = xNew<REAL>(in.numberofholes*2);
+		for (i=0;i<domain->Size()-1;i++){
+			contour=(Contour<IssmPDouble>*)domain->GetObjectByOffset(i+1);
+			GridInsideHole(&in.holelist[2*i+0],&in.holelist[2*i+1],contour->nods-1,contour->x,contour->y);
+		}
+	}
+
+	/* Make necessary initializations so that Triangle can return a triangulation in `out': */
+	out.pointlist             = (REAL*)NULL;
+	out.pointattributelist    = (REAL*)NULL;
+	out.pointmarkerlist       = (int *)NULL;
+	out.trianglelist          = (int *)NULL;
+	out.triangleattributelist = (REAL*)NULL;
+	out.neighborlist          = (int *)NULL;
+	out.segmentlist           = (int *)NULL;
+	out.segmentmarkerlist     = (int *)NULL;
+	out.edgelist              = (int *)NULL;
+	out.edgemarkerlist        = (int *)NULL;
+
+	/* Triangulate the points:.  Switches are chosen to read and write a  */
+	/*   PSLG (p), preserve the convex hull (c), number everything from  */
+	/*   zero (z), assign a regional attribute to each element (A), and  */
+	/*   produce an edge list (e), a Voronoi diagram (v), and a triangle */
+	/*   neighbor list (n).                                              */
+	sprintf(options,"%s%lf","pQzDq30ia",area); /*replace V by Q to quiet down the logging*/
+	triangulate(options, &in, &out, NULL);
+	/*report(&out, 0, 1, 1, 1, 1, 0);*/
+
+	/*Allocate index, x and y: */
+	index=xNew<int>(3*out.numberoftriangles);
+	x=xNew<double>(out.numberofpoints);
+	y=xNew<double>(out.numberofpoints);
+	segments=xNew<int>(3*out.numberofsegments);
+	segmentmarkerlist=xNew<int>(out.numberofsegments);
+
+	for (i = 0; i< out.numberoftriangles; i++) {
+		for (j = 0; j < out.numberofcorners; j++) {
+			index[3*i+j]=(int)out.trianglelist[i*out.numberofcorners+j]+1;
+		}
+	}
+	for (i = 0; i< out.numberofpoints; i++){
+		x[i]=(double)out.pointlist[i*2+0];
+		y[i]=(double)out.pointlist[i*2+1];
+	}
+	for (i = 0; i<out.numberofsegments;i++){
+		segments[3*i+0]=(int)out.segmentlist[i*2+0]+1;
+		segments[3*i+1]=(int)out.segmentlist[i*2+1]+1;
+		segmentmarkerlist[i]=(int)out.segmentmarkerlist[i];
+	}
+
+	/*Associate elements with segments: */
+	AssociateSegmentToElement(&segments,out.numberofsegments,index,out.numberoftriangles);
+
+	/*Order segments so that their normals point outside the domain: */
+	OrderSegments(&segments,out.numberofsegments, index,out.numberoftriangles);
+
+	/*Output : */
+	*pindex=index;
+	*px=x;
+	*py=y;
+	*psegments=segments;
+	*psegmentmarkerlist=segmentmarkerlist;
+	*pnels=out.numberoftriangles;
+	*pnods=out.numberofpoints;
+	*pnsegs=out.numberofsegments;
+#endif
+}
Index: /issm/trunk/src/c/modules/Trianglex/Trianglex.h
===================================================================
--- /issm/trunk/src/c/modules/Trianglex/Trianglex.h	(revision 22758)
+++ /issm/trunk/src/c/modules/Trianglex/Trianglex.h	(revision 22758)
@@ -0,0 +1,13 @@
+/*!\file:  Trianglex.h
+ * \brief header file for Trianglex module
+ */ 
+
+#ifndef _TRIANGLEX_H_
+#define _TRIANGLEX_H_
+
+#include <string.h>
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void Trianglex(int** pindex,IssmPDouble** px,IssmPDouble** py,int** psegments,int** psegmentmarkerlist,int* pnels,int* pnods, int* pnseg,Contours* domain,Contours* rifts,double area);
+#endif  /* _TRIANGLEX_H */
Index: /issm/trunk/src/c/modules/modules.h
===================================================================
--- /issm/trunk/src/c/modules/modules.h	(revision 22757)
+++ /issm/trunk/src/c/modules/modules.h	(revision 22758)
@@ -6,10 +6,13 @@
 #define _ISSM_MODULES_H_
 
+#ifdef _HAVE_BAMG_
+#include "./Bamgx/Bamgx.h"
+#include "./BamgConvertMeshx/BamgConvertMeshx.h"
+#include "./BamgTriangulatex/BamgTriangulatex.h"
+#endif
+
 /*Modules: */
 #include "./AllocateSystemMatricesx/AllocateSystemMatricesx.h"
 #include "./AverageOntoPartitionx/AverageOntoPartitionx.h"
-#include "./Bamgx/Bamgx.h"
-#include "./BamgConvertMeshx/BamgConvertMeshx.h"
-#include "./BamgTriangulatex/BamgTriangulatex.h"
 #include "./Calvingx/Calvingx.h"
 #include "./Chacox/Chacox.h"
@@ -30,4 +33,5 @@
 #include "./GetVectorFromControlInputsx/GetVectorFromControlInputsx.h"
 #include "./GiaDeflectionCorex/GiaDeflectionCorex.h"
+#include "./FourierLoveCorex/FourierLoveCorex.h"
 #include "./SetControlInputsFromVectorx/SetControlInputsFromVectorx.h"
 #include "./SetActiveNodesLSMx/SetActiveNodesLSMx.h"
@@ -56,4 +60,5 @@
 #include "./Krigingx/Krigingx.h"
 #include "./FloatingiceMeltingRatex/FloatingiceMeltingRatex.h"
+#include "./FloatingiceMeltingRatePicox/FloatingiceMeltingRatePicox.h"
 #include "./Mergesolutionfromftogx/Mergesolutionfromftogx.h"
 #include "./MeshPartitionx/MeshPartitionx.h"
@@ -87,6 +92,6 @@
 #include "./SpcNodesx/SpcNodesx.h"
 #include "./SurfaceAreax/SurfaceAreax.h"
-#include "./TriMeshx/TriMeshx.h"
-#include "./TriMeshProcessRiftsx/TriMeshProcessRiftsx.h"
+#include "./Trianglex/Trianglex.h"
+#include "./ProcessRiftsx/ProcessRiftsx.h"
 #include "./ThicknessAbsMisfitx/ThicknessAbsMisfitx.h"
 #include "./ThicknessAlongGradientx/ThicknessAlongGradientx.h"
Index: sm/trunk/src/c/shared/Bamg/BinaryRand.h
===================================================================
--- /issm/trunk/src/c/shared/Bamg/BinaryRand.h	(revision 22757)
+++ 	(revision )
@@ -1,18 +1,0 @@
-#ifndef _BINARYRAND_H_
-#define _BINARYRAND_H_
-
-#include <cstdlib>
-
-/*Return 1 or 0 randomly*/
-inline int BinaryRand(){
-	#ifdef RAND_MAX
-		/*RAND_MAX is defined by stdlib.h and is usually 32767*/
-		const long HalfRandMax = RAND_MAX/2;
-		return rand() < HalfRandMax;
-	#else
-		/*For sun machines, RAND_MAX is not defined, use 2^24*/
-		return rand() & 16384;
-	#endif
-} 
-
-#endif
Index: /issm/trunk/src/c/shared/Bamg/HeapSort.h
===================================================================
--- /issm/trunk/src/c/shared/Bamg/HeapSort.h	(revision 22757)
+++ /issm/trunk/src/c/shared/Bamg/HeapSort.h	(revision 22758)
@@ -60,5 +60,6 @@
 	c--; //the array must starts at 1 and not 0 
 	order = new int[n];
-	for(i=0;i<n;i++) order[i]=i+1;
+	for(i=0;i<n;i++) order[i]=i;
+	order--;
 
 	/*Sorting algorithm*/
@@ -81,6 +82,12 @@
 			if  (j>r) {c[i]=crit;order[i]=pos;break;}
 			if ((j<r) && (c[j] < c[j+1]))j++;
-			if (crit < c[j]) {c[i]=c[j];order[i]=order[j];}
-			else{c[i]=crit;order[i]=pos;break;}
+			if (crit < c[j]){
+				c[i]=c[j];
+				order[i]=order[j];
+			}
+			else{
+				c[i]=crit;order[i]=pos;
+				break;
+			}
 		}
 	}
Index: /issm/trunk/src/c/shared/Bamg/shared.h
===================================================================
--- /issm/trunk/src/c/shared/Bamg/shared.h	(revision 22757)
+++ /issm/trunk/src/c/shared/Bamg/shared.h	(revision 22758)
@@ -8,5 +8,4 @@
 #include "Abs.h"
 #include "BigPrimeNumber.h"
-#include "BinaryRand.h"
 #include "Exchange.h"
 #include "extrema.h"
Index: /issm/trunk/src/c/shared/Elements/ComputeD18OTemperaturePrecipitationFromPD.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/ComputeD18OTemperaturePrecipitationFromPD.cpp	(revision 22757)
+++ /issm/trunk/src/c/shared/Elements/ComputeD18OTemperaturePrecipitationFromPD.cpp	(revision 22758)
@@ -7,6 +7,6 @@
 #include "../Numerics/numerics.h"
 
-void ComputeD18OTemperaturePrecipitationFromPD(IssmDouble d018,IssmDouble dpermil,IssmDouble f,
-					       IssmDouble* PrecipitationPresentday,IssmDouble* TemperaturePresentday,
+void ComputeD18OTemperaturePrecipitationFromPD(IssmDouble d018,IssmDouble dpermil,bool isTemperatureScaled,
+			             IssmDouble f, IssmDouble* PrecipitationPresentday,IssmDouble* TemperaturePresentday,
 					       IssmDouble* monthlytemperaturesout, IssmDouble* monthlyprecout){
   
@@ -22,5 +22,7 @@
   for (int imonth = 0; imonth<12; imonth++){
     
-    monthlytemperaturestmp[imonth] = TemperaturePresentday[imonth] + deltaTemp;
+	 if (isTemperatureScaled)monthlytemperaturestmp[imonth] = TemperaturePresentday[imonth] + deltaTemp;
+	 else monthlytemperaturestmp[imonth] = TemperaturePresentday[imonth];
+
     monthlyprectmp[imonth] = PrecipitationPresentday[imonth]*exp((f/dpermil)*deltaTemp);
     
Index: /issm/trunk/src/c/shared/Elements/EstarComponents.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/EstarComponents.cpp	(revision 22757)
+++ /issm/trunk/src/c/shared/Elements/EstarComponents.cpp	(revision 22758)
@@ -3,10 +3,10 @@
 #include "../Exceptions/exceptions.h"
 #include "./elements.h"
-void EstarStrainrateQuantities(IssmDouble *pepseff, IssmDouble *pepsprime_norm, IssmDouble vx,IssmDouble vy,IssmDouble vz,IssmDouble vmag,IssmDouble* dvx,IssmDouble* dvy,IssmDouble* dvz,IssmDouble* dvmag){/*{{{*/
+void EstarStrainrateQuantities(IssmDouble *pepsprime_norm, IssmDouble vx,IssmDouble vy,IssmDouble vz,IssmDouble vmag,IssmDouble* dvx,IssmDouble* dvy,IssmDouble* dvz,IssmDouble* dvmag){/*{{{*/
 
 	/*Intermediaries*/
 	IssmDouble omega[3];
 	IssmDouble nrsp[3],nrsp_norm;
-	IssmDouble eps[3][3],epseff;
+	IssmDouble eps[3][3];
 	IssmDouble epsprime[3],epsprime_norm;
 
@@ -36,9 +36,4 @@
 	eps[1][0] = .5*(dvx[1]+dvy[0]); eps[1][1] = dvy[1];             eps[1][2] = .5*(dvy[2]+dvz[1]);
 	eps[2][0] = .5*(dvx[2]+dvz[0]); eps[2][1] = .5*(dvy[2]+dvz[1]); eps[2][2] = dvz[2];
-
-	/*effective strain rate*/
-	epseff = 0.;
-	/* eps_eff^2 = exx^2 + eyy^2 + exy^2 + exz^2 + eyz^2 + exx*eyy */
-	epseff = sqrt(eps[0][0]*eps[0][0] + eps[1][1]*eps[1][1] + eps[0][1]*eps[0][1] +  eps[0][2]*eps[0][2] + eps[1][2]*eps[1][2] + eps[0][0]*eps[1][1]);
 
 	/*Compute the shear strain rate on the non rotating shear plane*/
@@ -73,5 +68,4 @@
 	
 	/*Assign output pointers*/
-	*pepseff=epseff;
 	*pepsprime_norm=epsprime_norm;
 }/*}}}*/
Index: /issm/trunk/src/c/shared/Elements/PddSurfaceMassBalance.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/PddSurfaceMassBalance.cpp	(revision 22757)
+++ /issm/trunk/src/c/shared/Elements/PddSurfaceMassBalance.cpp	(revision 22758)
@@ -4,4 +4,5 @@
  */
 
+#include "../io/io.h"
 #include "./elements.h"
 #include "../Numerics/numerics.h"
@@ -11,5 +12,5 @@
 				 IssmDouble signorm, IssmDouble yts, IssmDouble h, IssmDouble s, IssmDouble desfac,
 				 IssmDouble s0t,IssmDouble s0p, IssmDouble rlaps,IssmDouble rlapslgm,
-				 IssmDouble TdiffTime,IssmDouble sealevTime,
+				 IssmDouble TdiffTime,IssmDouble sealevTime, IssmDouble pddsnowfac,IssmDouble pddicefac,
 				 IssmDouble rho_water,IssmDouble rho_ice){
 
@@ -67,4 +68,6 @@
   IssmDouble fsupT=0.5,  fsupndd=0.5;  // Tsurf mode factors for supice
   IssmDouble pddtj, hmx2;
+  IssmDouble pddsnowfac0=4.3, pddicefac0=8.3;
+  IssmDouble snowfac, icefac;
 
   sconv=(rho_water/rho_ice)/12.; //rhow_rain/rhoi / 12 months
@@ -128,17 +131,36 @@
   prect = qmp;     // total precipitation during 1 year taking into account des. ef.
   Tsum=Tsum/3;
+
+  snowfac=pddsnowfac0;
+  icefac=pddicefac0;
+  if (pddsnowfac>=0) {
+	  if (pddsnowfac<1.65) {
+		  _printf0_("WARNING: Pdd snow factor input, " << pddsnowfac << ", results in a negative value. It will be ignored. \n");
+	  }
+	  else{
+		snowfac=pddsnowfac;
+	  }
+  }
+  if (pddicefac>=0) {
+	  if (pddicefac>17.22) {
+		  _printf0_("WARNING: Pdd ice factor input, " << pddsnowfac << ", results in a negative value. It will be ignored. \n");
+	  }
+	  else{
+	    icefac=pddicefac;
+	  }
+  }
   
   /***** determine PDD factors *****/
   if(Tsum< -1.) {
-    snwmf=2.65*0.001;   //  ablation factor for snow per positive degree day.*0.001 to go from mm to m/ppd
+    snwmf=(2.65+snowfac-pddsnowfac0)*0.001;   //  ablation factor for snow per positive degree day.*0.001 to go from mm to m/ppd
     smf=17.22*0.001;    //  ablation factor for ice per pdd (Braithwaite 1995 from tarasov 2002)
   } 
   else if(Tsum< 10){
-    snwmf = (0.15*Tsum + 2.8)*0.001;
-    smf = (0.0067*pow((10.-Tsum),3) + 8.3)*0.001;
+    snwmf = (0.15*(Tsum+1) + (2.65+snowfac-pddsnowfac0))*0.001;
+    smf = (((icefac-pddicefac0)/(Tsum+1))*pow((10.-Tsum),3) + pddicefac0)*0.001;
   }
   else{
-    snwmf=4.3*0.001;
-    smf=8.3*0.001;
+    snwmf=snowfac*0.001;
+    smf=icefac*0.001;
   }
   snwmf=0.95*snwmf;
Index: /issm/trunk/src/c/shared/Elements/elements.h
===================================================================
--- /issm/trunk/src/c/shared/Elements/elements.h	(revision 22757)
+++ /issm/trunk/src/c/shared/Elements/elements.h	(revision 22758)
@@ -17,10 +17,10 @@
 IssmDouble EstarLambdaS(IssmDouble epseff, IssmDouble epsprime_norm);
 void EstarOmega(IssmDouble* omega,IssmDouble vx,IssmDouble vy,IssmDouble vz,IssmDouble vmag,IssmDouble* dvx,IssmDouble* dvy,IssmDouble* dvz, IssmDouble* dvmag);
-void EstarStrainrateQuantities(IssmDouble *pepseff, IssmDouble *pepsprime_norm, IssmDouble vx,IssmDouble vy,IssmDouble vz,IssmDouble vmag,IssmDouble* dvx,IssmDouble* dvy,IssmDouble* dvz,IssmDouble* dvmag);
+void EstarStrainrateQuantities(IssmDouble *pepsprime_norm, IssmDouble vx,IssmDouble vy,IssmDouble vz,IssmDouble vmag,IssmDouble* dvx,IssmDouble* dvy,IssmDouble* dvz,IssmDouble* dvmag);
 IssmDouble PddSurfaceMassBalance(IssmDouble* monthlytemperatures,  IssmDouble* monthlyprec,
 				 IssmDouble* pdds, IssmDouble* pds, IssmDouble* melt, IssmDouble* accu, IssmDouble signorm, 
 				 IssmDouble yts, IssmDouble h, IssmDouble s, IssmDouble desfac,IssmDouble s0t,
 				 IssmDouble s0p, IssmDouble rlaps, IssmDouble rlapslgm,
-				 IssmDouble TdiffTime,IssmDouble sealevTime,
+				 IssmDouble TdiffTime,IssmDouble sealevTime,IssmDouble pddsnowfac,IssmDouble pddicefac,
 				 IssmDouble rho_water, IssmDouble rho_ice);
 void ComputeDelta18oTemperaturePrecipitation(IssmDouble Delta18oSurfacePresent, IssmDouble Delta18oSurfaceLgm, IssmDouble Delta18oSurfaceTime,
@@ -33,6 +33,6 @@
 					   IssmDouble* TemperaturesLgm, IssmDouble* TemperaturesPresentday, 
 					   IssmDouble* monthlytemperaturesout, IssmDouble* monthlyprecout);
-void ComputeD18OTemperaturePrecipitationFromPD(IssmDouble d018,IssmDouble dpermil,IssmDouble f,
-					       IssmDouble* PrecipitationPresentday,IssmDouble* TemperaturePresentday,
+void ComputeD18OTemperaturePrecipitationFromPD(IssmDouble d018,IssmDouble dpermil,bool isTemperatureScaled,
+			             IssmDouble f, IssmDouble* PrecipitationPresentday,IssmDouble* TemperaturePresentday,
 					       IssmDouble* monthlytemperaturesout, IssmDouble* monthlyprecout);  
 IssmDouble DrainageFunctionWaterfraction(IssmDouble waterfraction, IssmDouble dt=0.);
Index: /issm/trunk/src/c/shared/Enum/EnumDefinitions.h
===================================================================
--- /issm/trunk/src/c/shared/Enum/EnumDefinitions.h	(revision 22757)
+++ /issm/trunk/src/c/shared/Enum/EnumDefinitions.h	(revision 22758)
@@ -8,545 +8,562 @@
 
 enum definitions{
-	FemModelEnum,
 	ParametersSTARTEnum,
-	/*Parameters {{{*/
+	/*Parameters{{{*/
 	AdolcParamEnum,
-	FSSolverEnum,
+	AmrDeviatoricErrorGroupThresholdEnum,
+	AmrDeviatoricErrorMaximumEnum,
+	AmrDeviatoricErrorResolutionEnum,
+	AmrDeviatoricErrorThresholdEnum,
+	AmrErrEnum,
+	AmrFieldEnum,
+	AmrGradationEnum,
+	AmrGroundingLineDistanceEnum,
+	AmrGroundingLineResolutionEnum,
+	AmrHmaxEnum,
+	AmrHminEnum,
+	AmrIceFrontDistanceEnum,
+	AmrIceFrontResolutionEnum,
+	AmrKeepMetricEnum,
+	AmrLagEnum,
+	AmrLevelMaxEnum,
+	AmrRestartEnum,
+	AmrThicknessErrorGroupThresholdEnum,
+	AmrThicknessErrorMaximumEnum,
+	AmrThicknessErrorResolutionEnum,
+	AmrThicknessErrorThresholdEnum,
+	AmrTypeEnum,
+	AnalysisCounterEnum,
+	AnalysisTypeEnum,
+	AugmentedLagrangianREnum,
+	AugmentedLagrangianRholambdaEnum,
+	AugmentedLagrangianRhopEnum,
+	AugmentedLagrangianRlambdaEnum,
+	AugmentedLagrangianThetaEnum,
+	AutodiffCbufsizeEnum,
+	AutodiffDependentObjectsEnum,
+	AutodiffDriverEnum,
+	AutodiffFosForwardIndexEnum,
+	AutodiffFosReverseIndexEnum,
+	AutodiffFovForwardIndicesEnum,
+	AutodiffGcTriggerMaxSizeEnum,
+	AutodiffGcTriggerRatioEnum,
+	AutodiffIsautodiffEnum,
+	AutodiffLbufsizeEnum,
+	AutodiffNumDependentsEnum,
+	AutodiffNumIndependentsEnum,
+	AutodiffObufsizeEnum,
+	AutodiffTbufsizeEnum,
+	AutodiffXpEnum,
+	BalancethicknessStabilizationEnum,
+	BasalforcingsBottomplumedepthEnum,
+	BasalforcingsCrustthicknessEnum,
+	BasalforcingsDeepwaterElevationEnum,
+	BasalforcingsDeepwaterMeltingRateEnum,
+	BasalforcingsDtbgEnum,
+	BasalforcingsEnum,
+	BasalforcingsLowercrustheatEnum,
+	BasalforcingsMantleconductivityEnum,
+	BasalforcingsMeltrateFactorEnum,
+	BasalforcingsNusseltEnum,
+	BasalforcingsPicoAverageOverturningEnum,
+	BasalforcingsPicoAverageSalinityEnum,
+	BasalforcingsPicoAverageTemperatureEnum,
+	BasalforcingsPicoBoxAreaEnum,
+	BasalforcingsPicoFarOceansalinityEnum,
+	BasalforcingsPicoFarOceantemperatureEnum,
+	BasalforcingsPicoGammaTEnum,
+	BasalforcingsPicoMaxboxcountEnum,
+	BasalforcingsPicoNumBasinsEnum,
+	BasalforcingsPicoOverturningCoeffEnum,
+	BasalforcingsPlumeradiusEnum,
+	BasalforcingsPlumexEnum,
+	BasalforcingsPlumeyEnum,
+	BasalforcingsThresholdThicknessEnum,
+	BasalforcingsTopplumedepthEnum,
+	BasalforcingsUppercrustheatEnum,
+	BasalforcingsUppercrustthicknessEnum,
+	BasalforcingsUpperdepthMeltEnum,
+	BasalforcingsUpperwaterElevationEnum,
+	CalvingCrevasseDepthEnum,
+	CalvingHeightAboveFloatationEnum,
+	CalvingLawEnum,
+	CalvingMaxEnum,
+	CalvingMinthicknessEnum,
+	ConfigurationTypeEnum,
+	ConstantsYtsEnum,
+	DamageC1Enum,
+	DamageC2Enum,
+	DamageC3Enum,
+	DamageEnum,
+	DamageEquivStressEnum,
+	DamageEvolutionNumRequestedOutputsEnum,
+	DamageEvolutionRequestedOutputsEnum,
+	DamageHealingEnum,
+	DamageKappaEnum,
+	DamageLawEnum,
+	DamageMaxDamageEnum,
+	DamageStabilizationEnum,
+	DamageStressThresholdEnum,
+	DebugProfilingEnum,
+	DomainDimensionEnum,
+	DomainTypeEnum,
+	EarthIdEnum,
+	EplZigZagCounterEnum,
+	EsaHElasticEnum,
+	EsaHemisphereEnum,
+	EsaRequestedOutputsEnum,
+	EsaUElasticEnum,
+	ExtrapolationVariableEnum,
 	FemModelCommEnum,
-	WorldCommEnum,
+	FlowequationFeFSEnum,
+	FlowequationIsFSEnum,
+	FlowequationIsHOEnum,
+	FlowequationIsL1L2Enum,
+	FlowequationIsSIAEnum,
+	FlowequationIsSSAEnum,
+	FrictionCouplingEnum,
+	FrictionFEnum,
+	FrictionGammaEnum,
+	FrictionLawEnum,
+	GiaCrossSectionShapeEnum,
+	GroundinglineMigrationEnum,
+	HydrologydcEplflipLockEnum,
+	HydrologydcEplThickCompEnum,
+	HydrologydcIsefficientlayerEnum,
+	HydrologydcLeakageFactorEnum,
+	HydrologydcMaxIterEnum,
+	HydrologydcPenaltyFactorEnum,
+	HydrologydcPenaltyLockEnum,
+	HydrologydcRelTolEnum,
+	HydrologydcSedimentlimitEnum,
+	HydrologydcSedimentlimitFlagEnum,
+	HydrologydcTransferFlagEnum,
+	HydrologydcUnconfinedFlagEnum,
+	HydrologydtEnum,
+	HydrologyModelEnum,
+	HydrologyNumRequestedOutputsEnum,
+	HydrologyRelaxationEnum,
+	HydrologyRequestedOutputsEnum,
+	HydrologySedimentKmaxEnum,
+	HydrologyshreveStabilizationEnum,
+	HydrologyStepsPerStepEnum,
+	HydrologyStorageEnum,
 	IcecapToEarthCommEnum,
-	NumModelsEnum,
-	ModelIdEnum,
-	EarthIdEnum,
-	SolutionTypeEnum,
-	AnalysisTypeEnum,
-	AnalysisCounterEnum,
-	ConfigurationTypeEnum,
+	IndexEnum,
+	InputFileNameEnum,
+	InputToDepthaverageInEnum,
+	InputToDepthaverageOutEnum,
 	InputToExtrudeEnum,
 	InputToL2ProjectEnum,
-	InputToDepthaverageInEnum,
-	InputToDepthaverageOutEnum,
 	InputToSmoothEnum,
+	InversionAlgorithmEnum,
+	InversionControlParametersEnum,
+	InversionControlScalingFactorsEnum,
+	ControlInputSizeMEnum,
+	ControlInputSizeNEnum,
+	InversionCostFunctionsEnum,
+	InversionDxminEnum,
+	InversionGatolEnum,
+	InversionGradientScalingEnum,
+	InversionGrtolEnum,
+	InversionGttolEnum,
+	InversionIncompleteAdjointEnum,
+	InversionIscontrolEnum,
+	InversionMaxiterEnum,
+	InversionMaxiterPerStepEnum,
+	InversionMaxstepsEnum,
+	InversionNstepsEnum,
+	InversionNumControlParametersEnum,
+	InversionNumCostFunctionsEnum,
+	InversionStepThresholdEnum,
+	InversionTypeEnum,
+	LevelsetReinitFrequencyEnum,
+	LevelsetStabilizationEnum,
+	LockFileNameEnum,
+	LoveAllowLayerDeletionEnum,
+	LoveForcingTypeEnum,
+	LoveFrequenciesEnum,
+	LoveG0Enum,
+	LoveKernelsEnum,
+	LoveMu0Enum,
+	LoveNfreqEnum,
+	LoveR0Enum,
+	LoveShNmaxEnum,
+	LoveShNminEnum,
+	MassFluxSegmentsEnum,
+	MassFluxSegmentsPresentEnum,
+	MasstransportHydrostaticAdjustmentEnum,
+	MasstransportIsfreesurfaceEnum,
+	MasstransportMinThicknessEnum,
+	MasstransportNumRequestedOutputsEnum,
+	MasstransportPenaltyFactorEnum,
+	MasstransportRequestedOutputsEnum,
+	MasstransportStabilizationEnum,
+	MeltingOffsetEnum,
+	MeshAverageVertexConnectivityEnum,
+	MeshElementtypeEnum,
+	MeshNumberoflayersEnum,
+	MeshNumberofverticesEnum,
+	ModelIdEnum,
+	NodesEnum,
+	NumModelsEnum,
+	OceanGridNxEnum,
+	OceanGridNyEnum,
+	OceanGridXEnum,
+	OceanGridYEnum,
+	OutputBufferPointerEnum,
+	OutputBufferSizePointerEnum,
+	OutputdefinitionEnum,
+	OutputFileNameEnum,
+	OutputFilePointerEnum,
+	ParamEnum,
+	ParametersEnum,
+	QmuErrNameEnum,
+	QmuInNameEnum,
+	QmuIsdakotaEnum,
+	QmuNumberofpartitionsEnum,
+	QmuOutNameEnum,
+	QmuPartitionEnum,
+	QmuResponsedescriptorsEnum,
+	QmuVariableDescriptorsEnum,
+	RestartFileNameEnum,
+	ResultsEnum,
+	RootPathEnum,
+	SaveResultsEnum,
+	SealevelriseAbstolEnum,
+	SealevelriseAngularVelocityEnum,
+	SealevelriseElasticEnum,
+	SealevelriseEquatorialMoiEnum,
+	SealevelriseFluidLoveEnum,
+	SealevelriseGElasticEnum,
+	SealevelriseHElasticEnum,
+	SealevelriseMaxiterEnum,
+	SealevelriseOceanAreaScalingEnum,
+	SealevelrisePolarMoiEnum,
+	SealevelriseReltolEnum,
+	SealevelriseRequestedOutputsEnum,
+	SealevelriseRigidEnum,
+	SealevelriseRotationEnum,
+	SealevelriseTidalLoveHEnum,
+	SealevelriseTidalLoveKEnum,
+	SealevelriseTransitionsEnum,
+	SealevelriseUElasticEnum,
+	SettingsIoGatherEnum,
+	SettingsOutputFrequencyEnum,
+	SettingsRecordingFrequencyEnum,
+	SettingsResultsOnNodesEnum,
+	SettingsSolverResidueThresholdEnum,
+	SettingsWaitonlockEnum,
+	SmbAdThreshEnum,
+	SmbAIceEnum,
+	SmbAIdxEnum,
+	SmbASnowEnum,
+	SmbCldFracEnum,
+	SmbDelta18oEnum,
+	SmbDelta18oSurfaceEnum,
+	SmbDenIdxEnum,
+	SmbDtEnum,
+	SmbEnum,
+	SmbFEnum,
+	SmbInitDensityScalingEnum,
+	SmbIsaccumulationEnum,
+	SmbIsalbedoEnum,
+	SmbIsd18opdEnum,
+	SmbIsdelta18oEnum,
+	SmbIsdensificationEnum,
+	SmbIsgraingrowthEnum,
+	SmbIsmeltEnum,
+	SmbIsmungsmEnum,
+	SmbIssetpddfacEnum,
+	SmbIsshortwaveEnum,
+	SmbIstemperaturescaledEnum,
+	SmbIsthermalEnum,
+	SmbIsturbulentfluxEnum,
+	SmbKEnum,
+	SmbNumRequestedOutputsEnum,
+	SmbPfacEnum,
+	SmbRequestedOutputsEnum,
+	SmbSealevEnum,
+	SmbSwIdxEnum,
+	SmbT0dryEnum,
+	SmbT0wetEnum,
+	SmbTdiffEnum,
+	SmbThermoDeltaTScalingEnum,
 	SmoothThicknessMultiplierEnum,
-	LevelsetStabilizationEnum,
-	/*}}}*/
-	/*Model fields {{{*/
-	AutodiffIsautodiffEnum, 
-	AutodiffNumDependentsEnum,
-	AutodiffDependentObjectsEnum,
-	AutodiffNumIndependentsEnum,
-	AutodiffJacobianEnum,
-	AutodiffXpEnum,
-	AutodiffDriverEnum,
-	AutodiffFosForwardIndexEnum,
-	AutodiffFovForwardIndicesEnum,
-	AutodiffFosReverseIndexEnum,
-	AutodiffKeepEnum,
-	AutodiffObufsizeEnum,
-	AutodiffLbufsizeEnum,
-	AutodiffCbufsizeEnum,
-	AutodiffTbufsizeEnum,
-	AutodiffGcTriggerRatioEnum,
-	AutodiffGcTriggerMaxSizeEnum,
-	BalancethicknessStabilizationEnum,
-	BalancethicknessThickeningRateEnum,
-	BasalforcingsEnum,
-	BasalforcingsGeothermalfluxEnum,
-	BasalforcingsGroundediceMeltingRateEnum,
-	BasalforcingsFloatingiceMeltingRateEnum,
-	BasalforcingsDeepwaterMeltingRateEnum,
-	BasalforcingsDeepwaterElevationEnum,
-	BasalforcingsUpperwaterElevationEnum,
-	BasalforcingsMeltrateFactorEnum,
-	BasalforcingsThresholdThicknessEnum,
-	BasalforcingsUpperdepthMeltEnum,
-	BasalforcingsMantleconductivityEnum,
-	BasalforcingsNusseltEnum,
-	BasalforcingsDtbgEnum,
-	BasalforcingsPlumeradiusEnum,
-	BasalforcingsTopplumedepthEnum,
-	BasalforcingsBottomplumedepthEnum,
-	BasalforcingsPlumexEnum,
-	BasalforcingsPlumeyEnum,
-	BasalforcingsCrustthicknessEnum,
-	BasalforcingsUppercrustthicknessEnum,
-	BasalforcingsUppercrustheatEnum,
-	BasalforcingsLowercrustheatEnum,
-	FloatingMeltRateEnum,
-	LinearFloatingMeltRateEnum,
-	MismipFloatingMeltRateEnum,
-	MantlePlumeGeothermalFluxEnum,
-	BedEnum,
-	BaseEnum,
-	ConstantsGEnum,
-	ConstantsReferencetemperatureEnum,
-	ConstantsYtsEnum,
-	DependentObjectEnum,
+	SolutionTypeEnum,
+	SteadystateMaxiterEnum,
+	SteadystateNumRequestedOutputsEnum,
+	SteadystateReltolEnum,
+	SteadystateRequestedOutputsEnum,
+	StepEnum,
 	StressbalanceAbstolEnum,
-	StressbalanceConvergenceNumStepsEnum,
+	StressbalanceFSreconditioningEnum,
 	StressbalanceIsnewtonEnum,
 	StressbalanceMaxiterEnum,
+	StressbalanceNumRequestedOutputsEnum,
 	StressbalancePenaltyFactorEnum,
 	StressbalanceReltolEnum,
-	StressbalanceNumRequestedOutputsEnum,
 	StressbalanceRequestedOutputsEnum,
 	StressbalanceRestolEnum,
 	StressbalanceRiftPenaltyThresholdEnum,
 	StressbalanceShelfDampeningEnum,
-	StressbalanceFSreconditioningEnum,
-	StressbalanceViscosityOvershootEnum,
-	LoadingforceXEnum,
-	LoadingforceYEnum,
-	LoadingforceZEnum,
-	FlowequationIsSIAEnum,
-	FlowequationIsSSAEnum,
-	FlowequationIsL1L2Enum,
-	FlowequationIsHOEnum,
-	FlowequationIsFSEnum,
-	FlowequationFeFSEnum,
-	FlowequationBorderFSEnum,
-	FrictionAsEnum,
-	FrictionCoefficientEnum,
-	FrictionCoefficientcoulombEnum,
-	FrictionPressureAdjustedTemperatureEnum,
-	FrictionPEnum,
-	FrictionQEnum,
-	FrictionMEnum,
-	FrictionCEnum,
-	FrictionLawEnum,
-	FrictionGammaEnum,
-	FrictionFEnum,
-	FrictionWaterLayerEnum,
-	FrictionEffectivePressureEnum,
-	FrictionCouplingEnum,
-	GeometryHydrostaticRatioEnum,
-	HydrologyModelEnum,
-	HydrologyshreveEnum,
-	HydrologyshreveStabilizationEnum,
-	HydrologydcEnum,
-	SedimentHeadEnum,
-	SedimentHeadOldEnum,
-	SedimentHeadResidualEnum,
+	ThermalIsdynamicbasalspcEnum,
+	ThermalIsenthalpyEnum,
+	ThermalMaxiterEnum,
+	ThermalNumRequestedOutputsEnum,
+	ThermalPenaltyFactorEnum,
+	ThermalPenaltyLockEnum,
+	ThermalPenaltyThresholdEnum,
+	ThermalReltolEnum,
+	ThermalRequestedOutputsEnum,
+	ThermalStabilizationEnum,
+	TimeEnum,
+	TimesteppingCflCoefficientEnum,
+	TimesteppingCouplingTimeEnum,
+	TimesteppingFinalTimeEnum,
+	TimesteppingInterpForcingsEnum,
+	TimesteppingStartTimeEnum,
+	TimesteppingTimeStepEnum,
+	TimesteppingTimeStepMaxEnum,
+	TimesteppingTimeStepMinEnum,
+	TimesteppingTypeEnum,
+	ToMITgcmCommEnum,
+	ToolkitsFileNameEnum,
+	ToolkitsOptionsAnalysesEnum,
+	ToolkitsOptionsStringsEnum,
+	ToolkitsTypesEnum,
+	TransientAmrFrequencyEnum,
+	TransientIscouplerEnum,
+	TransientIsdamageevolutionEnum,
+	TransientIsesaEnum,
+	TransientIsgiaEnum,
+	TransientIsgroundinglineEnum,
+	TransientIshydrologyEnum,
+	TransientIsmasstransportEnum,
+	TransientIsmovingfrontEnum,
+	TransientIsoceancouplingEnum,
+	TransientIsslrEnum,
+	TransientIssmbEnum,
+	TransientIsstressbalanceEnum,
+	TransientIsthermalEnum,
+	TransientNumRequestedOutputsEnum,
+	TransientRequestedOutputsEnum,
+	VelocityEnum,
+	WorldCommEnum,
+	/*}}}*/
+	ParametersENDEnum,
+	InputsSTARTEnum,
+	/*Inputs{{{*/
+	AdjointEnum,
+	AdjointxEnum,
+	AdjointyEnum,
+	AdjointzEnum,
+	AirEnum,
+	ApproximationEnum,
+	BalancethicknessMisfitEnum,
+	BalancethicknessOmega0Enum,
+	BalancethicknessOmegaEnum,
+	BalancethicknessThickeningRateEnum,
+	BasalforcingsFloatingiceMeltingRateEnum,
+	BasalforcingsGeothermalfluxEnum,
+	BasalforcingsGroundediceMeltingRateEnum,
+	BasalforcingsPicoBasinIdEnum,
+	BasalforcingsPicoBoxIdEnum,
+	BasalforcingsPicoSubShelfOceanOverturningEnum,
+	BasalforcingsPicoSubShelfOceanSalinityEnum,
+	BasalforcingsPicoSubShelfOceanTempEnum,
+	BaseEnum,
+	BedEnum,
+	BedSlopeXEnum,
+	BedSlopeYEnum,
+	CalvingCalvingrateEnum,
+	CalvingHabFractionEnum,
+	CalvinglevermannCoeffEnum,
+	CalvinglevermannMeltingrateEnum,
+	CalvingMeltingrateEnum,
+	CalvingratexAverageEnum,
+	CalvingratexEnum,
+	CalvingrateyAverageEnum,
+	CalvingrateyEnum,
+	CalvingStressThresholdFloatingiceEnum,
+	CalvingStressThresholdGroundediceEnum,
+	ConvergedEnum,
+	CrevasseDepthEnum,
+	DamageDbarEnum,
+	DamageDEnum,
+	DamageFEnum,
+	DeviatoricStressxxEnum,
+	DeviatoricStressxyEnum,
+	DeviatoricStressxzEnum,
+	DeviatoricStressyyEnum,
+	DeviatoricStressyzEnum,
+	DeviatoricStresszzEnum,
+	DistanceToCalvingfrontEnum,
+	DistanceToGroundinglineEnum,
+	Domain2DhorizontalEnum,
+	Domain2DverticalEnum,
+	Domain3DEnum,
+	DragCoefficientAbsGradientEnum,
+	DrivingStressXEnum,
+	DrivingStressYEnum,
 	EffectivePressureEnum,
+	EnthalpyEnum,
+	EnthalpyPicardEnum,
 	EplHeadEnum,
 	EplHeadOldEnum,
 	EplHeadSlopeXEnum,
 	EplHeadSlopeYEnum,
-	EplZigZagCounterEnum,
-	HydrologydcMaxIterEnum,
-	HydrologydcRelTolEnum,
-	HydrologydcSedimentCompressibilityEnum,
-	HydrologydcSedimentPorosityEnum,
-	HydrologydcSedimentThicknessEnum,
-	HydrologydcSedimentTransmitivityEnum,
-	HydrologydcWaterCompressibilityEnum,
-	HydrologydcMaskEplactiveNodeEnum,
-	HydrologydcMaskEplactiveEltEnum,
-	HydrologydcEplCompressibilityEnum,
-	HydrologydcEplPorosityEnum,
-	HydrologydcEplInitialThicknessEnum,
-	HydrologydcEplColapseThicknessEnum,
-	HydrologydcEplMaxThicknessEnum,
+	EsaDeltathicknessEnum,
+	EsaXmotionEnum,
+	EsaYmotionEnum,
+	EtaDiffEnum,
+	FrictionAsEnum,
+	FrictionCEnum,
+	FrictionCoefficientcoulombEnum,
+	FrictionCoefficientEnum,
+	FrictionEffectivePressureEnum,
+	FrictionMEnum,
+	FrictionPEnum,
+	FrictionPressureAdjustedTemperatureEnum,
+	FrictionQEnum,
+	FrictionWaterLayerEnum,
+	GeometryHydrostaticRatioEnum,
+	GiaLithosphereThicknessEnum,
+	GiaMantleViscosityEnum,
+	GradientEnum,
+	HydrologyBumpHeightEnum,
+	HydrologyBumpSpacingEnum,
+	HydrologydcBasalMoulinInputEnum,
 	HydrologydcEplThicknessEnum,
 	HydrologydcEplThicknessOldEnum,
-	HydrologydcEplThickCompEnum,
-	HydrologydcEplConductivityEnum,
-	HydrologydcIsefficientlayerEnum,
-	HydrologydcSedimentlimitFlagEnum,
-	HydrologydcSedimentlimitEnum,
-	HydrologydcTransferFlagEnum,
-	HydrologydcLeakageFactorEnum,
-	HydrologydcPenaltyFactorEnum,
-	HydrologydcPenaltyLockEnum,
-	HydrologydcEplflipLockEnum,
-	HydrologydcBasalMoulinInputEnum,
-	HydrologyLayerEnum,
-	HydrologySedimentEnum,
-	HydrologyEfficientEnum,
-	HydrologySedimentKmaxEnum,
-	HydrologysommersEnum,
+	HydrologydcMaskEplactiveEltEnum,
+	HydrologydcMaskEplactiveNodeEnum,
+	HydrologydcSedimentTransmitivityEnum,
+	HydrologyEnglacialInputEnum,
+	HydrologyGapHeightEnum,
 	HydrologyHeadEnum,
 	HydrologyHeadOldEnum,
-	HydrologyGapHeightEnum,
-	HydrologyBumpSpacingEnum,
-	HydrologyBumpHeightEnum,
-	HydrologyEnglacialInputEnum,
 	HydrologyMoulinInputEnum,
+	HydrologyNeumannfluxEnum,
 	HydrologyReynoldsEnum,
-	HydrologyNeumannfluxEnum,
-   HydrologyRelaxationEnum,
-	HydrologyBasalFluxEnum,
-	HydrologyStorageEnum,
-	InversionControlParametersEnum,
-	InversionControlScalingFactorsEnum,
-	InversionCostFunctionThresholdEnum,
+	HydrologyWaterVxEnum,
+	HydrologyWaterVyEnum,
+	IceEnum,
+	IceMaskNodeActivationEnum,
+	InputEnum,
 	InversionCostFunctionsCoefficientsEnum,
-	InversionCostFunctionsEnum,
-	InversionGradientScalingEnum,
-	InversionIscontrolEnum,
-	InversionTypeEnum,
-	InversionIncompleteAdjointEnum,
-	InversionMaxiterPerStepEnum,
-	InversionMaxiterEnum,
-	InversionMaxstepsEnum,
-	InversionFatolEnum,
-	InversionFrtolEnum,
-	InversionGatolEnum,
-	InversionGrtolEnum,
-	InversionGttolEnum,
-	InversionAlgorithmEnum,
-	InversionNstepsEnum,
-	InversionDxminEnum,
-	InversionNumControlParametersEnum,
-	InversionNumCostFunctionsEnum,
-	InversionStepThresholdEnum,
+	InversionSurfaceObsEnum,
 	InversionThicknessObsEnum,
-	InversionSurfaceObsEnum,
+	InversionVelObsEnum,
 	InversionVxObsEnum,
 	InversionVyObsEnum,
-	InversionVzObsEnum,
+	LevelsetfunctionSlopeXEnum,
+	LevelsetfunctionSlopeYEnum,
+	LoadingforceXEnum,
+	LoadingforceYEnum,
+	LoadingforceZEnum,
+	MaskGroundediceLevelsetEnum,
 	MaskIceLevelsetEnum,
-	MaskOceanLevelsetEnum,
-	MaskLandLevelsetEnum,
-	MaterialsBetaEnum,
-	MaterialsHeatcapacityEnum,
-	MaterialsLatentheatEnum,
-	MaterialsMeltingpointEnum,
-	MaterialsMixedLayerCapacityEnum,
+	MasstransportSpcthicknessEnum,
+	MaterialsRheologyBbarEnum,
 	MaterialsRheologyBEnum,
-	MaterialsRheologyBbarEnum,
-	MaterialsRheologyLawEnum,
+	MaterialsRheologyEbarEnum,
+	MaterialsRheologyEcbarEnum,
+	MaterialsRheologyEcEnum,
+	MaterialsRheologyEEnum,
+	MaterialsRheologyEsbarEnum,
+	MaterialsRheologyEsEnum,
 	MaterialsRheologyNEnum,
-	MaterialsRheologyEEnum,
-	MaterialsRheologyEbarEnum,
-	MaterialsRheologyEcEnum,
-	MaterialsRheologyEcbarEnum,
-	MaterialsRheologyEsEnum,
-	MaterialsRheologyEsbarEnum,
-	DamageDEnum,
-	DamageFEnum,
-	DamageDbarEnum,
-	DamageLawEnum,
-	DamageC1Enum,
-	DamageC2Enum,
-	DamageC3Enum,
-	DamageC4Enum,
-	DamageElementinterpEnum,
-	DamageHealingEnum,
-	DamageStressThresholdEnum,
-	DamageKappaEnum,
-	DamageStabilizationEnum,
-	DamageMaxiterEnum,
-	DamageMaxDamageEnum,
-	DamageEquivStressEnum,
-	DamageEvolutionNumRequestedOutputsEnum,
-	DamageEvolutionRequestedOutputsEnum,
-	DamageEnum,
-	NewDamageEnum,
-	StressIntensityFactorEnum,
-	CalvingLawEnum,
-	CalvingCalvingrateEnum,
-	CalvingMeltingrateEnum,
-	CalvingLevermannEnum,
-	CalvingDevEnum,
-	CalvingMinthicknessEnum,
-	DefaultCalvingEnum,
-	CalvinglevermannCoeffEnum,
-	CalvinglevermannMeltingrateEnum,
-	CalvingdevCoeffEnum,
-	CalvingratexEnum,
-	CalvingrateyEnum,
-	CalvingratexAverageEnum,
-	CalvingrateyAverageEnum,
-	CalvingStressThresholdGroundediceEnum,
-	CalvingStressThresholdFloatingiceEnum,
-	CalvingMaxEnum,
+	MeshScaleFactorEnum,
+	MeshVertexonbaseEnum,
+	MeshVertexonboundaryEnum,
+	MeshVertexonsurfaceEnum,
+	MisfitEnum,
+	NeumannfluxEnum,
+	NodeEnum,
+	OmegaAbsGradientEnum,
+	P0Enum,
+	P1Enum,
+	PressureEnum,
+	RheologyBAbsGradientEnum,
+	RheologyBbarAbsGradientEnum,
+	SealevelEnum,
+	SealevelriseDeltathicknessEnum,
+	SedimentHeadEnum,
+	SedimentHeadOldEnum,
+	SedimentHeadResidualEnum,
+	SigmaNNEnum,
+	SmbAccumulationEnum,
+	SmbAEnum,
+	SmbAiniEnum,
+	SmbAValueEnum,
+	SmbBMaxEnum,
+	SmbBMinEnum,
+	SmbBNegEnum,
+	SmbBPosEnum,
+	SmbCEnum,
+	SmbDEnum,
+	SmbDiniEnum,
+	SmbDlwrfEnum,
+	SmbDswrfEnum,
+	SmbDzEnum,
+	SmbDziniEnum,
+	SmbDzMinEnum,
+	SmbDzTopEnum,
+	SmbEAirEnum,
+	SmbECEnum,
+	SmbECiniEnum,
+	SmbElaEnum,
+	SmbEvaporationEnum,
+	SmbGdnEnum,
+	SmbGdniniEnum,
+	SmbGspEnum,
+	SmbGspiniEnum,
+	SmbHrefEnum,
+	SmbIsInitializedEnum,
+	SmbMassBalanceEnum,
+	SmbMeltEnum,
+	SmbMonthlytemperaturesEnum,
+	SmbPAirEnum,
+	SmbPddfacIceEnum,
+	SmbPddfacSnowEnum,
+	SmbPEnum,
+	SmbPrecipitationEnum,
+	SmbPrecipitationsLgmEnum,
+	SmbPrecipitationsPresentdayEnum,
+	SmbReEnum,
+	SmbRefreezeEnum,
+	SmbReiniEnum,
+	SmbRunoffEnum,
+	SmbS0pEnum,
+	SmbS0tEnum,
+	SmbSizeiniEnum,
+	SmbSmbrefEnum,
+	SmbTaEnum,
+	SmbTemperaturesLgmEnum,
+	SmbTemperaturesPresentdayEnum,
+	SmbTEnum,
+	SmbTeValueEnum,
+	SmbTiniEnum,
+	SmbTmeanEnum,
+	SmbTzEnum,
+	SmbVEnum,
+	SmbVzEnum,
+	SmbWEnum,
+	SmbWiniEnum,
+	SmbZMaxEnum,
+	SmbZMinEnum,
+	SmbZTopEnum,
+	SmbZYEnum,
+	StrainRateeffectiveEnum,
 	StrainRateparallelEnum,
 	StrainRateperpendicularEnum,
-	StrainRateeffectiveEnum,
-	MaterialsRhoIceEnum,
-	MaterialsRhoSeawaterEnum,
-	MaterialsRhoFreshwaterEnum,
-	MaterialsMuWaterEnum,
-	MaterialsThermalExchangeVelocityEnum,
-	MaterialsThermalconductivityEnum,
-	MaterialsTemperateiceconductivityEnum,
-	MaterialsLithosphereShearModulusEnum,
-	MaterialsLithosphereDensityEnum,
-	MaterialsMantleShearModulusEnum,
-	MaterialsMantleDensityEnum,
-	MaterialsEarthDensityEnum,
-	MeshAverageVertexConnectivityEnum,
-	MeshXEnum,
-	MeshYEnum,
-	MeshZEnum,
-	MeshElementsEnum,
-	MeshNumberofelementsEnum,
-	MeshNumberoflayersEnum,
-	MeshNumberofverticesEnum,
-	MeshVertexonbaseEnum,
-	MeshVertexonsurfaceEnum,
-	MeshVertexonboundaryEnum,
-	MeshElementtypeEnum,
-	DomainTypeEnum,
-	DomainDimensionEnum,
-	Domain2DhorizontalEnum,
-	Domain2DverticalEnum,
-	Domain3DEnum,
-	Domain3DsurfaceEnum,
-	MasstransportHydrostaticAdjustmentEnum,
-	MasstransportIsfreesurfaceEnum,
-	MasstransportMinThicknessEnum,
-	MasstransportPenaltyFactorEnum,
-	MasstransportSpcthicknessEnum,
-	MasstransportStabilizationEnum,
-	MasstransportNumRequestedOutputsEnum,
-	MasstransportRequestedOutputsEnum,
-	QmuIsdakotaEnum,
-	MassFluxSegmentsEnum,
-	MassFluxSegmentsPresentEnum,
-	QmuNumberofpartitionsEnum,
-	QmuNumberofresponsesEnum,
-	QmuPartitionEnum,
-	QmuResponsedescriptorsEnum,
-	QmuVariabledescriptorsEnum,
-	SettingsResultsOnNodesEnum,
-	SettingsIoGatherEnum,
-	SettingsLowmemEnum,
-	SettingsOutputFrequencyEnum,
-	SettingsRecordingFrequencyEnum,
-	SettingsWaitonlockEnum,
-	SettingsSolverResidueThresholdEnum,
-	DebugProfilingEnum,
-	ProfilingCurrentMemEnum,
-	ProfilingCurrentFlopsEnum,
-	ProfilingSolutionTimeEnum,
-	SteadystateMaxiterEnum,
-	SteadystateNumRequestedOutputsEnum,
-	SteadystateReltolEnum,
-	SteadystateRequestedOutputsEnum,
-	SurfaceEnum,
-	ThermalIsenthalpyEnum,
-	ThermalIsdynamicbasalspcEnum,
-	ThermalReltolEnum,
-	ThermalMaxiterEnum,
-	ThermalPenaltyFactorEnum,
-	ThermalPenaltyLockEnum,
-	ThermalPenaltyThresholdEnum,
-	ThermalSpctemperatureEnum,
-	ThermalStabilizationEnum,
-	ThermalNumRequestedOutputsEnum,
-	ThermalRequestedOutputsEnum,
-	GiaMantleViscosityEnum,
-	GiaLithosphereThicknessEnum,
-	ThicknessEnum,
-	TimesteppingStartTimeEnum,
-	TimesteppingFinalTimeEnum,
-	TimesteppingCflCoefficientEnum,
-	TimesteppingTimeAdaptEnum,
-	TimesteppingTimeStepEnum,
-	TimesteppingInterpForcingsEnum,
-	TransientIssmbEnum,
-	TransientIscouplerEnum,
-	TransientIsstressbalanceEnum,
-	TransientIsgroundinglineEnum,
-	TransientIsmasstransportEnum,
-	TransientIsthermalEnum,
-	TransientIsgiaEnum,
-	TransientIsesaEnum,
-	TransientIsdamageevolutionEnum,
-	TransientIshydrologyEnum,
-	TransientIsmovingfrontEnum,
-	TransientIsslrEnum,
-	TransientNumRequestedOutputsEnum,
-	TransientRequestedOutputsEnum,
-	BalancethicknessApparentMassbalanceEnum,
-	BalancethicknessDiffusionCoefficientEnum,
-	BalancethicknessOmegaEnum,
-	BalancethicknessD0Enum,
-	/*}}}*/
-	/*Smb{{{*/
-	SmbEnum,
-	SmbAnalysisEnum,
-	SmbSolutionEnum,
-	SmbNumRequestedOutputsEnum,
-	SmbRequestedOutputsEnum,
-	SmbIsInitializedEnum,
-	SmbDziniEnum,
-	SmbDiniEnum,
-	SmbReiniEnum,
-	SmbGdniniEnum,
-	SmbGspiniEnum,
-	SmbECiniEnum,
-	SmbWiniEnum,
-	SmbAiniEnum,
-	SmbTiniEnum,
-	SmbSizeiniEnum,
-	/*SMBforcing*/
-	SMBforcingEnum,
-	SmbMassBalanceEnum,
-	/*SMBgemb*/
-	SMBgembEnum,
-	SmbInitDensityScalingEnum,
-	SmbTaEnum,
-	SmbVEnum,
-	SmbDswrfEnum,
-	SmbDlwrfEnum,
-	SmbPEnum, 
-	SmbEAirEnum, 
-	SmbPAirEnum,
-	SmbTmeanEnum,
-	SmbCEnum,
-	SmbTzEnum,
-	SmbVzEnum, 
-	SmbDtEnum,
-	SmbDzEnum,
-	SmbAIdxEnum,
-	SmbSwIdxEnum,
-	SmbDenIdxEnum,
-	SmbZTopEnum, 
-	SmbDzTopEnum, 
-	SmbDzMinEnum, 
-	SmbZYEnum, 
-	SmbZMaxEnum, 
-	SmbZMinEnum, 
-	SmbOutputFreqEnum, 
-	SmbASnowEnum, 
-	SmbAIceEnum, 
-	SmbCldFracEnum, 
-	SmbT0wetEnum, 
-	SmbT0dryEnum, 
-	SmbKEnum, 
-	SmbDEnum,
-	SmbReEnum,
-	SmbGdnEnum,
-	SmbGspEnum,
-	SmbECEnum,
-	SmbWEnum,
-	SmbAEnum,
-	SmbTEnum,
-	SmbIsgraingrowthEnum,
-	SmbIsalbedoEnum,
-	SmbIsshortwaveEnum,
-	SmbIsthermalEnum,
-	SmbIsaccumulationEnum,
-	SmbIsmeltEnum,
-	SmbIsdensificationEnum,
-	SmbIsturbulentfluxEnum,
-	SmbDz_addEnum,
-	SmbM_addEnum,
-	/*SMBpdd*/
-	SMBpddEnum,	
-	SmbDelta18oEnum,
-	SmbDelta18oSurfaceEnum,
-	SmbIsdelta18oEnum,
-	SmbIsmungsmEnum,
-	SmbIsd18opdEnum,
-	SmbPrecipitationsPresentdayEnum,
-	SmbPrecipitationsLgmEnum,
-	SmbTemperaturesPresentdayEnum,
-	SmbTemperaturesLgmEnum,
-	SmbPrecipitationEnum,
-	SmbDesfacEnum,
-	SmbS0pEnum,
-	SmbS0tEnum,
-	SmbRlapsEnum,
-	SmbRlapslgmEnum,
-	SmbPfacEnum,
-	SmbTdiffEnum,
-	SmbSealevEnum,
-	SMBd18opddEnum,
-	SmbDpermilEnum,
-	SmbFEnum,
-	SMBgradientsEnum,
-	SmbMonthlytemperaturesEnum,
-	SmbHrefEnum,
-	SmbSmbrefEnum,
-	SmbBPosEnum,
-	SmbBNegEnum,
-	SMBhenningEnum,
-	SMBcomponentsEnum,
-	SmbAccumulationEnum,
-	SmbEvaporationEnum,
-	SmbRunoffEnum,
-	SMBmeltcomponentsEnum,
-	SmbMeltEnum,
-	SmbRefreezeEnum,
-	SMBgcmEnum,
-	/*SMBgradientsela*/
-	SMBgradientselaEnum,
-	SmbElaEnum,
-	SmbBMaxEnum,
-	SmbBMinEnum,
-	/*}}}*/
-	/*Inputs {{{*/
-	AdjointpEnum,
-	AdjointxEnum,
-	AdjointyEnum,
-	AdjointzEnum,
-	BalancethicknessMisfitEnum,
-	BedSlopeXEnum,
-	BedSlopeYEnum,
-	BoundaryEnum,
-	ConvergedEnum,
-	InternalEnum,
-	MassFluxEnum,
-	MeltingOffsetEnum,
-	MisfitEnum,
-	PressureEnum,
-	PressurePicardEnum,
-	AndroidFrictionCoefficientEnum,
-	ResetPenaltiesEnum,
-	SurfaceAbsVelMisfitEnum,
-	SurfaceAreaEnum,
-	SurfaceAverageVelMisfitEnum,
-	SurfaceLogVelMisfitEnum,
-	SurfaceLogVxVyMisfitEnum,
-	SurfaceRelVelMisfitEnum,
-	SurfaceSlopeXEnum,
-	SurfaceSlopeYEnum,
-	TemperatureEnum,
-	TemperaturePicardEnum,
-	TemperaturePDDEnum,
-	ThicknessAbsMisfitEnum,
-	SurfaceAbsMisfitEnum,
-	VelEnum,
-	VelocityEnum,
-	VxAverageEnum,
-	VxEnum,
-	VxPicardEnum,
-	VyAverageEnum,
-	VyEnum,
-	VyPicardEnum,
-	VzEnum,
-	VzSSAEnum,
-	VzHOEnum,
-	VzPicardEnum,
-	VzFSEnum,
-	VxMeshEnum,
-	VyMeshEnum,
-	VzMeshEnum,
-	EnthalpyEnum,
-	EnthalpyPicardEnum,
-	ThicknessAbsGradientEnum,
-	ThicknessAlongGradientEnum,
-	ThicknessAcrossGradientEnum,
-	ThicknessPositiveEnum,
-	IntMatParamEnum,
-	RheologyBbarAbsGradientEnum,
-	RheologyBAbsGradientEnum,
-	DragCoefficientAbsGradientEnum,
-	TransientInputEnum,
-	WaterfractionEnum,
-	WaterfractionDrainageEnum,
-	WaterfractionDrainageIntegratedEnum,
-	WatercolumnEnum,
-	ViscousHeatingEnum,
-	HydrologyWaterVxEnum,
-	HydrologyWaterVyEnum,
-	DrivingStressXEnum,
-	DrivingStressYEnum,
-	SigmaNNEnum,
-	StressTensorEnum,
+	StrainRatexxEnum,
+	StrainRatexyEnum,
+	StrainRatexzEnum,
+	StrainRateyyEnum,
+	StrainRateyzEnum,
+	StrainRatezzEnum,
+	StressMaxPrincipalEnum,
 	StressTensorxxEnum,
 	StressTensorxyEnum,
@@ -555,53 +572,316 @@
 	StressTensoryzEnum,
 	StressTensorzzEnum,
-	StressMaxPrincipalEnum,
-	DeviatoricStressEnum,
-	DeviatoricStressxxEnum,
-	DeviatoricStressxyEnum,
-	DeviatoricStressxzEnum,
-	DeviatoricStressyyEnum,
-	DeviatoricStressyzEnum,
-	DeviatoricStresszzEnum,
+	SurfaceAbsMisfitEnum,
+	SurfaceAbsVelMisfitEnum,
+	SurfaceAreaEnum,
+	SurfaceAverageVelMisfitEnum,
+	SurfaceEnum,
+	SurfaceLogVelMisfitEnum,
+	SurfaceLogVxVyMisfitEnum,
+	SurfaceObservationEnum,
+	SurfaceRelVelMisfitEnum,
+	SurfaceSlopeXEnum,
+	SurfaceSlopeYEnum,
+	TemperatureEnum,
+	TemperaturePicardEnum,
+	ThicknessAbsGradientEnum,
+	ThicknessAbsMisfitEnum,
+	ThicknessAcrossGradientEnum,
+	ThicknessAlongGradientEnum,
+	ThicknessEnum,
+	ThicknessPositiveEnum,
+	VelEnum,
+	VxAverageEnum,
+	VxEnum,
+	VxMeshEnum,
+	VxObsEnum,
+	VyAverageEnum,
+	VyEnum,
+	VyMeshEnum,
+	VyObsEnum,
+	VzEnum,
+	VzFSEnum,
+	VzHOEnum,
+	VzMeshEnum,
+	VzSSAEnum,
+	WatercolumnEnum,
+	WaterColumnOldEnum,
+	WaterfractionDrainageEnum,
+	WaterfractionDrainageIntegratedEnum,
+	WaterfractionEnum,
+	WaterheightEnum,
+	WeightsSurfaceObservationEnum,
+	/*}}}*/
+	InputsENDEnum,
+	/*Other{{{*/
+	AbsoluteEnum,
+	AdaptiveTimesteppingEnum,
+	AdjointBalancethickness2AnalysisEnum,
+	AdjointBalancethicknessAnalysisEnum,
+	AdjointHorizAnalysisEnum,
+	AdjointpEnum,
+	AggressiveMigrationEnum,
+	AmrBamgEnum,
+	AmrNeopzEnum,
+	AndroidFrictionCoefficientEnum,
+	ArrheniusEnum,
+	AutodiffJacobianEnum,
+	Balancethickness2AnalysisEnum,
+	Balancethickness2SolutionEnum,
+	BalancethicknessAnalysisEnum,
+	BalancethicknessApparentMassbalanceEnum,
+	BalancethicknessSoftAnalysisEnum,
+	BalancethicknessSoftSolutionEnum,
+	BalancethicknessSolutionEnum,
+	BalancethicknessSpcthicknessEnum,
+	BalancevelocityAnalysisEnum,
+	BalancevelocitySolutionEnum,
+	BasalCrevasseEnum,
+	BasalforcingsPicoEnum,
+	BedSlopeSolutionEnum,
+	BoolExternalResultEnum,
+	BoolInputEnum,
+	BoolParamEnum,
+	BoundaryEnum,
+	BuddJackaEnum,
+	CalvingDev2Enum,
+	CalvingHabEnum,
+	CalvingLevermannEnum,
+	CalvingVonmisesEnum,
+	CfsurfacelogvelEnum,
+	CfsurfacesquareEnum,
+	CfdragcoeffabsgradEnum,
+	ClosedEnum,
+	ColinearEnum,
+	ConstantsGEnum,
+	ConstantsReferencetemperatureEnum,
+	ConstraintsEnum,
+	ContactEnum,
+	ContourEnum,
+	ContoursEnum,
+	ControlInputEnum,
+	ControlInputValuesEnum,
+	ControlInputMinsEnum,
+	ControlInputMaxsEnum,
+	ControlInputGradEnum,
+	CrouzeixRaviartEnum,
+	CuffeyEnum,
+	CuffeyTemperateEnum,
+	DamageEvolutionAnalysisEnum,
+	DamageEvolutionSolutionEnum,
+	DataSetEnum,
+	DatasetInputEnum,
+	DataSetParamEnum,
+	DefaultAnalysisEnum,
+	DefaultCalvingEnum,
+	DegreeOfChannelizationEnum,
+	DenseEnum,
+	DependentObjectEnum,
+	DepthAverageAnalysisEnum,
 	DeviatoricStresseffectiveEnum,
+	DeviatoricStressErrorEstimatorEnum,
+	DivergenceEnum,
+	Domain3DsurfaceEnum,
+	DoubleArrayInputEnum,
+	DoubleExternalResultEnum,
+	DoubleInputEnum,
+	DoubleMatArrayParamEnum,
+	DoubleMatExternalResultEnum,
+	DoubleMatParamEnum,
+	DoubleParamEnum,
+	DoubleVecParamEnum,
+	EffectivePressureStackedEnum,
+	EffectivePressureTimeAverageEnum,
+	ElementEnum,
+	ElementHookEnum,
+	ElementSIdEnum,
+	EnthalpyAnalysisEnum,
+	EplHeadStackedEnum,
+	EplHeadTimeAverageEnum,
+	EsaAnalysisEnum,
+	EsaEmotionEnum,
+	EsaNmotionEnum,
+	EsaRotationrateEnum,
+	EsaSolutionEnum,
+	EsaStrainratexxEnum,
+	EsaStrainratexyEnum,
+	EsaStrainrateyyEnum,
+	EsaTransitionsEnum,
+	EsaUmotionEnum,
+	ExternalResultEnum,
+	ExtrapolationAnalysisEnum,
+	ExtrudeFromBaseAnalysisEnum,
+	ExtrudeFromTopAnalysisEnum,
+	FemModelEnum,
+	FileParamEnum,
+	FixedTimesteppingEnum,
+	FloatingAreaEnum,
+	FloatingAreaScaledEnum,
+	FloatingMeltRateEnum,
+	FlowequationBorderFSEnum,
+	FreeEnum,
+	FreeSurfaceBaseAnalysisEnum,
+	FreeSurfaceTopAnalysisEnum,
+	FSApproximationEnum,
+	FsetEnum,
+	FSpressureEnum,
+	FSSolverEnum,
+	FSvelocityEnum,
+	GaussPentaEnum,
+	GaussSegEnum,
+	GaussTetraEnum,
+	GaussTriaEnum,
+	GenericOptionEnum,
+	GenericParamEnum,
+	GiadWdtEnum,
+	GiaIvinsAnalysisEnum,
+	GiaSolutionEnum,
+	GiaWEnum,
+	Gradient1Enum,
+	Gradient2Enum,
+	Gradient3Enum,
+	GroundedAreaEnum,
+	GroundedAreaScaledEnum,
+	GroundingOnlyEnum,
+	GsetEnum,
+	GslEnum,
+	HOApproximationEnum,
+	HOFSApproximationEnum,
+	HookEnum,
+	HydrologyBasalFluxEnum,
+	HydrologyDCEfficientAnalysisEnum,
+	HydrologydcEnum,
+	HydrologydcEplColapseThicknessEnum,
+	HydrologydcEplCompressibilityEnum,
+	HydrologydcEplConductivityEnum,
+	HydrologydcEplInitialThicknessEnum,
+	HydrologydcEplMaxThicknessEnum,
+	HydrologydcEplPorosityEnum,
+	HydrologydcEplThicknessStackedEnum,
+	HydrologydcEplThicknessTimeAverageEnum,
+	HydrologyDCInefficientAnalysisEnum,
+	HydrologydcSedimentCompressibilityEnum,
+	HydrologydcSedimentPorosityEnum,
+	HydrologydcSedimentThicknessEnum,
+	HydrologydcWaterCompressibilityEnum,
+	HydrologyShreveAnalysisEnum,
+	HydrologyshreveEnum,
+	HydrologySolutionEnum,
+	HydrologySommersAnalysisEnum,
+	HydrologysommersEnum,
+	IceMassEnum,
+	IceMassScaledEnum,
+	IceVolumeAboveFloatationEnum,
+	IceVolumeAboveFloatationScaledEnum,
+	IceVolumeEnum,
+	IceVolumeScaledEnum,
+	IncrementalEnum,
+	IndexedEnum,
+	InternalEnum,
+	IntersectEnum,
+	IntExternalResultEnum,
+	IntInputEnum,
+	IntMatExternalResultEnum,
+	IntMatParamEnum,
+	IntParamEnum,
+	IntVecParamEnum,
+	InversionVzObsEnum,
+	JEnum,
+	L1L2ApproximationEnum,
+	L2ProjectionBaseAnalysisEnum,
+	L2ProjectionEPLAnalysisEnum,
+	LACrouzeixRaviartEnum,
 	LambdaSEnum,
-	StrainRateEnum,
-	StrainRatexxEnum,
-	StrainRatexyEnum,
-	StrainRatexzEnum,
-	StrainRateyyEnum,
-	StrainRateyzEnum,
-	StrainRatezzEnum,
-	DivergenceEnum,
+	LATaylorHoodEnum,
+	LevelsetAnalysisEnum,
+	LevelsetfunctionPicardEnum,
+	LinearFloatingMeltRateEnum,
+	LliboutryDuvalEnum,
+	LoadsEnum,
+	LoveAnalysisEnum,
+	LoveHiEnum,
+	LoveHrEnum,
+	LoveKernelsImagEnum,
+	LoveKernelsRealEnum,
+	LoveKiEnum,
+	LoveKrEnum,
+	LoveLiEnum,
+	LoveLrEnum,
+	LoveSolutionEnum,
+	MantlePlumeGeothermalFluxEnum,
+	MaskLandLevelsetEnum,
+	MaskOceanLevelsetEnum,
+	MassconaxpbyEnum,
+	MassconEnum,
+	MassfluxatgateEnum,
+	MassFluxEnum,
+	MasstransportAnalysisEnum,
+	MasstransportSolutionEnum,
+	MatdamageiceEnum,
+	MatenhancediceEnum,
+	MaterialsBetaEnum,
+	MaterialsEarthDensityEnum,
+	MaterialsEnum,
+	MaterialsHeatcapacityEnum,
+	MaterialsLatentheatEnum,
+	MaterialsLithosphereDensityEnum,
+	MaterialsLithosphereShearModulusEnum,
+	MaterialsMantleDensityEnum,
+	MaterialsMantleShearModulusEnum,
+	MaterialsMeltingpointEnum,
+	MaterialsMixedLayerCapacityEnum,
+	MaterialsMuWaterEnum,
+	MaterialsRheologyLawEnum,
+	MaterialsRhoFreshwaterEnum,
+	MaterialsRhoIceEnum,
+	MaterialsRhoSeawaterEnum,
+	MaterialsTemperateiceconductivityEnum,
+	MaterialsThermalconductivityEnum,
+	MaterialsThermalExchangeVelocityEnum,
+	MatestarEnum,
+	MaticeEnum,
+	MatlithoEnum,
+	MatparEnum,
+	MatrixParamEnum,
+	MaxAbsVxEnum,
+	MaxAbsVyEnum,
+	MaxAbsVzEnum,
 	MaxDivergenceEnum,
-	GiaCrossSectionShapeEnum,
-	GiadWdtEnum,
-	GiaWEnum, 
-	/*}}}*/
-	/*Results{{{*/
-	SaveResultsEnum,
-	BoolExternalResultEnum,
-	DoubleExternalResultEnum,
-	DoubleMatExternalResultEnum,
-	IntExternalResultEnum,
-	IntMatExternalResultEnum,
-	JEnum,
-	StringExternalResultEnum,
-	StepEnum,
-	TimeEnum,
-	WaterColumnOldEnum,
-	/*}}}*/
-	/*Output Definitions{{{*/
-	SurfaceObservationEnum,
-	WeightsSurfaceObservationEnum,
-	OutputdefinitionEnum,
+	MaxVelEnum,
+	MaxVxEnum,
+	MaxVyEnum,
+	MaxVzEnum,
+	MelangeEnum,
+	MeltingAnalysisEnum,
+	MeshElementsEnum,
+	MeshLatEnum,
+	MeshLongEnum,
+	MeshXEnum,
+	MeshYEnum,
+	MINIcondensedEnum,
+	MINIEnum,
+	MinVelEnum,
+	MinVxEnum,
+	MinVyEnum,
+	MinVzEnum,
+	MismipFloatingMeltRateEnum,
+	MoulinEnum,
+	MpiDenseEnum,
+	MpiEnum,
+	MpiSparseEnum,
+	MumpsEnum,
+	NewDamageEnum,
+	NodalEnum,
+	NodalvalueEnum,
+	NodeSIdEnum,
+	NoneApproximationEnum,
+	NoneEnum,
+	NumberedcostfunctionEnum,
+	NumericalfluxEnum,
+	OldGradientEnum,
+	OneLayerP4zEnum,
+	OpenEnum,
+	OptionEnum,
 	Outputdefinition1Enum,
-	Outputdefinition2Enum,
-	Outputdefinition3Enum,
-	Outputdefinition4Enum,
-	Outputdefinition5Enum,
-	Outputdefinition6Enum,
-	Outputdefinition7Enum,
-	Outputdefinition8Enum,
-	Outputdefinition9Enum,
 	Outputdefinition10Enum,
 	Outputdefinition11Enum,
@@ -624,4 +904,5 @@
 	Outputdefinition28Enum,
 	Outputdefinition29Enum,
+	Outputdefinition2Enum,
 	Outputdefinition30Enum,
 	Outputdefinition31Enum,
@@ -634,4 +915,5 @@
 	Outputdefinition38Enum,
 	Outputdefinition39Enum,
+	Outputdefinition3Enum,
 	Outputdefinition40Enum,
 	Outputdefinition41Enum,
@@ -644,4 +926,5 @@
 	Outputdefinition48Enum,
 	Outputdefinition49Enum,
+	Outputdefinition4Enum,
 	Outputdefinition50Enum,
 	Outputdefinition51Enum,
@@ -654,4 +937,5 @@
 	Outputdefinition58Enum,
 	Outputdefinition59Enum,
+	Outputdefinition5Enum,
 	Outputdefinition60Enum,
 	Outputdefinition61Enum,
@@ -664,4 +948,5 @@
 	Outputdefinition68Enum,
 	Outputdefinition69Enum,
+	Outputdefinition6Enum,
 	Outputdefinition70Enum,
 	Outputdefinition71Enum,
@@ -674,4 +959,5 @@
 	Outputdefinition78Enum,
 	Outputdefinition79Enum,
+	Outputdefinition7Enum,
 	Outputdefinition80Enum,
 	Outputdefinition81Enum,
@@ -684,4 +970,5 @@
 	Outputdefinition88Enum,
 	Outputdefinition89Enum,
+	Outputdefinition8Enum,
 	Outputdefinition90Enum,
 	Outputdefinition91Enum,
@@ -694,358 +981,148 @@
 	Outputdefinition98Enum,
 	Outputdefinition99Enum,
-	Outputdefinition100Enum,   
-	OutputdefinitionListEnum,
-	MassfluxatgateEnum,
-	NodalvalueEnum,
-	VxObsEnum,
-	VyObsEnum,
-	/*}}}*/
-	/*Relaxation{{{*/
-	AbsoluteEnum,
-	IncrementalEnum,
-	AugmentedLagrangianREnum,
-	AugmentedLagrangianRhopEnum,
-	AugmentedLagrangianRlambdaEnum,
-	AugmentedLagrangianRholambdaEnum,
-	AugmentedLagrangianThetaEnum,
-	/*}}}*/
-	/*Grounding Line{{{*/
-	NoneEnum,
-	AggressiveMigrationEnum,
+	Outputdefinition9Enum,
+	Outputdefinition100Enum,
+	P0ArrayEnum,
+	P1bubblecondensedEnum,
+	P1bubbleEnum,
+	P1DGEnum,
+	P1P1Enum,
+	P1P1GLSEnum,
+	P1xP2Enum,
+	P1xP3Enum,
+	P1xP4Enum,
+	P2bubblecondensedEnum,
+	P2bubbleEnum,
+	P2Enum,
+	P2xP1Enum,
+	P2xP4Enum,
+	PatersonEnum,
+	PengridEnum,
+	PenpairEnum,
+	PentaEnum,
+	PentaInputEnum,
+	ProfilerEnum,
+	ProfilingCurrentFlopsEnum,
+	ProfilingCurrentMemEnum,
+	ProfilingSolutionTimeEnum,
+	RegionaloutputEnum,
+	RegularEnum,
+	ResetPenaltiesEnum,
+	RiftfrontEnum,
+	ScaledEnum,
+	SealevelAbsoluteEnum,
+	SealevelEmotionEnum,
+	SealevelEustaticEnum,
+	SealevelInertiaTensorXZEnum,
+	SealevelInertiaTensorYZEnum,
+	SealevelInertiaTensorZZEnum,
+	SealevelNmotionEnum,
+	SealevelriseAnalysisEnum,
+	SealevelriseSolutionEnum,
+	SealevelriseStericRateEnum,
+	SealevelUmotionEnum,
+	SedimentHeadStackedEnum,
+	SedimentHeadTimeAverageEnum,
+	SegEnum,
+	SegInputEnum,
+	SegmentEnum,
+	SegmentRiftfrontEnum,
+	SeparateEnum,
+	SeqEnum,
+	SIAApproximationEnum,
+	SigmaVMEnum,
+	SmbAnalysisEnum,
+	SMBcomponentsEnum,
+	SMBd18opddEnum,
+	SmbDesfacEnum,
+	SmbDpermilEnum,
+	SmbDzAddEnum,
+	SmbFACEnum,
+	SMBforcingEnum,
+	SMBgcmEnum,
+	SMBgembEnum,
+	SMBgradientselaEnum,
+	SMBgradientsEnum,
+	SMBhenningEnum,
+	SmbMAddEnum,
+	SMBmeltcomponentsEnum,
+	SMBpddEnum,
+	SmbRlapsEnum,
+	SmbRlapslgmEnum,
+	SmbSolutionEnum,
+	SmoothAnalysisEnum,
 	SoftMigrationEnum,
+	SpcDynamicEnum,
+	SpcStaticEnum,
+	SpcTransientEnum,
+	SSAApproximationEnum,
+	SSAFSApproximationEnum,
+	SSAHOApproximationEnum,
+	SsetEnum,
+	SteadystateSolutionEnum,
+	StressbalanceAnalysisEnum,
+	StressbalanceConvergenceNumStepsEnum,
+	StressbalanceSIAAnalysisEnum,
+	StressbalanceSolutionEnum,
+	StressbalanceVerticalAnalysisEnum,
+	StressIntensityFactorEnum,
+	StringArrayParamEnum,
+	StringExternalResultEnum,
+	StringParamEnum,
+	SubelementMigration2Enum,
+	SubelementMigration3Enum,
 	SubelementMigrationEnum,
-	SubelementMigration2Enum,
-	ContactEnum,
-	GroundingOnlyEnum,
-	MaskGroundediceLevelsetEnum,
-	/*}}}*/
-	/*Parameters{{{*/
-	AdjointEnum,
-	ColinearEnum,
-	ControlSteadyEnum,
-	FsetEnum,
-	Gradient1Enum,
-	Gradient2Enum,
-	Gradient3Enum,
-	GradientEnum,
-	GroundinglineMigrationEnum,
-	GsetEnum,
-	IndexEnum,
-	IndexedEnum,
-	IntersectEnum,
-	NodalEnum,
-	OldGradientEnum,
-	OutputBufferPointerEnum,
-	OutputBufferSizePointerEnum,
-	OutputFilePointerEnum,
-	ToolkitsFileNameEnum,
-	RootPathEnum,
-	OutputFileNameEnum,
-	InputFileNameEnum,
-	LockFileNameEnum,
-	RestartFileNameEnum,
-	ToolkitsOptionsAnalysesEnum,
-	ToolkitsOptionsStringsEnum,
-	QmuErrNameEnum,
-	QmuInNameEnum,
-	QmuOutNameEnum,
-	RegularEnum,
-	ScaledEnum,
-	SeparateEnum,
-	SsetEnum,
-	/*}}}*/
-	/*Toolkits{{{*/
-	DenseEnum,
-	MpiDenseEnum,
-	MpiSparseEnum,
-	SeqEnum,
-	MpiEnum,
-	MumpsEnum,
-	GslEnum,
-	/*}}}*/
-	/*Rheology law (move to Material) {{{*/
-	CuffeyEnum,
-	BuddJackaEnum,
-	CuffeyTemperateEnum,
-	PatersonEnum,
-	ArrheniusEnum,
-	LliboutryDuvalEnum,
-	/*}}}*/
-	/*Levelset related enums (will be moved to appropriate place when finished){{{*/
-	ExtrapolationVariableEnum,
-	IceMaskNodeActivationEnum,
-	LevelsetfunctionSlopeXEnum,
-	LevelsetfunctionSlopeYEnum,
-	LevelsetfunctionPicardEnum,
-	LevelsetReinitFrequencyEnum,
-	/*}}}*/
-	/*Sea Level Rise{{{*/
-	SealevelEnum,
-	SealevelUmotionEnum,
-	SealevelNmotionEnum,
-	SealevelEmotionEnum,
-	SealevelAbsoluteEnum,
-	SealevelEustaticEnum,
-	SealevelriseDeltathicknessEnum,
-	SealevelriseMaxiterEnum,
-	SealevelriseReltolEnum,
-	SealevelriseAbstolEnum,
-	SealevelriseRigidEnum,
-	SealevelriseElasticEnum,
-	SealevelriseRotationEnum,
-	SealevelriseTidalLoveHEnum,
-	SealevelriseTidalLoveKEnum, 
-	SealevelriseFluidLoveEnum, 
-	SealevelriseEquatorialMoiEnum, 
-	SealevelrisePolarMoiEnum, 
-	SealevelriseAngularVelocityEnum,
-	SealevelriseOceanAreaScalingEnum,
-	SealevelriseGElasticEnum,
-	SealevelriseUElasticEnum,
-	SealevelriseHElasticEnum,
-	SealevelriseTransitionsEnum,
-	SealevelriseRequestedOutputsEnum,
-	SealevelriseNumRequestedOutputsEnum,
-	/*}}}*/
-	/*Elastic adjustment (ESA){{{*/
-	EsaUmotionEnum,
-	EsaNmotionEnum,
-	EsaEmotionEnum,
-	EsaStrainratexxEnum,
-   EsaStrainratexyEnum,
-   EsaStrainrateyyEnum,
-   EsaRotationrateEnum,
-	EsaDeltathicknessEnum,
-	EsaUElasticEnum,
-	EsaHElasticEnum,
-	EsaTransitionsEnum,
-	EsaRequestedOutputsEnum,
-	EsaNumRequestedOutputsEnum,
-	/*}}}*/
-	/*Adaptive mesh refinement (AMR){{{*/
-	AmrLevelMaxEnum,
-	AmrRegionLevel1Enum,
-	AmrRegionLevelMaxEnum,
-	TransientAmrFrequencyEnum,
-	/*}}}*/
-	ParametersENDEnum,
-	/*Coordinate Systems{{{*/
+	SurfaceCrevasseEnum,
+	SurfaceSlopeSolutionEnum,
+	TaylorHoodEnum,
+	TemperaturePDDEnum,
+	TetraEnum,
+	TetraInputEnum,
+	ThermalAnalysisEnum,
+	ThermalSolutionEnum,
+	ThermalSpctemperatureEnum,
+	ThicknessErrorEstimatorEnum,
+	TotalFloatingBmbEnum,
+	TotalFloatingBmbScaledEnum,
+	TotalGroundedBmbEnum,
+	TotalGroundedBmbScaledEnum,
+	TotalSmbEnum,
+	TotalSmbScaledEnum,
+	TransientArrayParamEnum,
+	TransientInputEnum,
+	TransientParamEnum,
+	TransientSolutionEnum,
+	TriaEnum,
+	TriaInputEnum,
+	UzawaPressureAnalysisEnum,
+	VectorParamEnum,
+	VertexEnum,
+	VertexPIdEnum,
+	VertexSIdEnum,
+	VerticesEnum,
+	ViscousHeatingEnum,
+	WaterEnum,
+	XTaylorHoodEnum,
 	XYEnum,
 	XYZEnum,
 	/*}}}*/
-	/*Objects {{{*/
-	GenericParamEnum,
-	BoolInputEnum,
-	BoolParamEnum,
-	ContourEnum,
-	ControlInputEnum,
-	DatasetInputEnum,
-	DoubleInputEnum,
-	DoubleArrayInputEnum,
-	DataSetParamEnum,
-	DoubleMatArrayParamEnum,
-	DoubleMatParamEnum,
-	DoubleParamEnum,
-	DoubleVecParamEnum,
-	ElementEnum,
-	ElementHookEnum,
-	HookEnum,
-	ExternalResultEnum,
-	FileParamEnum,
-	InputEnum,
-	IntInputEnum,
-	IntParamEnum,
-	IntVecParamEnum,
-	TransientParamEnum,
-	MaticeEnum,
-	MatdamageiceEnum,
-	MatenhancediceEnum,
-	MatestarEnum,
-	MatparEnum,
-	NodeEnum,
-	NumericalfluxEnum,
-	NeumannfluxEnum,
-	ParamEnum,
-	MoulinEnum,
-	PengridEnum,
-	PenpairEnum,
-	ProfilerEnum,
-	MatrixParamEnum,
-	MassconEnum,
-	MassconaxpbyEnum,
-	NodeSIdEnum,
-	ElementSIdEnum,
-	VectorParamEnum,
-	RiftfrontEnum,
-	SegmentEnum,
-	SegmentRiftfrontEnum,
-	SpcDynamicEnum,
-	SpcStaticEnum,
-	SpcTransientEnum,
-	StringArrayParamEnum,
-	StringParamEnum,
-	SegEnum,
-	SegInputEnum,
-	TriaEnum,
-	TriaInputEnum,
-	TetraEnum,
-	TetraInputEnum,
-	PentaEnum,
-	PentaInputEnum,
-	VertexEnum,
-	VertexPIdEnum,
-	VertexSIdEnum,
-	/*}}}*/
-	/*Options{{{*/
-	OptionEnum,
-	GenericOptionEnum,
-	OptionCellEnum,
-	OptionStructEnum,
-	/*}}}*/
-	/*Solutions and Analyses{{{ */
-	AdjointBalancethicknessAnalysisEnum,
-	AdjointBalancethickness2AnalysisEnum,
-	AdjointHorizAnalysisEnum,
-	DefaultAnalysisEnum,
-	BalancethicknessAnalysisEnum,
-	BalancethicknessSolutionEnum,
-	Balancethickness2AnalysisEnum,
-	Balancethickness2SolutionEnum,
-	BalancethicknessSoftAnalysisEnum,
-	BalancethicknessSoftSolutionEnum,
-	BalancevelocityAnalysisEnum,
-	BalancevelocitySolutionEnum,
-	L2ProjectionEPLAnalysisEnum,
-	L2ProjectionBaseAnalysisEnum,
-	BedSlopeSolutionEnum,
-	DamageEvolutionSolutionEnum,
-	DamageEvolutionAnalysisEnum,
-	StressbalanceAnalysisEnum,
-	StressbalanceSIAAnalysisEnum,
-	StressbalanceSolutionEnum,
-	StressbalanceVerticalAnalysisEnum,
-	EnthalpyAnalysisEnum,
-	HydrologyShreveAnalysisEnum,
-	HydrologyDCInefficientAnalysisEnum,
-	HydrologyDCEfficientAnalysisEnum,
-	HydrologySommersAnalysisEnum,
-	HydrologySolutionEnum,
-	MeltingAnalysisEnum,
-	MasstransportAnalysisEnum,
-	MasstransportSolutionEnum,
-	FreeSurfaceBaseAnalysisEnum,
-	FreeSurfaceTopAnalysisEnum,
-	ExtrudeFromBaseAnalysisEnum,
-	ExtrudeFromTopAnalysisEnum,
-	DepthAverageAnalysisEnum,
-	SealevelriseSolutionEnum,
-	SealevelriseAnalysisEnum,
-	SteadystateSolutionEnum,
-	SurfaceSlopeSolutionEnum,
-	SmoothAnalysisEnum,
-	ThermalAnalysisEnum,
-	ThermalSolutionEnum,
-	TransientSolutionEnum,
-	UzawaPressureAnalysisEnum,
-	GiaSolutionEnum,
-	GiaIvinsAnalysisEnum,
-	EsaSolutionEnum,
-	EsaAnalysisEnum,
-	MeshdeformationAnalysisEnum,
-	LevelsetAnalysisEnum,
-	ExtrapolationAnalysisEnum,
-	/*}}}*/
-	/*Approximations {{{*/
-	ApproximationEnum,
-	NoneApproximationEnum,
-	SIAApproximationEnum,
-	SSAApproximationEnum,
-	SSAHOApproximationEnum,
-	SSAFSApproximationEnum,
-	L1L2ApproximationEnum,
-	HOApproximationEnum,
-	HOFSApproximationEnum,
-	FSApproximationEnum,
-	FSvelocityEnum,
-	FSpressureEnum,
-	/*}}}*/
-	/*Gauss{{{*/
-	GaussSegEnum,
-	GaussTriaEnum,
-	GaussTetraEnum,
-	GaussPentaEnum,
-	/*}}}*/
-	/*Interpolation {{{*/
+	/*Unused?{{{*/
+	BalancethicknessD0Enum,
+	BalancethicknessDiffusionCoefficientEnum,
+	BilinearInterpEnum,
+	CalvingdevCoeffEnum,
+	DeviatoricStressEnum,
+	EtaAbsGradientEnum,
+	MeshZEnum,
+	NearestInterpEnum,
+	OutputdefinitionListEnum,
+	SealevelObsEnum,
+	SealevelWeightsEnum,
+	StrainRateEnum,
+	StressbalanceViscosityOvershootEnum,
+	StressTensorEnum,
+	SubelementMigration4Enum,
+	TimesteppingTimeAdaptEnum,
 	TriangleInterpEnum,
-	BilinearInterpEnum,
-	NearestInterpEnum,
-	/*}}}*/
-	/*Responses{{{*/
-	MinVelEnum,
-	MaxVelEnum,
-	MinVxEnum,
-	MaxVxEnum,
-	MaxAbsVxEnum,
-	MinVyEnum,
-	MaxVyEnum,
-	MaxAbsVyEnum,
-	MinVzEnum,
-	MaxVzEnum,
-	MaxAbsVzEnum,
-	FloatingAreaEnum,
-	GroundedAreaEnum,
-	IceMassEnum,
-	IceVolumeEnum,
-	IceVolumeAboveFloatationEnum,
-	TotalFloatingBmbEnum,
-	TotalGroundedBmbEnum,
-	TotalSmbEnum,
-	/*}}}*/
-	/*Element Interpolations{{{*/
-	P0Enum,
-	P0ArrayEnum,
-	P1Enum,
-	P1DGEnum,
-	P1bubbleEnum,
-	P1bubblecondensedEnum,
-	P2Enum,
-	P2bubbleEnum,
-	P2bubblecondensedEnum,
-	P2xP1Enum,
-	P1xP2Enum,
-	P1xP3Enum,
-	P2xP4Enum,
-	P1P1Enum,
-	P1P1GLSEnum,
-	MINIEnum,
-	MINIcondensedEnum,
-	TaylorHoodEnum,
-	LATaylorHoodEnum,
-	XTaylorHoodEnum,
-	OneLayerP4zEnum,
-	CrouzeixRaviartEnum,
-	LACrouzeixRaviartEnum,
-	/*}}}*/
-	/*Rift state {{{*/
-	ClosedEnum,
-	FreeEnum,
-	OpenEnum,
-	/*}}}*/
-	/*Fill {{{*/
-	AirEnum,
-	IceEnum,
-	MelangeEnum,
-	WaterEnum,
-	/*}}}*/
-	/*Datasets {{{*/
-	DataSetEnum,
-	ConstraintsEnum,
-	LoadsEnum,
-	MaterialsEnum,
-	NodesEnum,
-	ContoursEnum,
-	ParametersEnum,
-	VerticesEnum,
-	ResultsEnum,
 	/*}}}*/
 	MaximumNumberOfDefinitionsEnum
Index: /issm/trunk/src/c/shared/Enum/EnumToStringx.cpp
===================================================================
--- /issm/trunk/src/c/shared/Enum/EnumToStringx.cpp	(revision 22757)
+++ /issm/trunk/src/c/shared/Enum/EnumToStringx.cpp	(revision 22758)
@@ -17,534 +17,559 @@
 	switch(en){
 
-		case FemModelEnum : return "FemModel";
 		case ParametersSTARTEnum : return "ParametersSTART";
 		case AdolcParamEnum : return "AdolcParam";
-		case FSSolverEnum : return "FSSolver";
+		case AmrDeviatoricErrorGroupThresholdEnum : return "AmrDeviatoricErrorGroupThreshold";
+		case AmrDeviatoricErrorMaximumEnum : return "AmrDeviatoricErrorMaximum";
+		case AmrDeviatoricErrorResolutionEnum : return "AmrDeviatoricErrorResolution";
+		case AmrDeviatoricErrorThresholdEnum : return "AmrDeviatoricErrorThreshold";
+		case AmrErrEnum : return "AmrErr";
+		case AmrFieldEnum : return "AmrField";
+		case AmrGradationEnum : return "AmrGradation";
+		case AmrGroundingLineDistanceEnum : return "AmrGroundingLineDistance";
+		case AmrGroundingLineResolutionEnum : return "AmrGroundingLineResolution";
+		case AmrHmaxEnum : return "AmrHmax";
+		case AmrHminEnum : return "AmrHmin";
+		case AmrIceFrontDistanceEnum : return "AmrIceFrontDistance";
+		case AmrIceFrontResolutionEnum : return "AmrIceFrontResolution";
+		case AmrKeepMetricEnum : return "AmrKeepMetric";
+		case AmrLagEnum : return "AmrLag";
+		case AmrLevelMaxEnum : return "AmrLevelMax";
+		case AmrRestartEnum : return "AmrRestart";
+		case AmrThicknessErrorGroupThresholdEnum : return "AmrThicknessErrorGroupThreshold";
+		case AmrThicknessErrorMaximumEnum : return "AmrThicknessErrorMaximum";
+		case AmrThicknessErrorResolutionEnum : return "AmrThicknessErrorResolution";
+		case AmrThicknessErrorThresholdEnum : return "AmrThicknessErrorThreshold";
+		case AmrTypeEnum : return "AmrType";
+		case AnalysisCounterEnum : return "AnalysisCounter";
+		case AnalysisTypeEnum : return "AnalysisType";
+		case AugmentedLagrangianREnum : return "AugmentedLagrangianR";
+		case AugmentedLagrangianRholambdaEnum : return "AugmentedLagrangianRholambda";
+		case AugmentedLagrangianRhopEnum : return "AugmentedLagrangianRhop";
+		case AugmentedLagrangianRlambdaEnum : return "AugmentedLagrangianRlambda";
+		case AugmentedLagrangianThetaEnum : return "AugmentedLagrangianTheta";
+		case AutodiffCbufsizeEnum : return "AutodiffCbufsize";
+		case AutodiffDependentObjectsEnum : return "AutodiffDependentObjects";
+		case AutodiffDriverEnum : return "AutodiffDriver";
+		case AutodiffFosForwardIndexEnum : return "AutodiffFosForwardIndex";
+		case AutodiffFosReverseIndexEnum : return "AutodiffFosReverseIndex";
+		case AutodiffFovForwardIndicesEnum : return "AutodiffFovForwardIndices";
+		case AutodiffGcTriggerMaxSizeEnum : return "AutodiffGcTriggerMaxSize";
+		case AutodiffGcTriggerRatioEnum : return "AutodiffGcTriggerRatio";
+		case AutodiffIsautodiffEnum : return "AutodiffIsautodiff";
+		case AutodiffLbufsizeEnum : return "AutodiffLbufsize";
+		case AutodiffNumDependentsEnum : return "AutodiffNumDependents";
+		case AutodiffNumIndependentsEnum : return "AutodiffNumIndependents";
+		case AutodiffObufsizeEnum : return "AutodiffObufsize";
+		case AutodiffTbufsizeEnum : return "AutodiffTbufsize";
+		case AutodiffXpEnum : return "AutodiffXp";
+		case BalancethicknessStabilizationEnum : return "BalancethicknessStabilization";
+		case BasalforcingsBottomplumedepthEnum : return "BasalforcingsBottomplumedepth";
+		case BasalforcingsCrustthicknessEnum : return "BasalforcingsCrustthickness";
+		case BasalforcingsDeepwaterElevationEnum : return "BasalforcingsDeepwaterElevation";
+		case BasalforcingsDeepwaterMeltingRateEnum : return "BasalforcingsDeepwaterMeltingRate";
+		case BasalforcingsDtbgEnum : return "BasalforcingsDtbg";
+		case BasalforcingsEnum : return "Basalforcings";
+		case BasalforcingsLowercrustheatEnum : return "BasalforcingsLowercrustheat";
+		case BasalforcingsMantleconductivityEnum : return "BasalforcingsMantleconductivity";
+		case BasalforcingsMeltrateFactorEnum : return "BasalforcingsMeltrateFactor";
+		case BasalforcingsNusseltEnum : return "BasalforcingsNusselt";
+		case BasalforcingsPicoAverageOverturningEnum : return "BasalforcingsPicoAverageOverturning";
+		case BasalforcingsPicoAverageSalinityEnum : return "BasalforcingsPicoAverageSalinity";
+		case BasalforcingsPicoAverageTemperatureEnum : return "BasalforcingsPicoAverageTemperature";
+		case BasalforcingsPicoBoxAreaEnum : return "BasalforcingsPicoBoxArea";
+		case BasalforcingsPicoFarOceansalinityEnum : return "BasalforcingsPicoFarOceansalinity";
+		case BasalforcingsPicoFarOceantemperatureEnum : return "BasalforcingsPicoFarOceantemperature";
+		case BasalforcingsPicoGammaTEnum : return "BasalforcingsPicoGammaT";
+		case BasalforcingsPicoMaxboxcountEnum : return "BasalforcingsPicoMaxboxcount";
+		case BasalforcingsPicoNumBasinsEnum : return "BasalforcingsPicoNumBasins";
+		case BasalforcingsPicoOverturningCoeffEnum : return "BasalforcingsPicoOverturningCoeff";
+		case BasalforcingsPlumeradiusEnum : return "BasalforcingsPlumeradius";
+		case BasalforcingsPlumexEnum : return "BasalforcingsPlumex";
+		case BasalforcingsPlumeyEnum : return "BasalforcingsPlumey";
+		case BasalforcingsThresholdThicknessEnum : return "BasalforcingsThresholdThickness";
+		case BasalforcingsTopplumedepthEnum : return "BasalforcingsTopplumedepth";
+		case BasalforcingsUppercrustheatEnum : return "BasalforcingsUppercrustheat";
+		case BasalforcingsUppercrustthicknessEnum : return "BasalforcingsUppercrustthickness";
+		case BasalforcingsUpperdepthMeltEnum : return "BasalforcingsUpperdepthMelt";
+		case BasalforcingsUpperwaterElevationEnum : return "BasalforcingsUpperwaterElevation";
+		case CalvingCrevasseDepthEnum : return "CalvingCrevasseDepth";
+		case CalvingHeightAboveFloatationEnum : return "CalvingHeightAboveFloatation";
+		case CalvingLawEnum : return "CalvingLaw";
+		case CalvingMaxEnum : return "CalvingMax";
+		case CalvingMinthicknessEnum : return "CalvingMinthickness";
+		case ConfigurationTypeEnum : return "ConfigurationType";
+		case ConstantsYtsEnum : return "ConstantsYts";
+		case DamageC1Enum : return "DamageC1";
+		case DamageC2Enum : return "DamageC2";
+		case DamageC3Enum : return "DamageC3";
+		case DamageEnum : return "Damage";
+		case DamageEquivStressEnum : return "DamageEquivStress";
+		case DamageEvolutionNumRequestedOutputsEnum : return "DamageEvolutionNumRequestedOutputs";
+		case DamageEvolutionRequestedOutputsEnum : return "DamageEvolutionRequestedOutputs";
+		case DamageHealingEnum : return "DamageHealing";
+		case DamageKappaEnum : return "DamageKappa";
+		case DamageLawEnum : return "DamageLaw";
+		case DamageMaxDamageEnum : return "DamageMaxDamage";
+		case DamageStabilizationEnum : return "DamageStabilization";
+		case DamageStressThresholdEnum : return "DamageStressThreshold";
+		case DebugProfilingEnum : return "DebugProfiling";
+		case DomainDimensionEnum : return "DomainDimension";
+		case DomainTypeEnum : return "DomainType";
+		case EarthIdEnum : return "EarthId";
+		case EplZigZagCounterEnum : return "EplZigZagCounter";
+		case EsaHElasticEnum : return "EsaHElastic";
+		case EsaHemisphereEnum : return "EsaHemisphere";
+		case EsaRequestedOutputsEnum : return "EsaRequestedOutputs";
+		case EsaUElasticEnum : return "EsaUElastic";
+		case ExtrapolationVariableEnum : return "ExtrapolationVariable";
 		case FemModelCommEnum : return "FemModelComm";
-		case WorldCommEnum : return "WorldComm";
+		case FlowequationFeFSEnum : return "FlowequationFeFS";
+		case FlowequationIsFSEnum : return "FlowequationIsFS";
+		case FlowequationIsHOEnum : return "FlowequationIsHO";
+		case FlowequationIsL1L2Enum : return "FlowequationIsL1L2";
+		case FlowequationIsSIAEnum : return "FlowequationIsSIA";
+		case FlowequationIsSSAEnum : return "FlowequationIsSSA";
+		case FrictionCouplingEnum : return "FrictionCoupling";
+		case FrictionFEnum : return "FrictionF";
+		case FrictionGammaEnum : return "FrictionGamma";
+		case FrictionLawEnum : return "FrictionLaw";
+		case GiaCrossSectionShapeEnum : return "GiaCrossSectionShape";
+		case GroundinglineMigrationEnum : return "GroundinglineMigration";
+		case HydrologydcEplflipLockEnum : return "HydrologydcEplflipLock";
+		case HydrologydcEplThickCompEnum : return "HydrologydcEplThickComp";
+		case HydrologydcIsefficientlayerEnum : return "HydrologydcIsefficientlayer";
+		case HydrologydcLeakageFactorEnum : return "HydrologydcLeakageFactor";
+		case HydrologydcMaxIterEnum : return "HydrologydcMaxIter";
+		case HydrologydcPenaltyFactorEnum : return "HydrologydcPenaltyFactor";
+		case HydrologydcPenaltyLockEnum : return "HydrologydcPenaltyLock";
+		case HydrologydcRelTolEnum : return "HydrologydcRelTol";
+		case HydrologydcSedimentlimitEnum : return "HydrologydcSedimentlimit";
+		case HydrologydcSedimentlimitFlagEnum : return "HydrologydcSedimentlimitFlag";
+		case HydrologydcTransferFlagEnum : return "HydrologydcTransferFlag";
+		case HydrologydcUnconfinedFlagEnum : return "HydrologydcUnconfinedFlag";
+		case HydrologydtEnum : return "Hydrologydt";
+		case HydrologyModelEnum : return "HydrologyModel";
+		case HydrologyNumRequestedOutputsEnum : return "HydrologyNumRequestedOutputs";
+		case HydrologyRelaxationEnum : return "HydrologyRelaxation";
+		case HydrologyRequestedOutputsEnum : return "HydrologyRequestedOutputs";
+		case HydrologySedimentKmaxEnum : return "HydrologySedimentKmax";
+		case HydrologyshreveStabilizationEnum : return "HydrologyshreveStabilization";
+		case HydrologyStepsPerStepEnum : return "HydrologyStepsPerStep";
+		case HydrologyStorageEnum : return "HydrologyStorage";
 		case IcecapToEarthCommEnum : return "IcecapToEarthComm";
-		case NumModelsEnum : return "NumModels";
-		case ModelIdEnum : return "ModelId";
-		case EarthIdEnum : return "EarthId";
-		case SolutionTypeEnum : return "SolutionType";
-		case AnalysisTypeEnum : return "AnalysisType";
-		case AnalysisCounterEnum : return "AnalysisCounter";
-		case ConfigurationTypeEnum : return "ConfigurationType";
+		case IndexEnum : return "Index";
+		case InputFileNameEnum : return "InputFileName";
+		case InputToDepthaverageInEnum : return "InputToDepthaverageIn";
+		case InputToDepthaverageOutEnum : return "InputToDepthaverageOut";
 		case InputToExtrudeEnum : return "InputToExtrude";
 		case InputToL2ProjectEnum : return "InputToL2Project";
-		case InputToDepthaverageInEnum : return "InputToDepthaverageIn";
-		case InputToDepthaverageOutEnum : return "InputToDepthaverageOut";
 		case InputToSmoothEnum : return "InputToSmooth";
+		case InversionAlgorithmEnum : return "InversionAlgorithm";
+		case InversionControlParametersEnum : return "InversionControlParameters";
+		case InversionControlScalingFactorsEnum : return "InversionControlScalingFactors";
+		case ControlInputSizeMEnum : return "ControlInputSizeM";
+		case ControlInputSizeNEnum : return "ControlInputSizeN";
+		case InversionCostFunctionsEnum : return "InversionCostFunctions";
+		case InversionDxminEnum : return "InversionDxmin";
+		case InversionGatolEnum : return "InversionGatol";
+		case InversionGradientScalingEnum : return "InversionGradientScaling";
+		case InversionGrtolEnum : return "InversionGrtol";
+		case InversionGttolEnum : return "InversionGttol";
+		case InversionIncompleteAdjointEnum : return "InversionIncompleteAdjoint";
+		case InversionIscontrolEnum : return "InversionIscontrol";
+		case InversionMaxiterEnum : return "InversionMaxiter";
+		case InversionMaxiterPerStepEnum : return "InversionMaxiterPerStep";
+		case InversionMaxstepsEnum : return "InversionMaxsteps";
+		case InversionNstepsEnum : return "InversionNsteps";
+		case InversionNumControlParametersEnum : return "InversionNumControlParameters";
+		case InversionNumCostFunctionsEnum : return "InversionNumCostFunctions";
+		case InversionStepThresholdEnum : return "InversionStepThreshold";
+		case InversionTypeEnum : return "InversionType";
+		case LevelsetReinitFrequencyEnum : return "LevelsetReinitFrequency";
+		case LevelsetStabilizationEnum : return "LevelsetStabilization";
+		case LockFileNameEnum : return "LockFileName";
+		case LoveAllowLayerDeletionEnum : return "LoveAllowLayerDeletion";
+		case LoveForcingTypeEnum : return "LoveForcingType";
+		case LoveFrequenciesEnum : return "LoveFrequencies";
+		case LoveG0Enum : return "LoveG0";
+		case LoveKernelsEnum : return "LoveKernels";
+		case LoveMu0Enum : return "LoveMu0";
+		case LoveNfreqEnum : return "LoveNfreq";
+		case LoveR0Enum : return "LoveR0";
+		case LoveShNmaxEnum : return "LoveShNmax";
+		case LoveShNminEnum : return "LoveShNmin";
+		case MassFluxSegmentsEnum : return "MassFluxSegments";
+		case MassFluxSegmentsPresentEnum : return "MassFluxSegmentsPresent";
+		case MasstransportHydrostaticAdjustmentEnum : return "MasstransportHydrostaticAdjustment";
+		case MasstransportIsfreesurfaceEnum : return "MasstransportIsfreesurface";
+		case MasstransportMinThicknessEnum : return "MasstransportMinThickness";
+		case MasstransportNumRequestedOutputsEnum : return "MasstransportNumRequestedOutputs";
+		case MasstransportPenaltyFactorEnum : return "MasstransportPenaltyFactor";
+		case MasstransportRequestedOutputsEnum : return "MasstransportRequestedOutputs";
+		case MasstransportStabilizationEnum : return "MasstransportStabilization";
+		case MeltingOffsetEnum : return "MeltingOffset";
+		case MeshAverageVertexConnectivityEnum : return "MeshAverageVertexConnectivity";
+		case MeshElementtypeEnum : return "MeshElementtype";
+		case MeshNumberoflayersEnum : return "MeshNumberoflayers";
+		case MeshNumberofverticesEnum : return "MeshNumberofvertices";
+		case ModelIdEnum : return "ModelId";
+		case NodesEnum : return "Nodes";
+		case NumModelsEnum : return "NumModels";
+		case OceanGridNxEnum : return "OceanGridNx";
+		case OceanGridNyEnum : return "OceanGridNy";
+		case OceanGridXEnum : return "OceanGridX";
+		case OceanGridYEnum : return "OceanGridY";
+		case OutputBufferPointerEnum : return "OutputBufferPointer";
+		case OutputBufferSizePointerEnum : return "OutputBufferSizePointer";
+		case OutputdefinitionEnum : return "Outputdefinition";
+		case OutputFileNameEnum : return "OutputFileName";
+		case OutputFilePointerEnum : return "OutputFilePointer";
+		case ParamEnum : return "Param";
+		case ParametersEnum : return "Parameters";
+		case QmuErrNameEnum : return "QmuErrName";
+		case QmuInNameEnum : return "QmuInName";
+		case QmuIsdakotaEnum : return "QmuIsdakota";
+		case QmuNumberofpartitionsEnum : return "QmuNumberofpartitions";
+		case QmuOutNameEnum : return "QmuOutName";
+		case QmuPartitionEnum : return "QmuPartition";
+		case QmuResponsedescriptorsEnum : return "QmuResponsedescriptors";
+		case QmuVariableDescriptorsEnum : return "QmuVariableDescriptors";
+		case RestartFileNameEnum : return "RestartFileName";
+		case ResultsEnum : return "Results";
+		case RootPathEnum : return "RootPath";
+		case SaveResultsEnum : return "SaveResults";
+		case SealevelriseAbstolEnum : return "SealevelriseAbstol";
+		case SealevelriseAngularVelocityEnum : return "SealevelriseAngularVelocity";
+		case SealevelriseElasticEnum : return "SealevelriseElastic";
+		case SealevelriseEquatorialMoiEnum : return "SealevelriseEquatorialMoi";
+		case SealevelriseFluidLoveEnum : return "SealevelriseFluidLove";
+		case SealevelriseGElasticEnum : return "SealevelriseGElastic";
+		case SealevelriseHElasticEnum : return "SealevelriseHElastic";
+		case SealevelriseMaxiterEnum : return "SealevelriseMaxiter";
+		case SealevelriseOceanAreaScalingEnum : return "SealevelriseOceanAreaScaling";
+		case SealevelrisePolarMoiEnum : return "SealevelrisePolarMoi";
+		case SealevelriseReltolEnum : return "SealevelriseReltol";
+		case SealevelriseRequestedOutputsEnum : return "SealevelriseRequestedOutputs";
+		case SealevelriseRigidEnum : return "SealevelriseRigid";
+		case SealevelriseRotationEnum : return "SealevelriseRotation";
+		case SealevelriseTidalLoveHEnum : return "SealevelriseTidalLoveH";
+		case SealevelriseTidalLoveKEnum : return "SealevelriseTidalLoveK";
+		case SealevelriseTransitionsEnum : return "SealevelriseTransitions";
+		case SealevelriseUElasticEnum : return "SealevelriseUElastic";
+		case SettingsIoGatherEnum : return "SettingsIoGather";
+		case SettingsOutputFrequencyEnum : return "SettingsOutputFrequency";
+		case SettingsRecordingFrequencyEnum : return "SettingsRecordingFrequency";
+		case SettingsResultsOnNodesEnum : return "SettingsResultsOnNodes";
+		case SettingsSolverResidueThresholdEnum : return "SettingsSolverResidueThreshold";
+		case SettingsWaitonlockEnum : return "SettingsWaitonlock";
+		case SmbAdThreshEnum : return "SmbAdThresh";
+		case SmbAIceEnum : return "SmbAIce";
+		case SmbAIdxEnum : return "SmbAIdx";
+		case SmbASnowEnum : return "SmbASnow";
+		case SmbCldFracEnum : return "SmbCldFrac";
+		case SmbDelta18oEnum : return "SmbDelta18o";
+		case SmbDelta18oSurfaceEnum : return "SmbDelta18oSurface";
+		case SmbDenIdxEnum : return "SmbDenIdx";
+		case SmbDtEnum : return "SmbDt";
+		case SmbEnum : return "Smb";
+		case SmbFEnum : return "SmbF";
+		case SmbInitDensityScalingEnum : return "SmbInitDensityScaling";
+		case SmbIsaccumulationEnum : return "SmbIsaccumulation";
+		case SmbIsalbedoEnum : return "SmbIsalbedo";
+		case SmbIsd18opdEnum : return "SmbIsd18opd";
+		case SmbIsdelta18oEnum : return "SmbIsdelta18o";
+		case SmbIsdensificationEnum : return "SmbIsdensification";
+		case SmbIsgraingrowthEnum : return "SmbIsgraingrowth";
+		case SmbIsmeltEnum : return "SmbIsmelt";
+		case SmbIsmungsmEnum : return "SmbIsmungsm";
+		case SmbIssetpddfacEnum : return "SmbIssetpddfac";
+		case SmbIsshortwaveEnum : return "SmbIsshortwave";
+		case SmbIstemperaturescaledEnum : return "SmbIstemperaturescaled";
+		case SmbIsthermalEnum : return "SmbIsthermal";
+		case SmbIsturbulentfluxEnum : return "SmbIsturbulentflux";
+		case SmbKEnum : return "SmbK";
+		case SmbNumRequestedOutputsEnum : return "SmbNumRequestedOutputs";
+		case SmbPfacEnum : return "SmbPfac";
+		case SmbRequestedOutputsEnum : return "SmbRequestedOutputs";
+		case SmbSealevEnum : return "SmbSealev";
+		case SmbSwIdxEnum : return "SmbSwIdx";
+		case SmbT0dryEnum : return "SmbT0dry";
+		case SmbT0wetEnum : return "SmbT0wet";
+		case SmbTdiffEnum : return "SmbTdiff";
+		case SmbThermoDeltaTScalingEnum : return "SmbThermoDeltaTScaling";
 		case SmoothThicknessMultiplierEnum : return "SmoothThicknessMultiplier";
-		case LevelsetStabilizationEnum : return "LevelsetStabilization";
-		case AutodiffIsautodiffEnum : return "AutodiffIsautodiff";
-		case AutodiffNumDependentsEnum : return "AutodiffNumDependents";
-		case AutodiffDependentObjectsEnum : return "AutodiffDependentObjects";
-		case AutodiffNumIndependentsEnum : return "AutodiffNumIndependents";
-		case AutodiffJacobianEnum : return "AutodiffJacobian";
-		case AutodiffXpEnum : return "AutodiffXp";
-		case AutodiffDriverEnum : return "AutodiffDriver";
-		case AutodiffFosForwardIndexEnum : return "AutodiffFosForwardIndex";
-		case AutodiffFovForwardIndicesEnum : return "AutodiffFovForwardIndices";
-		case AutodiffFosReverseIndexEnum : return "AutodiffFosReverseIndex";
-		case AutodiffKeepEnum : return "AutodiffKeep";
-		case AutodiffObufsizeEnum : return "AutodiffObufsize";
-		case AutodiffLbufsizeEnum : return "AutodiffLbufsize";
-		case AutodiffCbufsizeEnum : return "AutodiffCbufsize";
-		case AutodiffTbufsizeEnum : return "AutodiffTbufsize";
-		case AutodiffGcTriggerRatioEnum : return "AutodiffGcTriggerRatio";
-		case AutodiffGcTriggerMaxSizeEnum : return "AutodiffGcTriggerMaxSize";
-		case BalancethicknessStabilizationEnum : return "BalancethicknessStabilization";
-		case BalancethicknessThickeningRateEnum : return "BalancethicknessThickeningRate";
-		case BasalforcingsEnum : return "Basalforcings";
-		case BasalforcingsGeothermalfluxEnum : return "BasalforcingsGeothermalflux";
-		case BasalforcingsGroundediceMeltingRateEnum : return "BasalforcingsGroundediceMeltingRate";
-		case BasalforcingsFloatingiceMeltingRateEnum : return "BasalforcingsFloatingiceMeltingRate";
-		case BasalforcingsDeepwaterMeltingRateEnum : return "BasalforcingsDeepwaterMeltingRate";
-		case BasalforcingsDeepwaterElevationEnum : return "BasalforcingsDeepwaterElevation";
-		case BasalforcingsUpperwaterElevationEnum : return "BasalforcingsUpperwaterElevation";
-		case BasalforcingsMeltrateFactorEnum : return "BasalforcingsMeltrateFactor";
-		case BasalforcingsThresholdThicknessEnum : return "BasalforcingsThresholdThickness";
-		case BasalforcingsUpperdepthMeltEnum : return "BasalforcingsUpperdepthMelt";
-		case BasalforcingsMantleconductivityEnum : return "BasalforcingsMantleconductivity";
-		case BasalforcingsNusseltEnum : return "BasalforcingsNusselt";
-		case BasalforcingsDtbgEnum : return "BasalforcingsDtbg";
-		case BasalforcingsPlumeradiusEnum : return "BasalforcingsPlumeradius";
-		case BasalforcingsTopplumedepthEnum : return "BasalforcingsTopplumedepth";
-		case BasalforcingsBottomplumedepthEnum : return "BasalforcingsBottomplumedepth";
-		case BasalforcingsPlumexEnum : return "BasalforcingsPlumex";
-		case BasalforcingsPlumeyEnum : return "BasalforcingsPlumey";
-		case BasalforcingsCrustthicknessEnum : return "BasalforcingsCrustthickness";
-		case BasalforcingsUppercrustthicknessEnum : return "BasalforcingsUppercrustthickness";
-		case BasalforcingsUppercrustheatEnum : return "BasalforcingsUppercrustheat";
-		case BasalforcingsLowercrustheatEnum : return "BasalforcingsLowercrustheat";
-		case FloatingMeltRateEnum : return "FloatingMeltRate";
-		case LinearFloatingMeltRateEnum : return "LinearFloatingMeltRate";
-		case MismipFloatingMeltRateEnum : return "MismipFloatingMeltRate";
-		case MantlePlumeGeothermalFluxEnum : return "MantlePlumeGeothermalFlux";
-		case BedEnum : return "Bed";
-		case BaseEnum : return "Base";
-		case ConstantsGEnum : return "ConstantsG";
-		case ConstantsReferencetemperatureEnum : return "ConstantsReferencetemperature";
-		case ConstantsYtsEnum : return "ConstantsYts";
-		case DependentObjectEnum : return "DependentObject";
+		case SolutionTypeEnum : return "SolutionType";
+		case SteadystateMaxiterEnum : return "SteadystateMaxiter";
+		case SteadystateNumRequestedOutputsEnum : return "SteadystateNumRequestedOutputs";
+		case SteadystateReltolEnum : return "SteadystateReltol";
+		case SteadystateRequestedOutputsEnum : return "SteadystateRequestedOutputs";
+		case StepEnum : return "Step";
 		case StressbalanceAbstolEnum : return "StressbalanceAbstol";
-		case StressbalanceConvergenceNumStepsEnum : return "StressbalanceConvergenceNumSteps";
+		case StressbalanceFSreconditioningEnum : return "StressbalanceFSreconditioning";
 		case StressbalanceIsnewtonEnum : return "StressbalanceIsnewton";
 		case StressbalanceMaxiterEnum : return "StressbalanceMaxiter";
+		case StressbalanceNumRequestedOutputsEnum : return "StressbalanceNumRequestedOutputs";
 		case StressbalancePenaltyFactorEnum : return "StressbalancePenaltyFactor";
 		case StressbalanceReltolEnum : return "StressbalanceReltol";
-		case StressbalanceNumRequestedOutputsEnum : return "StressbalanceNumRequestedOutputs";
 		case StressbalanceRequestedOutputsEnum : return "StressbalanceRequestedOutputs";
 		case StressbalanceRestolEnum : return "StressbalanceRestol";
 		case StressbalanceRiftPenaltyThresholdEnum : return "StressbalanceRiftPenaltyThreshold";
 		case StressbalanceShelfDampeningEnum : return "StressbalanceShelfDampening";
-		case StressbalanceFSreconditioningEnum : return "StressbalanceFSreconditioning";
-		case StressbalanceViscosityOvershootEnum : return "StressbalanceViscosityOvershoot";
-		case LoadingforceXEnum : return "LoadingforceX";
-		case LoadingforceYEnum : return "LoadingforceY";
-		case LoadingforceZEnum : return "LoadingforceZ";
-		case FlowequationIsSIAEnum : return "FlowequationIsSIA";
-		case FlowequationIsSSAEnum : return "FlowequationIsSSA";
-		case FlowequationIsL1L2Enum : return "FlowequationIsL1L2";
-		case FlowequationIsHOEnum : return "FlowequationIsHO";
-		case FlowequationIsFSEnum : return "FlowequationIsFS";
-		case FlowequationFeFSEnum : return "FlowequationFeFS";
-		case FlowequationBorderFSEnum : return "FlowequationBorderFS";
-		case FrictionAsEnum : return "FrictionAs";
-		case FrictionCoefficientEnum : return "FrictionCoefficient";
-		case FrictionCoefficientcoulombEnum : return "FrictionCoefficientcoulomb";
-		case FrictionPressureAdjustedTemperatureEnum : return "FrictionPressureAdjustedTemperature";
-		case FrictionPEnum : return "FrictionP";
-		case FrictionQEnum : return "FrictionQ";
-		case FrictionMEnum : return "FrictionM";
-		case FrictionCEnum : return "FrictionC";
-		case FrictionLawEnum : return "FrictionLaw";
-		case FrictionGammaEnum : return "FrictionGamma";
-		case FrictionFEnum : return "FrictionF";
-		case FrictionWaterLayerEnum : return "FrictionWaterLayer";
-		case FrictionEffectivePressureEnum : return "FrictionEffectivePressure";
-		case FrictionCouplingEnum : return "FrictionCoupling";
-		case GeometryHydrostaticRatioEnum : return "GeometryHydrostaticRatio";
-		case HydrologyModelEnum : return "HydrologyModel";
-		case HydrologyshreveEnum : return "Hydrologyshreve";
-		case HydrologyshreveStabilizationEnum : return "HydrologyshreveStabilization";
-		case HydrologydcEnum : return "Hydrologydc";
-		case SedimentHeadEnum : return "SedimentHead";
-		case SedimentHeadOldEnum : return "SedimentHeadOld";
-		case SedimentHeadResidualEnum : return "SedimentHeadResidual";
+		case ThermalIsdynamicbasalspcEnum : return "ThermalIsdynamicbasalspc";
+		case ThermalIsenthalpyEnum : return "ThermalIsenthalpy";
+		case ThermalMaxiterEnum : return "ThermalMaxiter";
+		case ThermalNumRequestedOutputsEnum : return "ThermalNumRequestedOutputs";
+		case ThermalPenaltyFactorEnum : return "ThermalPenaltyFactor";
+		case ThermalPenaltyLockEnum : return "ThermalPenaltyLock";
+		case ThermalPenaltyThresholdEnum : return "ThermalPenaltyThreshold";
+		case ThermalReltolEnum : return "ThermalReltol";
+		case ThermalRequestedOutputsEnum : return "ThermalRequestedOutputs";
+		case ThermalStabilizationEnum : return "ThermalStabilization";
+		case TimeEnum : return "Time";
+		case TimesteppingCflCoefficientEnum : return "TimesteppingCflCoefficient";
+		case TimesteppingCouplingTimeEnum : return "TimesteppingCouplingTime";
+		case TimesteppingFinalTimeEnum : return "TimesteppingFinalTime";
+		case TimesteppingInterpForcingsEnum : return "TimesteppingInterpForcings";
+		case TimesteppingStartTimeEnum : return "TimesteppingStartTime";
+		case TimesteppingTimeStepEnum : return "TimesteppingTimeStep";
+		case TimesteppingTimeStepMaxEnum : return "TimesteppingTimeStepMax";
+		case TimesteppingTimeStepMinEnum : return "TimesteppingTimeStepMin";
+		case TimesteppingTypeEnum : return "TimesteppingType";
+		case ToMITgcmCommEnum : return "ToMITgcmComm";
+		case ToolkitsFileNameEnum : return "ToolkitsFileName";
+		case ToolkitsOptionsAnalysesEnum : return "ToolkitsOptionsAnalyses";
+		case ToolkitsOptionsStringsEnum : return "ToolkitsOptionsStrings";
+		case ToolkitsTypesEnum : return "ToolkitsTypes";
+		case TransientAmrFrequencyEnum : return "TransientAmrFrequency";
+		case TransientIscouplerEnum : return "TransientIscoupler";
+		case TransientIsdamageevolutionEnum : return "TransientIsdamageevolution";
+		case TransientIsesaEnum : return "TransientIsesa";
+		case TransientIsgiaEnum : return "TransientIsgia";
+		case TransientIsgroundinglineEnum : return "TransientIsgroundingline";
+		case TransientIshydrologyEnum : return "TransientIshydrology";
+		case TransientIsmasstransportEnum : return "TransientIsmasstransport";
+		case TransientIsmovingfrontEnum : return "TransientIsmovingfront";
+		case TransientIsoceancouplingEnum : return "TransientIsoceancoupling";
+		case TransientIsslrEnum : return "TransientIsslr";
+		case TransientIssmbEnum : return "TransientIssmb";
+		case TransientIsstressbalanceEnum : return "TransientIsstressbalance";
+		case TransientIsthermalEnum : return "TransientIsthermal";
+		case TransientNumRequestedOutputsEnum : return "TransientNumRequestedOutputs";
+		case TransientRequestedOutputsEnum : return "TransientRequestedOutputs";
+		case VelocityEnum : return "Velocity";
+		case WorldCommEnum : return "WorldComm";
+		case ParametersENDEnum : return "ParametersEND";
+		case InputsSTARTEnum : return "InputsSTART";
+		case AdjointEnum : return "Adjoint";
+		case AdjointxEnum : return "Adjointx";
+		case AdjointyEnum : return "Adjointy";
+		case AdjointzEnum : return "Adjointz";
+		case AirEnum : return "Air";
+		case ApproximationEnum : return "Approximation";
+		case BalancethicknessMisfitEnum : return "BalancethicknessMisfit";
+		case BalancethicknessOmega0Enum : return "BalancethicknessOmega0";
+		case BalancethicknessOmegaEnum : return "BalancethicknessOmega";
+		case BalancethicknessThickeningRateEnum : return "BalancethicknessThickeningRate";
+		case BasalforcingsFloatingiceMeltingRateEnum : return "BasalforcingsFloatingiceMeltingRate";
+		case BasalforcingsGeothermalfluxEnum : return "BasalforcingsGeothermalflux";
+		case BasalforcingsGroundediceMeltingRateEnum : return "BasalforcingsGroundediceMeltingRate";
+		case BasalforcingsPicoBasinIdEnum : return "BasalforcingsPicoBasinId";
+		case BasalforcingsPicoBoxIdEnum : return "BasalforcingsPicoBoxId";
+		case BasalforcingsPicoSubShelfOceanOverturningEnum : return "BasalforcingsPicoSubShelfOceanOverturning";
+		case BasalforcingsPicoSubShelfOceanSalinityEnum : return "BasalforcingsPicoSubShelfOceanSalinity";
+		case BasalforcingsPicoSubShelfOceanTempEnum : return "BasalforcingsPicoSubShelfOceanTemp";
+		case BaseEnum : return "Base";
+		case BedEnum : return "Bed";
+		case BedSlopeXEnum : return "BedSlopeX";
+		case BedSlopeYEnum : return "BedSlopeY";
+		case CalvingCalvingrateEnum : return "CalvingCalvingrate";
+		case CalvingHabFractionEnum : return "CalvingHabFraction";
+		case CalvinglevermannCoeffEnum : return "CalvinglevermannCoeff";
+		case CalvinglevermannMeltingrateEnum : return "CalvinglevermannMeltingrate";
+		case CalvingMeltingrateEnum : return "CalvingMeltingrate";
+		case CalvingratexAverageEnum : return "CalvingratexAverage";
+		case CalvingratexEnum : return "Calvingratex";
+		case CalvingrateyAverageEnum : return "CalvingrateyAverage";
+		case CalvingrateyEnum : return "Calvingratey";
+		case CalvingStressThresholdFloatingiceEnum : return "CalvingStressThresholdFloatingice";
+		case CalvingStressThresholdGroundediceEnum : return "CalvingStressThresholdGroundedice";
+		case ConvergedEnum : return "Converged";
+		case CrevasseDepthEnum : return "CrevasseDepth";
+		case DamageDbarEnum : return "DamageDbar";
+		case DamageDEnum : return "DamageD";
+		case DamageFEnum : return "DamageF";
+		case DeviatoricStressxxEnum : return "DeviatoricStressxx";
+		case DeviatoricStressxyEnum : return "DeviatoricStressxy";
+		case DeviatoricStressxzEnum : return "DeviatoricStressxz";
+		case DeviatoricStressyyEnum : return "DeviatoricStressyy";
+		case DeviatoricStressyzEnum : return "DeviatoricStressyz";
+		case DeviatoricStresszzEnum : return "DeviatoricStresszz";
+		case DistanceToCalvingfrontEnum : return "DistanceToCalvingfront";
+		case DistanceToGroundinglineEnum : return "DistanceToGroundingline";
+		case Domain2DhorizontalEnum : return "Domain2Dhorizontal";
+		case Domain2DverticalEnum : return "Domain2Dvertical";
+		case Domain3DEnum : return "Domain3D";
+		case DragCoefficientAbsGradientEnum : return "DragCoefficientAbsGradient";
+		case DrivingStressXEnum : return "DrivingStressX";
+		case DrivingStressYEnum : return "DrivingStressY";
 		case EffectivePressureEnum : return "EffectivePressure";
+		case EnthalpyEnum : return "Enthalpy";
+		case EnthalpyPicardEnum : return "EnthalpyPicard";
 		case EplHeadEnum : return "EplHead";
 		case EplHeadOldEnum : return "EplHeadOld";
 		case EplHeadSlopeXEnum : return "EplHeadSlopeX";
 		case EplHeadSlopeYEnum : return "EplHeadSlopeY";
-		case EplZigZagCounterEnum : return "EplZigZagCounter";
-		case HydrologydcMaxIterEnum : return "HydrologydcMaxIter";
-		case HydrologydcRelTolEnum : return "HydrologydcRelTol";
-		case HydrologydcSedimentCompressibilityEnum : return "HydrologydcSedimentCompressibility";
-		case HydrologydcSedimentPorosityEnum : return "HydrologydcSedimentPorosity";
-		case HydrologydcSedimentThicknessEnum : return "HydrologydcSedimentThickness";
-		case HydrologydcSedimentTransmitivityEnum : return "HydrologydcSedimentTransmitivity";
-		case HydrologydcWaterCompressibilityEnum : return "HydrologydcWaterCompressibility";
-		case HydrologydcMaskEplactiveNodeEnum : return "HydrologydcMaskEplactiveNode";
-		case HydrologydcMaskEplactiveEltEnum : return "HydrologydcMaskEplactiveElt";
-		case HydrologydcEplCompressibilityEnum : return "HydrologydcEplCompressibility";
-		case HydrologydcEplPorosityEnum : return "HydrologydcEplPorosity";
-		case HydrologydcEplInitialThicknessEnum : return "HydrologydcEplInitialThickness";
-		case HydrologydcEplColapseThicknessEnum : return "HydrologydcEplColapseThickness";
-		case HydrologydcEplMaxThicknessEnum : return "HydrologydcEplMaxThickness";
+		case EsaDeltathicknessEnum : return "EsaDeltathickness";
+		case EsaXmotionEnum : return "EsaXmotion";
+		case EsaYmotionEnum : return "EsaYmotion";
+		case EtaDiffEnum : return "EtaDiff";
+		case FrictionAsEnum : return "FrictionAs";
+		case FrictionCEnum : return "FrictionC";
+		case FrictionCoefficientcoulombEnum : return "FrictionCoefficientcoulomb";
+		case FrictionCoefficientEnum : return "FrictionCoefficient";
+		case FrictionEffectivePressureEnum : return "FrictionEffectivePressure";
+		case FrictionMEnum : return "FrictionM";
+		case FrictionPEnum : return "FrictionP";
+		case FrictionPressureAdjustedTemperatureEnum : return "FrictionPressureAdjustedTemperature";
+		case FrictionQEnum : return "FrictionQ";
+		case FrictionWaterLayerEnum : return "FrictionWaterLayer";
+		case GeometryHydrostaticRatioEnum : return "GeometryHydrostaticRatio";
+		case GiaLithosphereThicknessEnum : return "GiaLithosphereThickness";
+		case GiaMantleViscosityEnum : return "GiaMantleViscosity";
+		case GradientEnum : return "Gradient";
+		case HydrologyBumpHeightEnum : return "HydrologyBumpHeight";
+		case HydrologyBumpSpacingEnum : return "HydrologyBumpSpacing";
+		case HydrologydcBasalMoulinInputEnum : return "HydrologydcBasalMoulinInput";
 		case HydrologydcEplThicknessEnum : return "HydrologydcEplThickness";
 		case HydrologydcEplThicknessOldEnum : return "HydrologydcEplThicknessOld";
-		case HydrologydcEplThickCompEnum : return "HydrologydcEplThickComp";
-		case HydrologydcEplConductivityEnum : return "HydrologydcEplConductivity";
-		case HydrologydcIsefficientlayerEnum : return "HydrologydcIsefficientlayer";
-		case HydrologydcSedimentlimitFlagEnum : return "HydrologydcSedimentlimitFlag";
-		case HydrologydcSedimentlimitEnum : return "HydrologydcSedimentlimit";
-		case HydrologydcTransferFlagEnum : return "HydrologydcTransferFlag";
-		case HydrologydcLeakageFactorEnum : return "HydrologydcLeakageFactor";
-		case HydrologydcPenaltyFactorEnum : return "HydrologydcPenaltyFactor";
-		case HydrologydcPenaltyLockEnum : return "HydrologydcPenaltyLock";
-		case HydrologydcEplflipLockEnum : return "HydrologydcEplflipLock";
-		case HydrologydcBasalMoulinInputEnum : return "HydrologydcBasalMoulinInput";
-		case HydrologyLayerEnum : return "HydrologyLayer";
-		case HydrologySedimentEnum : return "HydrologySediment";
-		case HydrologyEfficientEnum : return "HydrologyEfficient";
-		case HydrologySedimentKmaxEnum : return "HydrologySedimentKmax";
-		case HydrologysommersEnum : return "Hydrologysommers";
+		case HydrologydcMaskEplactiveEltEnum : return "HydrologydcMaskEplactiveElt";
+		case HydrologydcMaskEplactiveNodeEnum : return "HydrologydcMaskEplactiveNode";
+		case HydrologydcSedimentTransmitivityEnum : return "HydrologydcSedimentTransmitivity";
+		case HydrologyEnglacialInputEnum : return "HydrologyEnglacialInput";
+		case HydrologyGapHeightEnum : return "HydrologyGapHeight";
 		case HydrologyHeadEnum : return "HydrologyHead";
 		case HydrologyHeadOldEnum : return "HydrologyHeadOld";
-		case HydrologyGapHeightEnum : return "HydrologyGapHeight";
-		case HydrologyBumpSpacingEnum : return "HydrologyBumpSpacing";
-		case HydrologyBumpHeightEnum : return "HydrologyBumpHeight";
-		case HydrologyEnglacialInputEnum : return "HydrologyEnglacialInput";
 		case HydrologyMoulinInputEnum : return "HydrologyMoulinInput";
+		case HydrologyNeumannfluxEnum : return "HydrologyNeumannflux";
 		case HydrologyReynoldsEnum : return "HydrologyReynolds";
-		case HydrologyNeumannfluxEnum : return "HydrologyNeumannflux";
-		case HydrologyRelaxationEnum : return "HydrologyRelaxation";
-		case HydrologyBasalFluxEnum : return "HydrologyBasalFlux";
-		case HydrologyStorageEnum : return "HydrologyStorage";
-		case InversionControlParametersEnum : return "InversionControlParameters";
-		case InversionControlScalingFactorsEnum : return "InversionControlScalingFactors";
-		case InversionCostFunctionThresholdEnum : return "InversionCostFunctionThreshold";
+		case HydrologyWaterVxEnum : return "HydrologyWaterVx";
+		case HydrologyWaterVyEnum : return "HydrologyWaterVy";
+		case IceEnum : return "Ice";
+		case IceMaskNodeActivationEnum : return "IceMaskNodeActivation";
+		case InputEnum : return "Input";
 		case InversionCostFunctionsCoefficientsEnum : return "InversionCostFunctionsCoefficients";
-		case InversionCostFunctionsEnum : return "InversionCostFunctions";
-		case InversionGradientScalingEnum : return "InversionGradientScaling";
-		case InversionIscontrolEnum : return "InversionIscontrol";
-		case InversionTypeEnum : return "InversionType";
-		case InversionIncompleteAdjointEnum : return "InversionIncompleteAdjoint";
-		case InversionMaxiterPerStepEnum : return "InversionMaxiterPerStep";
-		case InversionMaxiterEnum : return "InversionMaxiter";
-		case InversionMaxstepsEnum : return "InversionMaxsteps";
-		case InversionFatolEnum : return "InversionFatol";
-		case InversionFrtolEnum : return "InversionFrtol";
-		case InversionGatolEnum : return "InversionGatol";
-		case InversionGrtolEnum : return "InversionGrtol";
-		case InversionGttolEnum : return "InversionGttol";
-		case InversionAlgorithmEnum : return "InversionAlgorithm";
-		case InversionNstepsEnum : return "InversionNsteps";
-		case InversionDxminEnum : return "InversionDxmin";
-		case InversionNumControlParametersEnum : return "InversionNumControlParameters";
-		case InversionNumCostFunctionsEnum : return "InversionNumCostFunctions";
-		case InversionStepThresholdEnum : return "InversionStepThreshold";
+		case InversionSurfaceObsEnum : return "InversionSurfaceObs";
 		case InversionThicknessObsEnum : return "InversionThicknessObs";
-		case InversionSurfaceObsEnum : return "InversionSurfaceObs";
+		case InversionVelObsEnum : return "InversionVelObs";
 		case InversionVxObsEnum : return "InversionVxObs";
 		case InversionVyObsEnum : return "InversionVyObs";
-		case InversionVzObsEnum : return "InversionVzObs";
+		case LevelsetfunctionSlopeXEnum : return "LevelsetfunctionSlopeX";
+		case LevelsetfunctionSlopeYEnum : return "LevelsetfunctionSlopeY";
+		case LoadingforceXEnum : return "LoadingforceX";
+		case LoadingforceYEnum : return "LoadingforceY";
+		case LoadingforceZEnum : return "LoadingforceZ";
+		case MaskGroundediceLevelsetEnum : return "MaskGroundediceLevelset";
 		case MaskIceLevelsetEnum : return "MaskIceLevelset";
-		case MaskOceanLevelsetEnum : return "MaskOceanLevelset";
-		case MaskLandLevelsetEnum : return "MaskLandLevelset";
-		case MaterialsBetaEnum : return "MaterialsBeta";
-		case MaterialsHeatcapacityEnum : return "MaterialsHeatcapacity";
-		case MaterialsLatentheatEnum : return "MaterialsLatentheat";
-		case MaterialsMeltingpointEnum : return "MaterialsMeltingpoint";
-		case MaterialsMixedLayerCapacityEnum : return "MaterialsMixedLayerCapacity";
+		case MasstransportSpcthicknessEnum : return "MasstransportSpcthickness";
+		case MaterialsRheologyBbarEnum : return "MaterialsRheologyBbar";
 		case MaterialsRheologyBEnum : return "MaterialsRheologyB";
-		case MaterialsRheologyBbarEnum : return "MaterialsRheologyBbar";
-		case MaterialsRheologyLawEnum : return "MaterialsRheologyLaw";
+		case MaterialsRheologyEbarEnum : return "MaterialsRheologyEbar";
+		case MaterialsRheologyEcbarEnum : return "MaterialsRheologyEcbar";
+		case MaterialsRheologyEcEnum : return "MaterialsRheologyEc";
+		case MaterialsRheologyEEnum : return "MaterialsRheologyE";
+		case MaterialsRheologyEsbarEnum : return "MaterialsRheologyEsbar";
+		case MaterialsRheologyEsEnum : return "MaterialsRheologyEs";
 		case MaterialsRheologyNEnum : return "MaterialsRheologyN";
-		case MaterialsRheologyEEnum : return "MaterialsRheologyE";
-		case MaterialsRheologyEbarEnum : return "MaterialsRheologyEbar";
-		case MaterialsRheologyEcEnum : return "MaterialsRheologyEc";
-		case MaterialsRheologyEcbarEnum : return "MaterialsRheologyEcbar";
-		case MaterialsRheologyEsEnum : return "MaterialsRheologyEs";
-		case MaterialsRheologyEsbarEnum : return "MaterialsRheologyEsbar";
-		case DamageDEnum : return "DamageD";
-		case DamageFEnum : return "DamageF";
-		case DamageDbarEnum : return "DamageDbar";
-		case DamageLawEnum : return "DamageLaw";
-		case DamageC1Enum : return "DamageC1";
-		case DamageC2Enum : return "DamageC2";
-		case DamageC3Enum : return "DamageC3";
-		case DamageC4Enum : return "DamageC4";
-		case DamageElementinterpEnum : return "DamageElementinterp";
-		case DamageHealingEnum : return "DamageHealing";
-		case DamageStressThresholdEnum : return "DamageStressThreshold";
-		case DamageKappaEnum : return "DamageKappa";
-		case DamageStabilizationEnum : return "DamageStabilization";
-		case DamageMaxiterEnum : return "DamageMaxiter";
-		case DamageMaxDamageEnum : return "DamageMaxDamage";
-		case DamageEquivStressEnum : return "DamageEquivStress";
-		case DamageEvolutionNumRequestedOutputsEnum : return "DamageEvolutionNumRequestedOutputs";
-		case DamageEvolutionRequestedOutputsEnum : return "DamageEvolutionRequestedOutputs";
-		case DamageEnum : return "Damage";
-		case NewDamageEnum : return "NewDamage";
-		case StressIntensityFactorEnum : return "StressIntensityFactor";
-		case CalvingLawEnum : return "CalvingLaw";
-		case CalvingCalvingrateEnum : return "CalvingCalvingrate";
-		case CalvingMeltingrateEnum : return "CalvingMeltingrate";
-		case CalvingLevermannEnum : return "CalvingLevermann";
-		case CalvingDevEnum : return "CalvingDev";
-		case CalvingMinthicknessEnum : return "CalvingMinthickness";
-		case DefaultCalvingEnum : return "DefaultCalving";
-		case CalvinglevermannCoeffEnum : return "CalvinglevermannCoeff";
-		case CalvinglevermannMeltingrateEnum : return "CalvinglevermannMeltingrate";
-		case CalvingdevCoeffEnum : return "CalvingdevCoeff";
-		case CalvingratexEnum : return "Calvingratex";
-		case CalvingrateyEnum : return "Calvingratey";
-		case CalvingratexAverageEnum : return "CalvingratexAverage";
-		case CalvingrateyAverageEnum : return "CalvingrateyAverage";
-		case CalvingStressThresholdGroundediceEnum : return "CalvingStressThresholdGroundedice";
-		case CalvingStressThresholdFloatingiceEnum : return "CalvingStressThresholdFloatingice";
-		case CalvingMaxEnum : return "CalvingMax";
+		case MeshScaleFactorEnum : return "MeshScaleFactor";
+		case MeshVertexonbaseEnum : return "MeshVertexonbase";
+		case MeshVertexonboundaryEnum : return "MeshVertexonboundary";
+		case MeshVertexonsurfaceEnum : return "MeshVertexonsurface";
+		case MisfitEnum : return "Misfit";
+		case NeumannfluxEnum : return "Neumannflux";
+		case NodeEnum : return "Node";
+		case OmegaAbsGradientEnum : return "OmegaAbsGradient";
+		case P0Enum : return "P0";
+		case P1Enum : return "P1";
+		case PressureEnum : return "Pressure";
+		case RheologyBAbsGradientEnum : return "RheologyBAbsGradient";
+		case RheologyBbarAbsGradientEnum : return "RheologyBbarAbsGradient";
+		case SealevelEnum : return "Sealevel";
+		case SealevelriseDeltathicknessEnum : return "SealevelriseDeltathickness";
+		case SedimentHeadEnum : return "SedimentHead";
+		case SedimentHeadOldEnum : return "SedimentHeadOld";
+		case SedimentHeadResidualEnum : return "SedimentHeadResidual";
+		case SigmaNNEnum : return "SigmaNN";
+		case SmbAccumulationEnum : return "SmbAccumulation";
+		case SmbAEnum : return "SmbA";
+		case SmbAiniEnum : return "SmbAini";
+		case SmbAValueEnum : return "SmbAValue";
+		case SmbBMaxEnum : return "SmbBMax";
+		case SmbBMinEnum : return "SmbBMin";
+		case SmbBNegEnum : return "SmbBNeg";
+		case SmbBPosEnum : return "SmbBPos";
+		case SmbCEnum : return "SmbC";
+		case SmbDEnum : return "SmbD";
+		case SmbDiniEnum : return "SmbDini";
+		case SmbDlwrfEnum : return "SmbDlwrf";
+		case SmbDswrfEnum : return "SmbDswrf";
+		case SmbDzEnum : return "SmbDz";
+		case SmbDziniEnum : return "SmbDzini";
+		case SmbDzMinEnum : return "SmbDzMin";
+		case SmbDzTopEnum : return "SmbDzTop";
+		case SmbEAirEnum : return "SmbEAir";
+		case SmbECEnum : return "SmbEC";
+		case SmbECiniEnum : return "SmbECini";
+		case SmbElaEnum : return "SmbEla";
+		case SmbEvaporationEnum : return "SmbEvaporation";
+		case SmbGdnEnum : return "SmbGdn";
+		case SmbGdniniEnum : return "SmbGdnini";
+		case SmbGspEnum : return "SmbGsp";
+		case SmbGspiniEnum : return "SmbGspini";
+		case SmbHrefEnum : return "SmbHref";
+		case SmbIsInitializedEnum : return "SmbIsInitialized";
+		case SmbMassBalanceEnum : return "SmbMassBalance";
+		case SmbMeltEnum : return "SmbMelt";
+		case SmbMonthlytemperaturesEnum : return "SmbMonthlytemperatures";
+		case SmbPAirEnum : return "SmbPAir";
+		case SmbPddfacIceEnum : return "SmbPddfacIce";
+		case SmbPddfacSnowEnum : return "SmbPddfacSnow";
+		case SmbPEnum : return "SmbP";
+		case SmbPrecipitationEnum : return "SmbPrecipitation";
+		case SmbPrecipitationsLgmEnum : return "SmbPrecipitationsLgm";
+		case SmbPrecipitationsPresentdayEnum : return "SmbPrecipitationsPresentday";
+		case SmbReEnum : return "SmbRe";
+		case SmbRefreezeEnum : return "SmbRefreeze";
+		case SmbReiniEnum : return "SmbReini";
+		case SmbRunoffEnum : return "SmbRunoff";
+		case SmbS0pEnum : return "SmbS0p";
+		case SmbS0tEnum : return "SmbS0t";
+		case SmbSizeiniEnum : return "SmbSizeini";
+		case SmbSmbrefEnum : return "SmbSmbref";
+		case SmbTaEnum : return "SmbTa";
+		case SmbTemperaturesLgmEnum : return "SmbTemperaturesLgm";
+		case SmbTemperaturesPresentdayEnum : return "SmbTemperaturesPresentday";
+		case SmbTEnum : return "SmbT";
+		case SmbTeValueEnum : return "SmbTeValue";
+		case SmbTiniEnum : return "SmbTini";
+		case SmbTmeanEnum : return "SmbTmean";
+		case SmbTzEnum : return "SmbTz";
+		case SmbVEnum : return "SmbV";
+		case SmbVzEnum : return "SmbVz";
+		case SmbWEnum : return "SmbW";
+		case SmbWiniEnum : return "SmbWini";
+		case SmbZMaxEnum : return "SmbZMax";
+		case SmbZMinEnum : return "SmbZMin";
+		case SmbZTopEnum : return "SmbZTop";
+		case SmbZYEnum : return "SmbZY";
+		case StrainRateeffectiveEnum : return "StrainRateeffective";
 		case StrainRateparallelEnum : return "StrainRateparallel";
 		case StrainRateperpendicularEnum : return "StrainRateperpendicular";
-		case StrainRateeffectiveEnum : return "StrainRateeffective";
-		case MaterialsRhoIceEnum : return "MaterialsRhoIce";
-		case MaterialsRhoSeawaterEnum : return "MaterialsRhoSeawater";
-		case MaterialsRhoFreshwaterEnum : return "MaterialsRhoFreshwater";
-		case MaterialsMuWaterEnum : return "MaterialsMuWater";
-		case MaterialsThermalExchangeVelocityEnum : return "MaterialsThermalExchangeVelocity";
-		case MaterialsThermalconductivityEnum : return "MaterialsThermalconductivity";
-		case MaterialsTemperateiceconductivityEnum : return "MaterialsTemperateiceconductivity";
-		case MaterialsLithosphereShearModulusEnum : return "MaterialsLithosphereShearModulus";
-		case MaterialsLithosphereDensityEnum : return "MaterialsLithosphereDensity";
-		case MaterialsMantleShearModulusEnum : return "MaterialsMantleShearModulus";
-		case MaterialsMantleDensityEnum : return "MaterialsMantleDensity";
-		case MaterialsEarthDensityEnum : return "MaterialsEarthDensity";
-		case MeshAverageVertexConnectivityEnum : return "MeshAverageVertexConnectivity";
-		case MeshXEnum : return "MeshX";
-		case MeshYEnum : return "MeshY";
-		case MeshZEnum : return "MeshZ";
-		case MeshElementsEnum : return "MeshElements";
-		case MeshNumberofelementsEnum : return "MeshNumberofelements";
-		case MeshNumberoflayersEnum : return "MeshNumberoflayers";
-		case MeshNumberofverticesEnum : return "MeshNumberofvertices";
-		case MeshVertexonbaseEnum : return "MeshVertexonbase";
-		case MeshVertexonsurfaceEnum : return "MeshVertexonsurface";
-		case MeshVertexonboundaryEnum : return "MeshVertexonboundary";
-		case MeshElementtypeEnum : return "MeshElementtype";
-		case DomainTypeEnum : return "DomainType";
-		case DomainDimensionEnum : return "DomainDimension";
-		case Domain2DhorizontalEnum : return "Domain2Dhorizontal";
-		case Domain2DverticalEnum : return "Domain2Dvertical";
-		case Domain3DEnum : return "Domain3D";
-		case Domain3DsurfaceEnum : return "Domain3Dsurface";
-		case MasstransportHydrostaticAdjustmentEnum : return "MasstransportHydrostaticAdjustment";
-		case MasstransportIsfreesurfaceEnum : return "MasstransportIsfreesurface";
-		case MasstransportMinThicknessEnum : return "MasstransportMinThickness";
-		case MasstransportPenaltyFactorEnum : return "MasstransportPenaltyFactor";
-		case MasstransportSpcthicknessEnum : return "MasstransportSpcthickness";
-		case MasstransportStabilizationEnum : return "MasstransportStabilization";
-		case MasstransportNumRequestedOutputsEnum : return "MasstransportNumRequestedOutputs";
-		case MasstransportRequestedOutputsEnum : return "MasstransportRequestedOutputs";
-		case QmuIsdakotaEnum : return "QmuIsdakota";
-		case MassFluxSegmentsEnum : return "MassFluxSegments";
-		case MassFluxSegmentsPresentEnum : return "MassFluxSegmentsPresent";
-		case QmuNumberofpartitionsEnum : return "QmuNumberofpartitions";
-		case QmuNumberofresponsesEnum : return "QmuNumberofresponses";
-		case QmuPartitionEnum : return "QmuPartition";
-		case QmuResponsedescriptorsEnum : return "QmuResponsedescriptors";
-		case QmuVariabledescriptorsEnum : return "QmuVariabledescriptors";
-		case SettingsResultsOnNodesEnum : return "SettingsResultsOnNodes";
-		case SettingsIoGatherEnum : return "SettingsIoGather";
-		case SettingsLowmemEnum : return "SettingsLowmem";
-		case SettingsOutputFrequencyEnum : return "SettingsOutputFrequency";
-		case SettingsRecordingFrequencyEnum : return "SettingsRecordingFrequency";
-		case SettingsWaitonlockEnum : return "SettingsWaitonlock";
-		case SettingsSolverResidueThresholdEnum : return "SettingsSolverResidueThreshold";
-		case DebugProfilingEnum : return "DebugProfiling";
-		case ProfilingCurrentMemEnum : return "ProfilingCurrentMem";
-		case ProfilingCurrentFlopsEnum : return "ProfilingCurrentFlops";
-		case ProfilingSolutionTimeEnum : return "ProfilingSolutionTime";
-		case SteadystateMaxiterEnum : return "SteadystateMaxiter";
-		case SteadystateNumRequestedOutputsEnum : return "SteadystateNumRequestedOutputs";
-		case SteadystateReltolEnum : return "SteadystateReltol";
-		case SteadystateRequestedOutputsEnum : return "SteadystateRequestedOutputs";
-		case SurfaceEnum : return "Surface";
-		case ThermalIsenthalpyEnum : return "ThermalIsenthalpy";
-		case ThermalIsdynamicbasalspcEnum : return "ThermalIsdynamicbasalspc";
-		case ThermalReltolEnum : return "ThermalReltol";
-		case ThermalMaxiterEnum : return "ThermalMaxiter";
-		case ThermalPenaltyFactorEnum : return "ThermalPenaltyFactor";
-		case ThermalPenaltyLockEnum : return "ThermalPenaltyLock";
-		case ThermalPenaltyThresholdEnum : return "ThermalPenaltyThreshold";
-		case ThermalSpctemperatureEnum : return "ThermalSpctemperature";
-		case ThermalStabilizationEnum : return "ThermalStabilization";
-		case ThermalNumRequestedOutputsEnum : return "ThermalNumRequestedOutputs";
-		case ThermalRequestedOutputsEnum : return "ThermalRequestedOutputs";
-		case GiaMantleViscosityEnum : return "GiaMantleViscosity";
-		case GiaLithosphereThicknessEnum : return "GiaLithosphereThickness";
-		case ThicknessEnum : return "Thickness";
-		case TimesteppingStartTimeEnum : return "TimesteppingStartTime";
-		case TimesteppingFinalTimeEnum : return "TimesteppingFinalTime";
-		case TimesteppingCflCoefficientEnum : return "TimesteppingCflCoefficient";
-		case TimesteppingTimeAdaptEnum : return "TimesteppingTimeAdapt";
-		case TimesteppingTimeStepEnum : return "TimesteppingTimeStep";
-		case TimesteppingInterpForcingsEnum : return "TimesteppingInterpForcings";
-		case TransientIssmbEnum : return "TransientIssmb";
-		case TransientIscouplerEnum : return "TransientIscoupler";
-		case TransientIsstressbalanceEnum : return "TransientIsstressbalance";
-		case TransientIsgroundinglineEnum : return "TransientIsgroundingline";
-		case TransientIsmasstransportEnum : return "TransientIsmasstransport";
-		case TransientIsthermalEnum : return "TransientIsthermal";
-		case TransientIsgiaEnum : return "TransientIsgia";
-		case TransientIsesaEnum : return "TransientIsesa";
-		case TransientIsdamageevolutionEnum : return "TransientIsdamageevolution";
-		case TransientIshydrologyEnum : return "TransientIshydrology";
-		case TransientIsmovingfrontEnum : return "TransientIsmovingfront";
-		case TransientIsslrEnum : return "TransientIsslr";
-		case TransientNumRequestedOutputsEnum : return "TransientNumRequestedOutputs";
-		case TransientRequestedOutputsEnum : return "TransientRequestedOutputs";
-		case BalancethicknessApparentMassbalanceEnum : return "BalancethicknessApparentMassbalance";
-		case BalancethicknessDiffusionCoefficientEnum : return "BalancethicknessDiffusionCoefficient";
-		case BalancethicknessOmegaEnum : return "BalancethicknessOmega";
-		case BalancethicknessD0Enum : return "BalancethicknessD0";
-		case SmbEnum : return "Smb";
-		case SmbAnalysisEnum : return "SmbAnalysis";
-		case SmbSolutionEnum : return "SmbSolution";
-		case SmbNumRequestedOutputsEnum : return "SmbNumRequestedOutputs";
-		case SmbRequestedOutputsEnum : return "SmbRequestedOutputs";
-		case SmbIsInitializedEnum : return "SmbIsInitialized";
-		case SmbDziniEnum : return "SmbDzini";
-		case SmbDiniEnum : return "SmbDini";
-		case SmbReiniEnum : return "SmbReini";
-		case SmbGdniniEnum : return "SmbGdnini";
-		case SmbGspiniEnum : return "SmbGspini";
-		case SmbECiniEnum : return "SmbECini";
-		case SmbWiniEnum : return "SmbWini";
-		case SmbAiniEnum : return "SmbAini";
-		case SmbTiniEnum : return "SmbTini";
-		case SmbSizeiniEnum : return "SmbSizeini";
-		case SMBforcingEnum : return "SMBforcing";
-		case SmbMassBalanceEnum : return "SmbMassBalance";
-		case SMBgembEnum : return "SMBgemb";
-		case SmbInitDensityScalingEnum : return "SmbInitDensityScaling";
-		case SmbTaEnum : return "SmbTa";
-		case SmbVEnum : return "SmbV";
-		case SmbDswrfEnum : return "SmbDswrf";
-		case SmbDlwrfEnum : return "SmbDlwrf";
-		case SmbPEnum : return "SmbP";
-		case SmbEAirEnum : return "SmbEAir";
-		case SmbPAirEnum : return "SmbPAir";
-		case SmbTmeanEnum : return "SmbTmean";
-		case SmbCEnum : return "SmbC";
-		case SmbTzEnum : return "SmbTz";
-		case SmbVzEnum : return "SmbVz";
-		case SmbDtEnum : return "SmbDt";
-		case SmbDzEnum : return "SmbDz";
-		case SmbAIdxEnum : return "SmbAIdx";
-		case SmbSwIdxEnum : return "SmbSwIdx";
-		case SmbDenIdxEnum : return "SmbDenIdx";
-		case SmbZTopEnum : return "SmbZTop";
-		case SmbDzTopEnum : return "SmbDzTop";
-		case SmbDzMinEnum : return "SmbDzMin";
-		case SmbZYEnum : return "SmbZY";
-		case SmbZMaxEnum : return "SmbZMax";
-		case SmbZMinEnum : return "SmbZMin";
-		case SmbOutputFreqEnum : return "SmbOutputFreq";
-		case SmbASnowEnum : return "SmbASnow";
-		case SmbAIceEnum : return "SmbAIce";
-		case SmbCldFracEnum : return "SmbCldFrac";
-		case SmbT0wetEnum : return "SmbT0wet";
-		case SmbT0dryEnum : return "SmbT0dry";
-		case SmbKEnum : return "SmbK";
-		case SmbDEnum : return "SmbD";
-		case SmbReEnum : return "SmbRe";
-		case SmbGdnEnum : return "SmbGdn";
-		case SmbGspEnum : return "SmbGsp";
-		case SmbECEnum : return "SmbEC";
-		case SmbWEnum : return "SmbW";
-		case SmbAEnum : return "SmbA";
-		case SmbTEnum : return "SmbT";
-		case SmbIsgraingrowthEnum : return "SmbIsgraingrowth";
-		case SmbIsalbedoEnum : return "SmbIsalbedo";
-		case SmbIsshortwaveEnum : return "SmbIsshortwave";
-		case SmbIsthermalEnum : return "SmbIsthermal";
-		case SmbIsaccumulationEnum : return "SmbIsaccumulation";
-		case SmbIsmeltEnum : return "SmbIsmelt";
-		case SmbIsdensificationEnum : return "SmbIsdensification";
-		case SmbIsturbulentfluxEnum : return "SmbIsturbulentflux";
-		case SmbDz_addEnum : return "SmbDz_add";
-		case SmbM_addEnum : return "SmbM_add";
-		case SMBpddEnum : return "SMBpdd";
-		case SmbDelta18oEnum : return "SmbDelta18o";
-		case SmbDelta18oSurfaceEnum : return "SmbDelta18oSurface";
-		case SmbIsdelta18oEnum : return "SmbIsdelta18o";
-		case SmbIsmungsmEnum : return "SmbIsmungsm";
-		case SmbIsd18opdEnum : return "SmbIsd18opd";
-		case SmbPrecipitationsPresentdayEnum : return "SmbPrecipitationsPresentday";
-		case SmbPrecipitationsLgmEnum : return "SmbPrecipitationsLgm";
-		case SmbTemperaturesPresentdayEnum : return "SmbTemperaturesPresentday";
-		case SmbTemperaturesLgmEnum : return "SmbTemperaturesLgm";
-		case SmbPrecipitationEnum : return "SmbPrecipitation";
-		case SmbDesfacEnum : return "SmbDesfac";
-		case SmbS0pEnum : return "SmbS0p";
-		case SmbS0tEnum : return "SmbS0t";
-		case SmbRlapsEnum : return "SmbRlaps";
-		case SmbRlapslgmEnum : return "SmbRlapslgm";
-		case SmbPfacEnum : return "SmbPfac";
-		case SmbTdiffEnum : return "SmbTdiff";
-		case SmbSealevEnum : return "SmbSealev";
-		case SMBd18opddEnum : return "SMBd18opdd";
-		case SmbDpermilEnum : return "SmbDpermil";
-		case SmbFEnum : return "SmbF";
-		case SMBgradientsEnum : return "SMBgradients";
-		case SmbMonthlytemperaturesEnum : return "SmbMonthlytemperatures";
-		case SmbHrefEnum : return "SmbHref";
-		case SmbSmbrefEnum : return "SmbSmbref";
-		case SmbBPosEnum : return "SmbBPos";
-		case SmbBNegEnum : return "SmbBNeg";
-		case SMBhenningEnum : return "SMBhenning";
-		case SMBcomponentsEnum : return "SMBcomponents";
-		case SmbAccumulationEnum : return "SmbAccumulation";
-		case SmbEvaporationEnum : return "SmbEvaporation";
-		case SmbRunoffEnum : return "SmbRunoff";
-		case SMBmeltcomponentsEnum : return "SMBmeltcomponents";
-		case SmbMeltEnum : return "SmbMelt";
-		case SmbRefreezeEnum : return "SmbRefreeze";
-		case SMBgcmEnum : return "SMBgcm";
-		case SMBgradientselaEnum : return "SMBgradientsela";
-		case SmbElaEnum : return "SmbEla";
-		case SmbBMaxEnum : return "SmbBMax";
-		case SmbBMinEnum : return "SmbBMin";
-		case AdjointpEnum : return "Adjointp";
-		case AdjointxEnum : return "Adjointx";
-		case AdjointyEnum : return "Adjointy";
-		case AdjointzEnum : return "Adjointz";
-		case BalancethicknessMisfitEnum : return "BalancethicknessMisfit";
-		case BedSlopeXEnum : return "BedSlopeX";
-		case BedSlopeYEnum : return "BedSlopeY";
-		case BoundaryEnum : return "Boundary";
-		case ConvergedEnum : return "Converged";
-		case InternalEnum : return "Internal";
-		case MassFluxEnum : return "MassFlux";
-		case MeltingOffsetEnum : return "MeltingOffset";
-		case MisfitEnum : return "Misfit";
-		case PressureEnum : return "Pressure";
-		case PressurePicardEnum : return "PressurePicard";
-		case AndroidFrictionCoefficientEnum : return "AndroidFrictionCoefficient";
-		case ResetPenaltiesEnum : return "ResetPenalties";
-		case SurfaceAbsVelMisfitEnum : return "SurfaceAbsVelMisfit";
-		case SurfaceAreaEnum : return "SurfaceArea";
-		case SurfaceAverageVelMisfitEnum : return "SurfaceAverageVelMisfit";
-		case SurfaceLogVelMisfitEnum : return "SurfaceLogVelMisfit";
-		case SurfaceLogVxVyMisfitEnum : return "SurfaceLogVxVyMisfit";
-		case SurfaceRelVelMisfitEnum : return "SurfaceRelVelMisfit";
-		case SurfaceSlopeXEnum : return "SurfaceSlopeX";
-		case SurfaceSlopeYEnum : return "SurfaceSlopeY";
-		case TemperatureEnum : return "Temperature";
-		case TemperaturePicardEnum : return "TemperaturePicard";
-		case TemperaturePDDEnum : return "TemperaturePDD";
-		case ThicknessAbsMisfitEnum : return "ThicknessAbsMisfit";
-		case SurfaceAbsMisfitEnum : return "SurfaceAbsMisfit";
-		case VelEnum : return "Vel";
-		case VelocityEnum : return "Velocity";
-		case VxAverageEnum : return "VxAverage";
-		case VxEnum : return "Vx";
-		case VxPicardEnum : return "VxPicard";
-		case VyAverageEnum : return "VyAverage";
-		case VyEnum : return "Vy";
-		case VyPicardEnum : return "VyPicard";
-		case VzEnum : return "Vz";
-		case VzSSAEnum : return "VzSSA";
-		case VzHOEnum : return "VzHO";
-		case VzPicardEnum : return "VzPicard";
-		case VzFSEnum : return "VzFS";
-		case VxMeshEnum : return "VxMesh";
-		case VyMeshEnum : return "VyMesh";
-		case VzMeshEnum : return "VzMesh";
-		case EnthalpyEnum : return "Enthalpy";
-		case EnthalpyPicardEnum : return "EnthalpyPicard";
-		case ThicknessAbsGradientEnum : return "ThicknessAbsGradient";
-		case ThicknessAlongGradientEnum : return "ThicknessAlongGradient";
-		case ThicknessAcrossGradientEnum : return "ThicknessAcrossGradient";
-		case ThicknessPositiveEnum : return "ThicknessPositive";
-		case IntMatParamEnum : return "IntMatParam";
-		case RheologyBbarAbsGradientEnum : return "RheologyBbarAbsGradient";
-		case RheologyBAbsGradientEnum : return "RheologyBAbsGradient";
-		case DragCoefficientAbsGradientEnum : return "DragCoefficientAbsGradient";
-		case TransientInputEnum : return "TransientInput";
-		case WaterfractionEnum : return "Waterfraction";
-		case WaterfractionDrainageEnum : return "WaterfractionDrainage";
-		case WaterfractionDrainageIntegratedEnum : return "WaterfractionDrainageIntegrated";
-		case WatercolumnEnum : return "Watercolumn";
-		case ViscousHeatingEnum : return "ViscousHeating";
-		case HydrologyWaterVxEnum : return "HydrologyWaterVx";
-		case HydrologyWaterVyEnum : return "HydrologyWaterVy";
-		case DrivingStressXEnum : return "DrivingStressX";
-		case DrivingStressYEnum : return "DrivingStressY";
-		case SigmaNNEnum : return "SigmaNN";
-		case StressTensorEnum : return "StressTensor";
+		case StrainRatexxEnum : return "StrainRatexx";
+		case StrainRatexyEnum : return "StrainRatexy";
+		case StrainRatexzEnum : return "StrainRatexz";
+		case StrainRateyyEnum : return "StrainRateyy";
+		case StrainRateyzEnum : return "StrainRateyz";
+		case StrainRatezzEnum : return "StrainRatezz";
+		case StressMaxPrincipalEnum : return "StressMaxPrincipal";
 		case StressTensorxxEnum : return "StressTensorxx";
 		case StressTensorxyEnum : return "StressTensorxy";
@@ -553,49 +578,314 @@
 		case StressTensoryzEnum : return "StressTensoryz";
 		case StressTensorzzEnum : return "StressTensorzz";
-		case StressMaxPrincipalEnum : return "StressMaxPrincipal";
-		case DeviatoricStressEnum : return "DeviatoricStress";
-		case DeviatoricStressxxEnum : return "DeviatoricStressxx";
-		case DeviatoricStressxyEnum : return "DeviatoricStressxy";
-		case DeviatoricStressxzEnum : return "DeviatoricStressxz";
-		case DeviatoricStressyyEnum : return "DeviatoricStressyy";
-		case DeviatoricStressyzEnum : return "DeviatoricStressyz";
-		case DeviatoricStresszzEnum : return "DeviatoricStresszz";
+		case SurfaceAbsMisfitEnum : return "SurfaceAbsMisfit";
+		case SurfaceAbsVelMisfitEnum : return "SurfaceAbsVelMisfit";
+		case SurfaceAreaEnum : return "SurfaceArea";
+		case SurfaceAverageVelMisfitEnum : return "SurfaceAverageVelMisfit";
+		case SurfaceEnum : return "Surface";
+		case SurfaceLogVelMisfitEnum : return "SurfaceLogVelMisfit";
+		case SurfaceLogVxVyMisfitEnum : return "SurfaceLogVxVyMisfit";
+		case SurfaceObservationEnum : return "SurfaceObservation";
+		case SurfaceRelVelMisfitEnum : return "SurfaceRelVelMisfit";
+		case SurfaceSlopeXEnum : return "SurfaceSlopeX";
+		case SurfaceSlopeYEnum : return "SurfaceSlopeY";
+		case TemperatureEnum : return "Temperature";
+		case TemperaturePicardEnum : return "TemperaturePicard";
+		case ThicknessAbsGradientEnum : return "ThicknessAbsGradient";
+		case ThicknessAbsMisfitEnum : return "ThicknessAbsMisfit";
+		case ThicknessAcrossGradientEnum : return "ThicknessAcrossGradient";
+		case ThicknessAlongGradientEnum : return "ThicknessAlongGradient";
+		case ThicknessEnum : return "Thickness";
+		case ThicknessPositiveEnum : return "ThicknessPositive";
+		case VelEnum : return "Vel";
+		case VxAverageEnum : return "VxAverage";
+		case VxEnum : return "Vx";
+		case VxMeshEnum : return "VxMesh";
+		case VxObsEnum : return "VxObs";
+		case VyAverageEnum : return "VyAverage";
+		case VyEnum : return "Vy";
+		case VyMeshEnum : return "VyMesh";
+		case VyObsEnum : return "VyObs";
+		case VzEnum : return "Vz";
+		case VzFSEnum : return "VzFS";
+		case VzHOEnum : return "VzHO";
+		case VzMeshEnum : return "VzMesh";
+		case VzSSAEnum : return "VzSSA";
+		case WatercolumnEnum : return "Watercolumn";
+		case WaterColumnOldEnum : return "WaterColumnOld";
+		case WaterfractionDrainageEnum : return "WaterfractionDrainage";
+		case WaterfractionDrainageIntegratedEnum : return "WaterfractionDrainageIntegrated";
+		case WaterfractionEnum : return "Waterfraction";
+		case WaterheightEnum : return "Waterheight";
+		case WeightsSurfaceObservationEnum : return "WeightsSurfaceObservation";
+		case InputsENDEnum : return "InputsEND";
+		case AbsoluteEnum : return "Absolute";
+		case AdaptiveTimesteppingEnum : return "AdaptiveTimestepping";
+		case AdjointBalancethickness2AnalysisEnum : return "AdjointBalancethickness2Analysis";
+		case AdjointBalancethicknessAnalysisEnum : return "AdjointBalancethicknessAnalysis";
+		case AdjointHorizAnalysisEnum : return "AdjointHorizAnalysis";
+		case AdjointpEnum : return "Adjointp";
+		case AggressiveMigrationEnum : return "AggressiveMigration";
+		case AmrBamgEnum : return "AmrBamg";
+		case AmrNeopzEnum : return "AmrNeopz";
+		case AndroidFrictionCoefficientEnum : return "AndroidFrictionCoefficient";
+		case ArrheniusEnum : return "Arrhenius";
+		case AutodiffJacobianEnum : return "AutodiffJacobian";
+		case Balancethickness2AnalysisEnum : return "Balancethickness2Analysis";
+		case Balancethickness2SolutionEnum : return "Balancethickness2Solution";
+		case BalancethicknessAnalysisEnum : return "BalancethicknessAnalysis";
+		case BalancethicknessApparentMassbalanceEnum : return "BalancethicknessApparentMassbalance";
+		case BalancethicknessSoftAnalysisEnum : return "BalancethicknessSoftAnalysis";
+		case BalancethicknessSoftSolutionEnum : return "BalancethicknessSoftSolution";
+		case BalancethicknessSolutionEnum : return "BalancethicknessSolution";
+		case BalancethicknessSpcthicknessEnum : return "BalancethicknessSpcthickness";
+		case BalancevelocityAnalysisEnum : return "BalancevelocityAnalysis";
+		case BalancevelocitySolutionEnum : return "BalancevelocitySolution";
+		case BasalCrevasseEnum : return "BasalCrevasse";
+		case BasalforcingsPicoEnum : return "BasalforcingsPico";
+		case BedSlopeSolutionEnum : return "BedSlopeSolution";
+		case BoolExternalResultEnum : return "BoolExternalResult";
+		case BoolInputEnum : return "BoolInput";
+		case BoolParamEnum : return "BoolParam";
+		case BoundaryEnum : return "Boundary";
+		case BuddJackaEnum : return "BuddJacka";
+		case CalvingDev2Enum : return "CalvingDev2";
+		case CalvingHabEnum : return "CalvingHab";
+		case CalvingLevermannEnum : return "CalvingLevermann";
+		case CalvingVonmisesEnum : return "CalvingVonmises";
+		case CfsurfacelogvelEnum : return "Cfsurfacelogvel";
+		case CfsurfacesquareEnum : return "Cfsurfacesquare";
+		case CfdragcoeffabsgradEnum : return "Cfdragcoeffabsgrad";
+		case ClosedEnum : return "Closed";
+		case ColinearEnum : return "Colinear";
+		case ConstantsGEnum : return "ConstantsG";
+		case ConstantsReferencetemperatureEnum : return "ConstantsReferencetemperature";
+		case ConstraintsEnum : return "Constraints";
+		case ContactEnum : return "Contact";
+		case ContourEnum : return "Contour";
+		case ContoursEnum : return "Contours";
+		case ControlInputEnum : return "ControlInput";
+		case ControlInputValuesEnum : return "ControlInputValues";
+		case ControlInputMinsEnum : return "ControlInputMins";
+		case ControlInputMaxsEnum : return "ControlInputMaxs";
+		case ControlInputGradEnum : return "ControlInputGrad";
+		case CrouzeixRaviartEnum : return "CrouzeixRaviart";
+		case CuffeyEnum : return "Cuffey";
+		case CuffeyTemperateEnum : return "CuffeyTemperate";
+		case DamageEvolutionAnalysisEnum : return "DamageEvolutionAnalysis";
+		case DamageEvolutionSolutionEnum : return "DamageEvolutionSolution";
+		case DataSetEnum : return "DataSet";
+		case DatasetInputEnum : return "DatasetInput";
+		case DataSetParamEnum : return "DataSetParam";
+		case DefaultAnalysisEnum : return "DefaultAnalysis";
+		case DefaultCalvingEnum : return "DefaultCalving";
+		case DegreeOfChannelizationEnum : return "DegreeOfChannelization";
+		case DenseEnum : return "Dense";
+		case DependentObjectEnum : return "DependentObject";
+		case DepthAverageAnalysisEnum : return "DepthAverageAnalysis";
 		case DeviatoricStresseffectiveEnum : return "DeviatoricStresseffective";
+		case DeviatoricStressErrorEstimatorEnum : return "DeviatoricStressErrorEstimator";
+		case DivergenceEnum : return "Divergence";
+		case Domain3DsurfaceEnum : return "Domain3Dsurface";
+		case DoubleArrayInputEnum : return "DoubleArrayInput";
+		case DoubleExternalResultEnum : return "DoubleExternalResult";
+		case DoubleInputEnum : return "DoubleInput";
+		case DoubleMatArrayParamEnum : return "DoubleMatArrayParam";
+		case DoubleMatExternalResultEnum : return "DoubleMatExternalResult";
+		case DoubleMatParamEnum : return "DoubleMatParam";
+		case DoubleParamEnum : return "DoubleParam";
+		case DoubleVecParamEnum : return "DoubleVecParam";
+		case EffectivePressureStackedEnum : return "EffectivePressureStacked";
+		case EffectivePressureTimeAverageEnum : return "EffectivePressureTimeAverage";
+		case ElementEnum : return "Element";
+		case ElementHookEnum : return "ElementHook";
+		case ElementSIdEnum : return "ElementSId";
+		case EnthalpyAnalysisEnum : return "EnthalpyAnalysis";
+		case EplHeadStackedEnum : return "EplHeadStacked";
+		case EplHeadTimeAverageEnum : return "EplHeadTimeAverage";
+		case EsaAnalysisEnum : return "EsaAnalysis";
+		case EsaEmotionEnum : return "EsaEmotion";
+		case EsaNmotionEnum : return "EsaNmotion";
+		case EsaRotationrateEnum : return "EsaRotationrate";
+		case EsaSolutionEnum : return "EsaSolution";
+		case EsaStrainratexxEnum : return "EsaStrainratexx";
+		case EsaStrainratexyEnum : return "EsaStrainratexy";
+		case EsaStrainrateyyEnum : return "EsaStrainrateyy";
+		case EsaTransitionsEnum : return "EsaTransitions";
+		case EsaUmotionEnum : return "EsaUmotion";
+		case ExternalResultEnum : return "ExternalResult";
+		case ExtrapolationAnalysisEnum : return "ExtrapolationAnalysis";
+		case ExtrudeFromBaseAnalysisEnum : return "ExtrudeFromBaseAnalysis";
+		case ExtrudeFromTopAnalysisEnum : return "ExtrudeFromTopAnalysis";
+		case FemModelEnum : return "FemModel";
+		case FileParamEnum : return "FileParam";
+		case FixedTimesteppingEnum : return "FixedTimestepping";
+		case FloatingAreaEnum : return "FloatingArea";
+		case FloatingAreaScaledEnum : return "FloatingAreaScaled";
+		case FloatingMeltRateEnum : return "FloatingMeltRate";
+		case FlowequationBorderFSEnum : return "FlowequationBorderFS";
+		case FreeEnum : return "Free";
+		case FreeSurfaceBaseAnalysisEnum : return "FreeSurfaceBaseAnalysis";
+		case FreeSurfaceTopAnalysisEnum : return "FreeSurfaceTopAnalysis";
+		case FSApproximationEnum : return "FSApproximation";
+		case FsetEnum : return "Fset";
+		case FSpressureEnum : return "FSpressure";
+		case FSSolverEnum : return "FSSolver";
+		case FSvelocityEnum : return "FSvelocity";
+		case GaussPentaEnum : return "GaussPenta";
+		case GaussSegEnum : return "GaussSeg";
+		case GaussTetraEnum : return "GaussTetra";
+		case GaussTriaEnum : return "GaussTria";
+		case GenericOptionEnum : return "GenericOption";
+		case GenericParamEnum : return "GenericParam";
+		case GiadWdtEnum : return "GiadWdt";
+		case GiaIvinsAnalysisEnum : return "GiaIvinsAnalysis";
+		case GiaSolutionEnum : return "GiaSolution";
+		case GiaWEnum : return "GiaW";
+		case Gradient1Enum : return "Gradient1";
+		case Gradient2Enum : return "Gradient2";
+		case Gradient3Enum : return "Gradient3";
+		case GroundedAreaEnum : return "GroundedArea";
+		case GroundedAreaScaledEnum : return "GroundedAreaScaled";
+		case GroundingOnlyEnum : return "GroundingOnly";
+		case GsetEnum : return "Gset";
+		case GslEnum : return "Gsl";
+		case HOApproximationEnum : return "HOApproximation";
+		case HOFSApproximationEnum : return "HOFSApproximation";
+		case HookEnum : return "Hook";
+		case HydrologyBasalFluxEnum : return "HydrologyBasalFlux";
+		case HydrologyDCEfficientAnalysisEnum : return "HydrologyDCEfficientAnalysis";
+		case HydrologydcEnum : return "Hydrologydc";
+		case HydrologydcEplColapseThicknessEnum : return "HydrologydcEplColapseThickness";
+		case HydrologydcEplCompressibilityEnum : return "HydrologydcEplCompressibility";
+		case HydrologydcEplConductivityEnum : return "HydrologydcEplConductivity";
+		case HydrologydcEplInitialThicknessEnum : return "HydrologydcEplInitialThickness";
+		case HydrologydcEplMaxThicknessEnum : return "HydrologydcEplMaxThickness";
+		case HydrologydcEplPorosityEnum : return "HydrologydcEplPorosity";
+		case HydrologydcEplThicknessStackedEnum : return "HydrologydcEplThicknessStacked";
+		case HydrologydcEplThicknessTimeAverageEnum : return "HydrologydcEplThicknessTimeAverage";
+		case HydrologyDCInefficientAnalysisEnum : return "HydrologyDCInefficientAnalysis";
+		case HydrologydcSedimentCompressibilityEnum : return "HydrologydcSedimentCompressibility";
+		case HydrologydcSedimentPorosityEnum : return "HydrologydcSedimentPorosity";
+		case HydrologydcSedimentThicknessEnum : return "HydrologydcSedimentThickness";
+		case HydrologydcWaterCompressibilityEnum : return "HydrologydcWaterCompressibility";
+		case HydrologyShreveAnalysisEnum : return "HydrologyShreveAnalysis";
+		case HydrologyshreveEnum : return "Hydrologyshreve";
+		case HydrologySolutionEnum : return "HydrologySolution";
+		case HydrologySommersAnalysisEnum : return "HydrologySommersAnalysis";
+		case HydrologysommersEnum : return "Hydrologysommers";
+		case IceMassEnum : return "IceMass";
+		case IceMassScaledEnum : return "IceMassScaled";
+		case IceVolumeAboveFloatationEnum : return "IceVolumeAboveFloatation";
+		case IceVolumeAboveFloatationScaledEnum : return "IceVolumeAboveFloatationScaled";
+		case IceVolumeEnum : return "IceVolume";
+		case IceVolumeScaledEnum : return "IceVolumeScaled";
+		case IncrementalEnum : return "Incremental";
+		case IndexedEnum : return "Indexed";
+		case InternalEnum : return "Internal";
+		case IntersectEnum : return "Intersect";
+		case IntExternalResultEnum : return "IntExternalResult";
+		case IntInputEnum : return "IntInput";
+		case IntMatExternalResultEnum : return "IntMatExternalResult";
+		case IntMatParamEnum : return "IntMatParam";
+		case IntParamEnum : return "IntParam";
+		case IntVecParamEnum : return "IntVecParam";
+		case InversionVzObsEnum : return "InversionVzObs";
+		case JEnum : return "J";
+		case L1L2ApproximationEnum : return "L1L2Approximation";
+		case L2ProjectionBaseAnalysisEnum : return "L2ProjectionBaseAnalysis";
+		case L2ProjectionEPLAnalysisEnum : return "L2ProjectionEPLAnalysis";
+		case LACrouzeixRaviartEnum : return "LACrouzeixRaviart";
 		case LambdaSEnum : return "LambdaS";
-		case StrainRateEnum : return "StrainRate";
-		case StrainRatexxEnum : return "StrainRatexx";
-		case StrainRatexyEnum : return "StrainRatexy";
-		case StrainRatexzEnum : return "StrainRatexz";
-		case StrainRateyyEnum : return "StrainRateyy";
-		case StrainRateyzEnum : return "StrainRateyz";
-		case StrainRatezzEnum : return "StrainRatezz";
-		case DivergenceEnum : return "Divergence";
+		case LATaylorHoodEnum : return "LATaylorHood";
+		case LevelsetAnalysisEnum : return "LevelsetAnalysis";
+		case LevelsetfunctionPicardEnum : return "LevelsetfunctionPicard";
+		case LinearFloatingMeltRateEnum : return "LinearFloatingMeltRate";
+		case LliboutryDuvalEnum : return "LliboutryDuval";
+		case LoadsEnum : return "Loads";
+		case LoveAnalysisEnum : return "LoveAnalysis";
+		case LoveHiEnum : return "LoveHi";
+		case LoveHrEnum : return "LoveHr";
+		case LoveKernelsImagEnum : return "LoveKernelsImag";
+		case LoveKernelsRealEnum : return "LoveKernelsReal";
+		case LoveKiEnum : return "LoveKi";
+		case LoveKrEnum : return "LoveKr";
+		case LoveLiEnum : return "LoveLi";
+		case LoveLrEnum : return "LoveLr";
+		case LoveSolutionEnum : return "LoveSolution";
+		case MantlePlumeGeothermalFluxEnum : return "MantlePlumeGeothermalFlux";
+		case MaskLandLevelsetEnum : return "MaskLandLevelset";
+		case MaskOceanLevelsetEnum : return "MaskOceanLevelset";
+		case MassconaxpbyEnum : return "Massconaxpby";
+		case MassconEnum : return "Masscon";
+		case MassfluxatgateEnum : return "Massfluxatgate";
+		case MassFluxEnum : return "MassFlux";
+		case MasstransportAnalysisEnum : return "MasstransportAnalysis";
+		case MasstransportSolutionEnum : return "MasstransportSolution";
+		case MatdamageiceEnum : return "Matdamageice";
+		case MatenhancediceEnum : return "Matenhancedice";
+		case MaterialsBetaEnum : return "MaterialsBeta";
+		case MaterialsEarthDensityEnum : return "MaterialsEarthDensity";
+		case MaterialsEnum : return "Materials";
+		case MaterialsHeatcapacityEnum : return "MaterialsHeatcapacity";
+		case MaterialsLatentheatEnum : return "MaterialsLatentheat";
+		case MaterialsLithosphereDensityEnum : return "MaterialsLithosphereDensity";
+		case MaterialsLithosphereShearModulusEnum : return "MaterialsLithosphereShearModulus";
+		case MaterialsMantleDensityEnum : return "MaterialsMantleDensity";
+		case MaterialsMantleShearModulusEnum : return "MaterialsMantleShearModulus";
+		case MaterialsMeltingpointEnum : return "MaterialsMeltingpoint";
+		case MaterialsMixedLayerCapacityEnum : return "MaterialsMixedLayerCapacity";
+		case MaterialsMuWaterEnum : return "MaterialsMuWater";
+		case MaterialsRheologyLawEnum : return "MaterialsRheologyLaw";
+		case MaterialsRhoFreshwaterEnum : return "MaterialsRhoFreshwater";
+		case MaterialsRhoIceEnum : return "MaterialsRhoIce";
+		case MaterialsRhoSeawaterEnum : return "MaterialsRhoSeawater";
+		case MaterialsTemperateiceconductivityEnum : return "MaterialsTemperateiceconductivity";
+		case MaterialsThermalconductivityEnum : return "MaterialsThermalconductivity";
+		case MaterialsThermalExchangeVelocityEnum : return "MaterialsThermalExchangeVelocity";
+		case MatestarEnum : return "Matestar";
+		case MaticeEnum : return "Matice";
+		case MatlithoEnum : return "Matlitho";
+		case MatparEnum : return "Matpar";
+		case MatrixParamEnum : return "MatrixParam";
+		case MaxAbsVxEnum : return "MaxAbsVx";
+		case MaxAbsVyEnum : return "MaxAbsVy";
+		case MaxAbsVzEnum : return "MaxAbsVz";
 		case MaxDivergenceEnum : return "MaxDivergence";
-		case GiaCrossSectionShapeEnum : return "GiaCrossSectionShape";
-		case GiadWdtEnum : return "GiadWdt";
-		case GiaWEnum : return "GiaW";
-		case SaveResultsEnum : return "SaveResults";
-		case BoolExternalResultEnum : return "BoolExternalResult";
-		case DoubleExternalResultEnum : return "DoubleExternalResult";
-		case DoubleMatExternalResultEnum : return "DoubleMatExternalResult";
-		case IntExternalResultEnum : return "IntExternalResult";
-		case IntMatExternalResultEnum : return "IntMatExternalResult";
-		case JEnum : return "J";
-		case StringExternalResultEnum : return "StringExternalResult";
-		case StepEnum : return "Step";
-		case TimeEnum : return "Time";
-		case WaterColumnOldEnum : return "WaterColumnOld";
-		case SurfaceObservationEnum : return "SurfaceObservation";
-		case WeightsSurfaceObservationEnum : return "WeightsSurfaceObservation";
-		case OutputdefinitionEnum : return "Outputdefinition";
+		case MaxVelEnum : return "MaxVel";
+		case MaxVxEnum : return "MaxVx";
+		case MaxVyEnum : return "MaxVy";
+		case MaxVzEnum : return "MaxVz";
+		case MelangeEnum : return "Melange";
+		case MeltingAnalysisEnum : return "MeltingAnalysis";
+		case MeshElementsEnum : return "MeshElements";
+		case MeshLatEnum : return "MeshLat";
+		case MeshLongEnum : return "MeshLong";
+		case MeshXEnum : return "MeshX";
+		case MeshYEnum : return "MeshY";
+		case MINIcondensedEnum : return "MINIcondensed";
+		case MINIEnum : return "MINI";
+		case MinVelEnum : return "MinVel";
+		case MinVxEnum : return "MinVx";
+		case MinVyEnum : return "MinVy";
+		case MinVzEnum : return "MinVz";
+		case MismipFloatingMeltRateEnum : return "MismipFloatingMeltRate";
+		case MoulinEnum : return "Moulin";
+		case MpiDenseEnum : return "MpiDense";
+		case MpiEnum : return "Mpi";
+		case MpiSparseEnum : return "MpiSparse";
+		case MumpsEnum : return "Mumps";
+		case NewDamageEnum : return "NewDamage";
+		case NodalEnum : return "Nodal";
+		case NodalvalueEnum : return "Nodalvalue";
+		case NodeSIdEnum : return "NodeSId";
+		case NoneApproximationEnum : return "NoneApproximation";
+		case NoneEnum : return "None";
+		case NumberedcostfunctionEnum : return "Numberedcostfunction";
+		case NumericalfluxEnum : return "Numericalflux";
+		case OldGradientEnum : return "OldGradient";
+		case OneLayerP4zEnum : return "OneLayerP4z";
+		case OpenEnum : return "Open";
+		case OptionEnum : return "Option";
 		case Outputdefinition1Enum : return "Outputdefinition1";
-		case Outputdefinition2Enum : return "Outputdefinition2";
-		case Outputdefinition3Enum : return "Outputdefinition3";
-		case Outputdefinition4Enum : return "Outputdefinition4";
-		case Outputdefinition5Enum : return "Outputdefinition5";
-		case Outputdefinition6Enum : return "Outputdefinition6";
-		case Outputdefinition7Enum : return "Outputdefinition7";
-		case Outputdefinition8Enum : return "Outputdefinition8";
-		case Outputdefinition9Enum : return "Outputdefinition9";
 		case Outputdefinition10Enum : return "Outputdefinition10";
 		case Outputdefinition11Enum : return "Outputdefinition11";
@@ -618,4 +908,5 @@
 		case Outputdefinition28Enum : return "Outputdefinition28";
 		case Outputdefinition29Enum : return "Outputdefinition29";
+		case Outputdefinition2Enum : return "Outputdefinition2";
 		case Outputdefinition30Enum : return "Outputdefinition30";
 		case Outputdefinition31Enum : return "Outputdefinition31";
@@ -628,4 +919,5 @@
 		case Outputdefinition38Enum : return "Outputdefinition38";
 		case Outputdefinition39Enum : return "Outputdefinition39";
+		case Outputdefinition3Enum : return "Outputdefinition3";
 		case Outputdefinition40Enum : return "Outputdefinition40";
 		case Outputdefinition41Enum : return "Outputdefinition41";
@@ -638,4 +930,5 @@
 		case Outputdefinition48Enum : return "Outputdefinition48";
 		case Outputdefinition49Enum : return "Outputdefinition49";
+		case Outputdefinition4Enum : return "Outputdefinition4";
 		case Outputdefinition50Enum : return "Outputdefinition50";
 		case Outputdefinition51Enum : return "Outputdefinition51";
@@ -648,4 +941,5 @@
 		case Outputdefinition58Enum : return "Outputdefinition58";
 		case Outputdefinition59Enum : return "Outputdefinition59";
+		case Outputdefinition5Enum : return "Outputdefinition5";
 		case Outputdefinition60Enum : return "Outputdefinition60";
 		case Outputdefinition61Enum : return "Outputdefinition61";
@@ -658,4 +952,5 @@
 		case Outputdefinition68Enum : return "Outputdefinition68";
 		case Outputdefinition69Enum : return "Outputdefinition69";
+		case Outputdefinition6Enum : return "Outputdefinition6";
 		case Outputdefinition70Enum : return "Outputdefinition70";
 		case Outputdefinition71Enum : return "Outputdefinition71";
@@ -668,4 +963,5 @@
 		case Outputdefinition78Enum : return "Outputdefinition78";
 		case Outputdefinition79Enum : return "Outputdefinition79";
+		case Outputdefinition7Enum : return "Outputdefinition7";
 		case Outputdefinition80Enum : return "Outputdefinition80";
 		case Outputdefinition81Enum : return "Outputdefinition81";
@@ -678,4 +974,5 @@
 		case Outputdefinition88Enum : return "Outputdefinition88";
 		case Outputdefinition89Enum : return "Outputdefinition89";
+		case Outputdefinition8Enum : return "Outputdefinition8";
 		case Outputdefinition90Enum : return "Outputdefinition90";
 		case Outputdefinition91Enum : return "Outputdefinition91";
@@ -688,316 +985,146 @@
 		case Outputdefinition98Enum : return "Outputdefinition98";
 		case Outputdefinition99Enum : return "Outputdefinition99";
+		case Outputdefinition9Enum : return "Outputdefinition9";
 		case Outputdefinition100Enum : return "Outputdefinition100";
-		case OutputdefinitionListEnum : return "OutputdefinitionList";
-		case MassfluxatgateEnum : return "Massfluxatgate";
-		case NodalvalueEnum : return "Nodalvalue";
-		case VxObsEnum : return "VxObs";
-		case VyObsEnum : return "VyObs";
-		case AbsoluteEnum : return "Absolute";
-		case IncrementalEnum : return "Incremental";
-		case AugmentedLagrangianREnum : return "AugmentedLagrangianR";
-		case AugmentedLagrangianRhopEnum : return "AugmentedLagrangianRhop";
-		case AugmentedLagrangianRlambdaEnum : return "AugmentedLagrangianRlambda";
-		case AugmentedLagrangianRholambdaEnum : return "AugmentedLagrangianRholambda";
-		case AugmentedLagrangianThetaEnum : return "AugmentedLagrangianTheta";
-		case NoneEnum : return "None";
-		case AggressiveMigrationEnum : return "AggressiveMigration";
-		case SoftMigrationEnum : return "SoftMigration";
-		case SubelementMigrationEnum : return "SubelementMigration";
-		case SubelementMigration2Enum : return "SubelementMigration2";
-		case ContactEnum : return "Contact";
-		case GroundingOnlyEnum : return "GroundingOnly";
-		case MaskGroundediceLevelsetEnum : return "MaskGroundediceLevelset";
-		case AdjointEnum : return "Adjoint";
-		case ColinearEnum : return "Colinear";
-		case ControlSteadyEnum : return "ControlSteady";
-		case FsetEnum : return "Fset";
-		case Gradient1Enum : return "Gradient1";
-		case Gradient2Enum : return "Gradient2";
-		case Gradient3Enum : return "Gradient3";
-		case GradientEnum : return "Gradient";
-		case GroundinglineMigrationEnum : return "GroundinglineMigration";
-		case GsetEnum : return "Gset";
-		case IndexEnum : return "Index";
-		case IndexedEnum : return "Indexed";
-		case IntersectEnum : return "Intersect";
-		case NodalEnum : return "Nodal";
-		case OldGradientEnum : return "OldGradient";
-		case OutputBufferPointerEnum : return "OutputBufferPointer";
-		case OutputBufferSizePointerEnum : return "OutputBufferSizePointer";
-		case OutputFilePointerEnum : return "OutputFilePointer";
-		case ToolkitsFileNameEnum : return "ToolkitsFileName";
-		case RootPathEnum : return "RootPath";
-		case OutputFileNameEnum : return "OutputFileName";
-		case InputFileNameEnum : return "InputFileName";
-		case LockFileNameEnum : return "LockFileName";
-		case RestartFileNameEnum : return "RestartFileName";
-		case ToolkitsOptionsAnalysesEnum : return "ToolkitsOptionsAnalyses";
-		case ToolkitsOptionsStringsEnum : return "ToolkitsOptionsStrings";
-		case QmuErrNameEnum : return "QmuErrName";
-		case QmuInNameEnum : return "QmuInName";
-		case QmuOutNameEnum : return "QmuOutName";
-		case RegularEnum : return "Regular";
-		case ScaledEnum : return "Scaled";
-		case SeparateEnum : return "Separate";
-		case SsetEnum : return "Sset";
-		case DenseEnum : return "Dense";
-		case MpiDenseEnum : return "MpiDense";
-		case MpiSparseEnum : return "MpiSparse";
-		case SeqEnum : return "Seq";
-		case MpiEnum : return "Mpi";
-		case MumpsEnum : return "Mumps";
-		case GslEnum : return "Gsl";
-		case CuffeyEnum : return "Cuffey";
-		case BuddJackaEnum : return "BuddJacka";
-		case CuffeyTemperateEnum : return "CuffeyTemperate";
+		case P0ArrayEnum : return "P0Array";
+		case P1bubblecondensedEnum : return "P1bubblecondensed";
+		case P1bubbleEnum : return "P1bubble";
+		case P1DGEnum : return "P1DG";
+		case P1P1Enum : return "P1P1";
+		case P1P1GLSEnum : return "P1P1GLS";
+		case P1xP2Enum : return "P1xP2";
+		case P1xP3Enum : return "P1xP3";
+		case P1xP4Enum : return "P1xP4";
+		case P2bubblecondensedEnum : return "P2bubblecondensed";
+		case P2bubbleEnum : return "P2bubble";
+		case P2Enum : return "P2";
+		case P2xP1Enum : return "P2xP1";
+		case P2xP4Enum : return "P2xP4";
 		case PatersonEnum : return "Paterson";
-		case ArrheniusEnum : return "Arrhenius";
-		case LliboutryDuvalEnum : return "LliboutryDuval";
-		case ExtrapolationVariableEnum : return "ExtrapolationVariable";
-		case IceMaskNodeActivationEnum : return "IceMaskNodeActivation";
-		case LevelsetfunctionSlopeXEnum : return "LevelsetfunctionSlopeX";
-		case LevelsetfunctionSlopeYEnum : return "LevelsetfunctionSlopeY";
-		case LevelsetfunctionPicardEnum : return "LevelsetfunctionPicard";
-		case LevelsetReinitFrequencyEnum : return "LevelsetReinitFrequency";
-		case SealevelEnum : return "Sealevel";
-		case SealevelUmotionEnum : return "SealevelUmotion";
-		case SealevelNmotionEnum : return "SealevelNmotion";
-		case SealevelEmotionEnum : return "SealevelEmotion";
-		case SealevelAbsoluteEnum : return "SealevelAbsolute";
-		case SealevelEustaticEnum : return "SealevelEustatic";
-		case SealevelriseDeltathicknessEnum : return "SealevelriseDeltathickness";
-		case SealevelriseMaxiterEnum : return "SealevelriseMaxiter";
-		case SealevelriseReltolEnum : return "SealevelriseReltol";
-		case SealevelriseAbstolEnum : return "SealevelriseAbstol";
-		case SealevelriseRigidEnum : return "SealevelriseRigid";
-		case SealevelriseElasticEnum : return "SealevelriseElastic";
-		case SealevelriseRotationEnum : return "SealevelriseRotation";
-		case SealevelriseTidalLoveHEnum : return "SealevelriseTidalLoveH";
-		case SealevelriseTidalLoveKEnum : return "SealevelriseTidalLoveK";
-		case SealevelriseFluidLoveEnum : return "SealevelriseFluidLove";
-		case SealevelriseEquatorialMoiEnum : return "SealevelriseEquatorialMoi";
-		case SealevelrisePolarMoiEnum : return "SealevelrisePolarMoi";
-		case SealevelriseAngularVelocityEnum : return "SealevelriseAngularVelocity";
-		case SealevelriseOceanAreaScalingEnum : return "SealevelriseOceanAreaScaling";
-		case SealevelriseGElasticEnum : return "SealevelriseGElastic";
-		case SealevelriseUElasticEnum : return "SealevelriseUElastic";
-		case SealevelriseHElasticEnum : return "SealevelriseHElastic";
-		case SealevelriseTransitionsEnum : return "SealevelriseTransitions";
-		case SealevelriseRequestedOutputsEnum : return "SealevelriseRequestedOutputs";
-		case SealevelriseNumRequestedOutputsEnum : return "SealevelriseNumRequestedOutputs";
-		case EsaUmotionEnum : return "EsaUmotion";
-		case EsaNmotionEnum : return "EsaNmotion";
-		case EsaEmotionEnum : return "EsaEmotion";
-		case EsaStrainratexxEnum : return "EsaStrainratexx";
-		case EsaStrainratexyEnum : return "EsaStrainratexy";
-		case EsaStrainrateyyEnum : return "EsaStrainrateyy";
-		case EsaRotationrateEnum : return "EsaRotationrate";
-		case EsaDeltathicknessEnum : return "EsaDeltathickness";
-		case EsaUElasticEnum : return "EsaUElastic";
-		case EsaHElasticEnum : return "EsaHElastic";
-		case EsaTransitionsEnum : return "EsaTransitions";
-		case EsaRequestedOutputsEnum : return "EsaRequestedOutputs";
-		case EsaNumRequestedOutputsEnum : return "EsaNumRequestedOutputs";
-		case AmrLevelMaxEnum : return "AmrLevelMax";
-		case AmrRegionLevel1Enum : return "AmrRegionLevel1";
-		case AmrRegionLevelMaxEnum : return "AmrRegionLevelMax";
-		case TransientAmrFrequencyEnum : return "TransientAmrFrequency";
-		case ParametersENDEnum : return "ParametersEND";
-		case XYEnum : return "XY";
-		case XYZEnum : return "XYZ";
-		case GenericParamEnum : return "GenericParam";
-		case BoolInputEnum : return "BoolInput";
-		case BoolParamEnum : return "BoolParam";
-		case ContourEnum : return "Contour";
-		case ControlInputEnum : return "ControlInput";
-		case DatasetInputEnum : return "DatasetInput";
-		case DoubleInputEnum : return "DoubleInput";
-		case DoubleArrayInputEnum : return "DoubleArrayInput";
-		case DataSetParamEnum : return "DataSetParam";
-		case DoubleMatArrayParamEnum : return "DoubleMatArrayParam";
-		case DoubleMatParamEnum : return "DoubleMatParam";
-		case DoubleParamEnum : return "DoubleParam";
-		case DoubleVecParamEnum : return "DoubleVecParam";
-		case ElementEnum : return "Element";
-		case ElementHookEnum : return "ElementHook";
-		case HookEnum : return "Hook";
-		case ExternalResultEnum : return "ExternalResult";
-		case FileParamEnum : return "FileParam";
-		case InputEnum : return "Input";
-		case IntInputEnum : return "IntInput";
-		case IntParamEnum : return "IntParam";
-		case IntVecParamEnum : return "IntVecParam";
-		case TransientParamEnum : return "TransientParam";
-		case MaticeEnum : return "Matice";
-		case MatdamageiceEnum : return "Matdamageice";
-		case MatenhancediceEnum : return "Matenhancedice";
-		case MatestarEnum : return "Matestar";
-		case MatparEnum : return "Matpar";
-		case NodeEnum : return "Node";
-		case NumericalfluxEnum : return "Numericalflux";
-		case NeumannfluxEnum : return "Neumannflux";
-		case ParamEnum : return "Param";
-		case MoulinEnum : return "Moulin";
 		case PengridEnum : return "Pengrid";
 		case PenpairEnum : return "Penpair";
+		case PentaEnum : return "Penta";
+		case PentaInputEnum : return "PentaInput";
 		case ProfilerEnum : return "Profiler";
-		case MatrixParamEnum : return "MatrixParam";
-		case MassconEnum : return "Masscon";
-		case MassconaxpbyEnum : return "Massconaxpby";
-		case NodeSIdEnum : return "NodeSId";
-		case ElementSIdEnum : return "ElementSId";
-		case VectorParamEnum : return "VectorParam";
+		case ProfilingCurrentFlopsEnum : return "ProfilingCurrentFlops";
+		case ProfilingCurrentMemEnum : return "ProfilingCurrentMem";
+		case ProfilingSolutionTimeEnum : return "ProfilingSolutionTime";
+		case RegionaloutputEnum : return "Regionaloutput";
+		case RegularEnum : return "Regular";
+		case ResetPenaltiesEnum : return "ResetPenalties";
 		case RiftfrontEnum : return "Riftfront";
+		case ScaledEnum : return "Scaled";
+		case SealevelAbsoluteEnum : return "SealevelAbsolute";
+		case SealevelEmotionEnum : return "SealevelEmotion";
+		case SealevelEustaticEnum : return "SealevelEustatic";
+		case SealevelInertiaTensorXZEnum : return "SealevelInertiaTensorXZ";
+		case SealevelInertiaTensorYZEnum : return "SealevelInertiaTensorYZ";
+		case SealevelInertiaTensorZZEnum : return "SealevelInertiaTensorZZ";
+		case SealevelNmotionEnum : return "SealevelNmotion";
+		case SealevelriseAnalysisEnum : return "SealevelriseAnalysis";
+		case SealevelriseSolutionEnum : return "SealevelriseSolution";
+		case SealevelriseStericRateEnum : return "SealevelriseStericRate";
+		case SealevelUmotionEnum : return "SealevelUmotion";
+		case SedimentHeadStackedEnum : return "SedimentHeadStacked";
+		case SedimentHeadTimeAverageEnum : return "SedimentHeadTimeAverage";
+		case SegEnum : return "Seg";
+		case SegInputEnum : return "SegInput";
 		case SegmentEnum : return "Segment";
 		case SegmentRiftfrontEnum : return "SegmentRiftfront";
+		case SeparateEnum : return "Separate";
+		case SeqEnum : return "Seq";
+		case SIAApproximationEnum : return "SIAApproximation";
+		case SigmaVMEnum : return "SigmaVM";
+		case SmbAnalysisEnum : return "SmbAnalysis";
+		case SMBcomponentsEnum : return "SMBcomponents";
+		case SMBd18opddEnum : return "SMBd18opdd";
+		case SmbDesfacEnum : return "SmbDesfac";
+		case SmbDpermilEnum : return "SmbDpermil";
+		case SmbDzAddEnum : return "SmbDzAdd";
+		case SmbFACEnum : return "SmbFAC";
+		case SMBforcingEnum : return "SMBforcing";
+		case SMBgcmEnum : return "SMBgcm";
+		case SMBgembEnum : return "SMBgemb";
+		case SMBgradientselaEnum : return "SMBgradientsela";
+		case SMBgradientsEnum : return "SMBgradients";
+		case SMBhenningEnum : return "SMBhenning";
+		case SmbMAddEnum : return "SmbMAdd";
+		case SMBmeltcomponentsEnum : return "SMBmeltcomponents";
+		case SMBpddEnum : return "SMBpdd";
+		case SmbRlapsEnum : return "SmbRlaps";
+		case SmbRlapslgmEnum : return "SmbRlapslgm";
+		case SmbSolutionEnum : return "SmbSolution";
+		case SmoothAnalysisEnum : return "SmoothAnalysis";
+		case SoftMigrationEnum : return "SoftMigration";
 		case SpcDynamicEnum : return "SpcDynamic";
 		case SpcStaticEnum : return "SpcStatic";
 		case SpcTransientEnum : return "SpcTransient";
+		case SSAApproximationEnum : return "SSAApproximation";
+		case SSAFSApproximationEnum : return "SSAFSApproximation";
+		case SSAHOApproximationEnum : return "SSAHOApproximation";
+		case SsetEnum : return "Sset";
+		case SteadystateSolutionEnum : return "SteadystateSolution";
+		case StressbalanceAnalysisEnum : return "StressbalanceAnalysis";
+		case StressbalanceConvergenceNumStepsEnum : return "StressbalanceConvergenceNumSteps";
+		case StressbalanceSIAAnalysisEnum : return "StressbalanceSIAAnalysis";
+		case StressbalanceSolutionEnum : return "StressbalanceSolution";
+		case StressbalanceVerticalAnalysisEnum : return "StressbalanceVerticalAnalysis";
+		case StressIntensityFactorEnum : return "StressIntensityFactor";
 		case StringArrayParamEnum : return "StringArrayParam";
+		case StringExternalResultEnum : return "StringExternalResult";
 		case StringParamEnum : return "StringParam";
-		case SegEnum : return "Seg";
-		case SegInputEnum : return "SegInput";
+		case SubelementMigration2Enum : return "SubelementMigration2";
+		case SubelementMigration3Enum : return "SubelementMigration3";
+		case SubelementMigrationEnum : return "SubelementMigration";
+		case SurfaceCrevasseEnum : return "SurfaceCrevasse";
+		case SurfaceSlopeSolutionEnum : return "SurfaceSlopeSolution";
+		case TaylorHoodEnum : return "TaylorHood";
+		case TemperaturePDDEnum : return "TemperaturePDD";
+		case TetraEnum : return "Tetra";
+		case TetraInputEnum : return "TetraInput";
+		case ThermalAnalysisEnum : return "ThermalAnalysis";
+		case ThermalSolutionEnum : return "ThermalSolution";
+		case ThermalSpctemperatureEnum : return "ThermalSpctemperature";
+		case ThicknessErrorEstimatorEnum : return "ThicknessErrorEstimator";
+		case TotalFloatingBmbEnum : return "TotalFloatingBmb";
+		case TotalFloatingBmbScaledEnum : return "TotalFloatingBmbScaled";
+		case TotalGroundedBmbEnum : return "TotalGroundedBmb";
+		case TotalGroundedBmbScaledEnum : return "TotalGroundedBmbScaled";
+		case TotalSmbEnum : return "TotalSmb";
+		case TotalSmbScaledEnum : return "TotalSmbScaled";
+		case TransientArrayParamEnum : return "TransientArrayParam";
+		case TransientInputEnum : return "TransientInput";
+		case TransientParamEnum : return "TransientParam";
+		case TransientSolutionEnum : return "TransientSolution";
 		case TriaEnum : return "Tria";
 		case TriaInputEnum : return "TriaInput";
-		case TetraEnum : return "Tetra";
-		case TetraInputEnum : return "TetraInput";
-		case PentaEnum : return "Penta";
-		case PentaInputEnum : return "PentaInput";
+		case UzawaPressureAnalysisEnum : return "UzawaPressureAnalysis";
+		case VectorParamEnum : return "VectorParam";
 		case VertexEnum : return "Vertex";
 		case VertexPIdEnum : return "VertexPId";
 		case VertexSIdEnum : return "VertexSId";
-		case OptionEnum : return "Option";
-		case GenericOptionEnum : return "GenericOption";
-		case OptionCellEnum : return "OptionCell";
-		case OptionStructEnum : return "OptionStruct";
-		case AdjointBalancethicknessAnalysisEnum : return "AdjointBalancethicknessAnalysis";
-		case AdjointBalancethickness2AnalysisEnum : return "AdjointBalancethickness2Analysis";
-		case AdjointHorizAnalysisEnum : return "AdjointHorizAnalysis";
-		case DefaultAnalysisEnum : return "DefaultAnalysis";
-		case BalancethicknessAnalysisEnum : return "BalancethicknessAnalysis";
-		case BalancethicknessSolutionEnum : return "BalancethicknessSolution";
-		case Balancethickness2AnalysisEnum : return "Balancethickness2Analysis";
-		case Balancethickness2SolutionEnum : return "Balancethickness2Solution";
-		case BalancethicknessSoftAnalysisEnum : return "BalancethicknessSoftAnalysis";
-		case BalancethicknessSoftSolutionEnum : return "BalancethicknessSoftSolution";
-		case BalancevelocityAnalysisEnum : return "BalancevelocityAnalysis";
-		case BalancevelocitySolutionEnum : return "BalancevelocitySolution";
-		case L2ProjectionEPLAnalysisEnum : return "L2ProjectionEPLAnalysis";
-		case L2ProjectionBaseAnalysisEnum : return "L2ProjectionBaseAnalysis";
-		case BedSlopeSolutionEnum : return "BedSlopeSolution";
-		case DamageEvolutionSolutionEnum : return "DamageEvolutionSolution";
-		case DamageEvolutionAnalysisEnum : return "DamageEvolutionAnalysis";
-		case StressbalanceAnalysisEnum : return "StressbalanceAnalysis";
-		case StressbalanceSIAAnalysisEnum : return "StressbalanceSIAAnalysis";
-		case StressbalanceSolutionEnum : return "StressbalanceSolution";
-		case StressbalanceVerticalAnalysisEnum : return "StressbalanceVerticalAnalysis";
-		case EnthalpyAnalysisEnum : return "EnthalpyAnalysis";
-		case HydrologyShreveAnalysisEnum : return "HydrologyShreveAnalysis";
-		case HydrologyDCInefficientAnalysisEnum : return "HydrologyDCInefficientAnalysis";
-		case HydrologyDCEfficientAnalysisEnum : return "HydrologyDCEfficientAnalysis";
-		case HydrologySommersAnalysisEnum : return "HydrologySommersAnalysis";
-		case HydrologySolutionEnum : return "HydrologySolution";
-		case MeltingAnalysisEnum : return "MeltingAnalysis";
-		case MasstransportAnalysisEnum : return "MasstransportAnalysis";
-		case MasstransportSolutionEnum : return "MasstransportSolution";
-		case FreeSurfaceBaseAnalysisEnum : return "FreeSurfaceBaseAnalysis";
-		case FreeSurfaceTopAnalysisEnum : return "FreeSurfaceTopAnalysis";
-		case ExtrudeFromBaseAnalysisEnum : return "ExtrudeFromBaseAnalysis";
-		case ExtrudeFromTopAnalysisEnum : return "ExtrudeFromTopAnalysis";
-		case DepthAverageAnalysisEnum : return "DepthAverageAnalysis";
-		case SealevelriseSolutionEnum : return "SealevelriseSolution";
-		case SealevelriseAnalysisEnum : return "SealevelriseAnalysis";
-		case SteadystateSolutionEnum : return "SteadystateSolution";
-		case SurfaceSlopeSolutionEnum : return "SurfaceSlopeSolution";
-		case SmoothAnalysisEnum : return "SmoothAnalysis";
-		case ThermalAnalysisEnum : return "ThermalAnalysis";
-		case ThermalSolutionEnum : return "ThermalSolution";
-		case TransientSolutionEnum : return "TransientSolution";
-		case UzawaPressureAnalysisEnum : return "UzawaPressureAnalysis";
-		case GiaSolutionEnum : return "GiaSolution";
-		case GiaIvinsAnalysisEnum : return "GiaIvinsAnalysis";
-		case EsaSolutionEnum : return "EsaSolution";
-		case EsaAnalysisEnum : return "EsaAnalysis";
-		case MeshdeformationAnalysisEnum : return "MeshdeformationAnalysis";
-		case LevelsetAnalysisEnum : return "LevelsetAnalysis";
-		case ExtrapolationAnalysisEnum : return "ExtrapolationAnalysis";
-		case ApproximationEnum : return "Approximation";
-		case NoneApproximationEnum : return "NoneApproximation";
-		case SIAApproximationEnum : return "SIAApproximation";
-		case SSAApproximationEnum : return "SSAApproximation";
-		case SSAHOApproximationEnum : return "SSAHOApproximation";
-		case SSAFSApproximationEnum : return "SSAFSApproximation";
-		case L1L2ApproximationEnum : return "L1L2Approximation";
-		case HOApproximationEnum : return "HOApproximation";
-		case HOFSApproximationEnum : return "HOFSApproximation";
-		case FSApproximationEnum : return "FSApproximation";
-		case FSvelocityEnum : return "FSvelocity";
-		case FSpressureEnum : return "FSpressure";
-		case GaussSegEnum : return "GaussSeg";
-		case GaussTriaEnum : return "GaussTria";
-		case GaussTetraEnum : return "GaussTetra";
-		case GaussPentaEnum : return "GaussPenta";
+		case VerticesEnum : return "Vertices";
+		case ViscousHeatingEnum : return "ViscousHeating";
+		case WaterEnum : return "Water";
+		case XTaylorHoodEnum : return "XTaylorHood";
+		case XYEnum : return "XY";
+		case XYZEnum : return "XYZ";
+		case BalancethicknessD0Enum : return "BalancethicknessD0";
+		case BalancethicknessDiffusionCoefficientEnum : return "BalancethicknessDiffusionCoefficient";
+		case BilinearInterpEnum : return "BilinearInterp";
+		case CalvingdevCoeffEnum : return "CalvingdevCoeff";
+		case DeviatoricStressEnum : return "DeviatoricStress";
+		case EtaAbsGradientEnum : return "EtaAbsGradient";
+		case MeshZEnum : return "MeshZ";
+		case NearestInterpEnum : return "NearestInterp";
+		case OutputdefinitionListEnum : return "OutputdefinitionList";
+		case SealevelObsEnum : return "SealevelObs";
+		case SealevelWeightsEnum : return "SealevelWeights";
+		case StrainRateEnum : return "StrainRate";
+		case StressbalanceViscosityOvershootEnum : return "StressbalanceViscosityOvershoot";
+		case StressTensorEnum : return "StressTensor";
+		case SubelementMigration4Enum : return "SubelementMigration4";
+		case TimesteppingTimeAdaptEnum : return "TimesteppingTimeAdapt";
 		case TriangleInterpEnum : return "TriangleInterp";
-		case BilinearInterpEnum : return "BilinearInterp";
-		case NearestInterpEnum : return "NearestInterp";
-		case MinVelEnum : return "MinVel";
-		case MaxVelEnum : return "MaxVel";
-		case MinVxEnum : return "MinVx";
-		case MaxVxEnum : return "MaxVx";
-		case MaxAbsVxEnum : return "MaxAbsVx";
-		case MinVyEnum : return "MinVy";
-		case MaxVyEnum : return "MaxVy";
-		case MaxAbsVyEnum : return "MaxAbsVy";
-		case MinVzEnum : return "MinVz";
-		case MaxVzEnum : return "MaxVz";
-		case MaxAbsVzEnum : return "MaxAbsVz";
-		case FloatingAreaEnum : return "FloatingArea";
-		case GroundedAreaEnum : return "GroundedArea";
-		case IceMassEnum : return "IceMass";
-		case IceVolumeEnum : return "IceVolume";
-		case IceVolumeAboveFloatationEnum : return "IceVolumeAboveFloatation";
-		case TotalFloatingBmbEnum : return "TotalFloatingBmb";
-		case TotalGroundedBmbEnum : return "TotalGroundedBmb";
-		case TotalSmbEnum : return "TotalSmb";
-		case P0Enum : return "P0";
-		case P0ArrayEnum : return "P0Array";
-		case P1Enum : return "P1";
-		case P1DGEnum : return "P1DG";
-		case P1bubbleEnum : return "P1bubble";
-		case P1bubblecondensedEnum : return "P1bubblecondensed";
-		case P2Enum : return "P2";
-		case P2bubbleEnum : return "P2bubble";
-		case P2bubblecondensedEnum : return "P2bubblecondensed";
-		case P2xP1Enum : return "P2xP1";
-		case P1xP2Enum : return "P1xP2";
-		case P1xP3Enum : return "P1xP3";
-		case P2xP4Enum : return "P2xP4";
-		case P1P1Enum : return "P1P1";
-		case P1P1GLSEnum : return "P1P1GLS";
-		case MINIEnum : return "MINI";
-		case MINIcondensedEnum : return "MINIcondensed";
-		case TaylorHoodEnum : return "TaylorHood";
-		case LATaylorHoodEnum : return "LATaylorHood";
-		case XTaylorHoodEnum : return "XTaylorHood";
-		case OneLayerP4zEnum : return "OneLayerP4z";
-		case CrouzeixRaviartEnum : return "CrouzeixRaviart";
-		case LACrouzeixRaviartEnum : return "LACrouzeixRaviart";
-		case ClosedEnum : return "Closed";
-		case FreeEnum : return "Free";
-		case OpenEnum : return "Open";
-		case AirEnum : return "Air";
-		case IceEnum : return "Ice";
-		case MelangeEnum : return "Melange";
-		case WaterEnum : return "Water";
-		case DataSetEnum : return "DataSet";
-		case ConstraintsEnum : return "Constraints";
-		case LoadsEnum : return "Loads";
-		case MaterialsEnum : return "Materials";
-		case NodesEnum : return "Nodes";
-		case ContoursEnum : return "Contours";
-		case ParametersEnum : return "Parameters";
-		case VerticesEnum : return "Vertices";
-		case ResultsEnum : return "Results";
 		case MaximumNumberOfDefinitionsEnum : return "MaximumNumberOfDefinitions";
 		default : return "unknown";
Index: /issm/trunk/src/c/shared/Enum/StringToEnumx.cpp
===================================================================
--- /issm/trunk/src/c/shared/Enum/StringToEnumx.cpp	(revision 22757)
+++ /issm/trunk/src/c/shared/Enum/StringToEnumx.cpp	(revision 22758)
@@ -17,546 +17,571 @@
 
    if(stage==1){
-	      if (strcmp(name,"FemModel")==0) return FemModelEnum;
-	      else if (strcmp(name,"ParametersSTART")==0) return ParametersSTARTEnum;
+	      if (strcmp(name,"ParametersSTART")==0) return ParametersSTARTEnum;
 	      else if (strcmp(name,"AdolcParam")==0) return AdolcParamEnum;
-	      else if (strcmp(name,"FSSolver")==0) return FSSolverEnum;
+	      else if (strcmp(name,"AmrDeviatoricErrorGroupThreshold")==0) return AmrDeviatoricErrorGroupThresholdEnum;
+	      else if (strcmp(name,"AmrDeviatoricErrorMaximum")==0) return AmrDeviatoricErrorMaximumEnum;
+	      else if (strcmp(name,"AmrDeviatoricErrorResolution")==0) return AmrDeviatoricErrorResolutionEnum;
+	      else if (strcmp(name,"AmrDeviatoricErrorThreshold")==0) return AmrDeviatoricErrorThresholdEnum;
+	      else if (strcmp(name,"AmrErr")==0) return AmrErrEnum;
+	      else if (strcmp(name,"AmrField")==0) return AmrFieldEnum;
+	      else if (strcmp(name,"AmrGradation")==0) return AmrGradationEnum;
+	      else if (strcmp(name,"AmrGroundingLineDistance")==0) return AmrGroundingLineDistanceEnum;
+	      else if (strcmp(name,"AmrGroundingLineResolution")==0) return AmrGroundingLineResolutionEnum;
+	      else if (strcmp(name,"AmrHmax")==0) return AmrHmaxEnum;
+	      else if (strcmp(name,"AmrHmin")==0) return AmrHminEnum;
+	      else if (strcmp(name,"AmrIceFrontDistance")==0) return AmrIceFrontDistanceEnum;
+	      else if (strcmp(name,"AmrIceFrontResolution")==0) return AmrIceFrontResolutionEnum;
+	      else if (strcmp(name,"AmrKeepMetric")==0) return AmrKeepMetricEnum;
+	      else if (strcmp(name,"AmrLag")==0) return AmrLagEnum;
+	      else if (strcmp(name,"AmrLevelMax")==0) return AmrLevelMaxEnum;
+	      else if (strcmp(name,"AmrRestart")==0) return AmrRestartEnum;
+	      else if (strcmp(name,"AmrThicknessErrorGroupThreshold")==0) return AmrThicknessErrorGroupThresholdEnum;
+	      else if (strcmp(name,"AmrThicknessErrorMaximum")==0) return AmrThicknessErrorMaximumEnum;
+	      else if (strcmp(name,"AmrThicknessErrorResolution")==0) return AmrThicknessErrorResolutionEnum;
+	      else if (strcmp(name,"AmrThicknessErrorThreshold")==0) return AmrThicknessErrorThresholdEnum;
+	      else if (strcmp(name,"AmrType")==0) return AmrTypeEnum;
+	      else if (strcmp(name,"AnalysisCounter")==0) return AnalysisCounterEnum;
+	      else if (strcmp(name,"AnalysisType")==0) return AnalysisTypeEnum;
+	      else if (strcmp(name,"AugmentedLagrangianR")==0) return AugmentedLagrangianREnum;
+	      else if (strcmp(name,"AugmentedLagrangianRholambda")==0) return AugmentedLagrangianRholambdaEnum;
+	      else if (strcmp(name,"AugmentedLagrangianRhop")==0) return AugmentedLagrangianRhopEnum;
+	      else if (strcmp(name,"AugmentedLagrangianRlambda")==0) return AugmentedLagrangianRlambdaEnum;
+	      else if (strcmp(name,"AugmentedLagrangianTheta")==0) return AugmentedLagrangianThetaEnum;
+	      else if (strcmp(name,"AutodiffCbufsize")==0) return AutodiffCbufsizeEnum;
+	      else if (strcmp(name,"AutodiffDependentObjects")==0) return AutodiffDependentObjectsEnum;
+	      else if (strcmp(name,"AutodiffDriver")==0) return AutodiffDriverEnum;
+	      else if (strcmp(name,"AutodiffFosForwardIndex")==0) return AutodiffFosForwardIndexEnum;
+	      else if (strcmp(name,"AutodiffFosReverseIndex")==0) return AutodiffFosReverseIndexEnum;
+	      else if (strcmp(name,"AutodiffFovForwardIndices")==0) return AutodiffFovForwardIndicesEnum;
+	      else if (strcmp(name,"AutodiffGcTriggerMaxSize")==0) return AutodiffGcTriggerMaxSizeEnum;
+	      else if (strcmp(name,"AutodiffGcTriggerRatio")==0) return AutodiffGcTriggerRatioEnum;
+	      else if (strcmp(name,"AutodiffIsautodiff")==0) return AutodiffIsautodiffEnum;
+	      else if (strcmp(name,"AutodiffLbufsize")==0) return AutodiffLbufsizeEnum;
+	      else if (strcmp(name,"AutodiffNumDependents")==0) return AutodiffNumDependentsEnum;
+	      else if (strcmp(name,"AutodiffNumIndependents")==0) return AutodiffNumIndependentsEnum;
+	      else if (strcmp(name,"AutodiffObufsize")==0) return AutodiffObufsizeEnum;
+	      else if (strcmp(name,"AutodiffTbufsize")==0) return AutodiffTbufsizeEnum;
+	      else if (strcmp(name,"AutodiffXp")==0) return AutodiffXpEnum;
+	      else if (strcmp(name,"BalancethicknessStabilization")==0) return BalancethicknessStabilizationEnum;
+	      else if (strcmp(name,"BasalforcingsBottomplumedepth")==0) return BasalforcingsBottomplumedepthEnum;
+	      else if (strcmp(name,"BasalforcingsCrustthickness")==0) return BasalforcingsCrustthicknessEnum;
+	      else if (strcmp(name,"BasalforcingsDeepwaterElevation")==0) return BasalforcingsDeepwaterElevationEnum;
+	      else if (strcmp(name,"BasalforcingsDeepwaterMeltingRate")==0) return BasalforcingsDeepwaterMeltingRateEnum;
+	      else if (strcmp(name,"BasalforcingsDtbg")==0) return BasalforcingsDtbgEnum;
+	      else if (strcmp(name,"Basalforcings")==0) return BasalforcingsEnum;
+	      else if (strcmp(name,"BasalforcingsLowercrustheat")==0) return BasalforcingsLowercrustheatEnum;
+	      else if (strcmp(name,"BasalforcingsMantleconductivity")==0) return BasalforcingsMantleconductivityEnum;
+	      else if (strcmp(name,"BasalforcingsMeltrateFactor")==0) return BasalforcingsMeltrateFactorEnum;
+	      else if (strcmp(name,"BasalforcingsNusselt")==0) return BasalforcingsNusseltEnum;
+	      else if (strcmp(name,"BasalforcingsPicoAverageOverturning")==0) return BasalforcingsPicoAverageOverturningEnum;
+	      else if (strcmp(name,"BasalforcingsPicoAverageSalinity")==0) return BasalforcingsPicoAverageSalinityEnum;
+	      else if (strcmp(name,"BasalforcingsPicoAverageTemperature")==0) return BasalforcingsPicoAverageTemperatureEnum;
+	      else if (strcmp(name,"BasalforcingsPicoBoxArea")==0) return BasalforcingsPicoBoxAreaEnum;
+	      else if (strcmp(name,"BasalforcingsPicoFarOceansalinity")==0) return BasalforcingsPicoFarOceansalinityEnum;
+	      else if (strcmp(name,"BasalforcingsPicoFarOceantemperature")==0) return BasalforcingsPicoFarOceantemperatureEnum;
+	      else if (strcmp(name,"BasalforcingsPicoGammaT")==0) return BasalforcingsPicoGammaTEnum;
+	      else if (strcmp(name,"BasalforcingsPicoMaxboxcount")==0) return BasalforcingsPicoMaxboxcountEnum;
+	      else if (strcmp(name,"BasalforcingsPicoNumBasins")==0) return BasalforcingsPicoNumBasinsEnum;
+	      else if (strcmp(name,"BasalforcingsPicoOverturningCoeff")==0) return BasalforcingsPicoOverturningCoeffEnum;
+	      else if (strcmp(name,"BasalforcingsPlumeradius")==0) return BasalforcingsPlumeradiusEnum;
+	      else if (strcmp(name,"BasalforcingsPlumex")==0) return BasalforcingsPlumexEnum;
+	      else if (strcmp(name,"BasalforcingsPlumey")==0) return BasalforcingsPlumeyEnum;
+	      else if (strcmp(name,"BasalforcingsThresholdThickness")==0) return BasalforcingsThresholdThicknessEnum;
+	      else if (strcmp(name,"BasalforcingsTopplumedepth")==0) return BasalforcingsTopplumedepthEnum;
+	      else if (strcmp(name,"BasalforcingsUppercrustheat")==0) return BasalforcingsUppercrustheatEnum;
+	      else if (strcmp(name,"BasalforcingsUppercrustthickness")==0) return BasalforcingsUppercrustthicknessEnum;
+	      else if (strcmp(name,"BasalforcingsUpperdepthMelt")==0) return BasalforcingsUpperdepthMeltEnum;
+	      else if (strcmp(name,"BasalforcingsUpperwaterElevation")==0) return BasalforcingsUpperwaterElevationEnum;
+	      else if (strcmp(name,"CalvingCrevasseDepth")==0) return CalvingCrevasseDepthEnum;
+	      else if (strcmp(name,"CalvingHeightAboveFloatation")==0) return CalvingHeightAboveFloatationEnum;
+	      else if (strcmp(name,"CalvingLaw")==0) return CalvingLawEnum;
+	      else if (strcmp(name,"CalvingMax")==0) return CalvingMaxEnum;
+	      else if (strcmp(name,"CalvingMinthickness")==0) return CalvingMinthicknessEnum;
+	      else if (strcmp(name,"ConfigurationType")==0) return ConfigurationTypeEnum;
+	      else if (strcmp(name,"ConstantsYts")==0) return ConstantsYtsEnum;
+	      else if (strcmp(name,"DamageC1")==0) return DamageC1Enum;
+	      else if (strcmp(name,"DamageC2")==0) return DamageC2Enum;
+	      else if (strcmp(name,"DamageC3")==0) return DamageC3Enum;
+	      else if (strcmp(name,"Damage")==0) return DamageEnum;
+	      else if (strcmp(name,"DamageEquivStress")==0) return DamageEquivStressEnum;
+	      else if (strcmp(name,"DamageEvolutionNumRequestedOutputs")==0) return DamageEvolutionNumRequestedOutputsEnum;
+	      else if (strcmp(name,"DamageEvolutionRequestedOutputs")==0) return DamageEvolutionRequestedOutputsEnum;
+	      else if (strcmp(name,"DamageHealing")==0) return DamageHealingEnum;
+	      else if (strcmp(name,"DamageKappa")==0) return DamageKappaEnum;
+	      else if (strcmp(name,"DamageLaw")==0) return DamageLawEnum;
+	      else if (strcmp(name,"DamageMaxDamage")==0) return DamageMaxDamageEnum;
+	      else if (strcmp(name,"DamageStabilization")==0) return DamageStabilizationEnum;
+	      else if (strcmp(name,"DamageStressThreshold")==0) return DamageStressThresholdEnum;
+	      else if (strcmp(name,"DebugProfiling")==0) return DebugProfilingEnum;
+	      else if (strcmp(name,"DomainDimension")==0) return DomainDimensionEnum;
+	      else if (strcmp(name,"DomainType")==0) return DomainTypeEnum;
+	      else if (strcmp(name,"EarthId")==0) return EarthIdEnum;
+	      else if (strcmp(name,"EplZigZagCounter")==0) return EplZigZagCounterEnum;
+	      else if (strcmp(name,"EsaHElastic")==0) return EsaHElasticEnum;
+	      else if (strcmp(name,"EsaHemisphere")==0) return EsaHemisphereEnum;
+	      else if (strcmp(name,"EsaRequestedOutputs")==0) return EsaRequestedOutputsEnum;
+	      else if (strcmp(name,"EsaUElastic")==0) return EsaUElasticEnum;
+	      else if (strcmp(name,"ExtrapolationVariable")==0) return ExtrapolationVariableEnum;
 	      else if (strcmp(name,"FemModelComm")==0) return FemModelCommEnum;
-	      else if (strcmp(name,"WorldComm")==0) return WorldCommEnum;
+	      else if (strcmp(name,"FlowequationFeFS")==0) return FlowequationFeFSEnum;
+	      else if (strcmp(name,"FlowequationIsFS")==0) return FlowequationIsFSEnum;
+	      else if (strcmp(name,"FlowequationIsHO")==0) return FlowequationIsHOEnum;
+	      else if (strcmp(name,"FlowequationIsL1L2")==0) return FlowequationIsL1L2Enum;
+	      else if (strcmp(name,"FlowequationIsSIA")==0) return FlowequationIsSIAEnum;
+	      else if (strcmp(name,"FlowequationIsSSA")==0) return FlowequationIsSSAEnum;
+	      else if (strcmp(name,"FrictionCoupling")==0) return FrictionCouplingEnum;
+	      else if (strcmp(name,"FrictionF")==0) return FrictionFEnum;
+	      else if (strcmp(name,"FrictionGamma")==0) return FrictionGammaEnum;
+	      else if (strcmp(name,"FrictionLaw")==0) return FrictionLawEnum;
+	      else if (strcmp(name,"GiaCrossSectionShape")==0) return GiaCrossSectionShapeEnum;
+	      else if (strcmp(name,"GroundinglineMigration")==0) return GroundinglineMigrationEnum;
+	      else if (strcmp(name,"HydrologydcEplflipLock")==0) return HydrologydcEplflipLockEnum;
+         else stage=2;
+   }
+   if(stage==2){
+	      if (strcmp(name,"HydrologydcEplThickComp")==0) return HydrologydcEplThickCompEnum;
+	      else if (strcmp(name,"HydrologydcIsefficientlayer")==0) return HydrologydcIsefficientlayerEnum;
+	      else if (strcmp(name,"HydrologydcLeakageFactor")==0) return HydrologydcLeakageFactorEnum;
+	      else if (strcmp(name,"HydrologydcMaxIter")==0) return HydrologydcMaxIterEnum;
+	      else if (strcmp(name,"HydrologydcPenaltyFactor")==0) return HydrologydcPenaltyFactorEnum;
+	      else if (strcmp(name,"HydrologydcPenaltyLock")==0) return HydrologydcPenaltyLockEnum;
+	      else if (strcmp(name,"HydrologydcRelTol")==0) return HydrologydcRelTolEnum;
+	      else if (strcmp(name,"HydrologydcSedimentlimit")==0) return HydrologydcSedimentlimitEnum;
+	      else if (strcmp(name,"HydrologydcSedimentlimitFlag")==0) return HydrologydcSedimentlimitFlagEnum;
+	      else if (strcmp(name,"HydrologydcTransferFlag")==0) return HydrologydcTransferFlagEnum;
+	      else if (strcmp(name,"HydrologydcUnconfinedFlag")==0) return HydrologydcUnconfinedFlagEnum;
+	      else if (strcmp(name,"Hydrologydt")==0) return HydrologydtEnum;
+	      else if (strcmp(name,"HydrologyModel")==0) return HydrologyModelEnum;
+	      else if (strcmp(name,"HydrologyNumRequestedOutputs")==0) return HydrologyNumRequestedOutputsEnum;
+	      else if (strcmp(name,"HydrologyRelaxation")==0) return HydrologyRelaxationEnum;
+	      else if (strcmp(name,"HydrologyRequestedOutputs")==0) return HydrologyRequestedOutputsEnum;
+	      else if (strcmp(name,"HydrologySedimentKmax")==0) return HydrologySedimentKmaxEnum;
+	      else if (strcmp(name,"HydrologyshreveStabilization")==0) return HydrologyshreveStabilizationEnum;
+	      else if (strcmp(name,"HydrologyStepsPerStep")==0) return HydrologyStepsPerStepEnum;
+	      else if (strcmp(name,"HydrologyStorage")==0) return HydrologyStorageEnum;
 	      else if (strcmp(name,"IcecapToEarthComm")==0) return IcecapToEarthCommEnum;
-	      else if (strcmp(name,"NumModels")==0) return NumModelsEnum;
-	      else if (strcmp(name,"ModelId")==0) return ModelIdEnum;
-	      else if (strcmp(name,"EarthId")==0) return EarthIdEnum;
-	      else if (strcmp(name,"SolutionType")==0) return SolutionTypeEnum;
-	      else if (strcmp(name,"AnalysisType")==0) return AnalysisTypeEnum;
-	      else if (strcmp(name,"AnalysisCounter")==0) return AnalysisCounterEnum;
-	      else if (strcmp(name,"ConfigurationType")==0) return ConfigurationTypeEnum;
+	      else if (strcmp(name,"Index")==0) return IndexEnum;
+	      else if (strcmp(name,"InputFileName")==0) return InputFileNameEnum;
+	      else if (strcmp(name,"InputToDepthaverageIn")==0) return InputToDepthaverageInEnum;
+	      else if (strcmp(name,"InputToDepthaverageOut")==0) return InputToDepthaverageOutEnum;
 	      else if (strcmp(name,"InputToExtrude")==0) return InputToExtrudeEnum;
 	      else if (strcmp(name,"InputToL2Project")==0) return InputToL2ProjectEnum;
-	      else if (strcmp(name,"InputToDepthaverageIn")==0) return InputToDepthaverageInEnum;
-	      else if (strcmp(name,"InputToDepthaverageOut")==0) return InputToDepthaverageOutEnum;
 	      else if (strcmp(name,"InputToSmooth")==0) return InputToSmoothEnum;
+	      else if (strcmp(name,"InversionAlgorithm")==0) return InversionAlgorithmEnum;
+	      else if (strcmp(name,"InversionControlParameters")==0) return InversionControlParametersEnum;
+	      else if (strcmp(name,"InversionControlScalingFactors")==0) return InversionControlScalingFactorsEnum;
+	      else if (strcmp(name,"ControlInputSizeM")==0) return ControlInputSizeMEnum;
+	      else if (strcmp(name,"ControlInputSizeN")==0) return ControlInputSizeNEnum;
+	      else if (strcmp(name,"InversionCostFunctions")==0) return InversionCostFunctionsEnum;
+	      else if (strcmp(name,"InversionDxmin")==0) return InversionDxminEnum;
+	      else if (strcmp(name,"InversionGatol")==0) return InversionGatolEnum;
+	      else if (strcmp(name,"InversionGradientScaling")==0) return InversionGradientScalingEnum;
+	      else if (strcmp(name,"InversionGrtol")==0) return InversionGrtolEnum;
+	      else if (strcmp(name,"InversionGttol")==0) return InversionGttolEnum;
+	      else if (strcmp(name,"InversionIncompleteAdjoint")==0) return InversionIncompleteAdjointEnum;
+	      else if (strcmp(name,"InversionIscontrol")==0) return InversionIscontrolEnum;
+	      else if (strcmp(name,"InversionMaxiter")==0) return InversionMaxiterEnum;
+	      else if (strcmp(name,"InversionMaxiterPerStep")==0) return InversionMaxiterPerStepEnum;
+	      else if (strcmp(name,"InversionMaxsteps")==0) return InversionMaxstepsEnum;
+	      else if (strcmp(name,"InversionNsteps")==0) return InversionNstepsEnum;
+	      else if (strcmp(name,"InversionNumControlParameters")==0) return InversionNumControlParametersEnum;
+	      else if (strcmp(name,"InversionNumCostFunctions")==0) return InversionNumCostFunctionsEnum;
+	      else if (strcmp(name,"InversionStepThreshold")==0) return InversionStepThresholdEnum;
+	      else if (strcmp(name,"InversionType")==0) return InversionTypeEnum;
+	      else if (strcmp(name,"LevelsetReinitFrequency")==0) return LevelsetReinitFrequencyEnum;
+	      else if (strcmp(name,"LevelsetStabilization")==0) return LevelsetStabilizationEnum;
+	      else if (strcmp(name,"LockFileName")==0) return LockFileNameEnum;
+	      else if (strcmp(name,"LoveAllowLayerDeletion")==0) return LoveAllowLayerDeletionEnum;
+	      else if (strcmp(name,"LoveForcingType")==0) return LoveForcingTypeEnum;
+	      else if (strcmp(name,"LoveFrequencies")==0) return LoveFrequenciesEnum;
+	      else if (strcmp(name,"LoveG0")==0) return LoveG0Enum;
+	      else if (strcmp(name,"LoveKernels")==0) return LoveKernelsEnum;
+	      else if (strcmp(name,"LoveMu0")==0) return LoveMu0Enum;
+	      else if (strcmp(name,"LoveNfreq")==0) return LoveNfreqEnum;
+	      else if (strcmp(name,"LoveR0")==0) return LoveR0Enum;
+	      else if (strcmp(name,"LoveShNmax")==0) return LoveShNmaxEnum;
+	      else if (strcmp(name,"LoveShNmin")==0) return LoveShNminEnum;
+	      else if (strcmp(name,"MassFluxSegments")==0) return MassFluxSegmentsEnum;
+	      else if (strcmp(name,"MassFluxSegmentsPresent")==0) return MassFluxSegmentsPresentEnum;
+	      else if (strcmp(name,"MasstransportHydrostaticAdjustment")==0) return MasstransportHydrostaticAdjustmentEnum;
+	      else if (strcmp(name,"MasstransportIsfreesurface")==0) return MasstransportIsfreesurfaceEnum;
+	      else if (strcmp(name,"MasstransportMinThickness")==0) return MasstransportMinThicknessEnum;
+	      else if (strcmp(name,"MasstransportNumRequestedOutputs")==0) return MasstransportNumRequestedOutputsEnum;
+	      else if (strcmp(name,"MasstransportPenaltyFactor")==0) return MasstransportPenaltyFactorEnum;
+	      else if (strcmp(name,"MasstransportRequestedOutputs")==0) return MasstransportRequestedOutputsEnum;
+	      else if (strcmp(name,"MasstransportStabilization")==0) return MasstransportStabilizationEnum;
+	      else if (strcmp(name,"MeltingOffset")==0) return MeltingOffsetEnum;
+	      else if (strcmp(name,"MeshAverageVertexConnectivity")==0) return MeshAverageVertexConnectivityEnum;
+	      else if (strcmp(name,"MeshElementtype")==0) return MeshElementtypeEnum;
+	      else if (strcmp(name,"MeshNumberoflayers")==0) return MeshNumberoflayersEnum;
+	      else if (strcmp(name,"MeshNumberofvertices")==0) return MeshNumberofverticesEnum;
+	      else if (strcmp(name,"ModelId")==0) return ModelIdEnum;
+	      else if (strcmp(name,"Nodes")==0) return NodesEnum;
+	      else if (strcmp(name,"NumModels")==0) return NumModelsEnum;
+	      else if (strcmp(name,"OceanGridNx")==0) return OceanGridNxEnum;
+	      else if (strcmp(name,"OceanGridNy")==0) return OceanGridNyEnum;
+	      else if (strcmp(name,"OceanGridX")==0) return OceanGridXEnum;
+	      else if (strcmp(name,"OceanGridY")==0) return OceanGridYEnum;
+	      else if (strcmp(name,"OutputBufferPointer")==0) return OutputBufferPointerEnum;
+	      else if (strcmp(name,"OutputBufferSizePointer")==0) return OutputBufferSizePointerEnum;
+	      else if (strcmp(name,"Outputdefinition")==0) return OutputdefinitionEnum;
+	      else if (strcmp(name,"OutputFileName")==0) return OutputFileNameEnum;
+	      else if (strcmp(name,"OutputFilePointer")==0) return OutputFilePointerEnum;
+	      else if (strcmp(name,"Param")==0) return ParamEnum;
+	      else if (strcmp(name,"Parameters")==0) return ParametersEnum;
+	      else if (strcmp(name,"QmuErrName")==0) return QmuErrNameEnum;
+	      else if (strcmp(name,"QmuInName")==0) return QmuInNameEnum;
+	      else if (strcmp(name,"QmuIsdakota")==0) return QmuIsdakotaEnum;
+	      else if (strcmp(name,"QmuNumberofpartitions")==0) return QmuNumberofpartitionsEnum;
+	      else if (strcmp(name,"QmuOutName")==0) return QmuOutNameEnum;
+	      else if (strcmp(name,"QmuPartition")==0) return QmuPartitionEnum;
+	      else if (strcmp(name,"QmuResponsedescriptors")==0) return QmuResponsedescriptorsEnum;
+	      else if (strcmp(name,"QmuVariableDescriptors")==0) return QmuVariableDescriptorsEnum;
+	      else if (strcmp(name,"RestartFileName")==0) return RestartFileNameEnum;
+	      else if (strcmp(name,"Results")==0) return ResultsEnum;
+	      else if (strcmp(name,"RootPath")==0) return RootPathEnum;
+	      else if (strcmp(name,"SaveResults")==0) return SaveResultsEnum;
+	      else if (strcmp(name,"SealevelriseAbstol")==0) return SealevelriseAbstolEnum;
+	      else if (strcmp(name,"SealevelriseAngularVelocity")==0) return SealevelriseAngularVelocityEnum;
+	      else if (strcmp(name,"SealevelriseElastic")==0) return SealevelriseElasticEnum;
+	      else if (strcmp(name,"SealevelriseEquatorialMoi")==0) return SealevelriseEquatorialMoiEnum;
+	      else if (strcmp(name,"SealevelriseFluidLove")==0) return SealevelriseFluidLoveEnum;
+	      else if (strcmp(name,"SealevelriseGElastic")==0) return SealevelriseGElasticEnum;
+	      else if (strcmp(name,"SealevelriseHElastic")==0) return SealevelriseHElasticEnum;
+	      else if (strcmp(name,"SealevelriseMaxiter")==0) return SealevelriseMaxiterEnum;
+	      else if (strcmp(name,"SealevelriseOceanAreaScaling")==0) return SealevelriseOceanAreaScalingEnum;
+	      else if (strcmp(name,"SealevelrisePolarMoi")==0) return SealevelrisePolarMoiEnum;
+	      else if (strcmp(name,"SealevelriseReltol")==0) return SealevelriseReltolEnum;
+	      else if (strcmp(name,"SealevelriseRequestedOutputs")==0) return SealevelriseRequestedOutputsEnum;
+	      else if (strcmp(name,"SealevelriseRigid")==0) return SealevelriseRigidEnum;
+	      else if (strcmp(name,"SealevelriseRotation")==0) return SealevelriseRotationEnum;
+	      else if (strcmp(name,"SealevelriseTidalLoveH")==0) return SealevelriseTidalLoveHEnum;
+	      else if (strcmp(name,"SealevelriseTidalLoveK")==0) return SealevelriseTidalLoveKEnum;
+	      else if (strcmp(name,"SealevelriseTransitions")==0) return SealevelriseTransitionsEnum;
+	      else if (strcmp(name,"SealevelriseUElastic")==0) return SealevelriseUElasticEnum;
+         else stage=3;
+   }
+   if(stage==3){
+	      if (strcmp(name,"SettingsIoGather")==0) return SettingsIoGatherEnum;
+	      else if (strcmp(name,"SettingsOutputFrequency")==0) return SettingsOutputFrequencyEnum;
+	      else if (strcmp(name,"SettingsRecordingFrequency")==0) return SettingsRecordingFrequencyEnum;
+	      else if (strcmp(name,"SettingsResultsOnNodes")==0) return SettingsResultsOnNodesEnum;
+	      else if (strcmp(name,"SettingsSolverResidueThreshold")==0) return SettingsSolverResidueThresholdEnum;
+	      else if (strcmp(name,"SettingsWaitonlock")==0) return SettingsWaitonlockEnum;
+	      else if (strcmp(name,"SmbAdThresh")==0) return SmbAdThreshEnum;
+	      else if (strcmp(name,"SmbAIce")==0) return SmbAIceEnum;
+	      else if (strcmp(name,"SmbAIdx")==0) return SmbAIdxEnum;
+	      else if (strcmp(name,"SmbASnow")==0) return SmbASnowEnum;
+	      else if (strcmp(name,"SmbCldFrac")==0) return SmbCldFracEnum;
+	      else if (strcmp(name,"SmbDelta18o")==0) return SmbDelta18oEnum;
+	      else if (strcmp(name,"SmbDelta18oSurface")==0) return SmbDelta18oSurfaceEnum;
+	      else if (strcmp(name,"SmbDenIdx")==0) return SmbDenIdxEnum;
+	      else if (strcmp(name,"SmbDt")==0) return SmbDtEnum;
+	      else if (strcmp(name,"Smb")==0) return SmbEnum;
+	      else if (strcmp(name,"SmbF")==0) return SmbFEnum;
+	      else if (strcmp(name,"SmbInitDensityScaling")==0) return SmbInitDensityScalingEnum;
+	      else if (strcmp(name,"SmbIsaccumulation")==0) return SmbIsaccumulationEnum;
+	      else if (strcmp(name,"SmbIsalbedo")==0) return SmbIsalbedoEnum;
+	      else if (strcmp(name,"SmbIsd18opd")==0) return SmbIsd18opdEnum;
+	      else if (strcmp(name,"SmbIsdelta18o")==0) return SmbIsdelta18oEnum;
+	      else if (strcmp(name,"SmbIsdensification")==0) return SmbIsdensificationEnum;
+	      else if (strcmp(name,"SmbIsgraingrowth")==0) return SmbIsgraingrowthEnum;
+	      else if (strcmp(name,"SmbIsmelt")==0) return SmbIsmeltEnum;
+	      else if (strcmp(name,"SmbIsmungsm")==0) return SmbIsmungsmEnum;
+	      else if (strcmp(name,"SmbIssetpddfac")==0) return SmbIssetpddfacEnum;
+	      else if (strcmp(name,"SmbIsshortwave")==0) return SmbIsshortwaveEnum;
+	      else if (strcmp(name,"SmbIstemperaturescaled")==0) return SmbIstemperaturescaledEnum;
+	      else if (strcmp(name,"SmbIsthermal")==0) return SmbIsthermalEnum;
+	      else if (strcmp(name,"SmbIsturbulentflux")==0) return SmbIsturbulentfluxEnum;
+	      else if (strcmp(name,"SmbK")==0) return SmbKEnum;
+	      else if (strcmp(name,"SmbNumRequestedOutputs")==0) return SmbNumRequestedOutputsEnum;
+	      else if (strcmp(name,"SmbPfac")==0) return SmbPfacEnum;
+	      else if (strcmp(name,"SmbRequestedOutputs")==0) return SmbRequestedOutputsEnum;
+	      else if (strcmp(name,"SmbSealev")==0) return SmbSealevEnum;
+	      else if (strcmp(name,"SmbSwIdx")==0) return SmbSwIdxEnum;
+	      else if (strcmp(name,"SmbT0dry")==0) return SmbT0dryEnum;
+	      else if (strcmp(name,"SmbT0wet")==0) return SmbT0wetEnum;
+	      else if (strcmp(name,"SmbTdiff")==0) return SmbTdiffEnum;
+	      else if (strcmp(name,"SmbThermoDeltaTScaling")==0) return SmbThermoDeltaTScalingEnum;
 	      else if (strcmp(name,"SmoothThicknessMultiplier")==0) return SmoothThicknessMultiplierEnum;
-	      else if (strcmp(name,"LevelsetStabilization")==0) return LevelsetStabilizationEnum;
-	      else if (strcmp(name,"AutodiffIsautodiff")==0) return AutodiffIsautodiffEnum;
-	      else if (strcmp(name,"AutodiffNumDependents")==0) return AutodiffNumDependentsEnum;
-	      else if (strcmp(name,"AutodiffDependentObjects")==0) return AutodiffDependentObjectsEnum;
-	      else if (strcmp(name,"AutodiffNumIndependents")==0) return AutodiffNumIndependentsEnum;
-	      else if (strcmp(name,"AutodiffJacobian")==0) return AutodiffJacobianEnum;
-	      else if (strcmp(name,"AutodiffXp")==0) return AutodiffXpEnum;
-	      else if (strcmp(name,"AutodiffDriver")==0) return AutodiffDriverEnum;
-	      else if (strcmp(name,"AutodiffFosForwardIndex")==0) return AutodiffFosForwardIndexEnum;
-	      else if (strcmp(name,"AutodiffFovForwardIndices")==0) return AutodiffFovForwardIndicesEnum;
-	      else if (strcmp(name,"AutodiffFosReverseIndex")==0) return AutodiffFosReverseIndexEnum;
-	      else if (strcmp(name,"AutodiffKeep")==0) return AutodiffKeepEnum;
-	      else if (strcmp(name,"AutodiffObufsize")==0) return AutodiffObufsizeEnum;
-	      else if (strcmp(name,"AutodiffLbufsize")==0) return AutodiffLbufsizeEnum;
-	      else if (strcmp(name,"AutodiffCbufsize")==0) return AutodiffCbufsizeEnum;
-	      else if (strcmp(name,"AutodiffTbufsize")==0) return AutodiffTbufsizeEnum;
-	      else if (strcmp(name,"AutodiffGcTriggerRatio")==0) return AutodiffGcTriggerRatioEnum;
-	      else if (strcmp(name,"AutodiffGcTriggerMaxSize")==0) return AutodiffGcTriggerMaxSizeEnum;
-	      else if (strcmp(name,"BalancethicknessStabilization")==0) return BalancethicknessStabilizationEnum;
-	      else if (strcmp(name,"BalancethicknessThickeningRate")==0) return BalancethicknessThickeningRateEnum;
-	      else if (strcmp(name,"Basalforcings")==0) return BasalforcingsEnum;
-	      else if (strcmp(name,"BasalforcingsGeothermalflux")==0) return BasalforcingsGeothermalfluxEnum;
-	      else if (strcmp(name,"BasalforcingsGroundediceMeltingRate")==0) return BasalforcingsGroundediceMeltingRateEnum;
-	      else if (strcmp(name,"BasalforcingsFloatingiceMeltingRate")==0) return BasalforcingsFloatingiceMeltingRateEnum;
-	      else if (strcmp(name,"BasalforcingsDeepwaterMeltingRate")==0) return BasalforcingsDeepwaterMeltingRateEnum;
-	      else if (strcmp(name,"BasalforcingsDeepwaterElevation")==0) return BasalforcingsDeepwaterElevationEnum;
-	      else if (strcmp(name,"BasalforcingsUpperwaterElevation")==0) return BasalforcingsUpperwaterElevationEnum;
-	      else if (strcmp(name,"BasalforcingsMeltrateFactor")==0) return BasalforcingsMeltrateFactorEnum;
-	      else if (strcmp(name,"BasalforcingsThresholdThickness")==0) return BasalforcingsThresholdThicknessEnum;
-	      else if (strcmp(name,"BasalforcingsUpperdepthMelt")==0) return BasalforcingsUpperdepthMeltEnum;
-	      else if (strcmp(name,"BasalforcingsMantleconductivity")==0) return BasalforcingsMantleconductivityEnum;
-	      else if (strcmp(name,"BasalforcingsNusselt")==0) return BasalforcingsNusseltEnum;
-	      else if (strcmp(name,"BasalforcingsDtbg")==0) return BasalforcingsDtbgEnum;
-	      else if (strcmp(name,"BasalforcingsPlumeradius")==0) return BasalforcingsPlumeradiusEnum;
-	      else if (strcmp(name,"BasalforcingsTopplumedepth")==0) return BasalforcingsTopplumedepthEnum;
-	      else if (strcmp(name,"BasalforcingsBottomplumedepth")==0) return BasalforcingsBottomplumedepthEnum;
-	      else if (strcmp(name,"BasalforcingsPlumex")==0) return BasalforcingsPlumexEnum;
-	      else if (strcmp(name,"BasalforcingsPlumey")==0) return BasalforcingsPlumeyEnum;
-	      else if (strcmp(name,"BasalforcingsCrustthickness")==0) return BasalforcingsCrustthicknessEnum;
-	      else if (strcmp(name,"BasalforcingsUppercrustthickness")==0) return BasalforcingsUppercrustthicknessEnum;
-	      else if (strcmp(name,"BasalforcingsUppercrustheat")==0) return BasalforcingsUppercrustheatEnum;
-	      else if (strcmp(name,"BasalforcingsLowercrustheat")==0) return BasalforcingsLowercrustheatEnum;
-	      else if (strcmp(name,"FloatingMeltRate")==0) return FloatingMeltRateEnum;
-	      else if (strcmp(name,"LinearFloatingMeltRate")==0) return LinearFloatingMeltRateEnum;
-	      else if (strcmp(name,"MismipFloatingMeltRate")==0) return MismipFloatingMeltRateEnum;
-	      else if (strcmp(name,"MantlePlumeGeothermalFlux")==0) return MantlePlumeGeothermalFluxEnum;
-	      else if (strcmp(name,"Bed")==0) return BedEnum;
-	      else if (strcmp(name,"Base")==0) return BaseEnum;
-	      else if (strcmp(name,"ConstantsG")==0) return ConstantsGEnum;
-	      else if (strcmp(name,"ConstantsReferencetemperature")==0) return ConstantsReferencetemperatureEnum;
-	      else if (strcmp(name,"ConstantsYts")==0) return ConstantsYtsEnum;
-	      else if (strcmp(name,"DependentObject")==0) return DependentObjectEnum;
+	      else if (strcmp(name,"SolutionType")==0) return SolutionTypeEnum;
+	      else if (strcmp(name,"SteadystateMaxiter")==0) return SteadystateMaxiterEnum;
+	      else if (strcmp(name,"SteadystateNumRequestedOutputs")==0) return SteadystateNumRequestedOutputsEnum;
+	      else if (strcmp(name,"SteadystateReltol")==0) return SteadystateReltolEnum;
+	      else if (strcmp(name,"SteadystateRequestedOutputs")==0) return SteadystateRequestedOutputsEnum;
+	      else if (strcmp(name,"Step")==0) return StepEnum;
 	      else if (strcmp(name,"StressbalanceAbstol")==0) return StressbalanceAbstolEnum;
-	      else if (strcmp(name,"StressbalanceConvergenceNumSteps")==0) return StressbalanceConvergenceNumStepsEnum;
+	      else if (strcmp(name,"StressbalanceFSreconditioning")==0) return StressbalanceFSreconditioningEnum;
 	      else if (strcmp(name,"StressbalanceIsnewton")==0) return StressbalanceIsnewtonEnum;
 	      else if (strcmp(name,"StressbalanceMaxiter")==0) return StressbalanceMaxiterEnum;
+	      else if (strcmp(name,"StressbalanceNumRequestedOutputs")==0) return StressbalanceNumRequestedOutputsEnum;
 	      else if (strcmp(name,"StressbalancePenaltyFactor")==0) return StressbalancePenaltyFactorEnum;
 	      else if (strcmp(name,"StressbalanceReltol")==0) return StressbalanceReltolEnum;
-	      else if (strcmp(name,"StressbalanceNumRequestedOutputs")==0) return StressbalanceNumRequestedOutputsEnum;
 	      else if (strcmp(name,"StressbalanceRequestedOutputs")==0) return StressbalanceRequestedOutputsEnum;
 	      else if (strcmp(name,"StressbalanceRestol")==0) return StressbalanceRestolEnum;
 	      else if (strcmp(name,"StressbalanceRiftPenaltyThreshold")==0) return StressbalanceRiftPenaltyThresholdEnum;
 	      else if (strcmp(name,"StressbalanceShelfDampening")==0) return StressbalanceShelfDampeningEnum;
-	      else if (strcmp(name,"StressbalanceFSreconditioning")==0) return StressbalanceFSreconditioningEnum;
-	      else if (strcmp(name,"StressbalanceViscosityOvershoot")==0) return StressbalanceViscosityOvershootEnum;
+	      else if (strcmp(name,"ThermalIsdynamicbasalspc")==0) return ThermalIsdynamicbasalspcEnum;
+	      else if (strcmp(name,"ThermalIsenthalpy")==0) return ThermalIsenthalpyEnum;
+	      else if (strcmp(name,"ThermalMaxiter")==0) return ThermalMaxiterEnum;
+	      else if (strcmp(name,"ThermalNumRequestedOutputs")==0) return ThermalNumRequestedOutputsEnum;
+	      else if (strcmp(name,"ThermalPenaltyFactor")==0) return ThermalPenaltyFactorEnum;
+	      else if (strcmp(name,"ThermalPenaltyLock")==0) return ThermalPenaltyLockEnum;
+	      else if (strcmp(name,"ThermalPenaltyThreshold")==0) return ThermalPenaltyThresholdEnum;
+	      else if (strcmp(name,"ThermalReltol")==0) return ThermalReltolEnum;
+	      else if (strcmp(name,"ThermalRequestedOutputs")==0) return ThermalRequestedOutputsEnum;
+	      else if (strcmp(name,"ThermalStabilization")==0) return ThermalStabilizationEnum;
+	      else if (strcmp(name,"Time")==0) return TimeEnum;
+	      else if (strcmp(name,"TimesteppingCflCoefficient")==0) return TimesteppingCflCoefficientEnum;
+	      else if (strcmp(name,"TimesteppingCouplingTime")==0) return TimesteppingCouplingTimeEnum;
+	      else if (strcmp(name,"TimesteppingFinalTime")==0) return TimesteppingFinalTimeEnum;
+	      else if (strcmp(name,"TimesteppingInterpForcings")==0) return TimesteppingInterpForcingsEnum;
+	      else if (strcmp(name,"TimesteppingStartTime")==0) return TimesteppingStartTimeEnum;
+	      else if (strcmp(name,"TimesteppingTimeStep")==0) return TimesteppingTimeStepEnum;
+	      else if (strcmp(name,"TimesteppingTimeStepMax")==0) return TimesteppingTimeStepMaxEnum;
+	      else if (strcmp(name,"TimesteppingTimeStepMin")==0) return TimesteppingTimeStepMinEnum;
+	      else if (strcmp(name,"TimesteppingType")==0) return TimesteppingTypeEnum;
+	      else if (strcmp(name,"ToMITgcmComm")==0) return ToMITgcmCommEnum;
+	      else if (strcmp(name,"ToolkitsFileName")==0) return ToolkitsFileNameEnum;
+	      else if (strcmp(name,"ToolkitsOptionsAnalyses")==0) return ToolkitsOptionsAnalysesEnum;
+	      else if (strcmp(name,"ToolkitsOptionsStrings")==0) return ToolkitsOptionsStringsEnum;
+	      else if (strcmp(name,"ToolkitsTypes")==0) return ToolkitsTypesEnum;
+	      else if (strcmp(name,"TransientAmrFrequency")==0) return TransientAmrFrequencyEnum;
+	      else if (strcmp(name,"TransientIscoupler")==0) return TransientIscouplerEnum;
+	      else if (strcmp(name,"TransientIsdamageevolution")==0) return TransientIsdamageevolutionEnum;
+	      else if (strcmp(name,"TransientIsesa")==0) return TransientIsesaEnum;
+	      else if (strcmp(name,"TransientIsgia")==0) return TransientIsgiaEnum;
+	      else if (strcmp(name,"TransientIsgroundingline")==0) return TransientIsgroundinglineEnum;
+	      else if (strcmp(name,"TransientIshydrology")==0) return TransientIshydrologyEnum;
+	      else if (strcmp(name,"TransientIsmasstransport")==0) return TransientIsmasstransportEnum;
+	      else if (strcmp(name,"TransientIsmovingfront")==0) return TransientIsmovingfrontEnum;
+	      else if (strcmp(name,"TransientIsoceancoupling")==0) return TransientIsoceancouplingEnum;
+	      else if (strcmp(name,"TransientIsslr")==0) return TransientIsslrEnum;
+	      else if (strcmp(name,"TransientIssmb")==0) return TransientIssmbEnum;
+	      else if (strcmp(name,"TransientIsstressbalance")==0) return TransientIsstressbalanceEnum;
+	      else if (strcmp(name,"TransientIsthermal")==0) return TransientIsthermalEnum;
+	      else if (strcmp(name,"TransientNumRequestedOutputs")==0) return TransientNumRequestedOutputsEnum;
+	      else if (strcmp(name,"TransientRequestedOutputs")==0) return TransientRequestedOutputsEnum;
+	      else if (strcmp(name,"Velocity")==0) return VelocityEnum;
+	      else if (strcmp(name,"WorldComm")==0) return WorldCommEnum;
+	      else if (strcmp(name,"ParametersEND")==0) return ParametersENDEnum;
+	      else if (strcmp(name,"InputsSTART")==0) return InputsSTARTEnum;
+	      else if (strcmp(name,"Adjoint")==0) return AdjointEnum;
+	      else if (strcmp(name,"Adjointx")==0) return AdjointxEnum;
+	      else if (strcmp(name,"Adjointy")==0) return AdjointyEnum;
+	      else if (strcmp(name,"Adjointz")==0) return AdjointzEnum;
+	      else if (strcmp(name,"Air")==0) return AirEnum;
+	      else if (strcmp(name,"Approximation")==0) return ApproximationEnum;
+	      else if (strcmp(name,"BalancethicknessMisfit")==0) return BalancethicknessMisfitEnum;
+	      else if (strcmp(name,"BalancethicknessOmega0")==0) return BalancethicknessOmega0Enum;
+	      else if (strcmp(name,"BalancethicknessOmega")==0) return BalancethicknessOmegaEnum;
+	      else if (strcmp(name,"BalancethicknessThickeningRate")==0) return BalancethicknessThickeningRateEnum;
+	      else if (strcmp(name,"BasalforcingsFloatingiceMeltingRate")==0) return BasalforcingsFloatingiceMeltingRateEnum;
+	      else if (strcmp(name,"BasalforcingsGeothermalflux")==0) return BasalforcingsGeothermalfluxEnum;
+	      else if (strcmp(name,"BasalforcingsGroundediceMeltingRate")==0) return BasalforcingsGroundediceMeltingRateEnum;
+	      else if (strcmp(name,"BasalforcingsPicoBasinId")==0) return BasalforcingsPicoBasinIdEnum;
+	      else if (strcmp(name,"BasalforcingsPicoBoxId")==0) return BasalforcingsPicoBoxIdEnum;
+	      else if (strcmp(name,"BasalforcingsPicoSubShelfOceanOverturning")==0) return BasalforcingsPicoSubShelfOceanOverturningEnum;
+         else stage=4;
+   }
+   if(stage==4){
+	      if (strcmp(name,"BasalforcingsPicoSubShelfOceanSalinity")==0) return BasalforcingsPicoSubShelfOceanSalinityEnum;
+	      else if (strcmp(name,"BasalforcingsPicoSubShelfOceanTemp")==0) return BasalforcingsPicoSubShelfOceanTempEnum;
+	      else if (strcmp(name,"Base")==0) return BaseEnum;
+	      else if (strcmp(name,"Bed")==0) return BedEnum;
+	      else if (strcmp(name,"BedSlopeX")==0) return BedSlopeXEnum;
+	      else if (strcmp(name,"BedSlopeY")==0) return BedSlopeYEnum;
+	      else if (strcmp(name,"CalvingCalvingrate")==0) return CalvingCalvingrateEnum;
+	      else if (strcmp(name,"CalvingHabFraction")==0) return CalvingHabFractionEnum;
+	      else if (strcmp(name,"CalvinglevermannCoeff")==0) return CalvinglevermannCoeffEnum;
+	      else if (strcmp(name,"CalvinglevermannMeltingrate")==0) return CalvinglevermannMeltingrateEnum;
+	      else if (strcmp(name,"CalvingMeltingrate")==0) return CalvingMeltingrateEnum;
+	      else if (strcmp(name,"CalvingratexAverage")==0) return CalvingratexAverageEnum;
+	      else if (strcmp(name,"Calvingratex")==0) return CalvingratexEnum;
+	      else if (strcmp(name,"CalvingrateyAverage")==0) return CalvingrateyAverageEnum;
+	      else if (strcmp(name,"Calvingratey")==0) return CalvingrateyEnum;
+	      else if (strcmp(name,"CalvingStressThresholdFloatingice")==0) return CalvingStressThresholdFloatingiceEnum;
+	      else if (strcmp(name,"CalvingStressThresholdGroundedice")==0) return CalvingStressThresholdGroundediceEnum;
+	      else if (strcmp(name,"Converged")==0) return ConvergedEnum;
+	      else if (strcmp(name,"CrevasseDepth")==0) return CrevasseDepthEnum;
+	      else if (strcmp(name,"DamageDbar")==0) return DamageDbarEnum;
+	      else if (strcmp(name,"DamageD")==0) return DamageDEnum;
+	      else if (strcmp(name,"DamageF")==0) return DamageFEnum;
+	      else if (strcmp(name,"DeviatoricStressxx")==0) return DeviatoricStressxxEnum;
+	      else if (strcmp(name,"DeviatoricStressxy")==0) return DeviatoricStressxyEnum;
+	      else if (strcmp(name,"DeviatoricStressxz")==0) return DeviatoricStressxzEnum;
+	      else if (strcmp(name,"DeviatoricStressyy")==0) return DeviatoricStressyyEnum;
+	      else if (strcmp(name,"DeviatoricStressyz")==0) return DeviatoricStressyzEnum;
+	      else if (strcmp(name,"DeviatoricStresszz")==0) return DeviatoricStresszzEnum;
+	      else if (strcmp(name,"DistanceToCalvingfront")==0) return DistanceToCalvingfrontEnum;
+	      else if (strcmp(name,"DistanceToGroundingline")==0) return DistanceToGroundinglineEnum;
+	      else if (strcmp(name,"Domain2Dhorizontal")==0) return Domain2DhorizontalEnum;
+	      else if (strcmp(name,"Domain2Dvertical")==0) return Domain2DverticalEnum;
+	      else if (strcmp(name,"Domain3D")==0) return Domain3DEnum;
+	      else if (strcmp(name,"DragCoefficientAbsGradient")==0) return DragCoefficientAbsGradientEnum;
+	      else if (strcmp(name,"DrivingStressX")==0) return DrivingStressXEnum;
+	      else if (strcmp(name,"DrivingStressY")==0) return DrivingStressYEnum;
+	      else if (strcmp(name,"EffectivePressure")==0) return EffectivePressureEnum;
+	      else if (strcmp(name,"Enthalpy")==0) return EnthalpyEnum;
+	      else if (strcmp(name,"EnthalpyPicard")==0) return EnthalpyPicardEnum;
+	      else if (strcmp(name,"EplHead")==0) return EplHeadEnum;
+	      else if (strcmp(name,"EplHeadOld")==0) return EplHeadOldEnum;
+	      else if (strcmp(name,"EplHeadSlopeX")==0) return EplHeadSlopeXEnum;
+	      else if (strcmp(name,"EplHeadSlopeY")==0) return EplHeadSlopeYEnum;
+	      else if (strcmp(name,"EsaDeltathickness")==0) return EsaDeltathicknessEnum;
+	      else if (strcmp(name,"EsaXmotion")==0) return EsaXmotionEnum;
+	      else if (strcmp(name,"EsaYmotion")==0) return EsaYmotionEnum;
+	      else if (strcmp(name,"EtaDiff")==0) return EtaDiffEnum;
+	      else if (strcmp(name,"FrictionAs")==0) return FrictionAsEnum;
+	      else if (strcmp(name,"FrictionC")==0) return FrictionCEnum;
+	      else if (strcmp(name,"FrictionCoefficientcoulomb")==0) return FrictionCoefficientcoulombEnum;
+	      else if (strcmp(name,"FrictionCoefficient")==0) return FrictionCoefficientEnum;
+	      else if (strcmp(name,"FrictionEffectivePressure")==0) return FrictionEffectivePressureEnum;
+	      else if (strcmp(name,"FrictionM")==0) return FrictionMEnum;
+	      else if (strcmp(name,"FrictionP")==0) return FrictionPEnum;
+	      else if (strcmp(name,"FrictionPressureAdjustedTemperature")==0) return FrictionPressureAdjustedTemperatureEnum;
+	      else if (strcmp(name,"FrictionQ")==0) return FrictionQEnum;
+	      else if (strcmp(name,"FrictionWaterLayer")==0) return FrictionWaterLayerEnum;
+	      else if (strcmp(name,"GeometryHydrostaticRatio")==0) return GeometryHydrostaticRatioEnum;
+	      else if (strcmp(name,"GiaLithosphereThickness")==0) return GiaLithosphereThicknessEnum;
+	      else if (strcmp(name,"GiaMantleViscosity")==0) return GiaMantleViscosityEnum;
+	      else if (strcmp(name,"Gradient")==0) return GradientEnum;
+	      else if (strcmp(name,"HydrologyBumpHeight")==0) return HydrologyBumpHeightEnum;
+	      else if (strcmp(name,"HydrologyBumpSpacing")==0) return HydrologyBumpSpacingEnum;
+	      else if (strcmp(name,"HydrologydcBasalMoulinInput")==0) return HydrologydcBasalMoulinInputEnum;
+	      else if (strcmp(name,"HydrologydcEplThickness")==0) return HydrologydcEplThicknessEnum;
+	      else if (strcmp(name,"HydrologydcEplThicknessOld")==0) return HydrologydcEplThicknessOldEnum;
+	      else if (strcmp(name,"HydrologydcMaskEplactiveElt")==0) return HydrologydcMaskEplactiveEltEnum;
+	      else if (strcmp(name,"HydrologydcMaskEplactiveNode")==0) return HydrologydcMaskEplactiveNodeEnum;
+	      else if (strcmp(name,"HydrologydcSedimentTransmitivity")==0) return HydrologydcSedimentTransmitivityEnum;
+	      else if (strcmp(name,"HydrologyEnglacialInput")==0) return HydrologyEnglacialInputEnum;
+	      else if (strcmp(name,"HydrologyGapHeight")==0) return HydrologyGapHeightEnum;
+	      else if (strcmp(name,"HydrologyHead")==0) return HydrologyHeadEnum;
+	      else if (strcmp(name,"HydrologyHeadOld")==0) return HydrologyHeadOldEnum;
+	      else if (strcmp(name,"HydrologyMoulinInput")==0) return HydrologyMoulinInputEnum;
+	      else if (strcmp(name,"HydrologyNeumannflux")==0) return HydrologyNeumannfluxEnum;
+	      else if (strcmp(name,"HydrologyReynolds")==0) return HydrologyReynoldsEnum;
+	      else if (strcmp(name,"HydrologyWaterVx")==0) return HydrologyWaterVxEnum;
+	      else if (strcmp(name,"HydrologyWaterVy")==0) return HydrologyWaterVyEnum;
+	      else if (strcmp(name,"Ice")==0) return IceEnum;
+	      else if (strcmp(name,"IceMaskNodeActivation")==0) return IceMaskNodeActivationEnum;
+	      else if (strcmp(name,"Input")==0) return InputEnum;
+	      else if (strcmp(name,"InversionCostFunctionsCoefficients")==0) return InversionCostFunctionsCoefficientsEnum;
+	      else if (strcmp(name,"InversionSurfaceObs")==0) return InversionSurfaceObsEnum;
+	      else if (strcmp(name,"InversionThicknessObs")==0) return InversionThicknessObsEnum;
+	      else if (strcmp(name,"InversionVelObs")==0) return InversionVelObsEnum;
+	      else if (strcmp(name,"InversionVxObs")==0) return InversionVxObsEnum;
+	      else if (strcmp(name,"InversionVyObs")==0) return InversionVyObsEnum;
+	      else if (strcmp(name,"LevelsetfunctionSlopeX")==0) return LevelsetfunctionSlopeXEnum;
+	      else if (strcmp(name,"LevelsetfunctionSlopeY")==0) return LevelsetfunctionSlopeYEnum;
 	      else if (strcmp(name,"LoadingforceX")==0) return LoadingforceXEnum;
 	      else if (strcmp(name,"LoadingforceY")==0) return LoadingforceYEnum;
 	      else if (strcmp(name,"LoadingforceZ")==0) return LoadingforceZEnum;
-	      else if (strcmp(name,"FlowequationIsSIA")==0) return FlowequationIsSIAEnum;
-	      else if (strcmp(name,"FlowequationIsSSA")==0) return FlowequationIsSSAEnum;
-	      else if (strcmp(name,"FlowequationIsL1L2")==0) return FlowequationIsL1L2Enum;
-	      else if (strcmp(name,"FlowequationIsHO")==0) return FlowequationIsHOEnum;
-	      else if (strcmp(name,"FlowequationIsFS")==0) return FlowequationIsFSEnum;
-	      else if (strcmp(name,"FlowequationFeFS")==0) return FlowequationFeFSEnum;
-	      else if (strcmp(name,"FlowequationBorderFS")==0) return FlowequationBorderFSEnum;
-	      else if (strcmp(name,"FrictionAs")==0) return FrictionAsEnum;
-	      else if (strcmp(name,"FrictionCoefficient")==0) return FrictionCoefficientEnum;
-	      else if (strcmp(name,"FrictionCoefficientcoulomb")==0) return FrictionCoefficientcoulombEnum;
-	      else if (strcmp(name,"FrictionPressureAdjustedTemperature")==0) return FrictionPressureAdjustedTemperatureEnum;
-	      else if (strcmp(name,"FrictionP")==0) return FrictionPEnum;
-	      else if (strcmp(name,"FrictionQ")==0) return FrictionQEnum;
-	      else if (strcmp(name,"FrictionM")==0) return FrictionMEnum;
-	      else if (strcmp(name,"FrictionC")==0) return FrictionCEnum;
-	      else if (strcmp(name,"FrictionLaw")==0) return FrictionLawEnum;
-	      else if (strcmp(name,"FrictionGamma")==0) return FrictionGammaEnum;
-	      else if (strcmp(name,"FrictionF")==0) return FrictionFEnum;
-	      else if (strcmp(name,"FrictionWaterLayer")==0) return FrictionWaterLayerEnum;
-	      else if (strcmp(name,"FrictionEffectivePressure")==0) return FrictionEffectivePressureEnum;
-	      else if (strcmp(name,"FrictionCoupling")==0) return FrictionCouplingEnum;
-	      else if (strcmp(name,"GeometryHydrostaticRatio")==0) return GeometryHydrostaticRatioEnum;
-	      else if (strcmp(name,"HydrologyModel")==0) return HydrologyModelEnum;
-	      else if (strcmp(name,"Hydrologyshreve")==0) return HydrologyshreveEnum;
-	      else if (strcmp(name,"HydrologyshreveStabilization")==0) return HydrologyshreveStabilizationEnum;
-	      else if (strcmp(name,"Hydrologydc")==0) return HydrologydcEnum;
+	      else if (strcmp(name,"MaskGroundediceLevelset")==0) return MaskGroundediceLevelsetEnum;
+	      else if (strcmp(name,"MaskIceLevelset")==0) return MaskIceLevelsetEnum;
+	      else if (strcmp(name,"MasstransportSpcthickness")==0) return MasstransportSpcthicknessEnum;
+	      else if (strcmp(name,"MaterialsRheologyBbar")==0) return MaterialsRheologyBbarEnum;
+	      else if (strcmp(name,"MaterialsRheologyB")==0) return MaterialsRheologyBEnum;
+	      else if (strcmp(name,"MaterialsRheologyEbar")==0) return MaterialsRheologyEbarEnum;
+	      else if (strcmp(name,"MaterialsRheologyEcbar")==0) return MaterialsRheologyEcbarEnum;
+	      else if (strcmp(name,"MaterialsRheologyEc")==0) return MaterialsRheologyEcEnum;
+	      else if (strcmp(name,"MaterialsRheologyE")==0) return MaterialsRheologyEEnum;
+	      else if (strcmp(name,"MaterialsRheologyEsbar")==0) return MaterialsRheologyEsbarEnum;
+	      else if (strcmp(name,"MaterialsRheologyEs")==0) return MaterialsRheologyEsEnum;
+	      else if (strcmp(name,"MaterialsRheologyN")==0) return MaterialsRheologyNEnum;
+	      else if (strcmp(name,"MeshScaleFactor")==0) return MeshScaleFactorEnum;
+	      else if (strcmp(name,"MeshVertexonbase")==0) return MeshVertexonbaseEnum;
+	      else if (strcmp(name,"MeshVertexonboundary")==0) return MeshVertexonboundaryEnum;
+	      else if (strcmp(name,"MeshVertexonsurface")==0) return MeshVertexonsurfaceEnum;
+	      else if (strcmp(name,"Misfit")==0) return MisfitEnum;
+	      else if (strcmp(name,"Neumannflux")==0) return NeumannfluxEnum;
+	      else if (strcmp(name,"Node")==0) return NodeEnum;
+	      else if (strcmp(name,"OmegaAbsGradient")==0) return OmegaAbsGradientEnum;
+	      else if (strcmp(name,"P0")==0) return P0Enum;
+	      else if (strcmp(name,"P1")==0) return P1Enum;
+	      else if (strcmp(name,"Pressure")==0) return PressureEnum;
+	      else if (strcmp(name,"RheologyBAbsGradient")==0) return RheologyBAbsGradientEnum;
+	      else if (strcmp(name,"RheologyBbarAbsGradient")==0) return RheologyBbarAbsGradientEnum;
+	      else if (strcmp(name,"Sealevel")==0) return SealevelEnum;
+	      else if (strcmp(name,"SealevelriseDeltathickness")==0) return SealevelriseDeltathicknessEnum;
 	      else if (strcmp(name,"SedimentHead")==0) return SedimentHeadEnum;
-	      else if (strcmp(name,"SedimentHeadOld")==0) return SedimentHeadOldEnum;
-	      else if (strcmp(name,"SedimentHeadResidual")==0) return SedimentHeadResidualEnum;
-	      else if (strcmp(name,"EffectivePressure")==0) return EffectivePressureEnum;
-	      else if (strcmp(name,"EplHead")==0) return EplHeadEnum;
-	      else if (strcmp(name,"EplHeadOld")==0) return EplHeadOldEnum;
-         else stage=2;
-   }
-   if(stage==2){
-	      if (strcmp(name,"EplHeadSlopeX")==0) return EplHeadSlopeXEnum;
-	      else if (strcmp(name,"EplHeadSlopeY")==0) return EplHeadSlopeYEnum;
-	      else if (strcmp(name,"EplZigZagCounter")==0) return EplZigZagCounterEnum;
-	      else if (strcmp(name,"HydrologydcMaxIter")==0) return HydrologydcMaxIterEnum;
-	      else if (strcmp(name,"HydrologydcRelTol")==0) return HydrologydcRelTolEnum;
-	      else if (strcmp(name,"HydrologydcSedimentCompressibility")==0) return HydrologydcSedimentCompressibilityEnum;
-	      else if (strcmp(name,"HydrologydcSedimentPorosity")==0) return HydrologydcSedimentPorosityEnum;
-	      else if (strcmp(name,"HydrologydcSedimentThickness")==0) return HydrologydcSedimentThicknessEnum;
-	      else if (strcmp(name,"HydrologydcSedimentTransmitivity")==0) return HydrologydcSedimentTransmitivityEnum;
-	      else if (strcmp(name,"HydrologydcWaterCompressibility")==0) return HydrologydcWaterCompressibilityEnum;
-	      else if (strcmp(name,"HydrologydcMaskEplactiveNode")==0) return HydrologydcMaskEplactiveNodeEnum;
-	      else if (strcmp(name,"HydrologydcMaskEplactiveElt")==0) return HydrologydcMaskEplactiveEltEnum;
-	      else if (strcmp(name,"HydrologydcEplCompressibility")==0) return HydrologydcEplCompressibilityEnum;
-	      else if (strcmp(name,"HydrologydcEplPorosity")==0) return HydrologydcEplPorosityEnum;
-	      else if (strcmp(name,"HydrologydcEplInitialThickness")==0) return HydrologydcEplInitialThicknessEnum;
-	      else if (strcmp(name,"HydrologydcEplColapseThickness")==0) return HydrologydcEplColapseThicknessEnum;
-	      else if (strcmp(name,"HydrologydcEplMaxThickness")==0) return HydrologydcEplMaxThicknessEnum;
-	      else if (strcmp(name,"HydrologydcEplThickness")==0) return HydrologydcEplThicknessEnum;
-	      else if (strcmp(name,"HydrologydcEplThicknessOld")==0) return HydrologydcEplThicknessOldEnum;
-	      else if (strcmp(name,"HydrologydcEplThickComp")==0) return HydrologydcEplThickCompEnum;
-	      else if (strcmp(name,"HydrologydcEplConductivity")==0) return HydrologydcEplConductivityEnum;
-	      else if (strcmp(name,"HydrologydcIsefficientlayer")==0) return HydrologydcIsefficientlayerEnum;
-	      else if (strcmp(name,"HydrologydcSedimentlimitFlag")==0) return HydrologydcSedimentlimitFlagEnum;
-	      else if (strcmp(name,"HydrologydcSedimentlimit")==0) return HydrologydcSedimentlimitEnum;
-	      else if (strcmp(name,"HydrologydcTransferFlag")==0) return HydrologydcTransferFlagEnum;
-	      else if (strcmp(name,"HydrologydcLeakageFactor")==0) return HydrologydcLeakageFactorEnum;
-	      else if (strcmp(name,"HydrologydcPenaltyFactor")==0) return HydrologydcPenaltyFactorEnum;
-	      else if (strcmp(name,"HydrologydcPenaltyLock")==0) return HydrologydcPenaltyLockEnum;
-	      else if (strcmp(name,"HydrologydcEplflipLock")==0) return HydrologydcEplflipLockEnum;
-	      else if (strcmp(name,"HydrologydcBasalMoulinInput")==0) return HydrologydcBasalMoulinInputEnum;
-	      else if (strcmp(name,"HydrologyLayer")==0) return HydrologyLayerEnum;
-	      else if (strcmp(name,"HydrologySediment")==0) return HydrologySedimentEnum;
-	      else if (strcmp(name,"HydrologyEfficient")==0) return HydrologyEfficientEnum;
-	      else if (strcmp(name,"HydrologySedimentKmax")==0) return HydrologySedimentKmaxEnum;
-	      else if (strcmp(name,"Hydrologysommers")==0) return HydrologysommersEnum;
-	      else if (strcmp(name,"HydrologyHead")==0) return HydrologyHeadEnum;
-	      else if (strcmp(name,"HydrologyHeadOld")==0) return HydrologyHeadOldEnum;
-	      else if (strcmp(name,"HydrologyGapHeight")==0) return HydrologyGapHeightEnum;
-	      else if (strcmp(name,"HydrologyBumpSpacing")==0) return HydrologyBumpSpacingEnum;
-	      else if (strcmp(name,"HydrologyBumpHeight")==0) return HydrologyBumpHeightEnum;
-	      else if (strcmp(name,"HydrologyEnglacialInput")==0) return HydrologyEnglacialInputEnum;
-	      else if (strcmp(name,"HydrologyMoulinInput")==0) return HydrologyMoulinInputEnum;
-	      else if (strcmp(name,"HydrologyReynolds")==0) return HydrologyReynoldsEnum;
-	      else if (strcmp(name,"HydrologyNeumannflux")==0) return HydrologyNeumannfluxEnum;
-	      else if (strcmp(name,"HydrologyRelaxation")==0) return HydrologyRelaxationEnum;
-	      else if (strcmp(name,"HydrologyBasalFlux")==0) return HydrologyBasalFluxEnum;
-	      else if (strcmp(name,"HydrologyStorage")==0) return HydrologyStorageEnum;
-	      else if (strcmp(name,"InversionControlParameters")==0) return InversionControlParametersEnum;
-	      else if (strcmp(name,"InversionControlScalingFactors")==0) return InversionControlScalingFactorsEnum;
-	      else if (strcmp(name,"InversionCostFunctionThreshold")==0) return InversionCostFunctionThresholdEnum;
-	      else if (strcmp(name,"InversionCostFunctionsCoefficients")==0) return InversionCostFunctionsCoefficientsEnum;
-	      else if (strcmp(name,"InversionCostFunctions")==0) return InversionCostFunctionsEnum;
-	      else if (strcmp(name,"InversionGradientScaling")==0) return InversionGradientScalingEnum;
-	      else if (strcmp(name,"InversionIscontrol")==0) return InversionIscontrolEnum;
-	      else if (strcmp(name,"InversionType")==0) return InversionTypeEnum;
-	      else if (strcmp(name,"InversionIncompleteAdjoint")==0) return InversionIncompleteAdjointEnum;
-	      else if (strcmp(name,"InversionMaxiterPerStep")==0) return InversionMaxiterPerStepEnum;
-	      else if (strcmp(name,"InversionMaxiter")==0) return InversionMaxiterEnum;
-	      else if (strcmp(name,"InversionMaxsteps")==0) return InversionMaxstepsEnum;
-	      else if (strcmp(name,"InversionFatol")==0) return InversionFatolEnum;
-	      else if (strcmp(name,"InversionFrtol")==0) return InversionFrtolEnum;
-	      else if (strcmp(name,"InversionGatol")==0) return InversionGatolEnum;
-	      else if (strcmp(name,"InversionGrtol")==0) return InversionGrtolEnum;
-	      else if (strcmp(name,"InversionGttol")==0) return InversionGttolEnum;
-	      else if (strcmp(name,"InversionAlgorithm")==0) return InversionAlgorithmEnum;
-	      else if (strcmp(name,"InversionNsteps")==0) return InversionNstepsEnum;
-	      else if (strcmp(name,"InversionDxmin")==0) return InversionDxminEnum;
-	      else if (strcmp(name,"InversionNumControlParameters")==0) return InversionNumControlParametersEnum;
-	      else if (strcmp(name,"InversionNumCostFunctions")==0) return InversionNumCostFunctionsEnum;
-	      else if (strcmp(name,"InversionStepThreshold")==0) return InversionStepThresholdEnum;
-	      else if (strcmp(name,"InversionThicknessObs")==0) return InversionThicknessObsEnum;
-	      else if (strcmp(name,"InversionSurfaceObs")==0) return InversionSurfaceObsEnum;
-	      else if (strcmp(name,"InversionVxObs")==0) return InversionVxObsEnum;
-	      else if (strcmp(name,"InversionVyObs")==0) return InversionVyObsEnum;
-	      else if (strcmp(name,"InversionVzObs")==0) return InversionVzObsEnum;
-	      else if (strcmp(name,"MaskIceLevelset")==0) return MaskIceLevelsetEnum;
-	      else if (strcmp(name,"MaskOceanLevelset")==0) return MaskOceanLevelsetEnum;
-	      else if (strcmp(name,"MaskLandLevelset")==0) return MaskLandLevelsetEnum;
-	      else if (strcmp(name,"MaterialsBeta")==0) return MaterialsBetaEnum;
-	      else if (strcmp(name,"MaterialsHeatcapacity")==0) return MaterialsHeatcapacityEnum;
-	      else if (strcmp(name,"MaterialsLatentheat")==0) return MaterialsLatentheatEnum;
-	      else if (strcmp(name,"MaterialsMeltingpoint")==0) return MaterialsMeltingpointEnum;
-	      else if (strcmp(name,"MaterialsMixedLayerCapacity")==0) return MaterialsMixedLayerCapacityEnum;
-	      else if (strcmp(name,"MaterialsRheologyB")==0) return MaterialsRheologyBEnum;
-	      else if (strcmp(name,"MaterialsRheologyBbar")==0) return MaterialsRheologyBbarEnum;
-	      else if (strcmp(name,"MaterialsRheologyLaw")==0) return MaterialsRheologyLawEnum;
-	      else if (strcmp(name,"MaterialsRheologyN")==0) return MaterialsRheologyNEnum;
-	      else if (strcmp(name,"MaterialsRheologyE")==0) return MaterialsRheologyEEnum;
-	      else if (strcmp(name,"MaterialsRheologyEbar")==0) return MaterialsRheologyEbarEnum;
-	      else if (strcmp(name,"MaterialsRheologyEc")==0) return MaterialsRheologyEcEnum;
-	      else if (strcmp(name,"MaterialsRheologyEcbar")==0) return MaterialsRheologyEcbarEnum;
-	      else if (strcmp(name,"MaterialsRheologyEs")==0) return MaterialsRheologyEsEnum;
-	      else if (strcmp(name,"MaterialsRheologyEsbar")==0) return MaterialsRheologyEsbarEnum;
-	      else if (strcmp(name,"DamageD")==0) return DamageDEnum;
-	      else if (strcmp(name,"DamageF")==0) return DamageFEnum;
-	      else if (strcmp(name,"DamageDbar")==0) return DamageDbarEnum;
-	      else if (strcmp(name,"DamageLaw")==0) return DamageLawEnum;
-	      else if (strcmp(name,"DamageC1")==0) return DamageC1Enum;
-	      else if (strcmp(name,"DamageC2")==0) return DamageC2Enum;
-	      else if (strcmp(name,"DamageC3")==0) return DamageC3Enum;
-	      else if (strcmp(name,"DamageC4")==0) return DamageC4Enum;
-	      else if (strcmp(name,"DamageElementinterp")==0) return DamageElementinterpEnum;
-	      else if (strcmp(name,"DamageHealing")==0) return DamageHealingEnum;
-	      else if (strcmp(name,"DamageStressThreshold")==0) return DamageStressThresholdEnum;
-	      else if (strcmp(name,"DamageKappa")==0) return DamageKappaEnum;
-	      else if (strcmp(name,"DamageStabilization")==0) return DamageStabilizationEnum;
-	      else if (strcmp(name,"DamageMaxiter")==0) return DamageMaxiterEnum;
-	      else if (strcmp(name,"DamageMaxDamage")==0) return DamageMaxDamageEnum;
-	      else if (strcmp(name,"DamageEquivStress")==0) return DamageEquivStressEnum;
-	      else if (strcmp(name,"DamageEvolutionNumRequestedOutputs")==0) return DamageEvolutionNumRequestedOutputsEnum;
-	      else if (strcmp(name,"DamageEvolutionRequestedOutputs")==0) return DamageEvolutionRequestedOutputsEnum;
-	      else if (strcmp(name,"Damage")==0) return DamageEnum;
-	      else if (strcmp(name,"NewDamage")==0) return NewDamageEnum;
-	      else if (strcmp(name,"StressIntensityFactor")==0) return StressIntensityFactorEnum;
-	      else if (strcmp(name,"CalvingLaw")==0) return CalvingLawEnum;
-	      else if (strcmp(name,"CalvingCalvingrate")==0) return CalvingCalvingrateEnum;
-	      else if (strcmp(name,"CalvingMeltingrate")==0) return CalvingMeltingrateEnum;
-	      else if (strcmp(name,"CalvingLevermann")==0) return CalvingLevermannEnum;
-	      else if (strcmp(name,"CalvingDev")==0) return CalvingDevEnum;
-	      else if (strcmp(name,"CalvingMinthickness")==0) return CalvingMinthicknessEnum;
-         else stage=3;
-   }
-   if(stage==3){
-	      if (strcmp(name,"DefaultCalving")==0) return DefaultCalvingEnum;
-	      else if (strcmp(name,"CalvinglevermannCoeff")==0) return CalvinglevermannCoeffEnum;
-	      else if (strcmp(name,"CalvinglevermannMeltingrate")==0) return CalvinglevermannMeltingrateEnum;
-	      else if (strcmp(name,"CalvingdevCoeff")==0) return CalvingdevCoeffEnum;
-	      else if (strcmp(name,"Calvingratex")==0) return CalvingratexEnum;
-	      else if (strcmp(name,"Calvingratey")==0) return CalvingrateyEnum;
-	      else if (strcmp(name,"CalvingratexAverage")==0) return CalvingratexAverageEnum;
-	      else if (strcmp(name,"CalvingrateyAverage")==0) return CalvingrateyAverageEnum;
-	      else if (strcmp(name,"CalvingStressThresholdGroundedice")==0) return CalvingStressThresholdGroundediceEnum;
-	      else if (strcmp(name,"CalvingStressThresholdFloatingice")==0) return CalvingStressThresholdFloatingiceEnum;
-	      else if (strcmp(name,"CalvingMax")==0) return CalvingMaxEnum;
-	      else if (strcmp(name,"StrainRateparallel")==0) return StrainRateparallelEnum;
-	      else if (strcmp(name,"StrainRateperpendicular")==0) return StrainRateperpendicularEnum;
-	      else if (strcmp(name,"StrainRateeffective")==0) return StrainRateeffectiveEnum;
-	      else if (strcmp(name,"MaterialsRhoIce")==0) return MaterialsRhoIceEnum;
-	      else if (strcmp(name,"MaterialsRhoSeawater")==0) return MaterialsRhoSeawaterEnum;
-	      else if (strcmp(name,"MaterialsRhoFreshwater")==0) return MaterialsRhoFreshwaterEnum;
-	      else if (strcmp(name,"MaterialsMuWater")==0) return MaterialsMuWaterEnum;
-	      else if (strcmp(name,"MaterialsThermalExchangeVelocity")==0) return MaterialsThermalExchangeVelocityEnum;
-	      else if (strcmp(name,"MaterialsThermalconductivity")==0) return MaterialsThermalconductivityEnum;
-	      else if (strcmp(name,"MaterialsTemperateiceconductivity")==0) return MaterialsTemperateiceconductivityEnum;
-	      else if (strcmp(name,"MaterialsLithosphereShearModulus")==0) return MaterialsLithosphereShearModulusEnum;
-	      else if (strcmp(name,"MaterialsLithosphereDensity")==0) return MaterialsLithosphereDensityEnum;
-	      else if (strcmp(name,"MaterialsMantleShearModulus")==0) return MaterialsMantleShearModulusEnum;
-	      else if (strcmp(name,"MaterialsMantleDensity")==0) return MaterialsMantleDensityEnum;
-	      else if (strcmp(name,"MaterialsEarthDensity")==0) return MaterialsEarthDensityEnum;
-	      else if (strcmp(name,"MeshAverageVertexConnectivity")==0) return MeshAverageVertexConnectivityEnum;
-	      else if (strcmp(name,"MeshX")==0) return MeshXEnum;
-	      else if (strcmp(name,"MeshY")==0) return MeshYEnum;
-	      else if (strcmp(name,"MeshZ")==0) return MeshZEnum;
-	      else if (strcmp(name,"MeshElements")==0) return MeshElementsEnum;
-	      else if (strcmp(name,"MeshNumberofelements")==0) return MeshNumberofelementsEnum;
-	      else if (strcmp(name,"MeshNumberoflayers")==0) return MeshNumberoflayersEnum;
-	      else if (strcmp(name,"MeshNumberofvertices")==0) return MeshNumberofverticesEnum;
-	      else if (strcmp(name,"MeshVertexonbase")==0) return MeshVertexonbaseEnum;
-	      else if (strcmp(name,"MeshVertexonsurface")==0) return MeshVertexonsurfaceEnum;
-	      else if (strcmp(name,"MeshVertexonboundary")==0) return MeshVertexonboundaryEnum;
-	      else if (strcmp(name,"MeshElementtype")==0) return MeshElementtypeEnum;
-	      else if (strcmp(name,"DomainType")==0) return DomainTypeEnum;
-	      else if (strcmp(name,"DomainDimension")==0) return DomainDimensionEnum;
-	      else if (strcmp(name,"Domain2Dhorizontal")==0) return Domain2DhorizontalEnum;
-	      else if (strcmp(name,"Domain2Dvertical")==0) return Domain2DverticalEnum;
-	      else if (strcmp(name,"Domain3D")==0) return Domain3DEnum;
-	      else if (strcmp(name,"Domain3Dsurface")==0) return Domain3DsurfaceEnum;
-	      else if (strcmp(name,"MasstransportHydrostaticAdjustment")==0) return MasstransportHydrostaticAdjustmentEnum;
-	      else if (strcmp(name,"MasstransportIsfreesurface")==0) return MasstransportIsfreesurfaceEnum;
-	      else if (strcmp(name,"MasstransportMinThickness")==0) return MasstransportMinThicknessEnum;
-	      else if (strcmp(name,"MasstransportPenaltyFactor")==0) return MasstransportPenaltyFactorEnum;
-	      else if (strcmp(name,"MasstransportSpcthickness")==0) return MasstransportSpcthicknessEnum;
-	      else if (strcmp(name,"MasstransportStabilization")==0) return MasstransportStabilizationEnum;
-	      else if (strcmp(name,"MasstransportNumRequestedOutputs")==0) return MasstransportNumRequestedOutputsEnum;
-	      else if (strcmp(name,"MasstransportRequestedOutputs")==0) return MasstransportRequestedOutputsEnum;
-	      else if (strcmp(name,"QmuIsdakota")==0) return QmuIsdakotaEnum;
-	      else if (strcmp(name,"MassFluxSegments")==0) return MassFluxSegmentsEnum;
-	      else if (strcmp(name,"MassFluxSegmentsPresent")==0) return MassFluxSegmentsPresentEnum;
-	      else if (strcmp(name,"QmuNumberofpartitions")==0) return QmuNumberofpartitionsEnum;
-	      else if (strcmp(name,"QmuNumberofresponses")==0) return QmuNumberofresponsesEnum;
-	      else if (strcmp(name,"QmuPartition")==0) return QmuPartitionEnum;
-	      else if (strcmp(name,"QmuResponsedescriptors")==0) return QmuResponsedescriptorsEnum;
-	      else if (strcmp(name,"QmuVariabledescriptors")==0) return QmuVariabledescriptorsEnum;
-	      else if (strcmp(name,"SettingsResultsOnNodes")==0) return SettingsResultsOnNodesEnum;
-	      else if (strcmp(name,"SettingsIoGather")==0) return SettingsIoGatherEnum;
-	      else if (strcmp(name,"SettingsLowmem")==0) return SettingsLowmemEnum;
-	      else if (strcmp(name,"SettingsOutputFrequency")==0) return SettingsOutputFrequencyEnum;
-	      else if (strcmp(name,"SettingsRecordingFrequency")==0) return SettingsRecordingFrequencyEnum;
-	      else if (strcmp(name,"SettingsWaitonlock")==0) return SettingsWaitonlockEnum;
-	      else if (strcmp(name,"SettingsSolverResidueThreshold")==0) return SettingsSolverResidueThresholdEnum;
-	      else if (strcmp(name,"DebugProfiling")==0) return DebugProfilingEnum;
-	      else if (strcmp(name,"ProfilingCurrentMem")==0) return ProfilingCurrentMemEnum;
-	      else if (strcmp(name,"ProfilingCurrentFlops")==0) return ProfilingCurrentFlopsEnum;
-	      else if (strcmp(name,"ProfilingSolutionTime")==0) return ProfilingSolutionTimeEnum;
-	      else if (strcmp(name,"SteadystateMaxiter")==0) return SteadystateMaxiterEnum;
-	      else if (strcmp(name,"SteadystateNumRequestedOutputs")==0) return SteadystateNumRequestedOutputsEnum;
-	      else if (strcmp(name,"SteadystateReltol")==0) return SteadystateReltolEnum;
-	      else if (strcmp(name,"SteadystateRequestedOutputs")==0) return SteadystateRequestedOutputsEnum;
-	      else if (strcmp(name,"Surface")==0) return SurfaceEnum;
-	      else if (strcmp(name,"ThermalIsenthalpy")==0) return ThermalIsenthalpyEnum;
-	      else if (strcmp(name,"ThermalIsdynamicbasalspc")==0) return ThermalIsdynamicbasalspcEnum;
-	      else if (strcmp(name,"ThermalReltol")==0) return ThermalReltolEnum;
-	      else if (strcmp(name,"ThermalMaxiter")==0) return ThermalMaxiterEnum;
-	      else if (strcmp(name,"ThermalPenaltyFactor")==0) return ThermalPenaltyFactorEnum;
-	      else if (strcmp(name,"ThermalPenaltyLock")==0) return ThermalPenaltyLockEnum;
-	      else if (strcmp(name,"ThermalPenaltyThreshold")==0) return ThermalPenaltyThresholdEnum;
-	      else if (strcmp(name,"ThermalSpctemperature")==0) return ThermalSpctemperatureEnum;
-	      else if (strcmp(name,"ThermalStabilization")==0) return ThermalStabilizationEnum;
-	      else if (strcmp(name,"ThermalNumRequestedOutputs")==0) return ThermalNumRequestedOutputsEnum;
-	      else if (strcmp(name,"ThermalRequestedOutputs")==0) return ThermalRequestedOutputsEnum;
-	      else if (strcmp(name,"GiaMantleViscosity")==0) return GiaMantleViscosityEnum;
-	      else if (strcmp(name,"GiaLithosphereThickness")==0) return GiaLithosphereThicknessEnum;
-	      else if (strcmp(name,"Thickness")==0) return ThicknessEnum;
-	      else if (strcmp(name,"TimesteppingStartTime")==0) return TimesteppingStartTimeEnum;
-	      else if (strcmp(name,"TimesteppingFinalTime")==0) return TimesteppingFinalTimeEnum;
-	      else if (strcmp(name,"TimesteppingCflCoefficient")==0) return TimesteppingCflCoefficientEnum;
-	      else if (strcmp(name,"TimesteppingTimeAdapt")==0) return TimesteppingTimeAdaptEnum;
-	      else if (strcmp(name,"TimesteppingTimeStep")==0) return TimesteppingTimeStepEnum;
-	      else if (strcmp(name,"TimesteppingInterpForcings")==0) return TimesteppingInterpForcingsEnum;
-	      else if (strcmp(name,"TransientIssmb")==0) return TransientIssmbEnum;
-	      else if (strcmp(name,"TransientIscoupler")==0) return TransientIscouplerEnum;
-	      else if (strcmp(name,"TransientIsstressbalance")==0) return TransientIsstressbalanceEnum;
-	      else if (strcmp(name,"TransientIsgroundingline")==0) return TransientIsgroundinglineEnum;
-	      else if (strcmp(name,"TransientIsmasstransport")==0) return TransientIsmasstransportEnum;
-	      else if (strcmp(name,"TransientIsthermal")==0) return TransientIsthermalEnum;
-	      else if (strcmp(name,"TransientIsgia")==0) return TransientIsgiaEnum;
-	      else if (strcmp(name,"TransientIsesa")==0) return TransientIsesaEnum;
-	      else if (strcmp(name,"TransientIsdamageevolution")==0) return TransientIsdamageevolutionEnum;
-	      else if (strcmp(name,"TransientIshydrology")==0) return TransientIshydrologyEnum;
-	      else if (strcmp(name,"TransientIsmovingfront")==0) return TransientIsmovingfrontEnum;
-	      else if (strcmp(name,"TransientIsslr")==0) return TransientIsslrEnum;
-	      else if (strcmp(name,"TransientNumRequestedOutputs")==0) return TransientNumRequestedOutputsEnum;
-	      else if (strcmp(name,"TransientRequestedOutputs")==0) return TransientRequestedOutputsEnum;
-	      else if (strcmp(name,"BalancethicknessApparentMassbalance")==0) return BalancethicknessApparentMassbalanceEnum;
-	      else if (strcmp(name,"BalancethicknessDiffusionCoefficient")==0) return BalancethicknessDiffusionCoefficientEnum;
-	      else if (strcmp(name,"BalancethicknessOmega")==0) return BalancethicknessOmegaEnum;
-	      else if (strcmp(name,"BalancethicknessD0")==0) return BalancethicknessD0Enum;
-	      else if (strcmp(name,"Smb")==0) return SmbEnum;
-	      else if (strcmp(name,"SmbAnalysis")==0) return SmbAnalysisEnum;
-	      else if (strcmp(name,"SmbSolution")==0) return SmbSolutionEnum;
-	      else if (strcmp(name,"SmbNumRequestedOutputs")==0) return SmbNumRequestedOutputsEnum;
-	      else if (strcmp(name,"SmbRequestedOutputs")==0) return SmbRequestedOutputsEnum;
-	      else if (strcmp(name,"SmbIsInitialized")==0) return SmbIsInitializedEnum;
-         else stage=4;
-   }
-   if(stage==4){
-	      if (strcmp(name,"SmbDzini")==0) return SmbDziniEnum;
-	      else if (strcmp(name,"SmbDini")==0) return SmbDiniEnum;
-	      else if (strcmp(name,"SmbReini")==0) return SmbReiniEnum;
-	      else if (strcmp(name,"SmbGdnini")==0) return SmbGdniniEnum;
-	      else if (strcmp(name,"SmbGspini")==0) return SmbGspiniEnum;
-	      else if (strcmp(name,"SmbECini")==0) return SmbECiniEnum;
-	      else if (strcmp(name,"SmbWini")==0) return SmbWiniEnum;
-	      else if (strcmp(name,"SmbAini")==0) return SmbAiniEnum;
-	      else if (strcmp(name,"SmbTini")==0) return SmbTiniEnum;
-	      else if (strcmp(name,"SmbSizeini")==0) return SmbSizeiniEnum;
-	      else if (strcmp(name,"SMBforcing")==0) return SMBforcingEnum;
-	      else if (strcmp(name,"SmbMassBalance")==0) return SmbMassBalanceEnum;
-	      else if (strcmp(name,"SMBgemb")==0) return SMBgembEnum;
-	      else if (strcmp(name,"SmbInitDensityScaling")==0) return SmbInitDensityScalingEnum;
-	      else if (strcmp(name,"SmbTa")==0) return SmbTaEnum;
-	      else if (strcmp(name,"SmbV")==0) return SmbVEnum;
-	      else if (strcmp(name,"SmbDswrf")==0) return SmbDswrfEnum;
-	      else if (strcmp(name,"SmbDlwrf")==0) return SmbDlwrfEnum;
-	      else if (strcmp(name,"SmbP")==0) return SmbPEnum;
-	      else if (strcmp(name,"SmbEAir")==0) return SmbEAirEnum;
-	      else if (strcmp(name,"SmbPAir")==0) return SmbPAirEnum;
-	      else if (strcmp(name,"SmbTmean")==0) return SmbTmeanEnum;
-	      else if (strcmp(name,"SmbC")==0) return SmbCEnum;
-	      else if (strcmp(name,"SmbTz")==0) return SmbTzEnum;
-	      else if (strcmp(name,"SmbVz")==0) return SmbVzEnum;
-	      else if (strcmp(name,"SmbDt")==0) return SmbDtEnum;
-	      else if (strcmp(name,"SmbDz")==0) return SmbDzEnum;
-	      else if (strcmp(name,"SmbAIdx")==0) return SmbAIdxEnum;
-	      else if (strcmp(name,"SmbSwIdx")==0) return SmbSwIdxEnum;
-	      else if (strcmp(name,"SmbDenIdx")==0) return SmbDenIdxEnum;
-	      else if (strcmp(name,"SmbZTop")==0) return SmbZTopEnum;
-	      else if (strcmp(name,"SmbDzTop")==0) return SmbDzTopEnum;
-	      else if (strcmp(name,"SmbDzMin")==0) return SmbDzMinEnum;
-	      else if (strcmp(name,"SmbZY")==0) return SmbZYEnum;
-	      else if (strcmp(name,"SmbZMax")==0) return SmbZMaxEnum;
-	      else if (strcmp(name,"SmbZMin")==0) return SmbZMinEnum;
-	      else if (strcmp(name,"SmbOutputFreq")==0) return SmbOutputFreqEnum;
-	      else if (strcmp(name,"SmbASnow")==0) return SmbASnowEnum;
-	      else if (strcmp(name,"SmbAIce")==0) return SmbAIceEnum;
-	      else if (strcmp(name,"SmbCldFrac")==0) return SmbCldFracEnum;
-	      else if (strcmp(name,"SmbT0wet")==0) return SmbT0wetEnum;
-	      else if (strcmp(name,"SmbT0dry")==0) return SmbT0dryEnum;
-	      else if (strcmp(name,"SmbK")==0) return SmbKEnum;
-	      else if (strcmp(name,"SmbD")==0) return SmbDEnum;
-	      else if (strcmp(name,"SmbRe")==0) return SmbReEnum;
-	      else if (strcmp(name,"SmbGdn")==0) return SmbGdnEnum;
-	      else if (strcmp(name,"SmbGsp")==0) return SmbGspEnum;
-	      else if (strcmp(name,"SmbEC")==0) return SmbECEnum;
-	      else if (strcmp(name,"SmbW")==0) return SmbWEnum;
-	      else if (strcmp(name,"SmbA")==0) return SmbAEnum;
-	      else if (strcmp(name,"SmbT")==0) return SmbTEnum;
-	      else if (strcmp(name,"SmbIsgraingrowth")==0) return SmbIsgraingrowthEnum;
-	      else if (strcmp(name,"SmbIsalbedo")==0) return SmbIsalbedoEnum;
-	      else if (strcmp(name,"SmbIsshortwave")==0) return SmbIsshortwaveEnum;
-	      else if (strcmp(name,"SmbIsthermal")==0) return SmbIsthermalEnum;
-	      else if (strcmp(name,"SmbIsaccumulation")==0) return SmbIsaccumulationEnum;
-	      else if (strcmp(name,"SmbIsmelt")==0) return SmbIsmeltEnum;
-	      else if (strcmp(name,"SmbIsdensification")==0) return SmbIsdensificationEnum;
-	      else if (strcmp(name,"SmbIsturbulentflux")==0) return SmbIsturbulentfluxEnum;
-	      else if (strcmp(name,"SmbDz_add")==0) return SmbDz_addEnum;
-	      else if (strcmp(name,"SmbM_add")==0) return SmbM_addEnum;
-	      else if (strcmp(name,"SMBpdd")==0) return SMBpddEnum;
-	      else if (strcmp(name,"SmbDelta18o")==0) return SmbDelta18oEnum;
-	      else if (strcmp(name,"SmbDelta18oSurface")==0) return SmbDelta18oSurfaceEnum;
-	      else if (strcmp(name,"SmbIsdelta18o")==0) return SmbIsdelta18oEnum;
-	      else if (strcmp(name,"SmbIsmungsm")==0) return SmbIsmungsmEnum;
-	      else if (strcmp(name,"SmbIsd18opd")==0) return SmbIsd18opdEnum;
-	      else if (strcmp(name,"SmbPrecipitationsPresentday")==0) return SmbPrecipitationsPresentdayEnum;
-	      else if (strcmp(name,"SmbPrecipitationsLgm")==0) return SmbPrecipitationsLgmEnum;
-	      else if (strcmp(name,"SmbTemperaturesPresentday")==0) return SmbTemperaturesPresentdayEnum;
-	      else if (strcmp(name,"SmbTemperaturesLgm")==0) return SmbTemperaturesLgmEnum;
-	      else if (strcmp(name,"SmbPrecipitation")==0) return SmbPrecipitationEnum;
-	      else if (strcmp(name,"SmbDesfac")==0) return SmbDesfacEnum;
-	      else if (strcmp(name,"SmbS0p")==0) return SmbS0pEnum;
-	      else if (strcmp(name,"SmbS0t")==0) return SmbS0tEnum;
-	      else if (strcmp(name,"SmbRlaps")==0) return SmbRlapsEnum;
-	      else if (strcmp(name,"SmbRlapslgm")==0) return SmbRlapslgmEnum;
-	      else if (strcmp(name,"SmbPfac")==0) return SmbPfacEnum;
-	      else if (strcmp(name,"SmbTdiff")==0) return SmbTdiffEnum;
-	      else if (strcmp(name,"SmbSealev")==0) return SmbSealevEnum;
-	      else if (strcmp(name,"SMBd18opdd")==0) return SMBd18opddEnum;
-	      else if (strcmp(name,"SmbDpermil")==0) return SmbDpermilEnum;
-	      else if (strcmp(name,"SmbF")==0) return SmbFEnum;
-	      else if (strcmp(name,"SMBgradients")==0) return SMBgradientsEnum;
-	      else if (strcmp(name,"SmbMonthlytemperatures")==0) return SmbMonthlytemperaturesEnum;
-	      else if (strcmp(name,"SmbHref")==0) return SmbHrefEnum;
-	      else if (strcmp(name,"SmbSmbref")==0) return SmbSmbrefEnum;
-	      else if (strcmp(name,"SmbBPos")==0) return SmbBPosEnum;
-	      else if (strcmp(name,"SmbBNeg")==0) return SmbBNegEnum;
-	      else if (strcmp(name,"SMBhenning")==0) return SMBhenningEnum;
-	      else if (strcmp(name,"SMBcomponents")==0) return SMBcomponentsEnum;
-	      else if (strcmp(name,"SmbAccumulation")==0) return SmbAccumulationEnum;
-	      else if (strcmp(name,"SmbEvaporation")==0) return SmbEvaporationEnum;
-	      else if (strcmp(name,"SmbRunoff")==0) return SmbRunoffEnum;
-	      else if (strcmp(name,"SMBmeltcomponents")==0) return SMBmeltcomponentsEnum;
-	      else if (strcmp(name,"SmbMelt")==0) return SmbMeltEnum;
-	      else if (strcmp(name,"SmbRefreeze")==0) return SmbRefreezeEnum;
-	      else if (strcmp(name,"SMBgcm")==0) return SMBgcmEnum;
-	      else if (strcmp(name,"SMBgradientsela")==0) return SMBgradientselaEnum;
-	      else if (strcmp(name,"SmbEla")==0) return SmbElaEnum;
-	      else if (strcmp(name,"SmbBMax")==0) return SmbBMaxEnum;
-	      else if (strcmp(name,"SmbBMin")==0) return SmbBMinEnum;
-	      else if (strcmp(name,"Adjointp")==0) return AdjointpEnum;
-	      else if (strcmp(name,"Adjointx")==0) return AdjointxEnum;
-	      else if (strcmp(name,"Adjointy")==0) return AdjointyEnum;
-	      else if (strcmp(name,"Adjointz")==0) return AdjointzEnum;
-	      else if (strcmp(name,"BalancethicknessMisfit")==0) return BalancethicknessMisfitEnum;
-	      else if (strcmp(name,"BedSlopeX")==0) return BedSlopeXEnum;
-	      else if (strcmp(name,"BedSlopeY")==0) return BedSlopeYEnum;
-	      else if (strcmp(name,"Boundary")==0) return BoundaryEnum;
-	      else if (strcmp(name,"Converged")==0) return ConvergedEnum;
-	      else if (strcmp(name,"Internal")==0) return InternalEnum;
-	      else if (strcmp(name,"MassFlux")==0) return MassFluxEnum;
-	      else if (strcmp(name,"MeltingOffset")==0) return MeltingOffsetEnum;
-	      else if (strcmp(name,"Misfit")==0) return MisfitEnum;
-	      else if (strcmp(name,"Pressure")==0) return PressureEnum;
-	      else if (strcmp(name,"PressurePicard")==0) return PressurePicardEnum;
-	      else if (strcmp(name,"AndroidFrictionCoefficient")==0) return AndroidFrictionCoefficientEnum;
-	      else if (strcmp(name,"ResetPenalties")==0) return ResetPenaltiesEnum;
-	      else if (strcmp(name,"SurfaceAbsVelMisfit")==0) return SurfaceAbsVelMisfitEnum;
          else stage=5;
    }
    if(stage==5){
-	      if (strcmp(name,"SurfaceArea")==0) return SurfaceAreaEnum;
-	      else if (strcmp(name,"SurfaceAverageVelMisfit")==0) return SurfaceAverageVelMisfitEnum;
-	      else if (strcmp(name,"SurfaceLogVelMisfit")==0) return SurfaceLogVelMisfitEnum;
-	      else if (strcmp(name,"SurfaceLogVxVyMisfit")==0) return SurfaceLogVxVyMisfitEnum;
-	      else if (strcmp(name,"SurfaceRelVelMisfit")==0) return SurfaceRelVelMisfitEnum;
-	      else if (strcmp(name,"SurfaceSlopeX")==0) return SurfaceSlopeXEnum;
-	      else if (strcmp(name,"SurfaceSlopeY")==0) return SurfaceSlopeYEnum;
-	      else if (strcmp(name,"Temperature")==0) return TemperatureEnum;
-	      else if (strcmp(name,"TemperaturePicard")==0) return TemperaturePicardEnum;
-	      else if (strcmp(name,"TemperaturePDD")==0) return TemperaturePDDEnum;
-	      else if (strcmp(name,"ThicknessAbsMisfit")==0) return ThicknessAbsMisfitEnum;
-	      else if (strcmp(name,"SurfaceAbsMisfit")==0) return SurfaceAbsMisfitEnum;
-	      else if (strcmp(name,"Vel")==0) return VelEnum;
-	      else if (strcmp(name,"Velocity")==0) return VelocityEnum;
-	      else if (strcmp(name,"VxAverage")==0) return VxAverageEnum;
-	      else if (strcmp(name,"Vx")==0) return VxEnum;
-	      else if (strcmp(name,"VxPicard")==0) return VxPicardEnum;
-	      else if (strcmp(name,"VyAverage")==0) return VyAverageEnum;
-	      else if (strcmp(name,"Vy")==0) return VyEnum;
-	      else if (strcmp(name,"VyPicard")==0) return VyPicardEnum;
-	      else if (strcmp(name,"Vz")==0) return VzEnum;
-	      else if (strcmp(name,"VzSSA")==0) return VzSSAEnum;
-	      else if (strcmp(name,"VzHO")==0) return VzHOEnum;
-	      else if (strcmp(name,"VzPicard")==0) return VzPicardEnum;
-	      else if (strcmp(name,"VzFS")==0) return VzFSEnum;
-	      else if (strcmp(name,"VxMesh")==0) return VxMeshEnum;
-	      else if (strcmp(name,"VyMesh")==0) return VyMeshEnum;
-	      else if (strcmp(name,"VzMesh")==0) return VzMeshEnum;
-	      else if (strcmp(name,"Enthalpy")==0) return EnthalpyEnum;
-	      else if (strcmp(name,"EnthalpyPicard")==0) return EnthalpyPicardEnum;
-	      else if (strcmp(name,"ThicknessAbsGradient")==0) return ThicknessAbsGradientEnum;
-	      else if (strcmp(name,"ThicknessAlongGradient")==0) return ThicknessAlongGradientEnum;
-	      else if (strcmp(name,"ThicknessAcrossGradient")==0) return ThicknessAcrossGradientEnum;
-	      else if (strcmp(name,"ThicknessPositive")==0) return ThicknessPositiveEnum;
-	      else if (strcmp(name,"IntMatParam")==0) return IntMatParamEnum;
-	      else if (strcmp(name,"RheologyBbarAbsGradient")==0) return RheologyBbarAbsGradientEnum;
-	      else if (strcmp(name,"RheologyBAbsGradient")==0) return RheologyBAbsGradientEnum;
-	      else if (strcmp(name,"DragCoefficientAbsGradient")==0) return DragCoefficientAbsGradientEnum;
-	      else if (strcmp(name,"TransientInput")==0) return TransientInputEnum;
-	      else if (strcmp(name,"Waterfraction")==0) return WaterfractionEnum;
-	      else if (strcmp(name,"WaterfractionDrainage")==0) return WaterfractionDrainageEnum;
-	      else if (strcmp(name,"WaterfractionDrainageIntegrated")==0) return WaterfractionDrainageIntegratedEnum;
-	      else if (strcmp(name,"Watercolumn")==0) return WatercolumnEnum;
-	      else if (strcmp(name,"ViscousHeating")==0) return ViscousHeatingEnum;
-	      else if (strcmp(name,"HydrologyWaterVx")==0) return HydrologyWaterVxEnum;
-	      else if (strcmp(name,"HydrologyWaterVy")==0) return HydrologyWaterVyEnum;
-	      else if (strcmp(name,"DrivingStressX")==0) return DrivingStressXEnum;
-	      else if (strcmp(name,"DrivingStressY")==0) return DrivingStressYEnum;
+	      if (strcmp(name,"SedimentHeadOld")==0) return SedimentHeadOldEnum;
+	      else if (strcmp(name,"SedimentHeadResidual")==0) return SedimentHeadResidualEnum;
 	      else if (strcmp(name,"SigmaNN")==0) return SigmaNNEnum;
-	      else if (strcmp(name,"StressTensor")==0) return StressTensorEnum;
+	      else if (strcmp(name,"SmbAccumulation")==0) return SmbAccumulationEnum;
+	      else if (strcmp(name,"SmbA")==0) return SmbAEnum;
+	      else if (strcmp(name,"SmbAini")==0) return SmbAiniEnum;
+	      else if (strcmp(name,"SmbAValue")==0) return SmbAValueEnum;
+	      else if (strcmp(name,"SmbBMax")==0) return SmbBMaxEnum;
+	      else if (strcmp(name,"SmbBMin")==0) return SmbBMinEnum;
+	      else if (strcmp(name,"SmbBNeg")==0) return SmbBNegEnum;
+	      else if (strcmp(name,"SmbBPos")==0) return SmbBPosEnum;
+	      else if (strcmp(name,"SmbC")==0) return SmbCEnum;
+	      else if (strcmp(name,"SmbD")==0) return SmbDEnum;
+	      else if (strcmp(name,"SmbDini")==0) return SmbDiniEnum;
+	      else if (strcmp(name,"SmbDlwrf")==0) return SmbDlwrfEnum;
+	      else if (strcmp(name,"SmbDswrf")==0) return SmbDswrfEnum;
+	      else if (strcmp(name,"SmbDz")==0) return SmbDzEnum;
+	      else if (strcmp(name,"SmbDzini")==0) return SmbDziniEnum;
+	      else if (strcmp(name,"SmbDzMin")==0) return SmbDzMinEnum;
+	      else if (strcmp(name,"SmbDzTop")==0) return SmbDzTopEnum;
+	      else if (strcmp(name,"SmbEAir")==0) return SmbEAirEnum;
+	      else if (strcmp(name,"SmbEC")==0) return SmbECEnum;
+	      else if (strcmp(name,"SmbECini")==0) return SmbECiniEnum;
+	      else if (strcmp(name,"SmbEla")==0) return SmbElaEnum;
+	      else if (strcmp(name,"SmbEvaporation")==0) return SmbEvaporationEnum;
+	      else if (strcmp(name,"SmbGdn")==0) return SmbGdnEnum;
+	      else if (strcmp(name,"SmbGdnini")==0) return SmbGdniniEnum;
+	      else if (strcmp(name,"SmbGsp")==0) return SmbGspEnum;
+	      else if (strcmp(name,"SmbGspini")==0) return SmbGspiniEnum;
+	      else if (strcmp(name,"SmbHref")==0) return SmbHrefEnum;
+	      else if (strcmp(name,"SmbIsInitialized")==0) return SmbIsInitializedEnum;
+	      else if (strcmp(name,"SmbMassBalance")==0) return SmbMassBalanceEnum;
+	      else if (strcmp(name,"SmbMelt")==0) return SmbMeltEnum;
+	      else if (strcmp(name,"SmbMonthlytemperatures")==0) return SmbMonthlytemperaturesEnum;
+	      else if (strcmp(name,"SmbPAir")==0) return SmbPAirEnum;
+	      else if (strcmp(name,"SmbPddfacIce")==0) return SmbPddfacIceEnum;
+	      else if (strcmp(name,"SmbPddfacSnow")==0) return SmbPddfacSnowEnum;
+	      else if (strcmp(name,"SmbP")==0) return SmbPEnum;
+	      else if (strcmp(name,"SmbPrecipitation")==0) return SmbPrecipitationEnum;
+	      else if (strcmp(name,"SmbPrecipitationsLgm")==0) return SmbPrecipitationsLgmEnum;
+	      else if (strcmp(name,"SmbPrecipitationsPresentday")==0) return SmbPrecipitationsPresentdayEnum;
+	      else if (strcmp(name,"SmbRe")==0) return SmbReEnum;
+	      else if (strcmp(name,"SmbRefreeze")==0) return SmbRefreezeEnum;
+	      else if (strcmp(name,"SmbReini")==0) return SmbReiniEnum;
+	      else if (strcmp(name,"SmbRunoff")==0) return SmbRunoffEnum;
+	      else if (strcmp(name,"SmbS0p")==0) return SmbS0pEnum;
+	      else if (strcmp(name,"SmbS0t")==0) return SmbS0tEnum;
+	      else if (strcmp(name,"SmbSizeini")==0) return SmbSizeiniEnum;
+	      else if (strcmp(name,"SmbSmbref")==0) return SmbSmbrefEnum;
+	      else if (strcmp(name,"SmbTa")==0) return SmbTaEnum;
+	      else if (strcmp(name,"SmbTemperaturesLgm")==0) return SmbTemperaturesLgmEnum;
+	      else if (strcmp(name,"SmbTemperaturesPresentday")==0) return SmbTemperaturesPresentdayEnum;
+	      else if (strcmp(name,"SmbT")==0) return SmbTEnum;
+	      else if (strcmp(name,"SmbTeValue")==0) return SmbTeValueEnum;
+	      else if (strcmp(name,"SmbTini")==0) return SmbTiniEnum;
+	      else if (strcmp(name,"SmbTmean")==0) return SmbTmeanEnum;
+	      else if (strcmp(name,"SmbTz")==0) return SmbTzEnum;
+	      else if (strcmp(name,"SmbV")==0) return SmbVEnum;
+	      else if (strcmp(name,"SmbVz")==0) return SmbVzEnum;
+	      else if (strcmp(name,"SmbW")==0) return SmbWEnum;
+	      else if (strcmp(name,"SmbWini")==0) return SmbWiniEnum;
+	      else if (strcmp(name,"SmbZMax")==0) return SmbZMaxEnum;
+	      else if (strcmp(name,"SmbZMin")==0) return SmbZMinEnum;
+	      else if (strcmp(name,"SmbZTop")==0) return SmbZTopEnum;
+	      else if (strcmp(name,"SmbZY")==0) return SmbZYEnum;
+	      else if (strcmp(name,"StrainRateeffective")==0) return StrainRateeffectiveEnum;
+	      else if (strcmp(name,"StrainRateparallel")==0) return StrainRateparallelEnum;
+	      else if (strcmp(name,"StrainRateperpendicular")==0) return StrainRateperpendicularEnum;
+	      else if (strcmp(name,"StrainRatexx")==0) return StrainRatexxEnum;
+	      else if (strcmp(name,"StrainRatexy")==0) return StrainRatexyEnum;
+	      else if (strcmp(name,"StrainRatexz")==0) return StrainRatexzEnum;
+	      else if (strcmp(name,"StrainRateyy")==0) return StrainRateyyEnum;
+	      else if (strcmp(name,"StrainRateyz")==0) return StrainRateyzEnum;
+	      else if (strcmp(name,"StrainRatezz")==0) return StrainRatezzEnum;
+	      else if (strcmp(name,"StressMaxPrincipal")==0) return StressMaxPrincipalEnum;
 	      else if (strcmp(name,"StressTensorxx")==0) return StressTensorxxEnum;
 	      else if (strcmp(name,"StressTensorxy")==0) return StressTensorxyEnum;
@@ -565,49 +590,323 @@
 	      else if (strcmp(name,"StressTensoryz")==0) return StressTensoryzEnum;
 	      else if (strcmp(name,"StressTensorzz")==0) return StressTensorzzEnum;
-	      else if (strcmp(name,"StressMaxPrincipal")==0) return StressMaxPrincipalEnum;
-	      else if (strcmp(name,"DeviatoricStress")==0) return DeviatoricStressEnum;
-	      else if (strcmp(name,"DeviatoricStressxx")==0) return DeviatoricStressxxEnum;
-	      else if (strcmp(name,"DeviatoricStressxy")==0) return DeviatoricStressxyEnum;
-	      else if (strcmp(name,"DeviatoricStressxz")==0) return DeviatoricStressxzEnum;
-	      else if (strcmp(name,"DeviatoricStressyy")==0) return DeviatoricStressyyEnum;
-	      else if (strcmp(name,"DeviatoricStressyz")==0) return DeviatoricStressyzEnum;
-	      else if (strcmp(name,"DeviatoricStresszz")==0) return DeviatoricStresszzEnum;
+	      else if (strcmp(name,"SurfaceAbsMisfit")==0) return SurfaceAbsMisfitEnum;
+	      else if (strcmp(name,"SurfaceAbsVelMisfit")==0) return SurfaceAbsVelMisfitEnum;
+	      else if (strcmp(name,"SurfaceArea")==0) return SurfaceAreaEnum;
+	      else if (strcmp(name,"SurfaceAverageVelMisfit")==0) return SurfaceAverageVelMisfitEnum;
+	      else if (strcmp(name,"Surface")==0) return SurfaceEnum;
+	      else if (strcmp(name,"SurfaceLogVelMisfit")==0) return SurfaceLogVelMisfitEnum;
+	      else if (strcmp(name,"SurfaceLogVxVyMisfit")==0) return SurfaceLogVxVyMisfitEnum;
+	      else if (strcmp(name,"SurfaceObservation")==0) return SurfaceObservationEnum;
+	      else if (strcmp(name,"SurfaceRelVelMisfit")==0) return SurfaceRelVelMisfitEnum;
+	      else if (strcmp(name,"SurfaceSlopeX")==0) return SurfaceSlopeXEnum;
+	      else if (strcmp(name,"SurfaceSlopeY")==0) return SurfaceSlopeYEnum;
+	      else if (strcmp(name,"Temperature")==0) return TemperatureEnum;
+	      else if (strcmp(name,"TemperaturePicard")==0) return TemperaturePicardEnum;
+	      else if (strcmp(name,"ThicknessAbsGradient")==0) return ThicknessAbsGradientEnum;
+	      else if (strcmp(name,"ThicknessAbsMisfit")==0) return ThicknessAbsMisfitEnum;
+	      else if (strcmp(name,"ThicknessAcrossGradient")==0) return ThicknessAcrossGradientEnum;
+	      else if (strcmp(name,"ThicknessAlongGradient")==0) return ThicknessAlongGradientEnum;
+	      else if (strcmp(name,"Thickness")==0) return ThicknessEnum;
+	      else if (strcmp(name,"ThicknessPositive")==0) return ThicknessPositiveEnum;
+	      else if (strcmp(name,"Vel")==0) return VelEnum;
+	      else if (strcmp(name,"VxAverage")==0) return VxAverageEnum;
+	      else if (strcmp(name,"Vx")==0) return VxEnum;
+	      else if (strcmp(name,"VxMesh")==0) return VxMeshEnum;
+	      else if (strcmp(name,"VxObs")==0) return VxObsEnum;
+	      else if (strcmp(name,"VyAverage")==0) return VyAverageEnum;
+	      else if (strcmp(name,"Vy")==0) return VyEnum;
+	      else if (strcmp(name,"VyMesh")==0) return VyMeshEnum;
+	      else if (strcmp(name,"VyObs")==0) return VyObsEnum;
+	      else if (strcmp(name,"Vz")==0) return VzEnum;
+	      else if (strcmp(name,"VzFS")==0) return VzFSEnum;
+	      else if (strcmp(name,"VzHO")==0) return VzHOEnum;
+	      else if (strcmp(name,"VzMesh")==0) return VzMeshEnum;
+	      else if (strcmp(name,"VzSSA")==0) return VzSSAEnum;
+	      else if (strcmp(name,"Watercolumn")==0) return WatercolumnEnum;
+	      else if (strcmp(name,"WaterColumnOld")==0) return WaterColumnOldEnum;
+	      else if (strcmp(name,"WaterfractionDrainage")==0) return WaterfractionDrainageEnum;
+	      else if (strcmp(name,"WaterfractionDrainageIntegrated")==0) return WaterfractionDrainageIntegratedEnum;
+	      else if (strcmp(name,"Waterfraction")==0) return WaterfractionEnum;
+	      else if (strcmp(name,"Waterheight")==0) return WaterheightEnum;
+         else stage=6;
+   }
+   if(stage==6){
+	      if (strcmp(name,"WeightsSurfaceObservation")==0) return WeightsSurfaceObservationEnum;
+	      else if (strcmp(name,"InputsEND")==0) return InputsENDEnum;
+	      else if (strcmp(name,"Absolute")==0) return AbsoluteEnum;
+	      else if (strcmp(name,"AdaptiveTimestepping")==0) return AdaptiveTimesteppingEnum;
+	      else if (strcmp(name,"AdjointBalancethickness2Analysis")==0) return AdjointBalancethickness2AnalysisEnum;
+	      else if (strcmp(name,"AdjointBalancethicknessAnalysis")==0) return AdjointBalancethicknessAnalysisEnum;
+	      else if (strcmp(name,"AdjointHorizAnalysis")==0) return AdjointHorizAnalysisEnum;
+	      else if (strcmp(name,"Adjointp")==0) return AdjointpEnum;
+	      else if (strcmp(name,"AggressiveMigration")==0) return AggressiveMigrationEnum;
+	      else if (strcmp(name,"AmrBamg")==0) return AmrBamgEnum;
+	      else if (strcmp(name,"AmrNeopz")==0) return AmrNeopzEnum;
+	      else if (strcmp(name,"AndroidFrictionCoefficient")==0) return AndroidFrictionCoefficientEnum;
+	      else if (strcmp(name,"Arrhenius")==0) return ArrheniusEnum;
+	      else if (strcmp(name,"AutodiffJacobian")==0) return AutodiffJacobianEnum;
+	      else if (strcmp(name,"Balancethickness2Analysis")==0) return Balancethickness2AnalysisEnum;
+	      else if (strcmp(name,"Balancethickness2Solution")==0) return Balancethickness2SolutionEnum;
+	      else if (strcmp(name,"BalancethicknessAnalysis")==0) return BalancethicknessAnalysisEnum;
+	      else if (strcmp(name,"BalancethicknessApparentMassbalance")==0) return BalancethicknessApparentMassbalanceEnum;
+	      else if (strcmp(name,"BalancethicknessSoftAnalysis")==0) return BalancethicknessSoftAnalysisEnum;
+	      else if (strcmp(name,"BalancethicknessSoftSolution")==0) return BalancethicknessSoftSolutionEnum;
+	      else if (strcmp(name,"BalancethicknessSolution")==0) return BalancethicknessSolutionEnum;
+	      else if (strcmp(name,"BalancethicknessSpcthickness")==0) return BalancethicknessSpcthicknessEnum;
+	      else if (strcmp(name,"BalancevelocityAnalysis")==0) return BalancevelocityAnalysisEnum;
+	      else if (strcmp(name,"BalancevelocitySolution")==0) return BalancevelocitySolutionEnum;
+	      else if (strcmp(name,"BasalCrevasse")==0) return BasalCrevasseEnum;
+	      else if (strcmp(name,"BasalforcingsPico")==0) return BasalforcingsPicoEnum;
+	      else if (strcmp(name,"BedSlopeSolution")==0) return BedSlopeSolutionEnum;
+	      else if (strcmp(name,"BoolExternalResult")==0) return BoolExternalResultEnum;
+	      else if (strcmp(name,"BoolInput")==0) return BoolInputEnum;
+	      else if (strcmp(name,"BoolParam")==0) return BoolParamEnum;
+	      else if (strcmp(name,"Boundary")==0) return BoundaryEnum;
+	      else if (strcmp(name,"BuddJacka")==0) return BuddJackaEnum;
+	      else if (strcmp(name,"CalvingDev2")==0) return CalvingDev2Enum;
+	      else if (strcmp(name,"CalvingHab")==0) return CalvingHabEnum;
+	      else if (strcmp(name,"CalvingLevermann")==0) return CalvingLevermannEnum;
+	      else if (strcmp(name,"CalvingVonmises")==0) return CalvingVonmisesEnum;
+	      else if (strcmp(name,"Cfsurfacelogvel")==0) return CfsurfacelogvelEnum;
+	      else if (strcmp(name,"Cfsurfacesquare")==0) return CfsurfacesquareEnum;
+	      else if (strcmp(name,"Cfdragcoeffabsgrad")==0) return CfdragcoeffabsgradEnum;
+	      else if (strcmp(name,"Closed")==0) return ClosedEnum;
+	      else if (strcmp(name,"Colinear")==0) return ColinearEnum;
+	      else if (strcmp(name,"ConstantsG")==0) return ConstantsGEnum;
+	      else if (strcmp(name,"ConstantsReferencetemperature")==0) return ConstantsReferencetemperatureEnum;
+	      else if (strcmp(name,"Constraints")==0) return ConstraintsEnum;
+	      else if (strcmp(name,"Contact")==0) return ContactEnum;
+	      else if (strcmp(name,"Contour")==0) return ContourEnum;
+	      else if (strcmp(name,"Contours")==0) return ContoursEnum;
+	      else if (strcmp(name,"ControlInput")==0) return ControlInputEnum;
+	      else if (strcmp(name,"ControlInputValues")==0) return ControlInputValuesEnum;
+	      else if (strcmp(name,"ControlInputMins")==0) return ControlInputMinsEnum;
+	      else if (strcmp(name,"ControlInputMaxs")==0) return ControlInputMaxsEnum;
+	      else if (strcmp(name,"ControlInputGrad")==0) return ControlInputGradEnum;
+	      else if (strcmp(name,"CrouzeixRaviart")==0) return CrouzeixRaviartEnum;
+	      else if (strcmp(name,"Cuffey")==0) return CuffeyEnum;
+	      else if (strcmp(name,"CuffeyTemperate")==0) return CuffeyTemperateEnum;
+	      else if (strcmp(name,"DamageEvolutionAnalysis")==0) return DamageEvolutionAnalysisEnum;
+	      else if (strcmp(name,"DamageEvolutionSolution")==0) return DamageEvolutionSolutionEnum;
+	      else if (strcmp(name,"DataSet")==0) return DataSetEnum;
+	      else if (strcmp(name,"DatasetInput")==0) return DatasetInputEnum;
+	      else if (strcmp(name,"DataSetParam")==0) return DataSetParamEnum;
+	      else if (strcmp(name,"DefaultAnalysis")==0) return DefaultAnalysisEnum;
+	      else if (strcmp(name,"DefaultCalving")==0) return DefaultCalvingEnum;
+	      else if (strcmp(name,"DegreeOfChannelization")==0) return DegreeOfChannelizationEnum;
+	      else if (strcmp(name,"Dense")==0) return DenseEnum;
+	      else if (strcmp(name,"DependentObject")==0) return DependentObjectEnum;
+	      else if (strcmp(name,"DepthAverageAnalysis")==0) return DepthAverageAnalysisEnum;
 	      else if (strcmp(name,"DeviatoricStresseffective")==0) return DeviatoricStresseffectiveEnum;
+	      else if (strcmp(name,"DeviatoricStressErrorEstimator")==0) return DeviatoricStressErrorEstimatorEnum;
+	      else if (strcmp(name,"Divergence")==0) return DivergenceEnum;
+	      else if (strcmp(name,"Domain3Dsurface")==0) return Domain3DsurfaceEnum;
+	      else if (strcmp(name,"DoubleArrayInput")==0) return DoubleArrayInputEnum;
+	      else if (strcmp(name,"DoubleExternalResult")==0) return DoubleExternalResultEnum;
+	      else if (strcmp(name,"DoubleInput")==0) return DoubleInputEnum;
+	      else if (strcmp(name,"DoubleMatArrayParam")==0) return DoubleMatArrayParamEnum;
+	      else if (strcmp(name,"DoubleMatExternalResult")==0) return DoubleMatExternalResultEnum;
+	      else if (strcmp(name,"DoubleMatParam")==0) return DoubleMatParamEnum;
+	      else if (strcmp(name,"DoubleParam")==0) return DoubleParamEnum;
+	      else if (strcmp(name,"DoubleVecParam")==0) return DoubleVecParamEnum;
+	      else if (strcmp(name,"EffectivePressureStacked")==0) return EffectivePressureStackedEnum;
+	      else if (strcmp(name,"EffectivePressureTimeAverage")==0) return EffectivePressureTimeAverageEnum;
+	      else if (strcmp(name,"Element")==0) return ElementEnum;
+	      else if (strcmp(name,"ElementHook")==0) return ElementHookEnum;
+	      else if (strcmp(name,"ElementSId")==0) return ElementSIdEnum;
+	      else if (strcmp(name,"EnthalpyAnalysis")==0) return EnthalpyAnalysisEnum;
+	      else if (strcmp(name,"EplHeadStacked")==0) return EplHeadStackedEnum;
+	      else if (strcmp(name,"EplHeadTimeAverage")==0) return EplHeadTimeAverageEnum;
+	      else if (strcmp(name,"EsaAnalysis")==0) return EsaAnalysisEnum;
+	      else if (strcmp(name,"EsaEmotion")==0) return EsaEmotionEnum;
+	      else if (strcmp(name,"EsaNmotion")==0) return EsaNmotionEnum;
+	      else if (strcmp(name,"EsaRotationrate")==0) return EsaRotationrateEnum;
+	      else if (strcmp(name,"EsaSolution")==0) return EsaSolutionEnum;
+	      else if (strcmp(name,"EsaStrainratexx")==0) return EsaStrainratexxEnum;
+	      else if (strcmp(name,"EsaStrainratexy")==0) return EsaStrainratexyEnum;
+	      else if (strcmp(name,"EsaStrainrateyy")==0) return EsaStrainrateyyEnum;
+	      else if (strcmp(name,"EsaTransitions")==0) return EsaTransitionsEnum;
+	      else if (strcmp(name,"EsaUmotion")==0) return EsaUmotionEnum;
+	      else if (strcmp(name,"ExternalResult")==0) return ExternalResultEnum;
+	      else if (strcmp(name,"ExtrapolationAnalysis")==0) return ExtrapolationAnalysisEnum;
+	      else if (strcmp(name,"ExtrudeFromBaseAnalysis")==0) return ExtrudeFromBaseAnalysisEnum;
+	      else if (strcmp(name,"ExtrudeFromTopAnalysis")==0) return ExtrudeFromTopAnalysisEnum;
+	      else if (strcmp(name,"FemModel")==0) return FemModelEnum;
+	      else if (strcmp(name,"FileParam")==0) return FileParamEnum;
+	      else if (strcmp(name,"FixedTimestepping")==0) return FixedTimesteppingEnum;
+	      else if (strcmp(name,"FloatingArea")==0) return FloatingAreaEnum;
+	      else if (strcmp(name,"FloatingAreaScaled")==0) return FloatingAreaScaledEnum;
+	      else if (strcmp(name,"FloatingMeltRate")==0) return FloatingMeltRateEnum;
+	      else if (strcmp(name,"FlowequationBorderFS")==0) return FlowequationBorderFSEnum;
+	      else if (strcmp(name,"Free")==0) return FreeEnum;
+	      else if (strcmp(name,"FreeSurfaceBaseAnalysis")==0) return FreeSurfaceBaseAnalysisEnum;
+	      else if (strcmp(name,"FreeSurfaceTopAnalysis")==0) return FreeSurfaceTopAnalysisEnum;
+	      else if (strcmp(name,"FSApproximation")==0) return FSApproximationEnum;
+	      else if (strcmp(name,"Fset")==0) return FsetEnum;
+	      else if (strcmp(name,"FSpressure")==0) return FSpressureEnum;
+	      else if (strcmp(name,"FSSolver")==0) return FSSolverEnum;
+	      else if (strcmp(name,"FSvelocity")==0) return FSvelocityEnum;
+	      else if (strcmp(name,"GaussPenta")==0) return GaussPentaEnum;
+	      else if (strcmp(name,"GaussSeg")==0) return GaussSegEnum;
+	      else if (strcmp(name,"GaussTetra")==0) return GaussTetraEnum;
+	      else if (strcmp(name,"GaussTria")==0) return GaussTriaEnum;
+	      else if (strcmp(name,"GenericOption")==0) return GenericOptionEnum;
+         else stage=7;
+   }
+   if(stage==7){
+	      if (strcmp(name,"GenericParam")==0) return GenericParamEnum;
+	      else if (strcmp(name,"GiadWdt")==0) return GiadWdtEnum;
+	      else if (strcmp(name,"GiaIvinsAnalysis")==0) return GiaIvinsAnalysisEnum;
+	      else if (strcmp(name,"GiaSolution")==0) return GiaSolutionEnum;
+	      else if (strcmp(name,"GiaW")==0) return GiaWEnum;
+	      else if (strcmp(name,"Gradient1")==0) return Gradient1Enum;
+	      else if (strcmp(name,"Gradient2")==0) return Gradient2Enum;
+	      else if (strcmp(name,"Gradient3")==0) return Gradient3Enum;
+	      else if (strcmp(name,"GroundedArea")==0) return GroundedAreaEnum;
+	      else if (strcmp(name,"GroundedAreaScaled")==0) return GroundedAreaScaledEnum;
+	      else if (strcmp(name,"GroundingOnly")==0) return GroundingOnlyEnum;
+	      else if (strcmp(name,"Gset")==0) return GsetEnum;
+	      else if (strcmp(name,"Gsl")==0) return GslEnum;
+	      else if (strcmp(name,"HOApproximation")==0) return HOApproximationEnum;
+	      else if (strcmp(name,"HOFSApproximation")==0) return HOFSApproximationEnum;
+	      else if (strcmp(name,"Hook")==0) return HookEnum;
+	      else if (strcmp(name,"HydrologyBasalFlux")==0) return HydrologyBasalFluxEnum;
+	      else if (strcmp(name,"HydrologyDCEfficientAnalysis")==0) return HydrologyDCEfficientAnalysisEnum;
+	      else if (strcmp(name,"Hydrologydc")==0) return HydrologydcEnum;
+	      else if (strcmp(name,"HydrologydcEplColapseThickness")==0) return HydrologydcEplColapseThicknessEnum;
+	      else if (strcmp(name,"HydrologydcEplCompressibility")==0) return HydrologydcEplCompressibilityEnum;
+	      else if (strcmp(name,"HydrologydcEplConductivity")==0) return HydrologydcEplConductivityEnum;
+	      else if (strcmp(name,"HydrologydcEplInitialThickness")==0) return HydrologydcEplInitialThicknessEnum;
+	      else if (strcmp(name,"HydrologydcEplMaxThickness")==0) return HydrologydcEplMaxThicknessEnum;
+	      else if (strcmp(name,"HydrologydcEplPorosity")==0) return HydrologydcEplPorosityEnum;
+	      else if (strcmp(name,"HydrologydcEplThicknessStacked")==0) return HydrologydcEplThicknessStackedEnum;
+	      else if (strcmp(name,"HydrologydcEplThicknessTimeAverage")==0) return HydrologydcEplThicknessTimeAverageEnum;
+	      else if (strcmp(name,"HydrologyDCInefficientAnalysis")==0) return HydrologyDCInefficientAnalysisEnum;
+	      else if (strcmp(name,"HydrologydcSedimentCompressibility")==0) return HydrologydcSedimentCompressibilityEnum;
+	      else if (strcmp(name,"HydrologydcSedimentPorosity")==0) return HydrologydcSedimentPorosityEnum;
+	      else if (strcmp(name,"HydrologydcSedimentThickness")==0) return HydrologydcSedimentThicknessEnum;
+	      else if (strcmp(name,"HydrologydcWaterCompressibility")==0) return HydrologydcWaterCompressibilityEnum;
+	      else if (strcmp(name,"HydrologyShreveAnalysis")==0) return HydrologyShreveAnalysisEnum;
+	      else if (strcmp(name,"Hydrologyshreve")==0) return HydrologyshreveEnum;
+	      else if (strcmp(name,"HydrologySolution")==0) return HydrologySolutionEnum;
+	      else if (strcmp(name,"HydrologySommersAnalysis")==0) return HydrologySommersAnalysisEnum;
+	      else if (strcmp(name,"Hydrologysommers")==0) return HydrologysommersEnum;
+	      else if (strcmp(name,"IceMass")==0) return IceMassEnum;
+	      else if (strcmp(name,"IceMassScaled")==0) return IceMassScaledEnum;
+	      else if (strcmp(name,"IceVolumeAboveFloatation")==0) return IceVolumeAboveFloatationEnum;
+	      else if (strcmp(name,"IceVolumeAboveFloatationScaled")==0) return IceVolumeAboveFloatationScaledEnum;
+	      else if (strcmp(name,"IceVolume")==0) return IceVolumeEnum;
+	      else if (strcmp(name,"IceVolumeScaled")==0) return IceVolumeScaledEnum;
+	      else if (strcmp(name,"Incremental")==0) return IncrementalEnum;
+	      else if (strcmp(name,"Indexed")==0) return IndexedEnum;
+	      else if (strcmp(name,"Internal")==0) return InternalEnum;
+	      else if (strcmp(name,"Intersect")==0) return IntersectEnum;
+	      else if (strcmp(name,"IntExternalResult")==0) return IntExternalResultEnum;
+	      else if (strcmp(name,"IntInput")==0) return IntInputEnum;
+	      else if (strcmp(name,"IntMatExternalResult")==0) return IntMatExternalResultEnum;
+	      else if (strcmp(name,"IntMatParam")==0) return IntMatParamEnum;
+	      else if (strcmp(name,"IntParam")==0) return IntParamEnum;
+	      else if (strcmp(name,"IntVecParam")==0) return IntVecParamEnum;
+	      else if (strcmp(name,"InversionVzObs")==0) return InversionVzObsEnum;
+	      else if (strcmp(name,"J")==0) return JEnum;
+	      else if (strcmp(name,"L1L2Approximation")==0) return L1L2ApproximationEnum;
+	      else if (strcmp(name,"L2ProjectionBaseAnalysis")==0) return L2ProjectionBaseAnalysisEnum;
+	      else if (strcmp(name,"L2ProjectionEPLAnalysis")==0) return L2ProjectionEPLAnalysisEnum;
+	      else if (strcmp(name,"LACrouzeixRaviart")==0) return LACrouzeixRaviartEnum;
 	      else if (strcmp(name,"LambdaS")==0) return LambdaSEnum;
-	      else if (strcmp(name,"StrainRate")==0) return StrainRateEnum;
-	      else if (strcmp(name,"StrainRatexx")==0) return StrainRatexxEnum;
-	      else if (strcmp(name,"StrainRatexy")==0) return StrainRatexyEnum;
-	      else if (strcmp(name,"StrainRatexz")==0) return StrainRatexzEnum;
-	      else if (strcmp(name,"StrainRateyy")==0) return StrainRateyyEnum;
-	      else if (strcmp(name,"StrainRateyz")==0) return StrainRateyzEnum;
-	      else if (strcmp(name,"StrainRatezz")==0) return StrainRatezzEnum;
-	      else if (strcmp(name,"Divergence")==0) return DivergenceEnum;
+	      else if (strcmp(name,"LATaylorHood")==0) return LATaylorHoodEnum;
+	      else if (strcmp(name,"LevelsetAnalysis")==0) return LevelsetAnalysisEnum;
+	      else if (strcmp(name,"LevelsetfunctionPicard")==0) return LevelsetfunctionPicardEnum;
+	      else if (strcmp(name,"LinearFloatingMeltRate")==0) return LinearFloatingMeltRateEnum;
+	      else if (strcmp(name,"LliboutryDuval")==0) return LliboutryDuvalEnum;
+	      else if (strcmp(name,"Loads")==0) return LoadsEnum;
+	      else if (strcmp(name,"LoveAnalysis")==0) return LoveAnalysisEnum;
+	      else if (strcmp(name,"LoveHi")==0) return LoveHiEnum;
+	      else if (strcmp(name,"LoveHr")==0) return LoveHrEnum;
+	      else if (strcmp(name,"LoveKernelsImag")==0) return LoveKernelsImagEnum;
+	      else if (strcmp(name,"LoveKernelsReal")==0) return LoveKernelsRealEnum;
+	      else if (strcmp(name,"LoveKi")==0) return LoveKiEnum;
+	      else if (strcmp(name,"LoveKr")==0) return LoveKrEnum;
+	      else if (strcmp(name,"LoveLi")==0) return LoveLiEnum;
+	      else if (strcmp(name,"LoveLr")==0) return LoveLrEnum;
+	      else if (strcmp(name,"LoveSolution")==0) return LoveSolutionEnum;
+	      else if (strcmp(name,"MantlePlumeGeothermalFlux")==0) return MantlePlumeGeothermalFluxEnum;
+	      else if (strcmp(name,"MaskLandLevelset")==0) return MaskLandLevelsetEnum;
+	      else if (strcmp(name,"MaskOceanLevelset")==0) return MaskOceanLevelsetEnum;
+	      else if (strcmp(name,"Massconaxpby")==0) return MassconaxpbyEnum;
+	      else if (strcmp(name,"Masscon")==0) return MassconEnum;
+	      else if (strcmp(name,"Massfluxatgate")==0) return MassfluxatgateEnum;
+	      else if (strcmp(name,"MassFlux")==0) return MassFluxEnum;
+	      else if (strcmp(name,"MasstransportAnalysis")==0) return MasstransportAnalysisEnum;
+	      else if (strcmp(name,"MasstransportSolution")==0) return MasstransportSolutionEnum;
+	      else if (strcmp(name,"Matdamageice")==0) return MatdamageiceEnum;
+	      else if (strcmp(name,"Matenhancedice")==0) return MatenhancediceEnum;
+	      else if (strcmp(name,"MaterialsBeta")==0) return MaterialsBetaEnum;
+	      else if (strcmp(name,"MaterialsEarthDensity")==0) return MaterialsEarthDensityEnum;
+	      else if (strcmp(name,"Materials")==0) return MaterialsEnum;
+	      else if (strcmp(name,"MaterialsHeatcapacity")==0) return MaterialsHeatcapacityEnum;
+	      else if (strcmp(name,"MaterialsLatentheat")==0) return MaterialsLatentheatEnum;
+	      else if (strcmp(name,"MaterialsLithosphereDensity")==0) return MaterialsLithosphereDensityEnum;
+	      else if (strcmp(name,"MaterialsLithosphereShearModulus")==0) return MaterialsLithosphereShearModulusEnum;
+	      else if (strcmp(name,"MaterialsMantleDensity")==0) return MaterialsMantleDensityEnum;
+	      else if (strcmp(name,"MaterialsMantleShearModulus")==0) return MaterialsMantleShearModulusEnum;
+	      else if (strcmp(name,"MaterialsMeltingpoint")==0) return MaterialsMeltingpointEnum;
+	      else if (strcmp(name,"MaterialsMixedLayerCapacity")==0) return MaterialsMixedLayerCapacityEnum;
+	      else if (strcmp(name,"MaterialsMuWater")==0) return MaterialsMuWaterEnum;
+	      else if (strcmp(name,"MaterialsRheologyLaw")==0) return MaterialsRheologyLawEnum;
+	      else if (strcmp(name,"MaterialsRhoFreshwater")==0) return MaterialsRhoFreshwaterEnum;
+	      else if (strcmp(name,"MaterialsRhoIce")==0) return MaterialsRhoIceEnum;
+	      else if (strcmp(name,"MaterialsRhoSeawater")==0) return MaterialsRhoSeawaterEnum;
+	      else if (strcmp(name,"MaterialsTemperateiceconductivity")==0) return MaterialsTemperateiceconductivityEnum;
+	      else if (strcmp(name,"MaterialsThermalconductivity")==0) return MaterialsThermalconductivityEnum;
+	      else if (strcmp(name,"MaterialsThermalExchangeVelocity")==0) return MaterialsThermalExchangeVelocityEnum;
+	      else if (strcmp(name,"Matestar")==0) return MatestarEnum;
+	      else if (strcmp(name,"Matice")==0) return MaticeEnum;
+	      else if (strcmp(name,"Matlitho")==0) return MatlithoEnum;
+	      else if (strcmp(name,"Matpar")==0) return MatparEnum;
+	      else if (strcmp(name,"MatrixParam")==0) return MatrixParamEnum;
+	      else if (strcmp(name,"MaxAbsVx")==0) return MaxAbsVxEnum;
+	      else if (strcmp(name,"MaxAbsVy")==0) return MaxAbsVyEnum;
+	      else if (strcmp(name,"MaxAbsVz")==0) return MaxAbsVzEnum;
 	      else if (strcmp(name,"MaxDivergence")==0) return MaxDivergenceEnum;
-	      else if (strcmp(name,"GiaCrossSectionShape")==0) return GiaCrossSectionShapeEnum;
-	      else if (strcmp(name,"GiadWdt")==0) return GiadWdtEnum;
-	      else if (strcmp(name,"GiaW")==0) return GiaWEnum;
-	      else if (strcmp(name,"SaveResults")==0) return SaveResultsEnum;
-	      else if (strcmp(name,"BoolExternalResult")==0) return BoolExternalResultEnum;
-	      else if (strcmp(name,"DoubleExternalResult")==0) return DoubleExternalResultEnum;
-	      else if (strcmp(name,"DoubleMatExternalResult")==0) return DoubleMatExternalResultEnum;
-	      else if (strcmp(name,"IntExternalResult")==0) return IntExternalResultEnum;
-	      else if (strcmp(name,"IntMatExternalResult")==0) return IntMatExternalResultEnum;
-	      else if (strcmp(name,"J")==0) return JEnum;
-	      else if (strcmp(name,"StringExternalResult")==0) return StringExternalResultEnum;
-	      else if (strcmp(name,"Step")==0) return StepEnum;
-	      else if (strcmp(name,"Time")==0) return TimeEnum;
-	      else if (strcmp(name,"WaterColumnOld")==0) return WaterColumnOldEnum;
-	      else if (strcmp(name,"SurfaceObservation")==0) return SurfaceObservationEnum;
-	      else if (strcmp(name,"WeightsSurfaceObservation")==0) return WeightsSurfaceObservationEnum;
-	      else if (strcmp(name,"Outputdefinition")==0) return OutputdefinitionEnum;
+	      else if (strcmp(name,"MaxVel")==0) return MaxVelEnum;
+	      else if (strcmp(name,"MaxVx")==0) return MaxVxEnum;
+	      else if (strcmp(name,"MaxVy")==0) return MaxVyEnum;
+	      else if (strcmp(name,"MaxVz")==0) return MaxVzEnum;
+	      else if (strcmp(name,"Melange")==0) return MelangeEnum;
+         else stage=8;
+   }
+   if(stage==8){
+	      if (strcmp(name,"MeltingAnalysis")==0) return MeltingAnalysisEnum;
+	      else if (strcmp(name,"MeshElements")==0) return MeshElementsEnum;
+	      else if (strcmp(name,"MeshLat")==0) return MeshLatEnum;
+	      else if (strcmp(name,"MeshLong")==0) return MeshLongEnum;
+	      else if (strcmp(name,"MeshX")==0) return MeshXEnum;
+	      else if (strcmp(name,"MeshY")==0) return MeshYEnum;
+	      else if (strcmp(name,"MINIcondensed")==0) return MINIcondensedEnum;
+	      else if (strcmp(name,"MINI")==0) return MINIEnum;
+	      else if (strcmp(name,"MinVel")==0) return MinVelEnum;
+	      else if (strcmp(name,"MinVx")==0) return MinVxEnum;
+	      else if (strcmp(name,"MinVy")==0) return MinVyEnum;
+	      else if (strcmp(name,"MinVz")==0) return MinVzEnum;
+	      else if (strcmp(name,"MismipFloatingMeltRate")==0) return MismipFloatingMeltRateEnum;
+	      else if (strcmp(name,"Moulin")==0) return MoulinEnum;
+	      else if (strcmp(name,"MpiDense")==0) return MpiDenseEnum;
+	      else if (strcmp(name,"Mpi")==0) return MpiEnum;
+	      else if (strcmp(name,"MpiSparse")==0) return MpiSparseEnum;
+	      else if (strcmp(name,"Mumps")==0) return MumpsEnum;
+	      else if (strcmp(name,"NewDamage")==0) return NewDamageEnum;
+	      else if (strcmp(name,"Nodal")==0) return NodalEnum;
+	      else if (strcmp(name,"Nodalvalue")==0) return NodalvalueEnum;
+	      else if (strcmp(name,"NodeSId")==0) return NodeSIdEnum;
+	      else if (strcmp(name,"NoneApproximation")==0) return NoneApproximationEnum;
+	      else if (strcmp(name,"None")==0) return NoneEnum;
+	      else if (strcmp(name,"Numberedcostfunction")==0) return NumberedcostfunctionEnum;
+	      else if (strcmp(name,"Numericalflux")==0) return NumericalfluxEnum;
+	      else if (strcmp(name,"OldGradient")==0) return OldGradientEnum;
+	      else if (strcmp(name,"OneLayerP4z")==0) return OneLayerP4zEnum;
+	      else if (strcmp(name,"Open")==0) return OpenEnum;
+	      else if (strcmp(name,"Option")==0) return OptionEnum;
 	      else if (strcmp(name,"Outputdefinition1")==0) return Outputdefinition1Enum;
-	      else if (strcmp(name,"Outputdefinition2")==0) return Outputdefinition2Enum;
-	      else if (strcmp(name,"Outputdefinition3")==0) return Outputdefinition3Enum;
-	      else if (strcmp(name,"Outputdefinition4")==0) return Outputdefinition4Enum;
-	      else if (strcmp(name,"Outputdefinition5")==0) return Outputdefinition5Enum;
-	      else if (strcmp(name,"Outputdefinition6")==0) return Outputdefinition6Enum;
-	      else if (strcmp(name,"Outputdefinition7")==0) return Outputdefinition7Enum;
-	      else if (strcmp(name,"Outputdefinition8")==0) return Outputdefinition8Enum;
-	      else if (strcmp(name,"Outputdefinition9")==0) return Outputdefinition9Enum;
 	      else if (strcmp(name,"Outputdefinition10")==0) return Outputdefinition10Enum;
 	      else if (strcmp(name,"Outputdefinition11")==0) return Outputdefinition11Enum;
@@ -629,8 +928,6 @@
 	      else if (strcmp(name,"Outputdefinition27")==0) return Outputdefinition27Enum;
 	      else if (strcmp(name,"Outputdefinition28")==0) return Outputdefinition28Enum;
-         else stage=6;
-   }
-   if(stage==6){
-	      if (strcmp(name,"Outputdefinition29")==0) return Outputdefinition29Enum;
+	      else if (strcmp(name,"Outputdefinition29")==0) return Outputdefinition29Enum;
+	      else if (strcmp(name,"Outputdefinition2")==0) return Outputdefinition2Enum;
 	      else if (strcmp(name,"Outputdefinition30")==0) return Outputdefinition30Enum;
 	      else if (strcmp(name,"Outputdefinition31")==0) return Outputdefinition31Enum;
@@ -643,4 +940,5 @@
 	      else if (strcmp(name,"Outputdefinition38")==0) return Outputdefinition38Enum;
 	      else if (strcmp(name,"Outputdefinition39")==0) return Outputdefinition39Enum;
+	      else if (strcmp(name,"Outputdefinition3")==0) return Outputdefinition3Enum;
 	      else if (strcmp(name,"Outputdefinition40")==0) return Outputdefinition40Enum;
 	      else if (strcmp(name,"Outputdefinition41")==0) return Outputdefinition41Enum;
@@ -653,4 +951,5 @@
 	      else if (strcmp(name,"Outputdefinition48")==0) return Outputdefinition48Enum;
 	      else if (strcmp(name,"Outputdefinition49")==0) return Outputdefinition49Enum;
+	      else if (strcmp(name,"Outputdefinition4")==0) return Outputdefinition4Enum;
 	      else if (strcmp(name,"Outputdefinition50")==0) return Outputdefinition50Enum;
 	      else if (strcmp(name,"Outputdefinition51")==0) return Outputdefinition51Enum;
@@ -663,4 +962,5 @@
 	      else if (strcmp(name,"Outputdefinition58")==0) return Outputdefinition58Enum;
 	      else if (strcmp(name,"Outputdefinition59")==0) return Outputdefinition59Enum;
+	      else if (strcmp(name,"Outputdefinition5")==0) return Outputdefinition5Enum;
 	      else if (strcmp(name,"Outputdefinition60")==0) return Outputdefinition60Enum;
 	      else if (strcmp(name,"Outputdefinition61")==0) return Outputdefinition61Enum;
@@ -673,4 +973,5 @@
 	      else if (strcmp(name,"Outputdefinition68")==0) return Outputdefinition68Enum;
 	      else if (strcmp(name,"Outputdefinition69")==0) return Outputdefinition69Enum;
+	      else if (strcmp(name,"Outputdefinition6")==0) return Outputdefinition6Enum;
 	      else if (strcmp(name,"Outputdefinition70")==0) return Outputdefinition70Enum;
 	      else if (strcmp(name,"Outputdefinition71")==0) return Outputdefinition71Enum;
@@ -683,4 +984,5 @@
 	      else if (strcmp(name,"Outputdefinition78")==0) return Outputdefinition78Enum;
 	      else if (strcmp(name,"Outputdefinition79")==0) return Outputdefinition79Enum;
+	      else if (strcmp(name,"Outputdefinition7")==0) return Outputdefinition7Enum;
 	      else if (strcmp(name,"Outputdefinition80")==0) return Outputdefinition80Enum;
 	      else if (strcmp(name,"Outputdefinition81")==0) return Outputdefinition81Enum;
@@ -693,7 +995,11 @@
 	      else if (strcmp(name,"Outputdefinition88")==0) return Outputdefinition88Enum;
 	      else if (strcmp(name,"Outputdefinition89")==0) return Outputdefinition89Enum;
+	      else if (strcmp(name,"Outputdefinition8")==0) return Outputdefinition8Enum;
 	      else if (strcmp(name,"Outputdefinition90")==0) return Outputdefinition90Enum;
 	      else if (strcmp(name,"Outputdefinition91")==0) return Outputdefinition91Enum;
-	      else if (strcmp(name,"Outputdefinition92")==0) return Outputdefinition92Enum;
+         else stage=9;
+   }
+   if(stage==9){
+	      if (strcmp(name,"Outputdefinition92")==0) return Outputdefinition92Enum;
 	      else if (strcmp(name,"Outputdefinition93")==0) return Outputdefinition93Enum;
 	      else if (strcmp(name,"Outputdefinition94")==0) return Outputdefinition94Enum;
@@ -703,327 +1009,151 @@
 	      else if (strcmp(name,"Outputdefinition98")==0) return Outputdefinition98Enum;
 	      else if (strcmp(name,"Outputdefinition99")==0) return Outputdefinition99Enum;
+	      else if (strcmp(name,"Outputdefinition9")==0) return Outputdefinition9Enum;
 	      else if (strcmp(name,"Outputdefinition100")==0) return Outputdefinition100Enum;
-	      else if (strcmp(name,"OutputdefinitionList")==0) return OutputdefinitionListEnum;
-	      else if (strcmp(name,"Massfluxatgate")==0) return MassfluxatgateEnum;
-	      else if (strcmp(name,"Nodalvalue")==0) return NodalvalueEnum;
-	      else if (strcmp(name,"VxObs")==0) return VxObsEnum;
-	      else if (strcmp(name,"VyObs")==0) return VyObsEnum;
-	      else if (strcmp(name,"Absolute")==0) return AbsoluteEnum;
-	      else if (strcmp(name,"Incremental")==0) return IncrementalEnum;
-	      else if (strcmp(name,"AugmentedLagrangianR")==0) return AugmentedLagrangianREnum;
-	      else if (strcmp(name,"AugmentedLagrangianRhop")==0) return AugmentedLagrangianRhopEnum;
-	      else if (strcmp(name,"AugmentedLagrangianRlambda")==0) return AugmentedLagrangianRlambdaEnum;
-	      else if (strcmp(name,"AugmentedLagrangianRholambda")==0) return AugmentedLagrangianRholambdaEnum;
-	      else if (strcmp(name,"AugmentedLagrangianTheta")==0) return AugmentedLagrangianThetaEnum;
-	      else if (strcmp(name,"None")==0) return NoneEnum;
-	      else if (strcmp(name,"AggressiveMigration")==0) return AggressiveMigrationEnum;
-	      else if (strcmp(name,"SoftMigration")==0) return SoftMigrationEnum;
-	      else if (strcmp(name,"SubelementMigration")==0) return SubelementMigrationEnum;
-	      else if (strcmp(name,"SubelementMigration2")==0) return SubelementMigration2Enum;
-	      else if (strcmp(name,"Contact")==0) return ContactEnum;
-	      else if (strcmp(name,"GroundingOnly")==0) return GroundingOnlyEnum;
-	      else if (strcmp(name,"MaskGroundediceLevelset")==0) return MaskGroundediceLevelsetEnum;
-	      else if (strcmp(name,"Adjoint")==0) return AdjointEnum;
-	      else if (strcmp(name,"Colinear")==0) return ColinearEnum;
-	      else if (strcmp(name,"ControlSteady")==0) return ControlSteadyEnum;
-	      else if (strcmp(name,"Fset")==0) return FsetEnum;
-	      else if (strcmp(name,"Gradient1")==0) return Gradient1Enum;
-	      else if (strcmp(name,"Gradient2")==0) return Gradient2Enum;
-	      else if (strcmp(name,"Gradient3")==0) return Gradient3Enum;
-	      else if (strcmp(name,"Gradient")==0) return GradientEnum;
-	      else if (strcmp(name,"GroundinglineMigration")==0) return GroundinglineMigrationEnum;
-	      else if (strcmp(name,"Gset")==0) return GsetEnum;
-	      else if (strcmp(name,"Index")==0) return IndexEnum;
-	      else if (strcmp(name,"Indexed")==0) return IndexedEnum;
-	      else if (strcmp(name,"Intersect")==0) return IntersectEnum;
-	      else if (strcmp(name,"Nodal")==0) return NodalEnum;
-	      else if (strcmp(name,"OldGradient")==0) return OldGradientEnum;
-	      else if (strcmp(name,"OutputBufferPointer")==0) return OutputBufferPointerEnum;
-	      else if (strcmp(name,"OutputBufferSizePointer")==0) return OutputBufferSizePointerEnum;
-	      else if (strcmp(name,"OutputFilePointer")==0) return OutputFilePointerEnum;
-	      else if (strcmp(name,"ToolkitsFileName")==0) return ToolkitsFileNameEnum;
-	      else if (strcmp(name,"RootPath")==0) return RootPathEnum;
-	      else if (strcmp(name,"OutputFileName")==0) return OutputFileNameEnum;
-	      else if (strcmp(name,"InputFileName")==0) return InputFileNameEnum;
-	      else if (strcmp(name,"LockFileName")==0) return LockFileNameEnum;
-	      else if (strcmp(name,"RestartFileName")==0) return RestartFileNameEnum;
-	      else if (strcmp(name,"ToolkitsOptionsAnalyses")==0) return ToolkitsOptionsAnalysesEnum;
-	      else if (strcmp(name,"ToolkitsOptionsStrings")==0) return ToolkitsOptionsStringsEnum;
-	      else if (strcmp(name,"QmuErrName")==0) return QmuErrNameEnum;
-	      else if (strcmp(name,"QmuInName")==0) return QmuInNameEnum;
-         else stage=7;
-   }
-   if(stage==7){
-	      if (strcmp(name,"QmuOutName")==0) return QmuOutNameEnum;
-	      else if (strcmp(name,"Regular")==0) return RegularEnum;
-	      else if (strcmp(name,"Scaled")==0) return ScaledEnum;
-	      else if (strcmp(name,"Separate")==0) return SeparateEnum;
-	      else if (strcmp(name,"Sset")==0) return SsetEnum;
-	      else if (strcmp(name,"Dense")==0) return DenseEnum;
-	      else if (strcmp(name,"MpiDense")==0) return MpiDenseEnum;
-	      else if (strcmp(name,"MpiSparse")==0) return MpiSparseEnum;
-	      else if (strcmp(name,"Seq")==0) return SeqEnum;
-	      else if (strcmp(name,"Mpi")==0) return MpiEnum;
-	      else if (strcmp(name,"Mumps")==0) return MumpsEnum;
-	      else if (strcmp(name,"Gsl")==0) return GslEnum;
-	      else if (strcmp(name,"Cuffey")==0) return CuffeyEnum;
-	      else if (strcmp(name,"BuddJacka")==0) return BuddJackaEnum;
-	      else if (strcmp(name,"CuffeyTemperate")==0) return CuffeyTemperateEnum;
+	      else if (strcmp(name,"P0Array")==0) return P0ArrayEnum;
+	      else if (strcmp(name,"P1bubblecondensed")==0) return P1bubblecondensedEnum;
+	      else if (strcmp(name,"P1bubble")==0) return P1bubbleEnum;
+	      else if (strcmp(name,"P1DG")==0) return P1DGEnum;
+	      else if (strcmp(name,"P1P1")==0) return P1P1Enum;
+	      else if (strcmp(name,"P1P1GLS")==0) return P1P1GLSEnum;
+	      else if (strcmp(name,"P1xP2")==0) return P1xP2Enum;
+	      else if (strcmp(name,"P1xP3")==0) return P1xP3Enum;
+	      else if (strcmp(name,"P1xP4")==0) return P1xP4Enum;
+	      else if (strcmp(name,"P2bubblecondensed")==0) return P2bubblecondensedEnum;
+	      else if (strcmp(name,"P2bubble")==0) return P2bubbleEnum;
+	      else if (strcmp(name,"P2")==0) return P2Enum;
+	      else if (strcmp(name,"P2xP1")==0) return P2xP1Enum;
+	      else if (strcmp(name,"P2xP4")==0) return P2xP4Enum;
 	      else if (strcmp(name,"Paterson")==0) return PatersonEnum;
-	      else if (strcmp(name,"Arrhenius")==0) return ArrheniusEnum;
-	      else if (strcmp(name,"LliboutryDuval")==0) return LliboutryDuvalEnum;
-	      else if (strcmp(name,"ExtrapolationVariable")==0) return ExtrapolationVariableEnum;
-	      else if (strcmp(name,"IceMaskNodeActivation")==0) return IceMaskNodeActivationEnum;
-	      else if (strcmp(name,"LevelsetfunctionSlopeX")==0) return LevelsetfunctionSlopeXEnum;
-	      else if (strcmp(name,"LevelsetfunctionSlopeY")==0) return LevelsetfunctionSlopeYEnum;
-	      else if (strcmp(name,"LevelsetfunctionPicard")==0) return LevelsetfunctionPicardEnum;
-	      else if (strcmp(name,"LevelsetReinitFrequency")==0) return LevelsetReinitFrequencyEnum;
-	      else if (strcmp(name,"Sealevel")==0) return SealevelEnum;
-	      else if (strcmp(name,"SealevelUmotion")==0) return SealevelUmotionEnum;
-	      else if (strcmp(name,"SealevelNmotion")==0) return SealevelNmotionEnum;
-	      else if (strcmp(name,"SealevelEmotion")==0) return SealevelEmotionEnum;
-	      else if (strcmp(name,"SealevelAbsolute")==0) return SealevelAbsoluteEnum;
-	      else if (strcmp(name,"SealevelEustatic")==0) return SealevelEustaticEnum;
-	      else if (strcmp(name,"SealevelriseDeltathickness")==0) return SealevelriseDeltathicknessEnum;
-	      else if (strcmp(name,"SealevelriseMaxiter")==0) return SealevelriseMaxiterEnum;
-	      else if (strcmp(name,"SealevelriseReltol")==0) return SealevelriseReltolEnum;
-	      else if (strcmp(name,"SealevelriseAbstol")==0) return SealevelriseAbstolEnum;
-	      else if (strcmp(name,"SealevelriseRigid")==0) return SealevelriseRigidEnum;
-	      else if (strcmp(name,"SealevelriseElastic")==0) return SealevelriseElasticEnum;
-	      else if (strcmp(name,"SealevelriseRotation")==0) return SealevelriseRotationEnum;
-	      else if (strcmp(name,"SealevelriseTidalLoveH")==0) return SealevelriseTidalLoveHEnum;
-	      else if (strcmp(name,"SealevelriseTidalLoveK")==0) return SealevelriseTidalLoveKEnum;
-	      else if (strcmp(name,"SealevelriseFluidLove")==0) return SealevelriseFluidLoveEnum;
-	      else if (strcmp(name,"SealevelriseEquatorialMoi")==0) return SealevelriseEquatorialMoiEnum;
-	      else if (strcmp(name,"SealevelrisePolarMoi")==0) return SealevelrisePolarMoiEnum;
-	      else if (strcmp(name,"SealevelriseAngularVelocity")==0) return SealevelriseAngularVelocityEnum;
-	      else if (strcmp(name,"SealevelriseOceanAreaScaling")==0) return SealevelriseOceanAreaScalingEnum;
-	      else if (strcmp(name,"SealevelriseGElastic")==0) return SealevelriseGElasticEnum;
-	      else if (strcmp(name,"SealevelriseUElastic")==0) return SealevelriseUElasticEnum;
-	      else if (strcmp(name,"SealevelriseHElastic")==0) return SealevelriseHElasticEnum;
-	      else if (strcmp(name,"SealevelriseTransitions")==0) return SealevelriseTransitionsEnum;
-	      else if (strcmp(name,"SealevelriseRequestedOutputs")==0) return SealevelriseRequestedOutputsEnum;
-	      else if (strcmp(name,"SealevelriseNumRequestedOutputs")==0) return SealevelriseNumRequestedOutputsEnum;
-	      else if (strcmp(name,"EsaUmotion")==0) return EsaUmotionEnum;
-	      else if (strcmp(name,"EsaNmotion")==0) return EsaNmotionEnum;
-	      else if (strcmp(name,"EsaEmotion")==0) return EsaEmotionEnum;
-	      else if (strcmp(name,"EsaStrainratexx")==0) return EsaStrainratexxEnum;
-	      else if (strcmp(name,"EsaStrainratexy")==0) return EsaStrainratexyEnum;
-	      else if (strcmp(name,"EsaStrainrateyy")==0) return EsaStrainrateyyEnum;
-	      else if (strcmp(name,"EsaRotationrate")==0) return EsaRotationrateEnum;
-	      else if (strcmp(name,"EsaDeltathickness")==0) return EsaDeltathicknessEnum;
-	      else if (strcmp(name,"EsaUElastic")==0) return EsaUElasticEnum;
-	      else if (strcmp(name,"EsaHElastic")==0) return EsaHElasticEnum;
-	      else if (strcmp(name,"EsaTransitions")==0) return EsaTransitionsEnum;
-	      else if (strcmp(name,"EsaRequestedOutputs")==0) return EsaRequestedOutputsEnum;
-	      else if (strcmp(name,"EsaNumRequestedOutputs")==0) return EsaNumRequestedOutputsEnum;
-	      else if (strcmp(name,"AmrLevelMax")==0) return AmrLevelMaxEnum;
-	      else if (strcmp(name,"AmrRegionLevel1")==0) return AmrRegionLevel1Enum;
-	      else if (strcmp(name,"AmrRegionLevelMax")==0) return AmrRegionLevelMaxEnum;
-	      else if (strcmp(name,"TransientAmrFrequency")==0) return TransientAmrFrequencyEnum;
-	      else if (strcmp(name,"ParametersEND")==0) return ParametersENDEnum;
-	      else if (strcmp(name,"XY")==0) return XYEnum;
-	      else if (strcmp(name,"XYZ")==0) return XYZEnum;
-	      else if (strcmp(name,"GenericParam")==0) return GenericParamEnum;
-	      else if (strcmp(name,"BoolInput")==0) return BoolInputEnum;
-	      else if (strcmp(name,"BoolParam")==0) return BoolParamEnum;
-	      else if (strcmp(name,"Contour")==0) return ContourEnum;
-	      else if (strcmp(name,"ControlInput")==0) return ControlInputEnum;
-	      else if (strcmp(name,"DatasetInput")==0) return DatasetInputEnum;
-	      else if (strcmp(name,"DoubleInput")==0) return DoubleInputEnum;
-	      else if (strcmp(name,"DoubleArrayInput")==0) return DoubleArrayInputEnum;
-	      else if (strcmp(name,"DataSetParam")==0) return DataSetParamEnum;
-	      else if (strcmp(name,"DoubleMatArrayParam")==0) return DoubleMatArrayParamEnum;
-	      else if (strcmp(name,"DoubleMatParam")==0) return DoubleMatParamEnum;
-	      else if (strcmp(name,"DoubleParam")==0) return DoubleParamEnum;
-	      else if (strcmp(name,"DoubleVecParam")==0) return DoubleVecParamEnum;
-	      else if (strcmp(name,"Element")==0) return ElementEnum;
-	      else if (strcmp(name,"ElementHook")==0) return ElementHookEnum;
-	      else if (strcmp(name,"Hook")==0) return HookEnum;
-	      else if (strcmp(name,"ExternalResult")==0) return ExternalResultEnum;
-	      else if (strcmp(name,"FileParam")==0) return FileParamEnum;
-	      else if (strcmp(name,"Input")==0) return InputEnum;
-	      else if (strcmp(name,"IntInput")==0) return IntInputEnum;
-	      else if (strcmp(name,"IntParam")==0) return IntParamEnum;
-	      else if (strcmp(name,"IntVecParam")==0) return IntVecParamEnum;
-	      else if (strcmp(name,"TransientParam")==0) return TransientParamEnum;
-	      else if (strcmp(name,"Matice")==0) return MaticeEnum;
-	      else if (strcmp(name,"Matdamageice")==0) return MatdamageiceEnum;
-	      else if (strcmp(name,"Matenhancedice")==0) return MatenhancediceEnum;
-	      else if (strcmp(name,"Matestar")==0) return MatestarEnum;
-	      else if (strcmp(name,"Matpar")==0) return MatparEnum;
-	      else if (strcmp(name,"Node")==0) return NodeEnum;
-	      else if (strcmp(name,"Numericalflux")==0) return NumericalfluxEnum;
-	      else if (strcmp(name,"Neumannflux")==0) return NeumannfluxEnum;
-	      else if (strcmp(name,"Param")==0) return ParamEnum;
-	      else if (strcmp(name,"Moulin")==0) return MoulinEnum;
 	      else if (strcmp(name,"Pengrid")==0) return PengridEnum;
 	      else if (strcmp(name,"Penpair")==0) return PenpairEnum;
+	      else if (strcmp(name,"Penta")==0) return PentaEnum;
+	      else if (strcmp(name,"PentaInput")==0) return PentaInputEnum;
 	      else if (strcmp(name,"Profiler")==0) return ProfilerEnum;
-	      else if (strcmp(name,"MatrixParam")==0) return MatrixParamEnum;
-	      else if (strcmp(name,"Masscon")==0) return MassconEnum;
-	      else if (strcmp(name,"Massconaxpby")==0) return MassconaxpbyEnum;
-	      else if (strcmp(name,"NodeSId")==0) return NodeSIdEnum;
-	      else if (strcmp(name,"ElementSId")==0) return ElementSIdEnum;
-	      else if (strcmp(name,"VectorParam")==0) return VectorParamEnum;
+	      else if (strcmp(name,"ProfilingCurrentFlops")==0) return ProfilingCurrentFlopsEnum;
+	      else if (strcmp(name,"ProfilingCurrentMem")==0) return ProfilingCurrentMemEnum;
+	      else if (strcmp(name,"ProfilingSolutionTime")==0) return ProfilingSolutionTimeEnum;
+	      else if (strcmp(name,"Regionaloutput")==0) return RegionaloutputEnum;
+	      else if (strcmp(name,"Regular")==0) return RegularEnum;
+	      else if (strcmp(name,"ResetPenalties")==0) return ResetPenaltiesEnum;
 	      else if (strcmp(name,"Riftfront")==0) return RiftfrontEnum;
+	      else if (strcmp(name,"Scaled")==0) return ScaledEnum;
+	      else if (strcmp(name,"SealevelAbsolute")==0) return SealevelAbsoluteEnum;
+	      else if (strcmp(name,"SealevelEmotion")==0) return SealevelEmotionEnum;
+	      else if (strcmp(name,"SealevelEustatic")==0) return SealevelEustaticEnum;
+	      else if (strcmp(name,"SealevelInertiaTensorXZ")==0) return SealevelInertiaTensorXZEnum;
+	      else if (strcmp(name,"SealevelInertiaTensorYZ")==0) return SealevelInertiaTensorYZEnum;
+	      else if (strcmp(name,"SealevelInertiaTensorZZ")==0) return SealevelInertiaTensorZZEnum;
+	      else if (strcmp(name,"SealevelNmotion")==0) return SealevelNmotionEnum;
+	      else if (strcmp(name,"SealevelriseAnalysis")==0) return SealevelriseAnalysisEnum;
+	      else if (strcmp(name,"SealevelriseSolution")==0) return SealevelriseSolutionEnum;
+	      else if (strcmp(name,"SealevelriseStericRate")==0) return SealevelriseStericRateEnum;
+	      else if (strcmp(name,"SealevelUmotion")==0) return SealevelUmotionEnum;
+	      else if (strcmp(name,"SedimentHeadStacked")==0) return SedimentHeadStackedEnum;
+	      else if (strcmp(name,"SedimentHeadTimeAverage")==0) return SedimentHeadTimeAverageEnum;
+	      else if (strcmp(name,"Seg")==0) return SegEnum;
+	      else if (strcmp(name,"SegInput")==0) return SegInputEnum;
 	      else if (strcmp(name,"Segment")==0) return SegmentEnum;
 	      else if (strcmp(name,"SegmentRiftfront")==0) return SegmentRiftfrontEnum;
+	      else if (strcmp(name,"Separate")==0) return SeparateEnum;
+	      else if (strcmp(name,"Seq")==0) return SeqEnum;
+	      else if (strcmp(name,"SIAApproximation")==0) return SIAApproximationEnum;
+	      else if (strcmp(name,"SigmaVM")==0) return SigmaVMEnum;
+	      else if (strcmp(name,"SmbAnalysis")==0) return SmbAnalysisEnum;
+	      else if (strcmp(name,"SMBcomponents")==0) return SMBcomponentsEnum;
+	      else if (strcmp(name,"SMBd18opdd")==0) return SMBd18opddEnum;
+	      else if (strcmp(name,"SmbDesfac")==0) return SmbDesfacEnum;
+	      else if (strcmp(name,"SmbDpermil")==0) return SmbDpermilEnum;
+	      else if (strcmp(name,"SmbDzAdd")==0) return SmbDzAddEnum;
+	      else if (strcmp(name,"SmbFAC")==0) return SmbFACEnum;
+	      else if (strcmp(name,"SMBforcing")==0) return SMBforcingEnum;
+	      else if (strcmp(name,"SMBgcm")==0) return SMBgcmEnum;
+	      else if (strcmp(name,"SMBgemb")==0) return SMBgembEnum;
+	      else if (strcmp(name,"SMBgradientsela")==0) return SMBgradientselaEnum;
+	      else if (strcmp(name,"SMBgradients")==0) return SMBgradientsEnum;
+	      else if (strcmp(name,"SMBhenning")==0) return SMBhenningEnum;
+	      else if (strcmp(name,"SmbMAdd")==0) return SmbMAddEnum;
+	      else if (strcmp(name,"SMBmeltcomponents")==0) return SMBmeltcomponentsEnum;
+	      else if (strcmp(name,"SMBpdd")==0) return SMBpddEnum;
+	      else if (strcmp(name,"SmbRlaps")==0) return SmbRlapsEnum;
+	      else if (strcmp(name,"SmbRlapslgm")==0) return SmbRlapslgmEnum;
+	      else if (strcmp(name,"SmbSolution")==0) return SmbSolutionEnum;
+	      else if (strcmp(name,"SmoothAnalysis")==0) return SmoothAnalysisEnum;
+	      else if (strcmp(name,"SoftMigration")==0) return SoftMigrationEnum;
 	      else if (strcmp(name,"SpcDynamic")==0) return SpcDynamicEnum;
 	      else if (strcmp(name,"SpcStatic")==0) return SpcStaticEnum;
 	      else if (strcmp(name,"SpcTransient")==0) return SpcTransientEnum;
+	      else if (strcmp(name,"SSAApproximation")==0) return SSAApproximationEnum;
+	      else if (strcmp(name,"SSAFSApproximation")==0) return SSAFSApproximationEnum;
+	      else if (strcmp(name,"SSAHOApproximation")==0) return SSAHOApproximationEnum;
+	      else if (strcmp(name,"Sset")==0) return SsetEnum;
+	      else if (strcmp(name,"SteadystateSolution")==0) return SteadystateSolutionEnum;
+	      else if (strcmp(name,"StressbalanceAnalysis")==0) return StressbalanceAnalysisEnum;
+	      else if (strcmp(name,"StressbalanceConvergenceNumSteps")==0) return StressbalanceConvergenceNumStepsEnum;
+	      else if (strcmp(name,"StressbalanceSIAAnalysis")==0) return StressbalanceSIAAnalysisEnum;
+	      else if (strcmp(name,"StressbalanceSolution")==0) return StressbalanceSolutionEnum;
+	      else if (strcmp(name,"StressbalanceVerticalAnalysis")==0) return StressbalanceVerticalAnalysisEnum;
+	      else if (strcmp(name,"StressIntensityFactor")==0) return StressIntensityFactorEnum;
 	      else if (strcmp(name,"StringArrayParam")==0) return StringArrayParamEnum;
+	      else if (strcmp(name,"StringExternalResult")==0) return StringExternalResultEnum;
 	      else if (strcmp(name,"StringParam")==0) return StringParamEnum;
-         else stage=8;
-   }
-   if(stage==8){
-	      if (strcmp(name,"Seg")==0) return SegEnum;
-	      else if (strcmp(name,"SegInput")==0) return SegInputEnum;
-	      else if (strcmp(name,"Tria")==0) return TriaEnum;
-	      else if (strcmp(name,"TriaInput")==0) return TriaInputEnum;
+	      else if (strcmp(name,"SubelementMigration2")==0) return SubelementMigration2Enum;
+	      else if (strcmp(name,"SubelementMigration3")==0) return SubelementMigration3Enum;
+	      else if (strcmp(name,"SubelementMigration")==0) return SubelementMigrationEnum;
+	      else if (strcmp(name,"SurfaceCrevasse")==0) return SurfaceCrevasseEnum;
+	      else if (strcmp(name,"SurfaceSlopeSolution")==0) return SurfaceSlopeSolutionEnum;
+	      else if (strcmp(name,"TaylorHood")==0) return TaylorHoodEnum;
+	      else if (strcmp(name,"TemperaturePDD")==0) return TemperaturePDDEnum;
 	      else if (strcmp(name,"Tetra")==0) return TetraEnum;
 	      else if (strcmp(name,"TetraInput")==0) return TetraInputEnum;
-	      else if (strcmp(name,"Penta")==0) return PentaEnum;
-	      else if (strcmp(name,"PentaInput")==0) return PentaInputEnum;
+	      else if (strcmp(name,"ThermalAnalysis")==0) return ThermalAnalysisEnum;
+	      else if (strcmp(name,"ThermalSolution")==0) return ThermalSolutionEnum;
+	      else if (strcmp(name,"ThermalSpctemperature")==0) return ThermalSpctemperatureEnum;
+	      else if (strcmp(name,"ThicknessErrorEstimator")==0) return ThicknessErrorEstimatorEnum;
+	      else if (strcmp(name,"TotalFloatingBmb")==0) return TotalFloatingBmbEnum;
+	      else if (strcmp(name,"TotalFloatingBmbScaled")==0) return TotalFloatingBmbScaledEnum;
+	      else if (strcmp(name,"TotalGroundedBmb")==0) return TotalGroundedBmbEnum;
+	      else if (strcmp(name,"TotalGroundedBmbScaled")==0) return TotalGroundedBmbScaledEnum;
+	      else if (strcmp(name,"TotalSmb")==0) return TotalSmbEnum;
+	      else if (strcmp(name,"TotalSmbScaled")==0) return TotalSmbScaledEnum;
+	      else if (strcmp(name,"TransientArrayParam")==0) return TransientArrayParamEnum;
+	      else if (strcmp(name,"TransientInput")==0) return TransientInputEnum;
+	      else if (strcmp(name,"TransientParam")==0) return TransientParamEnum;
+	      else if (strcmp(name,"TransientSolution")==0) return TransientSolutionEnum;
+         else stage=10;
+   }
+   if(stage==10){
+	      if (strcmp(name,"Tria")==0) return TriaEnum;
+	      else if (strcmp(name,"TriaInput")==0) return TriaInputEnum;
+	      else if (strcmp(name,"UzawaPressureAnalysis")==0) return UzawaPressureAnalysisEnum;
+	      else if (strcmp(name,"VectorParam")==0) return VectorParamEnum;
 	      else if (strcmp(name,"Vertex")==0) return VertexEnum;
 	      else if (strcmp(name,"VertexPId")==0) return VertexPIdEnum;
 	      else if (strcmp(name,"VertexSId")==0) return VertexSIdEnum;
-	      else if (strcmp(name,"Option")==0) return OptionEnum;
-	      else if (strcmp(name,"GenericOption")==0) return GenericOptionEnum;
-	      else if (strcmp(name,"OptionCell")==0) return OptionCellEnum;
-	      else if (strcmp(name,"OptionStruct")==0) return OptionStructEnum;
-	      else if (strcmp(name,"AdjointBalancethicknessAnalysis")==0) return AdjointBalancethicknessAnalysisEnum;
-	      else if (strcmp(name,"AdjointBalancethickness2Analysis")==0) return AdjointBalancethickness2AnalysisEnum;
-	      else if (strcmp(name,"AdjointHorizAnalysis")==0) return AdjointHorizAnalysisEnum;
-	      else if (strcmp(name,"DefaultAnalysis")==0) return DefaultAnalysisEnum;
-	      else if (strcmp(name,"BalancethicknessAnalysis")==0) return BalancethicknessAnalysisEnum;
-	      else if (strcmp(name,"BalancethicknessSolution")==0) return BalancethicknessSolutionEnum;
-	      else if (strcmp(name,"Balancethickness2Analysis")==0) return Balancethickness2AnalysisEnum;
-	      else if (strcmp(name,"Balancethickness2Solution")==0) return Balancethickness2SolutionEnum;
-	      else if (strcmp(name,"BalancethicknessSoftAnalysis")==0) return BalancethicknessSoftAnalysisEnum;
-	      else if (strcmp(name,"BalancethicknessSoftSolution")==0) return BalancethicknessSoftSolutionEnum;
-	      else if (strcmp(name,"BalancevelocityAnalysis")==0) return BalancevelocityAnalysisEnum;
-	      else if (strcmp(name,"BalancevelocitySolution")==0) return BalancevelocitySolutionEnum;
-	      else if (strcmp(name,"L2ProjectionEPLAnalysis")==0) return L2ProjectionEPLAnalysisEnum;
-	      else if (strcmp(name,"L2ProjectionBaseAnalysis")==0) return L2ProjectionBaseAnalysisEnum;
-	      else if (strcmp(name,"BedSlopeSolution")==0) return BedSlopeSolutionEnum;
-	      else if (strcmp(name,"DamageEvolutionSolution")==0) return DamageEvolutionSolutionEnum;
-	      else if (strcmp(name,"DamageEvolutionAnalysis")==0) return DamageEvolutionAnalysisEnum;
-	      else if (strcmp(name,"StressbalanceAnalysis")==0) return StressbalanceAnalysisEnum;
-	      else if (strcmp(name,"StressbalanceSIAAnalysis")==0) return StressbalanceSIAAnalysisEnum;
-	      else if (strcmp(name,"StressbalanceSolution")==0) return StressbalanceSolutionEnum;
-	      else if (strcmp(name,"StressbalanceVerticalAnalysis")==0) return StressbalanceVerticalAnalysisEnum;
-	      else if (strcmp(name,"EnthalpyAnalysis")==0) return EnthalpyAnalysisEnum;
-	      else if (strcmp(name,"HydrologyShreveAnalysis")==0) return HydrologyShreveAnalysisEnum;
-	      else if (strcmp(name,"HydrologyDCInefficientAnalysis")==0) return HydrologyDCInefficientAnalysisEnum;
-	      else if (strcmp(name,"HydrologyDCEfficientAnalysis")==0) return HydrologyDCEfficientAnalysisEnum;
-	      else if (strcmp(name,"HydrologySommersAnalysis")==0) return HydrologySommersAnalysisEnum;
-	      else if (strcmp(name,"HydrologySolution")==0) return HydrologySolutionEnum;
-	      else if (strcmp(name,"MeltingAnalysis")==0) return MeltingAnalysisEnum;
-	      else if (strcmp(name,"MasstransportAnalysis")==0) return MasstransportAnalysisEnum;
-	      else if (strcmp(name,"MasstransportSolution")==0) return MasstransportSolutionEnum;
-	      else if (strcmp(name,"FreeSurfaceBaseAnalysis")==0) return FreeSurfaceBaseAnalysisEnum;
-	      else if (strcmp(name,"FreeSurfaceTopAnalysis")==0) return FreeSurfaceTopAnalysisEnum;
-	      else if (strcmp(name,"ExtrudeFromBaseAnalysis")==0) return ExtrudeFromBaseAnalysisEnum;
-	      else if (strcmp(name,"ExtrudeFromTopAnalysis")==0) return ExtrudeFromTopAnalysisEnum;
-	      else if (strcmp(name,"DepthAverageAnalysis")==0) return DepthAverageAnalysisEnum;
-	      else if (strcmp(name,"SealevelriseSolution")==0) return SealevelriseSolutionEnum;
-	      else if (strcmp(name,"SealevelriseAnalysis")==0) return SealevelriseAnalysisEnum;
-	      else if (strcmp(name,"SteadystateSolution")==0) return SteadystateSolutionEnum;
-	      else if (strcmp(name,"SurfaceSlopeSolution")==0) return SurfaceSlopeSolutionEnum;
-	      else if (strcmp(name,"SmoothAnalysis")==0) return SmoothAnalysisEnum;
-	      else if (strcmp(name,"ThermalAnalysis")==0) return ThermalAnalysisEnum;
-	      else if (strcmp(name,"ThermalSolution")==0) return ThermalSolutionEnum;
-	      else if (strcmp(name,"TransientSolution")==0) return TransientSolutionEnum;
-	      else if (strcmp(name,"UzawaPressureAnalysis")==0) return UzawaPressureAnalysisEnum;
-	      else if (strcmp(name,"GiaSolution")==0) return GiaSolutionEnum;
-	      else if (strcmp(name,"GiaIvinsAnalysis")==0) return GiaIvinsAnalysisEnum;
-	      else if (strcmp(name,"EsaSolution")==0) return EsaSolutionEnum;
-	      else if (strcmp(name,"EsaAnalysis")==0) return EsaAnalysisEnum;
-	      else if (strcmp(name,"MeshdeformationAnalysis")==0) return MeshdeformationAnalysisEnum;
-	      else if (strcmp(name,"LevelsetAnalysis")==0) return LevelsetAnalysisEnum;
-	      else if (strcmp(name,"ExtrapolationAnalysis")==0) return ExtrapolationAnalysisEnum;
-	      else if (strcmp(name,"Approximation")==0) return ApproximationEnum;
-	      else if (strcmp(name,"NoneApproximation")==0) return NoneApproximationEnum;
-	      else if (strcmp(name,"SIAApproximation")==0) return SIAApproximationEnum;
-	      else if (strcmp(name,"SSAApproximation")==0) return SSAApproximationEnum;
-	      else if (strcmp(name,"SSAHOApproximation")==0) return SSAHOApproximationEnum;
-	      else if (strcmp(name,"SSAFSApproximation")==0) return SSAFSApproximationEnum;
-	      else if (strcmp(name,"L1L2Approximation")==0) return L1L2ApproximationEnum;
-	      else if (strcmp(name,"HOApproximation")==0) return HOApproximationEnum;
-	      else if (strcmp(name,"HOFSApproximation")==0) return HOFSApproximationEnum;
-	      else if (strcmp(name,"FSApproximation")==0) return FSApproximationEnum;
-	      else if (strcmp(name,"FSvelocity")==0) return FSvelocityEnum;
-	      else if (strcmp(name,"FSpressure")==0) return FSpressureEnum;
-	      else if (strcmp(name,"GaussSeg")==0) return GaussSegEnum;
-	      else if (strcmp(name,"GaussTria")==0) return GaussTriaEnum;
-	      else if (strcmp(name,"GaussTetra")==0) return GaussTetraEnum;
-	      else if (strcmp(name,"GaussPenta")==0) return GaussPentaEnum;
+	      else if (strcmp(name,"Vertices")==0) return VerticesEnum;
+	      else if (strcmp(name,"ViscousHeating")==0) return ViscousHeatingEnum;
+	      else if (strcmp(name,"Water")==0) return WaterEnum;
+	      else if (strcmp(name,"XTaylorHood")==0) return XTaylorHoodEnum;
+	      else if (strcmp(name,"XY")==0) return XYEnum;
+	      else if (strcmp(name,"XYZ")==0) return XYZEnum;
+	      else if (strcmp(name,"BalancethicknessD0")==0) return BalancethicknessD0Enum;
+	      else if (strcmp(name,"BalancethicknessDiffusionCoefficient")==0) return BalancethicknessDiffusionCoefficientEnum;
+	      else if (strcmp(name,"BilinearInterp")==0) return BilinearInterpEnum;
+	      else if (strcmp(name,"CalvingdevCoeff")==0) return CalvingdevCoeffEnum;
+	      else if (strcmp(name,"DeviatoricStress")==0) return DeviatoricStressEnum;
+	      else if (strcmp(name,"EtaAbsGradient")==0) return EtaAbsGradientEnum;
+	      else if (strcmp(name,"MeshZ")==0) return MeshZEnum;
+	      else if (strcmp(name,"NearestInterp")==0) return NearestInterpEnum;
+	      else if (strcmp(name,"OutputdefinitionList")==0) return OutputdefinitionListEnum;
+	      else if (strcmp(name,"SealevelObs")==0) return SealevelObsEnum;
+	      else if (strcmp(name,"SealevelWeights")==0) return SealevelWeightsEnum;
+	      else if (strcmp(name,"StrainRate")==0) return StrainRateEnum;
+	      else if (strcmp(name,"StressbalanceViscosityOvershoot")==0) return StressbalanceViscosityOvershootEnum;
+	      else if (strcmp(name,"StressTensor")==0) return StressTensorEnum;
+	      else if (strcmp(name,"SubelementMigration4")==0) return SubelementMigration4Enum;
+	      else if (strcmp(name,"TimesteppingTimeAdapt")==0) return TimesteppingTimeAdaptEnum;
 	      else if (strcmp(name,"TriangleInterp")==0) return TriangleInterpEnum;
-	      else if (strcmp(name,"BilinearInterp")==0) return BilinearInterpEnum;
-	      else if (strcmp(name,"NearestInterp")==0) return NearestInterpEnum;
-	      else if (strcmp(name,"MinVel")==0) return MinVelEnum;
-	      else if (strcmp(name,"MaxVel")==0) return MaxVelEnum;
-	      else if (strcmp(name,"MinVx")==0) return MinVxEnum;
-	      else if (strcmp(name,"MaxVx")==0) return MaxVxEnum;
-	      else if (strcmp(name,"MaxAbsVx")==0) return MaxAbsVxEnum;
-	      else if (strcmp(name,"MinVy")==0) return MinVyEnum;
-	      else if (strcmp(name,"MaxVy")==0) return MaxVyEnum;
-	      else if (strcmp(name,"MaxAbsVy")==0) return MaxAbsVyEnum;
-	      else if (strcmp(name,"MinVz")==0) return MinVzEnum;
-	      else if (strcmp(name,"MaxVz")==0) return MaxVzEnum;
-	      else if (strcmp(name,"MaxAbsVz")==0) return MaxAbsVzEnum;
-	      else if (strcmp(name,"FloatingArea")==0) return FloatingAreaEnum;
-	      else if (strcmp(name,"GroundedArea")==0) return GroundedAreaEnum;
-	      else if (strcmp(name,"IceMass")==0) return IceMassEnum;
-	      else if (strcmp(name,"IceVolume")==0) return IceVolumeEnum;
-	      else if (strcmp(name,"IceVolumeAboveFloatation")==0) return IceVolumeAboveFloatationEnum;
-	      else if (strcmp(name,"TotalFloatingBmb")==0) return TotalFloatingBmbEnum;
-	      else if (strcmp(name,"TotalGroundedBmb")==0) return TotalGroundedBmbEnum;
-	      else if (strcmp(name,"TotalSmb")==0) return TotalSmbEnum;
-	      else if (strcmp(name,"P0")==0) return P0Enum;
-	      else if (strcmp(name,"P0Array")==0) return P0ArrayEnum;
-	      else if (strcmp(name,"P1")==0) return P1Enum;
-	      else if (strcmp(name,"P1DG")==0) return P1DGEnum;
-	      else if (strcmp(name,"P1bubble")==0) return P1bubbleEnum;
-	      else if (strcmp(name,"P1bubblecondensed")==0) return P1bubblecondensedEnum;
-	      else if (strcmp(name,"P2")==0) return P2Enum;
-	      else if (strcmp(name,"P2bubble")==0) return P2bubbleEnum;
-	      else if (strcmp(name,"P2bubblecondensed")==0) return P2bubblecondensedEnum;
-	      else if (strcmp(name,"P2xP1")==0) return P2xP1Enum;
-	      else if (strcmp(name,"P1xP2")==0) return P1xP2Enum;
-	      else if (strcmp(name,"P1xP3")==0) return P1xP3Enum;
-	      else if (strcmp(name,"P2xP4")==0) return P2xP4Enum;
-	      else if (strcmp(name,"P1P1")==0) return P1P1Enum;
-	      else if (strcmp(name,"P1P1GLS")==0) return P1P1GLSEnum;
-	      else if (strcmp(name,"MINI")==0) return MINIEnum;
-         else stage=9;
-   }
-   if(stage==9){
-	      if (strcmp(name,"MINIcondensed")==0) return MINIcondensedEnum;
-	      else if (strcmp(name,"TaylorHood")==0) return TaylorHoodEnum;
-	      else if (strcmp(name,"LATaylorHood")==0) return LATaylorHoodEnum;
-	      else if (strcmp(name,"XTaylorHood")==0) return XTaylorHoodEnum;
-	      else if (strcmp(name,"OneLayerP4z")==0) return OneLayerP4zEnum;
-	      else if (strcmp(name,"CrouzeixRaviart")==0) return CrouzeixRaviartEnum;
-	      else if (strcmp(name,"LACrouzeixRaviart")==0) return LACrouzeixRaviartEnum;
-	      else if (strcmp(name,"Closed")==0) return ClosedEnum;
-	      else if (strcmp(name,"Free")==0) return FreeEnum;
-	      else if (strcmp(name,"Open")==0) return OpenEnum;
-	      else if (strcmp(name,"Air")==0) return AirEnum;
-	      else if (strcmp(name,"Ice")==0) return IceEnum;
-	      else if (strcmp(name,"Melange")==0) return MelangeEnum;
-	      else if (strcmp(name,"Water")==0) return WaterEnum;
-	      else if (strcmp(name,"DataSet")==0) return DataSetEnum;
-	      else if (strcmp(name,"Constraints")==0) return ConstraintsEnum;
-	      else if (strcmp(name,"Loads")==0) return LoadsEnum;
-	      else if (strcmp(name,"Materials")==0) return MaterialsEnum;
-	      else if (strcmp(name,"Nodes")==0) return NodesEnum;
-	      else if (strcmp(name,"Contours")==0) return ContoursEnum;
-	      else if (strcmp(name,"Parameters")==0) return ParametersEnum;
-	      else if (strcmp(name,"Vertices")==0) return VerticesEnum;
-	      else if (strcmp(name,"Results")==0) return ResultsEnum;
 	      else if (strcmp(name,"MaximumNumberOfDefinitions")==0) return MaximumNumberOfDefinitionsEnum;
-         else stage=10;
+         else stage=11;
    }
 	/*If we reach this point, the string provided has not been found*/
Index: /issm/trunk/src/c/shared/Enum/Synchronize.sh
===================================================================
--- /issm/trunk/src/c/shared/Enum/Synchronize.sh	(revision 22757)
+++ /issm/trunk/src/c/shared/Enum/Synchronize.sh	(revision 22758)
@@ -13,4 +13,5 @@
 
 #Deal with Analyses
+if false ; then
 #Build EnumToAnalysis.cpp {{{
 #Header
@@ -85,4 +86,5 @@
 END
 #}}}
+fi
 
 #Enum to String conversions
Index: /issm/trunk/src/c/shared/Exceptions/exceptions.h
===================================================================
--- /issm/trunk/src/c/shared/Exceptions/exceptions.h	(revision 22757)
+++ /issm/trunk/src/c/shared/Exceptions/exceptions.h	(revision 22758)
@@ -61,13 +61,13 @@
 	catch(ErrorException &exception){\
 		exception.Report();\
-		return 0;\
+		return 1;\
 	}\
 	catch(exception& e) {\
 		_printf_("Standard exception: " << e.what() << "\n\n");\
-		return 0;\
+		return 1;\
 	}\
 	catch(...){\
 		_printf_("An unexpected error occurred \n\n");\
-		return 0;\
+		return 1;\
 	}
 /*}}}*/
Index: /issm/trunk/src/c/shared/FSanalyticals/fsanalyticals.cpp
===================================================================
--- /issm/trunk/src/c/shared/FSanalyticals/fsanalyticals.cpp	(revision 22757)
+++ /issm/trunk/src/c/shared/FSanalyticals/fsanalyticals.cpp	(revision 22758)
@@ -9,4 +9,6 @@
  * case 6: 3d test with sinusoidal functions, non homogeneous Dirichlet conditions
  *
+ * case 103: 3d test sin(z) HO
+ *
  * case 201: 3d test quadratic functions FS, ESTAR flow law
  * case 202: 3d test quadratic functions HO, ESTAR flow law
@@ -74,4 +76,6 @@
 		case 101: 
 			return 4*pow(x, 2)*y*z*pow(x - 1, 2)*(z - 1) + 8*pow(x, 2)*y*z*(y - 1)*(2*y - 1)*(z - 1) + 2*pow(x, 2)*y*pow(x - 1, 2)*(y - 1)*(2*y - 1) + 4*pow(x, 2)*z*pow(x - 1, 2)*(y - 1)*(z - 1) + 2*pow(x, 2)*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) - 12*x*pow(y, 2)*z*(x - 1)*(y - 1)*(z - 1) - 6*x*pow(y, 2)*z*(2*x - 1)*(y - 1)*(z - 1) - 12*x*y*z*(x - 1)*pow(y - 1, 2)*(z - 1) + 32*x*y*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) - 6*x*y*z*(2*x - 1)*pow(y - 1, 2)*(z - 1) - 6*pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + 8*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 6*y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1);
+		case 103:
+			return 50*pow(M_PI, 2)*x*y*(x - 1)*(y - 1)*pow(sin(5*M_PI*z), 2) - 50*pow(M_PI, 2)*x*y*(x - 1)*(y - 1)*pow(cos(5*M_PI*z), 2) - 3*x*y*pow(sin(4*M_PI*z), 2) - 2*x*(x - 1)*pow(sin(5*M_PI*z), 2) - 3*x*(y - 1)*pow(sin(4*M_PI*z), 2) - 3*y*(x - 1)*pow(sin(4*M_PI*z), 2) - 8*y*(y - 1)*pow(sin(5*M_PI*z), 2) - 3*(x - 1)*(y - 1)*pow(sin(4*M_PI*z), 2);
 		case 201:
 			return pow(x, 2)*y*pow(x - 1, 2)*(y - 1)*(2*y - 1)/pow((1.0L/6.0L)*pow(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2) + x*pow(y, 2)*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2) + (1.0L/6.0L)*pow(pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1) + pow(x, 2)*y*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1), 2) + (4.0L/3.0L)*pow(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + x*y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2) + (4.0L/3.0L)*pow(pow(x, 2)*y*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) + x*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1), 2) + (1.0L/6.0L)*pow(2*pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(z - 1) + pow(x, 2)*y*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 2*x*pow(y, 2)*z*(x - 1)*pow(y - 1, 2)*(z - 1) - x*pow(y, 2)*z*(2*x - 1)*pow(y - 1, 2)*(z - 1) - pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2), 1.0L/3.0L) + y - 1.0L/18.0L*(pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1) + pow(x, 2)*y*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1))*(2*pow(x, 2)*y*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1) + pow(x, 2)*y*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1)) + 2*x*pow(y, 2)*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2) + x*pow(y, 2)*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1)) + 8*(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + x*y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1))*(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1) + x*pow(y, 2)*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + x*y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2) + x*y*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1)) + 8*(pow(x, 2)*y*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) + x*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1))*(pow(x, 2)*y*z*(x - 1)*(y - 1)*(2*y - 1) + pow(x, 2)*y*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) + x*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1) + x*y*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1)) + (2*pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(z - 1) + pow(x, 2)*y*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 2*x*pow(y, 2)*z*(x - 1)*pow(y - 1, 2)*(z - 1) - x*pow(y, 2)*z*(2*x - 1)*pow(y - 1, 2)*(z - 1) - pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1))*(2*pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1) + pow(x, 2)*y*z*pow(x - 1, 2)*(2*y - 1) + 2*pow(x, 2)*y*pow(x - 1, 2)*(y - 1)*(z - 1) + pow(x, 2)*y*pow(x - 1, 2)*(2*y - 1)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(y - 1)*(2*y - 1) + pow(x, 2)*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 2*x*pow(y, 2)*z*(x - 1)*pow(y - 1, 2) - x*pow(y, 2)*z*(2*x - 1)*pow(y - 1, 2) - 2*x*pow(y, 2)*(x - 1)*pow(y - 1, 2)*(z - 1) - x*pow(y, 2)*(2*x - 1)*pow(y - 1, 2)*(z - 1) - pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2) - pow(y, 2)*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1)))/pow((1.0L/6.0L)*pow(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2) + x*pow(y, 2)*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2) + (1.0L/6.0L)*pow(pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1) + pow(x, 2)*y*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1), 2) + (4.0L/3.0L)*pow(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + x*y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2) + (4.0L/3.0L)*pow(pow(x, 2)*y*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) + x*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1), 2) + (1.0L/6.0L)*pow(2*pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(z - 1) + pow(x, 2)*y*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 2*x*pow(y, 2)*z*(x - 1)*pow(y - 1, 2)*(z - 1) - x*pow(y, 2)*z*(2*x - 1)*pow(y - 1, 2)*(z - 1) - pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2), 4.0L/3.0L) - 2.0L/9.0L*(pow(x, 2)*y*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) + x*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1))*((x*pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2) + x*pow(y, 2)*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1))*(2*x*pow(y, 2)*z*(x - 1)*pow(y - 1, 2) + x*pow(y, 2)*z*(2*x - 1)*pow(y - 1, 2) + 2*x*pow(y, 2)*(x - 1)*pow(y - 1, 2)*(z - 1) + x*pow(y, 2)*(2*x - 1)*pow(y - 1, 2)*(z - 1) + pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2) + pow(y, 2)*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1)) + 2*(pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1) + pow(x, 2)*y*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1))*(pow(x, 2)*y*z*(x - 1)*(y - 1)*(2*y - 1) + pow(x, 2)*y*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) + x*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1) + x*y*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1)) + 8*(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + x*y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1))*(2*x*pow(y, 2)*z*(x - 1)*(y - 1)*(z - 1) + x*pow(y, 2)*z*(2*x - 1)*(y - 1)*(z - 1) + 2*x*y*z*(x - 1)*pow(y - 1, 2)*(z - 1) + x*y*z*(2*x - 1)*pow(y - 1, 2)*(z - 1) + pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1)) + 8*(pow(x, 2)*y*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) + x*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1))*(pow(x, 2)*y*z*(y - 1)*(2*y - 1)*(z - 1) + 4*x*y*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) + y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1)) + 2*(2*pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(z - 1) + pow(x, 2)*y*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 2*x*pow(y, 2)*z*(x - 1)*pow(y - 1, 2)*(z - 1) - x*pow(y, 2)*z*(2*x - 1)*pow(y - 1, 2)*(z - 1) - pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1))*(2*pow(x, 2)*y*z*(x - 1)*(y - 1)*(z - 1) + pow(x, 2)*y*z*(x - 1)*(2*y - 1)*(z - 1) + pow(x, 2)*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) - 2*x*pow(y, 2)*z*pow(y - 1, 2)*(z - 1) + 2*x*y*z*pow(x - 1, 2)*(y - 1)*(z - 1) + x*y*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) + x*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 2*pow(y, 2)*z*(x - 1)*pow(y - 1, 2)*(z - 1) - pow(y, 2)*z*(2*x - 1)*pow(y - 1, 2)*(z - 1)))/pow((1.0L/6.0L)*pow(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2) + x*pow(y, 2)*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2) + (1.0L/6.0L)*pow(pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1) + pow(x, 2)*y*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1), 2) + (4.0L/3.0L)*pow(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + x*y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2) + (4.0L/3.0L)*pow(pow(x, 2)*y*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) + x*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1), 2) + (1.0L/6.0L)*pow(2*pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(z - 1) + pow(x, 2)*y*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 2*x*pow(y, 2)*z*(x - 1)*pow(y - 1, 2)*(z - 1) - x*pow(y, 2)*z*(2*x - 1)*pow(y - 1, 2)*(z - 1) - pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2), 4.0L/3.0L) + 2*(pow(x, 2)*y*z*(y - 1)*(2*y - 1)*(z - 1) + 4*x*y*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) + y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1))/pow((1.0L/6.0L)*pow(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2) + x*pow(y, 2)*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2) + (1.0L/6.0L)*pow(pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1) + pow(x, 2)*y*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1), 2) + (4.0L/3.0L)*pow(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + x*y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2) + (4.0L/3.0L)*pow(pow(x, 2)*y*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) + x*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1), 2) + (1.0L/6.0L)*pow(2*pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(z - 1) + pow(x, 2)*y*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 2*x*pow(y, 2)*z*(x - 1)*pow(y - 1, 2)*(z - 1) - x*pow(y, 2)*z*(2*x - 1)*pow(y - 1, 2)*(z - 1) - pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2), 1.0L/3.0L) - 1.0L/18.0L*(2*(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2) + x*pow(y, 2)*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1))*(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1) + x*pow(y, 2)*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + x*y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2) + x*y*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1)) + (pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1) + pow(x, 2)*y*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1))*(2*pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1) + pow(x, 2)*y*z*pow(x - 1, 2)*(2*y - 1) + 2*pow(x, 2)*y*pow(x - 1, 2)*(y - 1)*(z - 1) + pow(x, 2)*y*pow(x - 1, 2)*(2*y - 1)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(y - 1)*(2*y - 1) + pow(x, 2)*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1)) + 8*(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + x*y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1))*(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*(z - 1) + 4*x*y*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + x*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1)) + 8*(pow(x, 2)*y*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) + x*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1))*(2*pow(x, 2)*y*z*(x - 1)*(y - 1)*(z - 1) + pow(x, 2)*y*z*(x - 1)*(2*y - 1)*(z - 1) + pow(x, 2)*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) + 2*x*y*z*pow(x - 1, 2)*(y - 1)*(z - 1) + x*y*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) + x*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1)) + 2*(2*pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(z - 1) + pow(x, 2)*y*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 2*x*pow(y, 2)*z*(x - 1)*pow(y - 1, 2)*(z - 1) - x*pow(y, 2)*z*(2*x - 1)*pow(y - 1, 2)*(z - 1) - pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1))*(2*pow(x, 2)*y*z*pow(x - 1, 2)*(z - 1) + 2*pow(x, 2)*z*pow(x - 1, 2)*(y - 1)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) - 2*x*pow(y, 2)*z*(x - 1)*(y - 1)*(z - 1) - x*pow(y, 2)*z*(2*x - 1)*(y - 1)*(z - 1) - 2*x*y*z*(x - 1)*pow(y - 1, 2)*(z - 1) - x*y*z*(2*x - 1)*pow(y - 1, 2)*(z - 1) - pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) - y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1)))*(2*pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(z - 1) + pow(x, 2)*y*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 2*x*pow(y, 2)*z*(x - 1)*pow(y - 1, 2)*(z - 1) - x*pow(y, 2)*z*(2*x - 1)*pow(y - 1, 2)*(z - 1) - pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1))/pow((1.0L/6.0L)*pow(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2) + x*pow(y, 2)*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2) + (1.0L/6.0L)*pow(pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1) + pow(x, 2)*y*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1), 2) + (4.0L/3.0L)*pow(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + x*y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2) + (4.0L/3.0L)*pow(pow(x, 2)*y*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) + x*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1), 2) + (1.0L/6.0L)*pow(2*pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(z - 1) + pow(x, 2)*y*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 2*x*pow(y, 2)*z*(x - 1)*pow(y - 1, 2)*(z - 1) - x*pow(y, 2)*z*(2*x - 1)*pow(y - 1, 2)*(z - 1) - pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2), 4.0L/3.0L) - 1.0L/2.0L + (2*pow(x, 2)*y*z*pow(x - 1, 2)*(z - 1) + 2*pow(x, 2)*z*pow(x - 1, 2)*(y - 1)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) - 2*x*pow(y, 2)*z*(x - 1)*(y - 1)*(z - 1) - x*pow(y, 2)*z*(2*x - 1)*(y - 1)*(z - 1) - 2*x*y*z*(x - 1)*pow(y - 1, 2)*(z - 1) - x*y*z*(2*x - 1)*pow(y - 1, 2)*(z - 1) - pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) - y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1))/pow((1.0L/6.0L)*pow(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2) + x*pow(y, 2)*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2) + (1.0L/6.0L)*pow(pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1) + pow(x, 2)*y*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1), 2) + (4.0L/3.0L)*pow(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + x*y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2) + (4.0L/3.0L)*pow(pow(x, 2)*y*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) + x*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1), 2) + (1.0L/6.0L)*pow(2*pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(z - 1) + pow(x, 2)*y*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 2*x*pow(y, 2)*z*(x - 1)*pow(y - 1, 2)*(z - 1) - x*pow(y, 2)*z*(2*x - 1)*pow(y - 1, 2)*(z - 1) - pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2), 1.0L/3.0L);
@@ -144,4 +148,6 @@
 		case 101: 
 			return 12*pow(x, 2)*y*z*(x - 1)*(y - 1)*(z - 1) + 6*pow(x, 2)*y*z*(x - 1)*(2*y - 1)*(z - 1) + 6*pow(x, 2)*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) - 8*x*pow(y, 2)*z*(x - 1)*(2*x - 1)*(z - 1) - 4*x*pow(y, 2)*z*pow(y - 1, 2)*(z - 1) - 2*x*pow(y, 2)*(x - 1)*(2*x - 1)*pow(y - 1, 2) + 12*x*y*z*pow(x - 1, 2)*(y - 1)*(z - 1) + 6*x*y*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) - 32*x*y*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + 6*x*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 8*x*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1) - 4*pow(y, 2)*z*(x - 1)*pow(y - 1, 2)*(z - 1) - 2*pow(y, 2)*z*(2*x - 1)*pow(y - 1, 2)*(z - 1);
+		case 103:
+			return 32*pow(PI, 2)*x*y*(x - 1)*(y - 1)*pow(sin(4*PI*z), 2) - 32*pow(PI, 2)*x*y*(x - 1)*(y - 1)*pow(cos(4*PI*z), 2) - 3*x*y*pow(sin(5*PI*z), 2) - 8*x*(x - 1)*pow(sin(4*PI*z), 2) - 3*x*(y - 1)*pow(sin(5*PI*z), 2) - 3*y*(x - 1)*pow(sin(5*PI*z), 2) - 2*y*(y - 1)*pow(sin(4*PI*z), 2) - 3*(x - 1)*(y - 1)*pow(sin(5*PI*z), 2);
 		case 201:
 			return -x*pow(y, 2)*(x - 1)*(2*x - 1)*pow(y - 1, 2)/pow((1.0L/6.0L)*pow(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2) + x*pow(y, 2)*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2) + (1.0L/6.0L)*pow(pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1) + pow(x, 2)*y*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1), 2) + (4.0L/3.0L)*pow(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + x*y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2) + (4.0L/3.0L)*pow(pow(x, 2)*y*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) + x*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1), 2) + (1.0L/6.0L)*pow(2*pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(z - 1) + pow(x, 2)*y*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 2*x*pow(y, 2)*z*(x - 1)*pow(y - 1, 2)*(z - 1) - x*pow(y, 2)*z*(2*x - 1)*pow(y - 1, 2)*(z - 1) - pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2), 1.0L/3.0L) + x + (1.0L/18.0L)*(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2) + x*pow(y, 2)*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1))*(2*pow(x, 2)*y*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1) + pow(x, 2)*y*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1)) + 2*x*pow(y, 2)*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2) + x*pow(y, 2)*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1)) + 8*(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + x*y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1))*(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1) + x*pow(y, 2)*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + x*y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2) + x*y*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1)) + 8*(pow(x, 2)*y*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) + x*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1))*(pow(x, 2)*y*z*(x - 1)*(y - 1)*(2*y - 1) + pow(x, 2)*y*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) + x*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1) + x*y*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1)) + (2*pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(z - 1) + pow(x, 2)*y*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 2*x*pow(y, 2)*z*(x - 1)*pow(y - 1, 2)*(z - 1) - x*pow(y, 2)*z*(2*x - 1)*pow(y - 1, 2)*(z - 1) - pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1))*(2*pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1) + pow(x, 2)*y*z*pow(x - 1, 2)*(2*y - 1) + 2*pow(x, 2)*y*pow(x - 1, 2)*(y - 1)*(z - 1) + pow(x, 2)*y*pow(x - 1, 2)*(2*y - 1)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(y - 1)*(2*y - 1) + pow(x, 2)*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 2*x*pow(y, 2)*z*(x - 1)*pow(y - 1, 2) - x*pow(y, 2)*z*(2*x - 1)*pow(y - 1, 2) - 2*x*pow(y, 2)*(x - 1)*pow(y - 1, 2)*(z - 1) - x*pow(y, 2)*(2*x - 1)*pow(y - 1, 2)*(z - 1) - pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2) - pow(y, 2)*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1)))/pow((1.0L/6.0L)*pow(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2) + x*pow(y, 2)*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2) + (1.0L/6.0L)*pow(pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1) + pow(x, 2)*y*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1), 2) + (4.0L/3.0L)*pow(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + x*y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2) + (4.0L/3.0L)*pow(pow(x, 2)*y*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) + x*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1), 2) + (1.0L/6.0L)*pow(2*pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(z - 1) + pow(x, 2)*y*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 2*x*pow(y, 2)*z*(x - 1)*pow(y - 1, 2)*(z - 1) - x*pow(y, 2)*z*(2*x - 1)*pow(y - 1, 2)*(z - 1) - pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2), 4.0L/3.0L) + (2.0L/9.0L)*(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + x*y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1))*(2*(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2) + x*pow(y, 2)*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1))*(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1) + x*pow(y, 2)*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + x*y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2) + x*y*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1)) + (pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1) + pow(x, 2)*y*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1))*(2*pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1) + pow(x, 2)*y*z*pow(x - 1, 2)*(2*y - 1) + 2*pow(x, 2)*y*pow(x - 1, 2)*(y - 1)*(z - 1) + pow(x, 2)*y*pow(x - 1, 2)*(2*y - 1)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(y - 1)*(2*y - 1) + pow(x, 2)*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1)) + 8*(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + x*y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1))*(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*(z - 1) + 4*x*y*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + x*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1)) + 8*(pow(x, 2)*y*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) + x*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1))*(2*pow(x, 2)*y*z*(x - 1)*(y - 1)*(z - 1) + pow(x, 2)*y*z*(x - 1)*(2*y - 1)*(z - 1) + pow(x, 2)*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) + 2*x*y*z*pow(x - 1, 2)*(y - 1)*(z - 1) + x*y*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) + x*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1)) + 2*(2*pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(z - 1) + pow(x, 2)*y*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 2*x*pow(y, 2)*z*(x - 1)*pow(y - 1, 2)*(z - 1) - x*pow(y, 2)*z*(2*x - 1)*pow(y - 1, 2)*(z - 1) - pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1))*(2*pow(x, 2)*y*z*pow(x - 1, 2)*(z - 1) + 2*pow(x, 2)*z*pow(x - 1, 2)*(y - 1)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) - 2*x*pow(y, 2)*z*(x - 1)*(y - 1)*(z - 1) - x*pow(y, 2)*z*(2*x - 1)*(y - 1)*(z - 1) - 2*x*y*z*(x - 1)*pow(y - 1, 2)*(z - 1) - x*y*z*(2*x - 1)*pow(y - 1, 2)*(z - 1) - pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) - y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1)))/pow((1.0L/6.0L)*pow(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2) + x*pow(y, 2)*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2) + (1.0L/6.0L)*pow(pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1) + pow(x, 2)*y*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1), 2) + (4.0L/3.0L)*pow(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + x*y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2) + (4.0L/3.0L)*pow(pow(x, 2)*y*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) + x*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1), 2) + (1.0L/6.0L)*pow(2*pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(z - 1) + pow(x, 2)*y*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 2*x*pow(y, 2)*z*(x - 1)*pow(y - 1, 2)*(z - 1) - x*pow(y, 2)*z*(2*x - 1)*pow(y - 1, 2)*(z - 1) - pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2), 4.0L/3.0L) - 2*(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*(z - 1) + 4*x*y*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + x*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1))/pow((1.0L/6.0L)*pow(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2) + x*pow(y, 2)*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2) + (1.0L/6.0L)*pow(pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1) + pow(x, 2)*y*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1), 2) + (4.0L/3.0L)*pow(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + x*y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2) + (4.0L/3.0L)*pow(pow(x, 2)*y*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) + x*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1), 2) + (1.0L/6.0L)*pow(2*pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(z - 1) + pow(x, 2)*y*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 2*x*pow(y, 2)*z*(x - 1)*pow(y - 1, 2)*(z - 1) - x*pow(y, 2)*z*(2*x - 1)*pow(y - 1, 2)*(z - 1) - pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2), 1.0L/3.0L) - 1.0L/18.0L*((x*pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2) + x*pow(y, 2)*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1))*(2*x*pow(y, 2)*z*(x - 1)*pow(y - 1, 2) + x*pow(y, 2)*z*(2*x - 1)*pow(y - 1, 2) + 2*x*pow(y, 2)*(x - 1)*pow(y - 1, 2)*(z - 1) + x*pow(y, 2)*(2*x - 1)*pow(y - 1, 2)*(z - 1) + pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2) + pow(y, 2)*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1)) + 2*(pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1) + pow(x, 2)*y*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1))*(pow(x, 2)*y*z*(x - 1)*(y - 1)*(2*y - 1) + pow(x, 2)*y*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) + x*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1) + x*y*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1)) + 8*(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + x*y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1))*(2*x*pow(y, 2)*z*(x - 1)*(y - 1)*(z - 1) + x*pow(y, 2)*z*(2*x - 1)*(y - 1)*(z - 1) + 2*x*y*z*(x - 1)*pow(y - 1, 2)*(z - 1) + x*y*z*(2*x - 1)*pow(y - 1, 2)*(z - 1) + pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1)) + 8*(pow(x, 2)*y*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) + x*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1))*(pow(x, 2)*y*z*(y - 1)*(2*y - 1)*(z - 1) + 4*x*y*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) + y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1)) + 2*(2*pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(z - 1) + pow(x, 2)*y*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 2*x*pow(y, 2)*z*(x - 1)*pow(y - 1, 2)*(z - 1) - x*pow(y, 2)*z*(2*x - 1)*pow(y - 1, 2)*(z - 1) - pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1))*(2*pow(x, 2)*y*z*(x - 1)*(y - 1)*(z - 1) + pow(x, 2)*y*z*(x - 1)*(2*y - 1)*(z - 1) + pow(x, 2)*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) - 2*x*pow(y, 2)*z*pow(y - 1, 2)*(z - 1) + 2*x*y*z*pow(x - 1, 2)*(y - 1)*(z - 1) + x*y*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) + x*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 2*pow(y, 2)*z*(x - 1)*pow(y - 1, 2)*(z - 1) - pow(y, 2)*z*(2*x - 1)*pow(y - 1, 2)*(z - 1)))*(2*pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(z - 1) + pow(x, 2)*y*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 2*x*pow(y, 2)*z*(x - 1)*pow(y - 1, 2)*(z - 1) - x*pow(y, 2)*z*(2*x - 1)*pow(y - 1, 2)*(z - 1) - pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1))/pow((1.0L/6.0L)*pow(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2) + x*pow(y, 2)*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2) + (1.0L/6.0L)*pow(pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1) + pow(x, 2)*y*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1), 2) + (4.0L/3.0L)*pow(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + x*y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2) + (4.0L/3.0L)*pow(pow(x, 2)*y*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) + x*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1), 2) + (1.0L/6.0L)*pow(2*pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(z - 1) + pow(x, 2)*y*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 2*x*pow(y, 2)*z*(x - 1)*pow(y - 1, 2)*(z - 1) - x*pow(y, 2)*z*(2*x - 1)*pow(y - 1, 2)*(z - 1) - pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2), 4.0L/3.0L) - 1.0L/2.0L + (2*pow(x, 2)*y*z*(x - 1)*(y - 1)*(z - 1) + pow(x, 2)*y*z*(x - 1)*(2*y - 1)*(z - 1) + pow(x, 2)*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) - 2*x*pow(y, 2)*z*pow(y - 1, 2)*(z - 1) + 2*x*y*z*pow(x - 1, 2)*(y - 1)*(z - 1) + x*y*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) + x*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 2*pow(y, 2)*z*(x - 1)*pow(y - 1, 2)*(z - 1) - pow(y, 2)*z*(2*x - 1)*pow(y - 1, 2)*(z - 1))/pow((1.0L/6.0L)*pow(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2) + x*pow(y, 2)*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2) + (1.0L/6.0L)*pow(pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1) + pow(x, 2)*y*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1), 2) + (4.0L/3.0L)*pow(x*pow(y, 2)*z*(x - 1)*(2*x - 1)*(y - 1)*(z - 1) + x*y*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2) + (4.0L/3.0L)*pow(pow(x, 2)*y*z*(x - 1)*(y - 1)*(2*y - 1)*(z - 1) + x*y*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1), 2) + (1.0L/6.0L)*pow(2*pow(x, 2)*y*z*pow(x - 1, 2)*(y - 1)*(z - 1) + pow(x, 2)*y*z*pow(x - 1, 2)*(2*y - 1)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(y - 1)*(2*y - 1)*(z - 1) - 2*x*pow(y, 2)*z*(x - 1)*pow(y - 1, 2)*(z - 1) - x*pow(y, 2)*z*(2*x - 1)*pow(y - 1, 2)*(z - 1) - pow(y, 2)*z*(x - 1)*(2*x - 1)*pow(y - 1, 2)*(z - 1), 2), 1.0L/3.0L);
Index: /issm/trunk/src/c/shared/Numerics/GaussPoints.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/GaussPoints.cpp	(revision 22757)
+++ /issm/trunk/src/c/shared/Numerics/GaussPoints.cpp	(revision 22758)
@@ -1691,19 +1691,2 @@
 
 }/*}}}*/
-
-/*Element Gauss points TO BE REMOVED*/
-void gaussQuad( IssmPDouble** pxgaus, IssmPDouble** pxwgt, IssmPDouble** pegaus, IssmPDouble** pewgt, int nigaus, int njgaus ) {/*{{{*/
-	/*Gauss quadrature points for the quadrilaterial.*/
-
-	/*get the gauss points using the product of two line rules  */
-	GaussLegendreLinear(pxgaus, pxwgt, nigaus);
-	GaussLegendreLinear(pegaus, pewgt, njgaus);
-}/*}}}*/
-void gaussHexa( IssmPDouble** pxgaus, IssmPDouble** pxwgt, IssmPDouble** pegaus, IssmPDouble** pewgt, IssmPDouble** pzgaus, IssmPDouble ** pzwgt, int nigaus, int njgaus, int nkgaus ) {/*{{{*/
-	/*Gauss quadrature points for the hexahedron.*/
-
-	/*  get the gauss points using the product of three line rules  */
-	GaussLegendreLinear(pxgaus, pxwgt, nigaus);
-	GaussLegendreLinear(pegaus, pewgt, njgaus);
-	GaussLegendreLinear(pzgaus, pzwgt, nkgaus);
-}/*}}}*/
Index: /issm/trunk/src/c/shared/Numerics/GaussPoints.h
===================================================================
--- /issm/trunk/src/c/shared/Numerics/GaussPoints.h	(revision 22757)
+++ /issm/trunk/src/c/shared/Numerics/GaussPoints.h	(revision 22758)
@@ -18,6 +18,3 @@
 void GaussRecur(IssmPDouble* zero, IssmPDouble* weight, int n, IssmPDouble* alpha, IssmPDouble* beta);
 
-void gaussQuad(IssmPDouble** pxgaus, IssmPDouble** pxwgt, IssmPDouble** pegaus, IssmPDouble** pewgt, int nigaus, int njgaus);
-void gaussHexa(IssmPDouble** pxgaus, IssmPDouble** pxwgt, IssmPDouble** pegaus, IssmPDouble** pewgt, IssmPDouble** pzgaus, IssmPDouble ** pzwgt, int nigaus, int njgaus, int nkgaus);
-
 #endif
Index: /issm/trunk/src/c/shared/Sorting/binary_search.cpp
===================================================================
--- /issm/trunk/src/c/shared/Sorting/binary_search.cpp	(revision 22757)
+++ /issm/trunk/src/c/shared/Sorting/binary_search.cpp	(revision 22758)
@@ -15,6 +15,6 @@
 
 	/*output: */
-	int offset;  //offset, if found
-	int found=0; //found=0 if target is not found, 1 otherwise.
+	int offset=0;  //offset, if found
+	int found=0;   //found=0 if target is not found, 1 otherwise.
 
 	/*intermediary: */
Index: /issm/trunk/src/c/shared/Triangle/AssociateSegmentToElement.cpp
===================================================================
--- /issm/trunk/src/c/shared/Triangle/AssociateSegmentToElement.cpp	(revision 22758)
+++ /issm/trunk/src/c/shared/Triangle/AssociateSegmentToElement.cpp	(revision 22758)
@@ -0,0 +1,24 @@
+/*!\file:  AssociateSegmentToElement.cpp
+ * \brief for each segment, look for the corresponding element.
+ */ 
+
+#include "./triangle.h"
+
+int AssociateSegmentToElement(int** psegments,int nseg,int* index,int nel){
+
+	/*node indices: */
+	int A,B;
+
+	/*Recover segments: */
+	int* segments=*psegments;
+
+	for(int i=0;i<nseg;i++){
+		A=segments[3*i+0];
+		B=segments[3*i+1];
+		segments[3*i+2]=FindElement(A,B,index,nel)+1; //matlab indexing.
+	}
+
+	/*Assign output pointers: */
+	*psegments=segments;
+	return 1;
+}
Index: /issm/trunk/src/c/shared/Triangle/GridInsideHole.cpp
===================================================================
--- /issm/trunk/src/c/shared/Triangle/GridInsideHole.cpp	(revision 22758)
+++ /issm/trunk/src/c/shared/Triangle/GridInsideHole.cpp	(revision 22758)
@@ -0,0 +1,51 @@
+/*
+ * GridInsideHole.c:
+ * from a convex set of points, figure out a point that for sure lies inside the profile.
+ */
+
+#include <math.h>
+
+#include "./triangle.h"
+#include "../Exp/exp.h"
+
+#undef M_PI
+#define M_PI 3.141592653589793238462643
+
+int GridInsideHole(double* px0,double* py0,int n,double* x,double* y){
+
+	double flag=0.0;
+	double xA,xB,xC,xD,xE;
+	double yA,yB,yC,yD,yE;
+
+	/*Take first and last vertices: */
+	xA=x[0];
+	yA=y[0];
+	xB=x[n-1];
+	yB=y[n-1];
+
+	/*Figure out middle of segment [A B]: */
+	xC=(xA+xB)/2;
+	yC=(yA+yB)/2;
+
+	/*D and E are on each side of segment [A B], on the median line between segment [A  B], 
+	 *at an angle of 10 degree (less than the minimum 30 enforced by the quality of the mesh: */
+	xD=xC+tan(10./180.*M_PI)*(yC-yA);
+	yD=yC+tan(10./180.*M_PI)*(xA-xC);
+	xE=xC-tan(10./180.*M_PI)*(yC-yA);
+	yE=yC-tan(10./180.*M_PI)*(xA-xC);
+
+	/*Either E or D is inside profile (x,y): */
+	IsInPolySerial(&flag,&xD,&yD,1,x,y,n,2);
+	/*FIXME: used to be 'flag' and not '!flag', check*/
+	if(!flag){
+		/*D is inside the poly: */
+		*px0=xD;
+		*py0=yD;
+	}
+	else{
+		/*E is inside the poly: */
+		*px0=xE;
+		*py0=yE;
+	}
+	return 1;
+}
Index: /issm/trunk/src/c/shared/Triangle/OrderSegments.cpp
===================================================================
--- /issm/trunk/src/c/shared/Triangle/OrderSegments.cpp	(revision 22758)
+++ /issm/trunk/src/c/shared/Triangle/OrderSegments.cpp	(revision 22758)
@@ -0,0 +1,46 @@
+/*
+ * OrderSegments.c: 
+ * reorder segments so that their normals point outside the domain outline.
+ */
+#include "./triangle.h"
+
+int OrderSegments(int** psegments,int nseg,int* index,int nel){
+
+	/*vertex indices: */
+	int A,B;
+
+	/*element index*/
+	int el;
+
+	/*Recover segments: */
+	int* segments=*psegments;
+
+	for(int i=0;i<nseg;i++){
+		A=segments[3*i+0];
+		B=segments[3*i+1];
+		el=segments[3*i+2]-1; //after AssociateSegmentToElement, el was a matlab index, we need the c index now.
+
+		if (index[3*el+0]==A){
+			if (index[3*el+2]==B){
+				segments[3*i+0]=B;
+				segments[3*i+1]=A;
+			}
+		}
+		else if (index[3*el+1]==A){
+			if (index[3*el+0]==B){
+				segments[3*i+0]=B;
+				segments[3*i+1]=A;
+			}
+		}
+		else{
+			if (index[3*el+1]==B){
+				segments[3*i+0]=B;
+				segments[3*i+1]=A;
+			}
+		}
+	}
+
+	/*Assign output pointers: */
+	*psegments=segments;
+	return 1;
+}
Index: /issm/trunk/src/c/shared/Triangle/SplitMeshForRifts.cpp
===================================================================
--- /issm/trunk/src/c/shared/Triangle/SplitMeshForRifts.cpp	(revision 22758)
+++ /issm/trunk/src/c/shared/Triangle/SplitMeshForRifts.cpp	(revision 22758)
@@ -0,0 +1,96 @@
+/*
+ * SplitMeshForRifts.c:
+ */
+#include "./triangle.h"
+#include "../MemOps/MemOps.h"
+
+int SplitMeshForRifts(int* pnel,int** pindex,int* pnods,double** px,double** py,int* pnsegs,int** psegments,int** psegmentmarkerlist){
+
+	/*Some notes on dimensions: 
+	index  of size nelx3
+	x and y of size nodsx1
+	segments of size nsegsx3*/
+
+	int i,j,k,l;
+	int node;
+	int el;
+	int  nriftsegs;
+	int* riftsegments=NULL; 
+	int* flags=NULL;
+	int  NumGridElementListOnOneSideOfRift;
+	int* GridElementListOnOneSideOfRift=NULL;
+
+	/*Recover input: */
+	int     nel               = *pnel;
+	int    *index             = *pindex;
+	int     nods              = *pnods;
+	double *x                 = *px;
+	double *y                 = *py;
+	int     nsegs             = *pnsegs;
+	int    *segments          = *psegments;
+	int    *segmentmarkerlist = *psegmentmarkerlist;
+
+	/*Establish list of segments that belong to a rift: */
+	/*riftsegments of size nriftsegsx4 (4 for first element on segment,second element,first node and second snode)*/
+	RiftSegmentsFromSegments(&nriftsegs,&riftsegments,nel,index,nsegs,segments);
+
+	/*Go through all nodes of the rift segments, and start splitting the mesh: */
+	flags=xNewZeroInit<int>(nods); //to make sure we don't split the same nodes twice!
+	for (i=0;i<nriftsegs;i++){
+		for (j=0;j<2;j++){
+
+			node=riftsegments[4*i+j+2];
+			if(flags[node-1]){
+				/*This node was already split, skip:*/
+				continue;
+			}
+			else{
+				flags[node-1]=1;
+			}
+
+			if(IsGridOnRift(riftsegments,nriftsegs,node)){
+
+				DetermineGridElementListOnOneSideOfRift(&NumGridElementListOnOneSideOfRift,&GridElementListOnOneSideOfRift,i,nriftsegs,riftsegments,node,index,nel);
+
+				/*Summary: we have for node, a list of elements
+				 * (GridElementListOnOneSideOfRift, of size
+				 * NumGridElementListOnOneSideOfRift) that all contain node 
+				 *and that are on the same side of the rift. For all these
+				 elements, we clone node into another node, and we swap all
+				 instances of node in the triangulation *for those elements, to the
+				 new node.*/
+
+				//create new node
+				x=xReNew<double>(x,nods,nods+1);
+				y=xReNew<double>(y,nods,nods+1);
+				x[nods]=x[node-1]; //matlab indexing
+				y[nods]=y[node-1]; //matlab indexing
+
+				//augment number of nodes 
+				nods++;
+
+				//change elements owning this node
+				for (k=0;k<NumGridElementListOnOneSideOfRift;k++){
+					el=GridElementListOnOneSideOfRift[k];
+					for (l=0;l<3;l++){
+						if (index[3*el+l]==node) index[3*el+l]=nods; //again, matlab indexing.
+					}
+				}
+			}// if(IsGridOnRift(riftsegments,nriftsegs,node))
+		} //for(j=0;j<2;j++)
+	} //for (i=0;i<nriftsegs;i++)
+
+	/*update segments: they got modified completely by adding new nodes.*/
+	UpdateSegments(&segments,&segmentmarkerlist, &nsegs,index,x,y,riftsegments,nriftsegs,nods,nel);
+
+	/*Assign output pointers: */
+	*pnel=nel;
+	*pindex=index;
+	*pnods=nods;
+	*px=x;
+	*py=y;
+	*pnsegs=nsegs;
+	*psegments=segments;
+	*psegmentmarkerlist=segmentmarkerlist;
+	return 1;
+}
Index: /issm/trunk/src/c/shared/Triangle/TriangleUtils.cpp
===================================================================
--- /issm/trunk/src/c/shared/Triangle/TriangleUtils.cpp	(revision 22758)
+++ /issm/trunk/src/c/shared/Triangle/TriangleUtils.cpp	(revision 22758)
@@ -0,0 +1,912 @@
+/*
+ * TriangleUtils: mesh manipulation routines: 
+ */
+
+#include <stdio.h>
+
+#include "./triangle.h"
+#include "../Exceptions/exceptions.h"
+#include "../MemOps/MemOps.h"
+
+#define RIFTPENALTYPAIRSWIDTH 8
+int IsGridOnRift(int* riftsegments, int nriftsegs, int node){/*{{{*/
+
+	/*Does this node belong to 4 elements, or just 2? If it belongs to 4 elements, it is inside a rift, 
+	 *if it belongs to 2 elements, it is on the tip of a rift, or it has already been split across the rift (see below).*/
+
+	int i;
+	int j;
+	int count;
+
+	count=0;
+	for (i=0;i<nriftsegs;i++){
+		for (j=0;j<2;j++){
+			if ((*(riftsegments+4*i+2+j))==node) count++;
+		}
+	}
+	if (count==2){
+		return 1;
+	}
+	else{
+		return 0;
+	}
+}/*}}}*/
+int GridElementsList(int** pGridElements, int* pNumGridElements,int node,int* index,int nel){/*{{{*/
+
+	/*From a node, recover all the elements that are connected to it: */
+	int i,j;
+	int noerr=1;
+
+	int max_number_elements=12;
+	int current_size;
+	int NumGridElements;
+	int* GridElements=NULL;
+	int* GridElementsRealloc=NULL;
+
+	/*From a mesh with 30 degrees minimum angle, we get 12 possible elements that own 
+	 * the node. We start by allocating GridElements with that size, and realloc 
+	 * more if needed.*/
+
+	current_size=max_number_elements;
+	NumGridElements=0;
+	GridElements=xNew<int>(max_number_elements);
+
+	for (i=0;i<nel;i++){
+		for (j=0;j<3;j++){
+			if (index[3*i+j]==node){
+				if (NumGridElements<=(current_size-1)){
+					GridElements[NumGridElements]=i;
+					NumGridElements++;
+					break;
+				}
+				else{
+					/*Reallocate another max_number_elements slots in the GridElements: */
+					GridElementsRealloc=xReNew<int>(GridElements,current_size,(current_size+max_number_elements));
+					if (!GridElementsRealloc){
+						noerr=0;
+						goto cleanup_and_return;
+					}
+					current_size+=max_number_elements;
+					GridElements=GridElementsRealloc;
+					GridElements[NumGridElements]=i;
+					NumGridElements++;
+					break;
+				}
+			}
+		}
+	}
+	cleanup_and_return:
+	if(!noerr){
+		xDelete<int>(GridElements);
+	}
+	/*Allocate return pointers: */
+	*pGridElements=GridElements;
+	*pNumGridElements=NumGridElements;
+	return noerr;
+}/*}}}*/
+int IsNeighbor(int el1,int el2,int* index){/*{{{*/
+	/*From a triangulation held in index, figure out if elements 1 and 2 have two nodes in common: */
+	int i,j;
+	int count=0;
+	for (i=0;i<3;i++){
+		for (j=0;j<3;j++){
+			if (index[3*el1+i]==index[3*el2+j])count++;
+		}
+	}
+	if (count==2){
+		return 1;
+	}
+	else{
+		return 0;
+	}
+}/*}}}*/
+int IsOnRift(int el,int nriftsegs,int* riftsegments){/*{{{*/
+	/*From a list of elements segments, figure out if el belongs to it: */
+	int i;
+	for (i=0;i<nriftsegs;i++){
+		if ((*(riftsegments+4*i+0)==el) || (*(riftsegments+4*i+1)==el)){
+			return 1;
+		}
+	}
+	return 0;
+}/*}}}*/
+void RiftSegmentsFromSegments(int* pnriftsegs, int** priftsegments, int nel,int* index,int nsegs,int* segments){/*{{{*/
+
+	int i,counter;
+	int el,el2;
+
+	int  nriftsegs;
+	int* riftsegments=NULL;
+	int* riftsegments_uncompressed=NULL; 
+	int  element_nodes[3];
+
+	/*Allocate segmentflags: */
+	riftsegments_uncompressed=xNewZeroInit<int>(nsegs*5);
+
+	/*Find the segments that belong to a rift: they are the ones that see two elements. The other ones belong to a boundary 
+	 *or a hole: */
+	nriftsegs=0;
+	for (i=0;i<nsegs;i++){
+		el=(int)*(segments+3*i+2)-1; //element found in AssociateSegmentToElements
+		/*Temporarily set nodes belonging to the segments to -1 in the triangulation index, and 
+		 *then  proceed to find another element that owns the segment. If we don't find it, we know 
+		 *we are dealing with a boundary or hole, otherwise, we are dealing with a rift: */
+		element_nodes[0]=*(index+3*el+0);
+		element_nodes[1]=*(index+3*el+1);
+		element_nodes[2]=*(index+3*el+2);
+
+		index[3*el+0]=-1;
+		index[3*el+1]=-1;
+		index[3*el+2]=-1;
+
+		el2=FindElement(*(segments+3*i+0),*(segments+3*i+1),index,nel); 
+
+		/*Restore index: */
+		index[3*el+0]=element_nodes[0];
+		index[3*el+1]=element_nodes[1];
+		index[3*el+2]=element_nodes[2];
+
+		if (el2!=-1){
+			/*el and el2 are on a segment rift, facing one another, plug them into riftsegments_uncompressed: */
+		    riftsegments_uncompressed[5*i+0]=1;
+		    riftsegments_uncompressed[5*i+1]=el;
+		    riftsegments_uncompressed[5*i+2]=el2;
+		    riftsegments_uncompressed[5*i+3]=segments[3*i+0];
+			 riftsegments_uncompressed[5*i+4]=segments[3*i+1];
+			 nriftsegs++;
+		}
+	}
+
+	/*Compress riftsegments_uncompressed:*/
+	riftsegments=xNew<int>(nriftsegs*4);
+	counter=0;
+	for (i=0;i<nsegs;i++){
+		if (riftsegments_uncompressed[5*i+0]){
+			riftsegments[counter*4+0]=riftsegments_uncompressed[5*i+1];
+			riftsegments[counter*4+1]=riftsegments_uncompressed[5*i+2];
+			riftsegments[counter*4+2]=riftsegments_uncompressed[5*i+3];
+			riftsegments[counter*4+3]=riftsegments_uncompressed[5*i+4];
+			counter++;
+		}
+	}
+	xDelete<int>(riftsegments_uncompressed);
+
+	/*Assign output pointers: */
+	*priftsegments=riftsegments;
+	*pnriftsegs=nriftsegs;
+}/*}}}*/
+int DetermineGridElementListOnOneSideOfRift(int* pNumGridElementListOnOneSideOfRift, int** pGridElementListOnOneSideOfRift, int segmentnumber, int nriftsegs, int* riftsegments, int node,int* index,int nel){/*{{{*/
+
+	int noerr=1;
+	int k,l,counter;
+	int newel;
+
+	int* GridElements=NULL;
+	int  NumGridElements;
+
+	/*Output: */
+	int NumGridElementListOnOneSideOfRift;
+	int* GridElementListOnOneSideOfRift=NULL;
+
+	/*Build a list of all the elements connected to this node: */
+	GridElementsList(&GridElements,&NumGridElements,node,index,nel);
+
+	/*Figure out the list of elements  that are on the same side of the rift. To do so, we start from one 
+	 * side of the rift and keep rotating in the same direction:*/
+	GridElementListOnOneSideOfRift=xNew<int>(NumGridElements);
+	//bootstrap the GridElementListOnOneSideOfRift by filling elements from riftsegments: */
+	GridElementListOnOneSideOfRift[0]=*(riftsegments+4*segmentnumber+0); /*this one does not belong to the same side, but is just there 
+															   for a rotation direction, we 'll take it out when we are 
+															   done rotating*/
+	GridElementListOnOneSideOfRift[1]=*(riftsegments+4*segmentnumber+1);
+	counter=1;
+	for (;;){
+		/*Find neighbour of element GridElementListOnOneSideOfRift[counter], not 
+		 * equal to GridElementListOnOneSideOfRift[counter-1]*/
+		for (k=0;k<NumGridElements;k++){
+			if(IsNeighbor(GridElements[k],GridElementListOnOneSideOfRift[counter],index)){
+				/*Verify this element is not already in our list of element on the same side of the rift: */
+				newel=1;
+				for (l=0;l<=counter;l++){
+					if (GridElements[k]==GridElementListOnOneSideOfRift[l]){
+						newel=0;
+						break;
+					}
+				}
+				if (newel){
+					counter++;
+					GridElementListOnOneSideOfRift[counter]=GridElements[k];
+					if (IsOnRift(GridElements[k],nriftsegs,riftsegments)){
+						break;
+					}
+					k=-1;
+				}
+			}
+		}
+		/*Reduce counter by 1 and get rift of first element in GridElementListOnOneSideOfRift:*/
+		NumGridElementListOnOneSideOfRift=counter;
+		for (l=0;l<NumGridElementListOnOneSideOfRift;l++){
+			GridElementListOnOneSideOfRift[l]=GridElementListOnOneSideOfRift[l+1];
+		}
+		break;
+	}// for (;;)
+
+	/*Free ressources: */
+	xDelete<int>(GridElements);
+	/*Assign output pointers: */
+	*pNumGridElementListOnOneSideOfRift=NumGridElementListOnOneSideOfRift;
+	*pGridElementListOnOneSideOfRift=GridElementListOnOneSideOfRift;
+	return noerr;
+}/*}}}*/
+int UpdateSegments(int** psegments,int** psegmentmarkerlist, int* pnsegs,int* index, double* x,double* y,int* riftsegments,int nriftsegs,int nods,int nel){/*{{{*/
+
+	int noerr=1;
+	int i,j,k;
+	int el1,el2;
+
+	int *segments          = NULL;
+	int *segmentmarkerlist = NULL;
+	int  nsegs;
+
+	/*Recover input: */
+	segments          = *psegments;
+	segmentmarkerlist = *psegmentmarkerlist;
+	nsegs             = *pnsegs;
+
+	/*Reallocate segments: */
+	segments         =xReNew<int>(segments,         nsegs*3,(nsegs+nriftsegs)*3);
+	segmentmarkerlist=xReNew<int>(segmentmarkerlist,nsegs,(nsegs+nriftsegs));
+
+	/*First, update the existing segments to the new nodes :*/
+	for (i=0;i<nriftsegs;i++){
+		el1=riftsegments[4*i+0];
+		el2=riftsegments[4*i+1];
+		for (j=0;j<nsegs;j++){
+			if (segments[3*j+2]==(el1+1)){
+				/*segment j is the same as rift segment i.Let's update segments[j][:] using  element el1 and the corresponding rift segment.
+				 *Because riftsegments does not represent a list of rift segments anymore (it got heavily modified in SplitElementsForRifts, 
+				 *we can only rely on the position (x,y) of the rift nodes to create a segment:*/
+				for (k=0;k<3;k++){
+					if ((x[*(index+el1*3+k)-1]==x[*(segments+3*j+0)-1]) && (y[*(index+el1*3+k)-1]==y[*(segments+3*j+0)-1])){
+						*(segments+3*j+0)=*(index+el1*3+k); _assert_(segments[3*j+0]<nods+1);
+						break;
+					}
+				}
+				for (k=0;k<3;k++){
+					if ((x[*(index+el1*3+k)-1]==x[*(segments+3*j+1)-1])  && (y[*(index+el1*3+k)-1]==y[*(segments+3*j+1)-1])){
+						*(segments+3*j+1)=*(index+el1*3+k); _assert_(segments[3*j+1]<nods+1);
+						break;
+					}
+				}
+				/*Deal with el2: */
+				*(segments+3*(nsegs+i)+2)=el2+1;
+				*(segmentmarkerlist+(nsegs+i))=*(segmentmarkerlist+j);
+				for (k=0;k<3;k++){
+					if ((x[*(index+el2*3+k)-1]==x[*(segments+3*j+0)-1]) && (y[*(index+el2*3+k)-1]==y[*(segments+3*j+0)-1])){
+						*(segments+3*(nsegs+i)+0)=*(index+el2*3+k); _assert_(segments[3*(nsegs+i)+0]<nods+1);
+						break;
+					}
+				}
+				for (k=0;k<3;k++){
+					if ((x[*(index+el2*3+k)-1]==x[*(segments+3*j+1)-1]) && (y[*(index+el2*3+k)-1]==y[*(segments+3*j+1)-1])){
+						*(segments+3*(nsegs+i)+1)=*(index+el2*3+k); _assert_(segments[3*(nsegs+i)+1]<nods+1);
+						break;
+					}
+				}
+			}
+			if (*(segments+3*j+2)==(el2+1)){
+				/*segment j is the same as rift segment i.*/
+				/*Let's update segments[j][:] using  element el2 and the corresponding rift segment: */
+				for (k=0;k<3;k++){
+					if ((x[*(index+el2*3+k)-1]==x[*(segments+3*j+0)-1]) && (y[*(index+el2*3+k)-1]==y[*(segments+3*j+0)-1])){
+						*(segments+3*j+0)=*(index+el2*3+k); _assert_(segments[3*j+0]<nods+1);
+						break;
+					}
+				}
+				for (k=0;k<3;k++){
+					if ((x[*(index+el2*3+k)-1]==x[*(segments+3*j+1)-1]) && (y[*(index+el2*3+k)-1]==y[*(segments+3*j+1)-1])){
+						*(segments+3*j+1)=*(index+el2*3+k);_assert_(segments[3*j+1]<nods+1);
+						break;
+					}
+				}
+				/*Deal with el1: */
+				*(segments+3*(nsegs+i)+2)=el1+1;
+				*(segmentmarkerlist+(nsegs+i))=*(segmentmarkerlist+j);
+				for (k=0;k<3;k++){
+					if ((x[*(index+el1*3+k)-1]==x[*(segments+3*j+0)-1]) && (y[*(index+el1*3+k)-1]==y[*(segments+3*j+0)-1])){
+						*(segments+3*(nsegs+i)+0)=*(index+el1*3+k);_assert_(segments[3*(nsegs+i)+0]<nods+1);
+						break;
+					}
+				}
+				for (k=0;k<3;k++){
+					if ((x[*(index+el1*3+k)-1]==x[*(segments+3*j+1)-1]) && (y[*(index+el1*3+k)-1]==y[*(segments+3*j+1)-1])){
+						*(segments+3*(nsegs+i)+1)=*(index+el1*3+k);_assert_(segments[3*(nsegs+i)+1]<nods+1);
+						break;
+					}
+				}
+			}
+		}
+	}
+	nsegs+=nriftsegs;
+
+	/*Assign output pointers: */
+	*psegments=segments;
+	*psegmentmarkerlist=segmentmarkerlist;
+	*pnsegs=nsegs;
+
+	return noerr;
+}/*}}}*/
+int FindElement(int A,int B,int* index,int nel){/*{{{*/
+
+	int el=-1;
+	for (int n=0;n<nel;n++){
+		if(((index[3*n+0]==A) || (index[3*n+1]==A) || (index[3*n+2]==A)) && ((index[3*n+0]==B) || (index[3*n+1]==B) || (index[3*n+2]==B))){
+			el=n;
+			break;
+		}
+	}
+	return el;
+}/*}}}*/
+int SplitRiftSegments(int** psegments,int** psegmentmarkerlist, int* pnumsegs, int* pnumrifts,int** priftsnumsegs,int*** priftssegments,int numrifts,int nods,int nel){/*{{{*/
+
+	/*Using segment markers, wring out the rift segments from the segments. Rift markers are 
+	 *of the form 2+i where i=0 to number of rifts */
+
+	int noerr=1;
+	int i,j,counter;
+
+	/*input: */
+	int *segments          = NULL;
+	int *segmentmarkerlist = NULL;
+	int numsegs;
+
+	/*output: */
+	int   new_numsegs;
+	int  *riftsnumsegs       = NULL;
+	int **riftssegments      = NULL;
+	int  *new_segments       = NULL;
+	int  *new_segmentmarkers = NULL;
+
+	/*intermediary: */
+	int* riftsegment=NULL;
+
+	/*Recover input arguments: */
+	segments          = *psegments;
+	numsegs           = *pnumsegs;
+	segmentmarkerlist = *psegmentmarkerlist;
+
+	/*First, figure out  how many segments will be left in 'segments': */
+	counter=0;
+	for (i=0;i<numsegs;i++){
+		if (segmentmarkerlist[i]==1)counter++; //1 is default marker for non-rifts;
+	}
+	/*Allocate new segments: */
+	new_numsegs=counter;
+	new_segments=xNew<int>(new_numsegs*3);
+	new_segmentmarkers=xNew<int>(new_numsegs);
+
+	/*Copy new segments info : */
+	counter=0;
+	for (i=0;i<numsegs;i++){
+		if (segmentmarkerlist[i]==1){
+			new_segments[3*counter+0]=segments[3*i+0];
+			new_segments[3*counter+1]=segments[3*i+1];
+			new_segments[3*counter+2]=segments[3*i+2];
+			new_segmentmarkers[counter]=segmentmarkerlist[i];
+			counter++;
+		}
+	}
+
+	/*Now deal with rift segments: */
+	riftsnumsegs=xNew<int>(numrifts);
+	riftssegments=xNew<int*>(numrifts);
+	for (i=0;i<numrifts;i++){
+		/*Figure out how many segments for rift i: */
+		counter=0;
+		for (j=0;j<numsegs;j++){
+			if (segmentmarkerlist[j]==2+i)counter++;
+		}
+		riftsnumsegs[i]=counter;
+		riftsegment=xNew<int>(counter*3);
+		/*Copy new segments info :*/
+		counter=0;
+		for (j=0;j<numsegs;j++){
+			if (segmentmarkerlist[j]==(2+i)){
+				riftsegment[3*counter+0]=segments[3*j+0];_assert_(riftsegment[3*counter+0]<nods+1);
+				riftsegment[3*counter+1]=segments[3*j+1];_assert_(riftsegment[3*counter+1]<nods+1);
+				riftsegment[3*counter+2]=segments[3*j+2];_assert_(riftsegment[3*counter+2]<nel+1);
+				counter++;
+			}
+		}
+		*(riftssegments+i)=riftsegment;
+	}
+
+	/*Free ressources: */
+	xDelete<int>(segments);
+
+	/*Assign output pointers: */
+	*psegments=new_segments;
+	*psegmentmarkerlist=new_segmentmarkers;
+	*pnumsegs=new_numsegs;
+	*pnumrifts=numrifts;
+	*priftssegments=riftssegments;
+	*priftsnumsegs=riftsnumsegs;
+	return noerr;
+}/*}}}*/
+int PairRiftElements(int** priftsnumpairs,int*** priftspairs,int numrifts,int* riftsnumsegments,int** riftssegments,double* x,double* y){/*{{{*/
+
+	int noerr=1;
+	int i,j,k;
+
+	/*output: */
+	int  *riftsnumpairs = NULL;
+	int **riftspairs    = NULL;
+
+	/*intermediary :*/
+	int  numsegs;
+	int* segments=NULL;
+	int* pairs=NULL;
+	int  node1,node2,node3,node4;
+
+	riftsnumpairs=xNew<int>(numrifts);
+	riftspairs=xNew<int*>(numrifts);
+	for (i=0;i<numrifts;i++){
+		segments=riftssegments[i];
+		numsegs =riftsnumsegments[i];
+		riftsnumpairs[i]=numsegs;
+		pairs=xNew<int>(2*numsegs);
+		for (j=0;j<numsegs;j++){
+			pairs[2*j+0]=segments[3*j+2]; //retrieve element to which this segment belongs.
+			node1=segments[3*j+0]-1; node2=segments[3*j+1]-1;
+			/*Find element facing on other side of rift: */
+			for (k=0;k<numsegs;k++){
+				if (k==j)continue;
+				node3=segments[3*k+0]-1; node4=segments[3*k+1]-1;
+				/*We are trying to find 2 elements, where position of node3 == position of node1, and position of node4 == position of node2*/
+				if (   ((x[node3]==x[node1]) && (y[node3]==y[node1]) && (x[node4]==x[node2]) && (y[node4]==y[node2]))
+				    || ((x[node3]==x[node2]) && (y[node3]==y[node2]) && (x[node4]==x[node1]) && (y[node4]==y[node1]))  ){
+					/*We found the corresponding element: */
+					pairs[2*j+1]=segments[3*k+2];
+					break;
+				}
+			}
+		}
+		riftspairs[i]=pairs;
+	}
+
+	/*Assign output pointers: */
+	*priftsnumpairs=riftsnumpairs;
+	*priftspairs=riftspairs;
+	return noerr;
+}/*}}}*/
+int IsRiftPresent(int* priftflag,int* pnumrifts,int* segmentmarkerlist,int nsegs){/*{{{*/
+
+	int i;
+	int noerr=1;
+
+	/*output: */
+	int riftflag=0;
+	int numrifts=0;
+
+	int maxmark=1; //default marker for regular segments
+
+	/*Any marker >=2 indicates a certain rift: */
+	numrifts=0;
+	for (i=0;i<nsegs;i++){
+		if (segmentmarkerlist[i]>maxmark){
+			numrifts++;
+			maxmark=segmentmarkerlist[i];
+		}
+	}
+	if(numrifts)riftflag=1;
+
+	/*Assign output pointers:*/
+	*priftflag=riftflag;
+	*pnumrifts=numrifts;
+	return noerr;
+}/*}}}*/
+int OrderRifts(int** priftstips,int** riftssegments,int** riftspairs,int numrifts,int* riftsnumsegments,double* x,double* y,int nods,int nels){/*{{{*/
+
+	int noerr=1;
+	int i,j,k,counter;
+
+	/*intermediary: */
+	int *riftsegments = NULL;
+	int *riftpairs    = NULL;
+	int numsegs;
+
+	/*ordering and copy: */
+	int *order             = NULL;
+	int *riftsegments_copy = NULL;
+	int *riftpairs_copy    = NULL;
+
+	/*node and element manipulation: */
+	int node1,node2,node3,node4,temp_node,tip1,tip2,node;
+	int el2;
+	int already_ordered=0;
+
+	/*output: */
+	int* riftstips=NULL;
+
+	/*Allocate byproduct of this routine, riftstips: */
+	riftstips=xNew<int>(numrifts*2);
+
+	/*Go through all rifts: */
+	for (i=0;i<numrifts;i++){
+		riftsegments = riftssegments[i];
+		riftpairs    = riftspairs[i];
+		numsegs      = riftsnumsegments[i];
+
+		/*Allocate copy of riftsegments and riftpairs, 
+		 *as well as ordering vector: */
+		riftsegments_copy=xNew<int>(numsegs*3);
+		riftpairs_copy=xNew<int>(numsegs*2);
+		order=xNew<int>(numsegs);
+
+		/*First find the tips, using the pairs. If a pair of elements has one node in common, this node is a rift tip: */
+		tip1=-1;
+		tip2=-1;
+
+		for (j=0;j<numsegs;j++){
+			el2=*(riftpairs+2*j+1);
+			node1=*(riftsegments+3*j+0);
+			node2=*(riftsegments+3*j+1);
+			/*Summary, el1 and el2 are facing one another across the rift. node1 and node2 belong to el1 and 
+			 *are located on the rift. Find node3 and node4, nodes belonging to el2 and located on the rift: */
+			for (k=0;k<numsegs;k++){
+				if (*(riftsegments+3*k+2)==el2){
+					node3=*(riftsegments+3*k+0);
+					node4=*(riftsegments+3*k+1);
+					break;
+				}
+			}
+			/* Make sure node3 faces node1 and node4 faces node2: */
+			_assert_(node1<nods+1 && node4<nods+1);
+			_assert_(node1>0 && node4>0);
+			if ((x[node1-1]==x[node4-1]) && (y[node1-1]==y[node4-1])){
+				/*Swap node3 and node4:*/
+				temp_node=node3;
+				node3=node4;
+				node4=temp_node;
+			}
+
+			/*Figure out if a tip is on this element: */
+			if (node3==node1){
+				/*node1 is a tip*/
+				if (tip1==-1) {
+					tip1=node1;
+					continue;
+				}
+				if ((tip2==-1) && (node1!=tip1)){
+					tip2=node1;
+					break;
+				}
+			}
+
+			if (node4==node2){
+				/*node2 is a tip*/
+				if (tip1==-1){
+					tip1=node2;
+					continue;
+				}
+				if ((tip2==-1) && (node2!=tip1)){
+					tip2=node2;
+					break;
+				}
+			}
+		}
+
+		/*Record tips in riftstips: */
+		*(riftstips+2*i+0)=tip1;
+		*(riftstips+2*i+1)=tip2;
+
+		/*We have the two tips for this rift.  Go from tip1 to tip2, and figure out the order in which segments are sequential. 
+		 *Because two elements are connected to tip1, we chose one first, which defines the direction we are rotating along the rift. */
+		node=tip1;
+		for (counter=0;counter<numsegs;counter++){
+			for (j=0;j<numsegs;j++){
+				node1=*(riftsegments+3*j+0);
+				node2=*(riftsegments+3*j+1);
+
+				if ((node1==node) || (node2==node)){
+					/*Ok, this segment is connected to node, plug its index into order, unless we already plugged it before: */
+					already_ordered=0;
+					for (k=0;k<counter;k++){
+						if(order[k]==j){
+							already_ordered=1;
+							break;
+						}
+					}
+					if (!already_ordered){
+						order[counter]=j;
+						if(node1==node){
+							node=node2;
+						}
+						else if(node2==node){
+							node=node1;
+						}
+						break;
+					}
+				}
+			}
+		}
+
+		/*Using the order vector, and the riftsegments_copy and riftspairs_copy, reorder the segments and the pairs: */
+		for (j=0;j<numsegs;j++){
+			_assert_(order[j]<numsegs);
+			*(riftsegments_copy+3*j+0)=*(riftsegments+3*order[j]+0);
+			*(riftsegments_copy+3*j+1)=*(riftsegments+3*order[j]+1);
+			*(riftsegments_copy+3*j+2)=*(riftsegments+3*order[j]+2);
+			*(riftpairs_copy+2*j+0)=*(riftpairs+2*order[j]+0);
+			*(riftpairs_copy+2*j+1)=*(riftpairs+2*order[j]+1);
+		}
+
+		for (j=0;j<numsegs;j++){
+			*(riftsegments+3*j+0)=*(riftsegments_copy+3*j+0);
+			*(riftsegments+3*j+1)=*(riftsegments_copy+3*j+1);
+			*(riftsegments+3*j+2)=*(riftsegments_copy+3*j+2);
+			*(riftpairs+2*j+0)=*(riftpairs_copy+2*j+0);
+			*(riftpairs+2*j+1)=*(riftpairs_copy+2*j+1);
+		}
+
+		xDelete<int>(order);
+		xDelete<int>(riftsegments_copy);
+		xDelete<int>(riftpairs_copy);
+
+	}
+
+	/*Assign output pointer:*/
+	*priftstips=riftstips;
+	return noerr;
+}/*}}}*/
+int PenaltyPairs(double*** priftspenaltypairs,int** priftsnumpenaltypairs,int numrifts,int** riftssegments,/*{{{*/
+		int* riftsnumsegs,int** riftspairs,int* riftstips,double* x,double* y){
+
+	int noerr=1;
+	int i,j,k,k0;
+
+	double el1,el2,node1,node2,node3,node4;
+	double temp_node;
+
+	/*output: */
+	double **riftspenaltypairs    = NULL;
+	double  *riftpenaltypairs     = NULL;
+	int     *riftsnumpenaltypairs = NULL;
+
+	/*intermediary: */
+	int numsegs;
+	int* riftsegments=NULL;
+	int* riftpairs=NULL;
+	int counter;
+	double normal[2];
+	double length;
+	int    k1,k2;
+
+	/*Allocate: */
+	riftspenaltypairs=xNew<double*>(numrifts);
+	riftsnumpenaltypairs=xNew<int>(numrifts);
+
+	for(i=0;i<numrifts;i++){
+		numsegs=riftsnumsegs[i];
+		riftsegments=riftssegments[i];
+		riftpairs=riftspairs[i];
+
+		/*allocate riftpenaltypairs, and riftnumpenaltypairs: */
+		if((numsegs/2-1)!=0)riftpenaltypairs=xNewZeroInit<double>((numsegs/2-1)*RIFTPENALTYPAIRSWIDTH);
+
+		/*Go through only one flank of the rifts, not counting the tips: */
+		counter=0;
+		for(j=0;j<(numsegs/2);j++){
+			el1=*(riftpairs+2*j+0);
+			el2=*(riftpairs+2*j+1);
+			node1=*(riftsegments+3*j+0);
+			node2=*(riftsegments+3*j+1);
+			/*Find segment index to recover node3 and node4, facing node1 and node2: */
+			k0=-1;
+			for(k=0;k<numsegs;k++){
+				if(*(riftsegments+3*k+2)==el2){
+					k0=k;
+					break;
+				}
+			}
+			node3=*(riftsegments+3*k0+0);
+			node4=*(riftsegments+3*k0+1);
+
+			/* Make sure node3 faces node1 and node4 faces node2: */
+			if ((x[(int)node1-1]==x[(int)node4-1]) && (y[(int)node1-1]==y[(int)node4-1])){
+				/*Swap node3 and node4:*/
+				temp_node=node3;
+				node3=node4;
+				node4=temp_node;
+			}	
+			/*Ok, we have node1 facing node3, and node2 facing node4. Compute the normal to 
+			 *this segment, and its length: */
+			normal[0]=cos(atan2(x[(int)node1-1]-x[(int)node2-1],y[(int)node2-1]-y[(int)node1-1]));
+			normal[1]=sin(atan2(x[(int)node1-1]-x[(int)node2-1],y[(int)node2-1]-y[(int)node1-1]));
+			length=sqrt(pow(x[(int)node2-1]-x[(int)node1-1],(double)2)+pow(y[(int)node2-1]-y[(int)node1-1],(double)2));
+
+			/*Be careful here, we want penalty loads on each node, not on each segment. This means we cannot plug node1,
+			 * node2, node3 and node4 directly into riftpenaltypairs. We need to include node1, node2, node3 and node4, 
+			 * only once. We'll add the normals and the lengths : */
+
+			if(node1!=node3){ //exclude tips from loads
+				k1=-1;
+				for(k=0;k<counter;k++){
+					if( (*(riftpenaltypairs+k*7+0))==node1){
+						k1=k; 
+						break;
+					}
+				}
+				if(k1==-1){
+					*(riftpenaltypairs+counter*7+0)=node1;
+					*(riftpenaltypairs+counter*7+1)=node3;
+					*(riftpenaltypairs+counter*7+2)=el1;
+					*(riftpenaltypairs+counter*7+3)=el2;
+					*(riftpenaltypairs+counter*7+4)=normal[0];
+					*(riftpenaltypairs+counter*7+5)=normal[1];
+					*(riftpenaltypairs+counter*7+6)=length/2;
+					counter++;
+				}
+				else{
+					*(riftpenaltypairs+k1*7+4)+=normal[0];
+					*(riftpenaltypairs+k1*7+5)+=normal[1];
+					*(riftpenaltypairs+k1*7+6)+=length/2;
+				}
+			}
+			if(node2!=node4){
+				k2=-1;
+				for(k=0;k<counter;k++){
+					if( (*(riftpenaltypairs+k*7+0))==node2){
+						k2=k;
+						break;
+					}
+				}
+				if(k2==-1){
+					*(riftpenaltypairs+counter*7+0)=node2;
+					*(riftpenaltypairs+counter*7+1)=node4;
+					*(riftpenaltypairs+counter*7+2)=el1;
+					*(riftpenaltypairs+counter*7+3)=el2;
+					*(riftpenaltypairs+counter*7+4)=normal[0];
+					*(riftpenaltypairs+counter*7+5)=normal[1];
+					*(riftpenaltypairs+counter*7+6)=length/2;
+					counter++;
+				}
+				else{
+					*(riftpenaltypairs+k2*7+4)+=normal[0];
+					*(riftpenaltypairs+k2*7+5)+=normal[1];
+					*(riftpenaltypairs+k2*7+6)+=length/2;
+				}
+			}
+		}
+		/*Renormalize normals: */
+		for(j=0;j<counter;j++){
+			double magnitude=sqrt(pow( double(riftpenaltypairs[j*7+4]),2) + pow( double(riftpenaltypairs[j*7+5]),2) );
+			*(riftpenaltypairs+j*7+4)=*(riftpenaltypairs+j*7+4)/magnitude;
+			*(riftpenaltypairs+j*7+5)=*(riftpenaltypairs+j*7+5)/magnitude;
+		}
+
+		riftspenaltypairs[i]=riftpenaltypairs;
+		riftsnumpenaltypairs[i]=(numsegs/2-1);
+	}
+
+	/*Assign output pointers: */
+	*priftspenaltypairs=riftspenaltypairs;
+	*priftsnumpenaltypairs=riftsnumpenaltypairs;
+	return noerr;
+}/*}}}*/
+int RemoveCornersFromRifts(int** pindex,int* pnel,double** px,double** py,int* pnods,int* segments,int* segmentmarkers,int num_seg){/*{{{*/
+
+	int noerr=1;
+	int i,j,k;
+	int node1,node2,node3;
+	int el;
+	double  pair[2];
+	int     pair_count=0;
+	int     triple=0;
+
+	/*Recover input: */
+	int    *index = *pindex;
+	int     nel   = *pnel;
+	double *x     = *px;
+	double *y     = *py;
+	int     nods  = *pnods;
+
+	for (i=0;i<num_seg;i++){
+		node1=*(segments+3*i+0);
+		node2=*(segments+3*i+1);
+		/*Find all elements connected to [node1 node2]: */
+		pair_count=0;
+		for (j=0;j<nel;j++){
+			if (*(index+3*j+0)==node1){
+				if ((*(index+3*j+1)==node2) || (*(index+3*j+2)==node2)){
+					pair[pair_count]=j;
+					pair_count++;
+				}
+			}
+			if (*(index+3*j+1)==node1){
+				if ((*(index+3*j+0)==node2) || (*(index+3*j+2)==node2)){
+					pair[pair_count]=j;
+					pair_count++;
+				}
+			}
+			if (*(index+3*j+2)==node1){
+				if ((*(index+3*j+0)==node2) || (*(index+3*j+1)==node2)){
+					pair[pair_count]=j;
+					pair_count++;
+				}
+			}
+		}
+		/*Ok, we have pair_count elements connected to this segment. For each of these elements, 
+		 *figure out if the third node also belongs to a segment: */
+		if ((pair_count==0) || (pair_count==1)){ //we only select the rift segments, which belong to  2 elements
+			continue;
+		}
+		else{
+			for (j=0;j<pair_count;j++){
+				el=(int)pair[j];
+				triple=0;
+				/*First find node3: */
+				if (*(index+3*el+0)==node1){
+					if (*(index+3*el+1)==node2)node3=*(index+3*el+2);
+					else node3=*(index+3*el+1);
+				}
+				if (*(index+3*el+1)==node1){
+					if (*(index+3*el+0)==node2)node3=*(index+3*el+2);
+					else node3=*(index+3*el+0);
+				}
+				if (*(index+3*el+2)==node1){
+					if (*(index+3*el+0)==node2)node3=*(index+3*el+1);
+					else node3=*(index+3*el+0);
+				}
+				/*Ok, we have node3. Does node3 belong to a segment? : */
+				for (k=0;k<num_seg;k++){
+					if ((node3==*(segments+3*k+0)) || (node3==*(segments+3*k+1))){
+						triple=1;
+						break;
+					}
+				}
+				if(triple==1){
+					/*el is a corner element: we need to split it in 3 triangles: */
+					x=xReNew<double>(x,nods,nods+1);
+					y=xReNew<double>(y,nods,nods+1);
+					x[nods]=(x[(int)node1-1]+x[(int)node2-1]+x[(int)node3-1])/3;
+					y[nods]=(y[(int)node1-1]+y[(int)node2-1]+y[(int)node3-1])/3;
+					index=xReNew<int>(index,nel*3,(nel+2*3));
+					/*First, reassign element el: */
+					*(index+3*el+0)=node1;
+					*(index+3*el+1)=node2;
+					*(index+3*el+2)=nods+1;
+					/*Other two elements: */
+					*(index+3*nel+0)=node2;
+					*(index+3*nel+1)=node3;
+					*(index+3*nel+2)=nods+1;
+
+					*(index+3*(nel+1)+0)=node3;
+					*(index+3*(nel+1)+1)=node1;
+					*(index+3*(nel+1)+2)=nods+1;
+					/*we need  to change the segment elements corresponding to el: */
+					for (k=0;k<num_seg;k++){
+						if (*(segments+3*k+2)==(el+1)){
+							if ( ((*(segments+3*k+0)==node1) && (*(segments+3*k+1)==node2)) || ((*(segments+3*k+0)==node2) && (*(segments+3*k+1)==node1))) *(segments+3*k+2)=el+1;
+							if ( ((*(segments+3*k+0)==node2) && (*(segments+3*k+1)==node3)) || ((*(segments+3*k+0)==node3) && (*(segments+3*k+1)==node2))) *(segments+3*k+2)=nel+1;
+							if ( ((*(segments+3*k+0)==node3) && (*(segments+3*k+1)==node1)) || ((*(segments+3*k+0)==node1) && (*(segments+3*k+1)==node3))) *(segments+3*k+2)=nel+2;
+						}
+					}
+
+					nods=nods+1;
+					nel=nel+2;
+					i=0;
+					break;
+				}
+			} //for (j=0;j<pair_count;j++)
+		}
+	}// for (i=0;i<num_seg;i++)
+
+	/*Assign output pointers: */
+	*pindex=index;
+	*pnel=nel;
+	*px=x;
+	*py=y;
+	*pnods=nods;
+	return noerr;
+}/*}}}*/
Index: /issm/trunk/src/c/shared/Triangle/triangle.h
===================================================================
--- /issm/trunk/src/c/shared/Triangle/triangle.h	(revision 22758)
+++ /issm/trunk/src/c/shared/Triangle/triangle.h	(revision 22758)
@@ -0,0 +1,33 @@
+/*!\file:  triangle.h
+ * \brief
+ */ 
+
+#ifndef _SHARED_TRIANGLE_H
+#define _SHARED_TRIANGLE_H
+
+#include <stdio.h>
+#include <math.h>
+
+//#define REAL double //took  it out because it may conflict with stdlib.h defines. put back if necessary
+int AssociateSegmentToElement(int** psegments,int nseg,int* index,int nel);
+int OrderSegments(int** psegments,int nseg, int* index,int nel);
+int GridInsideHole(double* px0,double* py0,int n,double* x,double* y);
+int FindElement(int A,int B,int* index,int nel);
+int SplitMeshForRifts(int* pnel,int** pindex,int* pnods,double** px,double** py,int* pnsegs,int** psegments,int** psegmentmarkerlist);
+int IsGridOnRift(int* riftsegments, int nriftsegs, int node);
+int GridElementsList(int** pGridElements, int* pNumGridElements,int node,double * index,int nel);
+int IsNeighbor(int el1,int el2,int* index);
+int IsOnRift(int el,int nriftsegs,int* riftsegments);
+void RiftSegmentsFromSegments(int* pnriftsegs, int** priftsegments, int nel,int* index, int nsegs,int* segments);
+int DetermineGridElementListOnOneSideOfRift(int* pNumGridElementListOnOneSideOfRift, int** pGridElementListOnOneSideOfRift,int segmentnumber, int nriftsegs,int* riftsegments, int node,int* index,int nel);
+int UpdateSegments(int** psegments,int** psegmentmarkerlist, int* pnsegs,int* index, double* x,double* y,int* riftsegments,int nriftsegs,int nods,int nel);
+int FindElement(double A,double B,int* index,int nel);
+int IsRiftPresent(int* priftflag,int* pnumrifts,int* segmentmarkerlist,int nsegs);
+int SplitRiftSegments(int** psegments,int** psegmentmarkerlist, int* pnumsegs, int* pnumrifts,int** priftsnumsegs,int*** priftssegments,int numrifts,int nods,int nels);
+int OrderRifts(int** priftstips,int** riftssegments,int** riftspairs,int numrifts,int* riftsnumsegments,double* x,double* y,int nods,int nels);
+int PenaltyPairs(double*** priftspenaltypairs,int** priftsnumpenaltypairs,int numrifts,int**  riftssegments,
+		int* riftsnumsegments,int** riftspairs,int* riftstips,double* x,double* y);
+int RemoveCornersFromRifts(int** pindex,int* pnel,double** px,double** py,int* pnods,int* segments,int* segmentmarkers,int num_seg);
+int PairRiftElements(int** priftsnumpairs,int*** priftspairs,int numrifts,int* riftsnumsegments,int** riftssegments,double* x,double* y);
+
+#endif  /* _SHARED_TRIANGLE_H */
Index: /issm/trunk/src/c/shared/io/Marshalling/IoCodeConversions.cpp
===================================================================
--- /issm/trunk/src/c/shared/io/Marshalling/IoCodeConversions.cpp	(revision 22757)
+++ /issm/trunk/src/c/shared/io/Marshalling/IoCodeConversions.cpp	(revision 22758)
@@ -11,54 +11,134 @@
 	/*output*/
 	char* fieldname = NULL;
-	int   param_enum = -1;
-
-	if(strcmp(string_in,"Thickness")==0){
+	int   input_enum = -1;
+
+	if(strcmp(string_in,"Thickness")==0 || strcmp(string_in,"md.geometry.thickness")==0){
 		const char* field = "md.geometry.thickness";
-		param_enum        = ThicknessEnum;
+		input_enum        = ThicknessEnum;
 		fieldname=xNew<char>((strlen(field)+1)); xMemCpy<char>(fieldname,field,(strlen(field)+1));
 	}
 	else if(strcmp(string_in,"MaterialsRheologyB")==0){
 		const char* field = "md.materials.rheology_B";
-		param_enum        = MaterialsRheologyBEnum;
+		input_enum        = MaterialsRheologyBEnum;
 		fieldname=xNew<char>((strlen(field)+1)); xMemCpy<char>(fieldname,field,(strlen(field)+1));
 	}
 	else if(strcmp(string_in,"SmbMassBalance")==0){
 		const char* field = "md.smb.mass_balance";
-		param_enum        = SmbMassBalanceEnum;
+		input_enum        = SmbMassBalanceEnum;
 		fieldname=xNew<char>((strlen(field)+1)); xMemCpy<char>(fieldname,field,(strlen(field)+1));
 	}
 	else if(strcmp(string_in,"SmbAccumulation")==0){
 		const char* field = "md.smb.accumulation";
-		param_enum        = SmbAccumulationEnum;
+		input_enum        = SmbAccumulationEnum;
 		fieldname=xNew<char>((strlen(field)+1)); xMemCpy<char>(fieldname,field,(strlen(field)+1));
 	}
 	else if(strcmp(string_in,"SmbMelt")==0){
 		const char* field = "md.smb.melt";
-		param_enum        = SmbMeltEnum;
+		input_enum        = SmbMeltEnum;
 		fieldname=xNew<char>((strlen(field)+1)); xMemCpy<char>(fieldname,field,(strlen(field)+1));
 	}
 	else if(strcmp(string_in,"SmbRefreeze")==0){
 		const char* field = "md.smb.refreeze";
-		param_enum        = SmbRefreezeEnum;
+		input_enum        = SmbRefreezeEnum;
 		fieldname=xNew<char>((strlen(field)+1)); xMemCpy<char>(fieldname,field,(strlen(field)+1));
 	}
 	else if(strcmp(string_in,"SmbRunoff")==0){
 		const char* field = "md.smb.runoff";
-		param_enum        = SmbRunoffEnum;
+		input_enum        = SmbRunoffEnum;
 		fieldname=xNew<char>((strlen(field)+1)); xMemCpy<char>(fieldname,field,(strlen(field)+1));
 	}
 	else if(strcmp(string_in,"SmbEvaporation")==0){
 		const char* field = "md.smb.evaporation";
-		param_enum        = SmbEvaporationEnum;
+		input_enum        = SmbEvaporationEnum;
+		fieldname=xNew<char>((strlen(field)+1)); xMemCpy<char>(fieldname,field,(strlen(field)+1));
+	}
+	else if(strcmp(string_in,"SmbTa")==0){
+		const char* field = "md.smb.Ta";
+		input_enum        = SmbTaEnum;
+		fieldname=xNew<char>((strlen(field)+1)); xMemCpy<char>(fieldname,field,(strlen(field)+1));
+	}
+	else if(strcmp(string_in,"SmbV")==0){
+		const char* field = "md.smb.V";
+		input_enum        = SmbVEnum;
+		fieldname=xNew<char>((strlen(field)+1)); xMemCpy<char>(fieldname,field,(strlen(field)+1));
+	}
+	else if(strcmp(string_in,"SmbDswrf")==0){
+		const char* field = "md.smb.dswrf";
+		input_enum        = SmbDswrfEnum;
+		fieldname=xNew<char>((strlen(field)+1)); xMemCpy<char>(fieldname,field,(strlen(field)+1));
+	}
+	else if(strcmp(string_in,"SmbDlwrf")==0){
+		const char* field = "md.smb.dlwrf";
+		input_enum        = SmbDlwrfEnum;
+		fieldname=xNew<char>((strlen(field)+1)); xMemCpy<char>(fieldname,field,(strlen(field)+1));
+	}
+	else if(strcmp(string_in,"SmbP")==0){
+		const char* field = "md.smb.P";
+		input_enum        = SmbPEnum;
+		fieldname=xNew<char>((strlen(field)+1)); xMemCpy<char>(fieldname,field,(strlen(field)+1));
+	}
+	else if(strcmp(string_in,"SmbEAir")==0){
+		const char* field = "md.smb.eAir";
+		input_enum        = SmbEAirEnum;
+		fieldname=xNew<char>((strlen(field)+1)); xMemCpy<char>(fieldname,field,(strlen(field)+1));
+	}
+	else if(strcmp(string_in,"SmbPAir")==0){
+		const char* field = "md.smb.pAir";
+		input_enum        = SmbPAirEnum;
+		fieldname=xNew<char>((strlen(field)+1)); xMemCpy<char>(fieldname,field,(strlen(field)+1));
+	}
+	else if(strcmp(string_in,"SmbVz")==0){
+		const char* field = "md.smb.Vz";
+		input_enum        = SmbVzEnum;
+		fieldname=xNew<char>((strlen(field)+1)); xMemCpy<char>(fieldname,field,(strlen(field)+1));
+	}
+	else if(strcmp(string_in,"SmbTz")==0){
+		const char* field = "md.smb.Tz";
+		input_enum        = SmbTzEnum;
+		fieldname=xNew<char>((strlen(field)+1)); xMemCpy<char>(fieldname,field,(strlen(field)+1));
+	}
+	else if(strcmp(string_in,"SmbC")==0){
+		const char* field = "md.smb.C";
+		input_enum        = SmbCEnum;
 		fieldname=xNew<char>((strlen(field)+1)); xMemCpy<char>(fieldname,field,(strlen(field)+1));
 	}
 	else if(strcmp(string_in,"BasalforcingsFloatingiceMeltingRate")==0){
 		const char* field = "md.basalforcings.floatingice_melting_rate";
-		param_enum        = BasalforcingsFloatingiceMeltingRateEnum;
-		fieldname=xNew<char>((strlen(field)+1)); xMemCpy<char>(fieldname,field,(strlen(field)+1));
-	}
-	else if(strcmp(string_in,"FrictionCoefficient")==0){
+		input_enum        = BasalforcingsFloatingiceMeltingRateEnum;
+		fieldname=xNew<char>((strlen(field)+1)); xMemCpy<char>(fieldname,field,(strlen(field)+1));
+	}
+	else if(strcmp(string_in,"FrictionCoefficient")==0 || strcmp(string_in,"md.friction.coefficient")==0){
 		const char* field = "md.friction.coefficient";
-		param_enum        = FrictionCoefficientEnum;
+		input_enum        = FrictionCoefficientEnum;
+		fieldname=xNew<char>((strlen(field)+1)); xMemCpy<char>(fieldname,field,(strlen(field)+1));
+	}
+	else if(strcmp(string_in,"Vx")==0){
+		 const char* field = "md.initialization.vx";
+		 input_enum        = VxEnum;
+		 fieldname=xNew<char>((strlen(field)+1)); xMemCpy<char>(fieldname,field,(strlen(field)+1));
+	 }
+	else if(strcmp(string_in,"Vy")==0){
+		 const char* field = "md.initialization.vy";
+		 input_enum        = VyEnum;
+		 fieldname=xNew<char>((strlen(field)+1)); xMemCpy<char>(fieldname,field,(strlen(field)+1));
+	 }
+	else if(strcmp(string_in,"BalancethicknessThickeningRate")==0){
+		 const char* field = "md.balancethickness.thickening_rate";
+		 input_enum        = BalancethicknessThickeningRateEnum;
+		 fieldname=xNew<char>((strlen(field)+1)); xMemCpy<char>(fieldname,field,(strlen(field)+1));
+	}
+	else if(strcmp(string_in,"BalancethicknessSpcthickness")==0){
+		 const char* field = "md.balancethickness.spcthickness";
+		 input_enum        = BalancethicknessSpcthicknessEnum;
+		 fieldname=xNew<char>((strlen(field)+1)); xMemCpy<char>(fieldname,field,(strlen(field)+1));
+	}
+	else if(strcmp(string_in,"CalvingMeltingrate")==0){
+		const char* field = "md.calving.meltingrate";
+		input_enum        = CalvingMeltingrateEnum;
+		fieldname=xNew<char>((strlen(field)+1)); xMemCpy<char>(fieldname,field,(strlen(field)+1));
+	}
+	else if(strcmp(string_in,"CalvingStressThresholdGroundedice")==0){
+		const char* field = "md.calving.stress_threshold_groundedice";
+		input_enum        = CalvingStressThresholdGroundediceEnum;
 		fieldname=xNew<char>((strlen(field)+1)); xMemCpy<char>(fieldname,field,(strlen(field)+1));
 	}
@@ -68,5 +148,5 @@
 
 	/*Assign output pointers*/
-	*out_enum = param_enum;
+	*out_enum = input_enum;
 	*pfield   = fieldname;
 	return;
@@ -92,4 +172,5 @@
 		case 3: return MismipFloatingMeltRateEnum;
 		case 4: return MantlePlumeGeothermalFluxEnum;
+		case 5: return BasalforcingsPicoEnum;
 		default: _error_("Marshalled Basal Forcings code \""<<enum_in<<"\" not supported yet");
 	}
@@ -98,7 +179,10 @@
 	switch(enum_in){
 		case 1: return DefaultCalvingEnum;
-		case 2: return CalvingDevEnum;
+		case 2: return CalvingVonmisesEnum;
 		case 3: return CalvingLevermannEnum;
 		case 4: return CalvingMinthicknessEnum;
+		case 5: return CalvingHabEnum;
+		case 6: return CalvingCrevasseDepthEnum;
+		case 7: return CalvingDev2Enum;
 		default: _error_("Marshalled Calving law code \""<<enum_in<<"\" not supported yet");
 	}
@@ -118,5 +202,21 @@
 		case 3: return MaticeEnum;
 		case 4: return MatenhancediceEnum;
+		case 5: return MatlithoEnum;
+		case 6: return MaterialsEnum;
 		default: _error_("Marshalled materials code \""<<enum_in<<"\" not supported yet"); 
+	}
+}/*}}}*/
+int IoCodeToEnumTimestepping(int enum_in){/*{{{*/
+	switch(enum_in){
+		case 1: return FixedTimesteppingEnum;
+		case 2: return AdaptiveTimesteppingEnum; 
+		default: _error_("Marshalled materials code \""<<enum_in<<"\" not supported yet"); 
+	}
+}/*}}}*/
+int IoCodeToEnumAmr(int enum_in){/*{{{*/
+	switch(enum_in){
+		case 1: return AmrBamgEnum;
+		case 2: return AmrNeopzEnum; 
+		default: _error_("Marshalled AMR code \""<<enum_in<<"\" not supported yet"); 
 	}
 }/*}}}*/
Index: /issm/trunk/src/c/shared/io/Marshalling/IoCodeConversions.h
===================================================================
--- /issm/trunk/src/c/shared/io/Marshalling/IoCodeConversions.h	(revision 22757)
+++ /issm/trunk/src/c/shared/io/Marshalling/IoCodeConversions.h	(revision 22758)
@@ -9,4 +9,6 @@
 int IoCodeToEnumHydrology(int enum_in);
 int IoCodeToEnumMaterials(int enum_in);
+int IoCodeToEnumTimestepping(int enum_in);
+int IoCodeToEnumAmr(int enum_in);
 
 int IoCodeToEnumVertexEquation(int enum_in);
Index: /issm/trunk/src/c/shared/shared.h
===================================================================
--- /issm/trunk/src/c/shared/shared.h	(revision 22757)
+++ /issm/trunk/src/c/shared/shared.h	(revision 22758)
@@ -19,5 +19,5 @@
 #include "./String/sharedstring.h"
 #include "./Threads/issm_threads.h"
-#include "./TriMesh/trimesh.h"
+#include "./Triangle/triangle.h"
 #include "./LatLong/latlong.h"
 
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_adjoint_linear.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_adjoint_linear.cpp	(revision 22757)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_adjoint_linear.cpp	(revision 22758)
@@ -29,5 +29,9 @@
 	CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
 	Reduceloadx(pf, Kfs, ys,true); delete Kfs; //true means spc = 0
+
+	femmodel->profiler->Start(SOLVER);
 	Solverx(&uf, Kff, pf, NULL, df, femmodel->parameters); delete Kff; delete pf; delete df;
+	femmodel->profiler->Stop(SOLVER);
+
 	Mergesolutionfromftogx(&ug, uf,ys,femmodel->nodes,femmodel->parameters,true); delete ys; //true means spc0
 	InputUpdateFromSolutionx(femmodel,ug);
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_fct.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_fct.cpp	(revision 22757)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_fct.cpp	(revision 22758)
@@ -404,5 +404,7 @@
 	
 	/*Go solve lower order solution*/
+	femmodel->profiler->Start(SOLVER);
 	SolverxPetsc(&u,LHS,RHS,NULL,NULL, femmodel->parameters); 
+	femmodel->profiler->Stop(SOLVER);
 	MatFree(&LHS);
 	VecFree(&RHS);
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_hydro_nonlinear.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_hydro_nonlinear.cpp	(revision 22757)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_hydro_nonlinear.cpp	(revision 22758)
@@ -47,5 +47,4 @@
 	IssmDouble ndu_epl,nu_epl;
 	IssmDouble ThickCount,L2Count;
-	
 	/*Recover parameters: */
 	femmodel->SetCurrentConfiguration(HydrologyDCInefficientAnalysisEnum);
@@ -53,5 +52,4 @@
 	femmodel->parameters->FindParam(&hydro_maxiter,HydrologydcMaxIterEnum);
 	femmodel->parameters->FindParam(&eps_hyd,HydrologydcRelTolEnum);
-
 	hydrocount=1;
 	hydroconverged=false;
@@ -62,5 +60,4 @@
 	GetSolutionFromInputsx(&ug_sed,femmodel);	
 	Reducevectorgtofx(&uf_sed, ug_sed, femmodel->nodes,femmodel->parameters);
-
 	if(isefficientlayer) {
 		inefanalysis = new HydrologyDCInefficientAnalysis();
@@ -90,5 +87,4 @@
 		InputUpdateFromConstantx(femmodel,false,ConvergedEnum);
 		femmodel->UpdateConstraintsx();
-		femmodel->parameters->SetParam(HydrologySedimentEnum,HydrologyLayerEnum);
 		
 		/*Reset constraint on the ZigZag Lock*/
@@ -108,5 +104,9 @@
 				Reduceloadx(pf,Kfs,ys); delete Kfs;
 				delete uf_sed;
+
+				femmodel->profiler->Start(SOLVER);
 				Solverx(&uf_sed,Kff,pf,uf_sed_sub_iter,df,femmodel->parameters);
+				femmodel->profiler->Stop(SOLVER);
+
 				delete Kff; delete pf; delete df;
 				delete ug_sed;
@@ -163,5 +163,4 @@
 			InputUpdateFromConstantx(femmodel,true,ResetPenaltiesEnum);
 			InputUpdateFromConstantx(femmodel,false,ConvergedEnum);
-			femmodel->parameters->SetParam(HydrologyEfficientEnum,HydrologyLayerEnum);
 
 			for(;;){
@@ -191,5 +190,7 @@
 				Reduceloadx(pf,Kfs,ys); delete Kfs;
 				delete uf_epl;
+				femmodel->profiler->Start(SOLVER);
 				Solverx(&uf_epl,Kff,pf,uf_epl_sub_iter,df,femmodel->parameters);
+				femmodel->profiler->Stop(SOLVER);
 				delete Kff; delete pf; delete df;
 				delete uf_epl_sub_iter;
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_la.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_la.cpp	(revision 22757)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_la.cpp	(revision 22758)
@@ -64,5 +64,9 @@
 			CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
 			Reduceloadx(pf, Kfs, ys); delete Kfs;
+
+			femmodel->profiler->Start(SOLVER);
 			Solverx(&uf, Kff, pf, NULL, df, femmodel->parameters); 
+			femmodel->profiler->Stop(SOLVER);
+
 			delete Kff; delete pf; delete df;
 			Mergesolutionfromftogx(&ug, uf,ys,femmodel->nodes,femmodel->parameters);delete uf; delete ys;
@@ -95,5 +99,9 @@
 		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
 		Reduceloadx(pf, Kfs, ys); delete Kfs;
+
+		femmodel->profiler->Start(SOLVER);
 		Solverx(&uf, Kff, pf, NULL, df, femmodel->parameters); 
+		femmodel->profiler->Stop(SOLVER);
+
 		delete Kff; delete pf; delete df;
 		Mergesolutionfromftogx(&pug, uf,ys,femmodel->nodes,femmodel->parameters); delete uf; delete ys;
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_la_theta.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_la_theta.cpp	(revision 22757)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_la_theta.cpp	(revision 22758)
@@ -59,5 +59,9 @@
 		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
 		Reduceloadx(pf, Kfs, ys); delete Kfs;
+
+		femmodel->profiler->Start(SOLVER);
 		Solverx(&uf, Kff, pf, NULL, df, femmodel->parameters); 
+		femmodel->profiler->Stop(SOLVER);
+
 		delete Kff; delete pf; delete df;
 		Mergesolutionfromftogx(&ug, uf,ys,femmodel->nodes,femmodel->parameters);delete uf; delete ys;
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_linear.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_linear.cpp	(revision 22757)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_linear.cpp	(revision 22758)
@@ -35,5 +35,8 @@
 	CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
 	Reduceloadx(pf, Kfs, ys); delete Kfs;
+
+	femmodel->profiler->Start(SOLVER);
 	Solverx(&uf, Kff, pf, NULL, df, femmodel->parameters); 
+	femmodel->profiler->Stop(SOLVER);
 	
 	/*Check that the solver converged nicely: */
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_newton.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_newton.cpp	(revision 22757)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_newton.cpp	(revision 22758)
@@ -63,5 +63,7 @@
 			CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
 			Reduceloadx(pf,Kfs,ys);delete Kfs;
+			femmodel->profiler->Start(SOLVER);
 			Solverx(&uf,Kff,pf,old_uf,df,femmodel->parameters);delete df; delete Kff; delete pf;
+			femmodel->profiler->Stop(SOLVER);
 			Mergesolutionfromftogx(&ug,uf,ys,femmodel->nodes,femmodel->parameters);delete ys;
 			InputUpdateFromSolutionx(femmodel,ug);
@@ -81,5 +83,7 @@
 
 		CreateJacobianMatrixx(&Jff,femmodel,kmax);
+		femmodel->profiler->Start(SOLVER);
 		Solverx(&duf,Jff,pJf,NULL,NULL,femmodel->parameters); delete Jff; delete pJf;
+		femmodel->profiler->Stop(SOLVER);
 		uf->AXPY(duf, 1.0); delete duf;
 		Mergesolutionfromftogx(&ug,uf,ys,femmodel->nodes,femmodel->parameters);delete ys;
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_nonlinear.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_nonlinear.cpp	(revision 22757)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_nonlinear.cpp	(revision 22758)
@@ -67,5 +67,7 @@
 		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
 		Reduceloadx(pf, Kfs, ys); delete Kfs;
+		femmodel->profiler->Start(SOLVER);
 		Solverx(&uf, Kff, pf, old_uf, df, femmodel->parameters);
+		femmodel->profiler->Stop(SOLVER);
 		Mergesolutionfromftogx(&ug, uf,ys,femmodel->nodes,femmodel->parameters);delete ys;
 
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_shakti_nonlinear.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_shakti_nonlinear.cpp	(revision 22758)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_shakti_nonlinear.cpp	(revision 22758)
@@ -0,0 +1,78 @@
+/*!\file: solutionsequence_nonlinear.cpp
+ * \brief: core of a non-linear solution, using fixed-point method 
+ */ 
+
+#include "./solutionsequences.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+void solutionsequence_shakti_nonlinear(FemModel* femmodel){
+
+	/*intermediary: */
+	Matrix<IssmDouble>* Kff = NULL;
+	Matrix<IssmDouble>* Kfs = NULL;
+	Vector<IssmDouble>* ug  = NULL;
+	Vector<IssmDouble>* uf  = NULL;
+	Vector<IssmDouble>* old_uf = NULL;
+	Vector<IssmDouble>* pf  = NULL;
+	Vector<IssmDouble>* df  = NULL;
+	Vector<IssmDouble>* ys  = NULL;
+
+	/*parameters:*/
+	int max_nonlinear_iterations;
+	int configuration_type;
+	IssmDouble eps_res,eps_rel,eps_abs;
+
+	/*Recover parameters: */
+	femmodel->parameters->FindParam(&max_nonlinear_iterations,StressbalanceMaxiterEnum);
+	femmodel->parameters->FindParam(&eps_res,StressbalanceRestolEnum);
+	femmodel->parameters->FindParam(&eps_rel,StressbalanceReltolEnum);
+	femmodel->parameters->FindParam(&eps_abs,StressbalanceAbstolEnum);
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	femmodel->UpdateConstraintsx();
+
+	int  count=0;
+	bool converged=false;
+
+	/*Start non-linear iteration using input velocity: */
+	GetSolutionFromInputsx(&ug,femmodel);
+	Reducevectorgtofx(&uf, ug, femmodel->nodes,femmodel->parameters);
+
+	//Update once again the solution to make sure that vx and vxold are similar (for next step in transient or steadystate)
+	InputUpdateFromConstantx(femmodel,converged,ConvergedEnum);
+
+	for(;;){
+		/*save pointer to old solution*/
+		delete old_uf;old_uf=uf;
+		delete ug;
+
+		SystemMatricesx(&Kff,&Kfs,&pf,&df,NULL,femmodel);
+		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
+		Reduceloadx(pf, Kfs, ys); delete Kfs;
+		femmodel->profiler->Start(SOLVER);
+		Solverx(&uf, Kff, pf, old_uf, df, femmodel->parameters);
+		femmodel->profiler->Stop(SOLVER);
+		Mergesolutionfromftogx(&ug, uf,ys,femmodel->nodes,femmodel->parameters);delete ys;
+
+		convergence(&converged,Kff,pf,uf,old_uf,eps_res,eps_rel,eps_abs); delete Kff; delete pf; delete df;
+		InputUpdateFromConstantx(femmodel,converged,ConvergedEnum);
+		InputUpdateFromSolutionx(femmodel,ug);
+
+		/*Increase count: */
+		count++;
+		if(count>=max_nonlinear_iterations){
+			_printf0_("   maximum number of nonlinear iterations (" << max_nonlinear_iterations << ") exceeded\n"); 
+			converged = true;
+		}
+		if(converged) break;
+	}
+
+	if(VerboseConvergence()) _printf0_("\n   total number of iterations: " << count << "\n");
+
+	/*clean-up*/
+	delete uf;
+	delete ug;
+	delete old_uf;
+}
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_stokescoupling_nonlinear.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_stokescoupling_nonlinear.cpp	(revision 22757)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_stokescoupling_nonlinear.cpp	(revision 22758)
@@ -68,5 +68,7 @@
 		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
 		Reduceloadx(pf_horiz, Kfs_horiz, ys); delete Kfs_horiz;
+		femmodel->profiler->Start(SOLVER);
 		Solverx(&uf_horiz, Kff_horiz, pf_horiz, old_uf_horiz, df_horiz,femmodel->parameters);
+		femmodel->profiler->Stop(SOLVER);
 		Mergesolutionfromftogx(&ug_horiz, uf_horiz,ys,femmodel->nodes,femmodel->parameters); delete ys;
 		InputUpdateFromSolutionx(femmodel,ug_horiz);
@@ -82,5 +84,7 @@
 		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
 		Reduceloadx(pf_vert, Kfs_vert, ys); delete Kfs_vert;
+		femmodel->profiler->Start(SOLVER);
 		Solverx(&uf_vert, Kff_vert, pf_vert, NULL, df_vert,femmodel->parameters); delete Kff_vert; delete pf_vert; delete df_vert;
+		femmodel->profiler->Stop(SOLVER);
 		Mergesolutionfromftogx(&ug_vert, uf_vert,ys,femmodel->nodes,femmodel->parameters);
 		delete uf_vert; 
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_thermal_nonlinear.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_thermal_nonlinear.cpp	(revision 22757)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_thermal_nonlinear.cpp	(revision 22758)
@@ -77,5 +77,7 @@
 		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
 		Reduceloadx(pf, Kfs, ys); delete Kfs;
+		femmodel->profiler->Start(SOLVER);
 		Solverx(&tf, Kff, pf, tf_old, df, femmodel->parameters);
+		femmodel->profiler->Stop(SOLVER);
 		Mergesolutionfromftogx(&tg, tf,ys,femmodel->nodes,femmodel->parameters); delete ys;
 		if(isenthalpy){ 
Index: /issm/trunk/src/c/solutionsequences/solutionsequences.h
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequences.h	(revision 22757)
+++ /issm/trunk/src/c/solutionsequences/solutionsequences.h	(revision 22758)
@@ -14,4 +14,5 @@
 void solutionsequence_thermal_nonlinear(FemModel* femmodel);
 void solutionsequence_hydro_nonlinear(FemModel* femmodel);
+void solutionsequence_shakti_nonlinear(FemModel* femmodel);
 void solutionsequence_nonlinear(FemModel* femmodel,bool conserve_loads);
 void solutionsequence_newton(FemModel* femmodel);
Index: /issm/trunk/src/c/toolkits/ToolkitOptions.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/ToolkitOptions.cpp	(revision 22757)
+++ /issm/trunk/src/c/toolkits/ToolkitOptions.cpp	(revision 22758)
@@ -9,21 +9,24 @@
 #include "../shared/MemOps/MemOps.h"
 
-void ToolkitOptions::Init(char* options){ /*{{{*/
+void  ToolkitOptions::Init(const char* toolkit_in,const char* options){ /*{{{*/
 
 	/*First, avoid a leak: */
 	xDelete<char>(toolkitoptions);
+	xDelete<char>(toolkittype);
 
 	/*copy options into toolkitoptions:*/
+	_assert_(toolkit_in);
 	_assert_(options);
-	toolkitoptions= xNew<char>(strlen(options)+1); 
-	sprintf(toolkitoptions,   "%s",options);
-
+	toolkittype = xNew<char>(strlen(toolkit_in)+1); 
+	sprintf(toolkittype,"%s",toolkit_in);
+	toolkitoptions = xNew<char>(strlen(options)+1); 
+	sprintf(toolkitoptions,"%s",options);
 }/*}}}*/
 char* ToolkitOptions::GetToolkitType(){  /*{{{*/
 
-	/*Look for token: -toolkit, and return value:*/
-
-	return TokenValue(toolkitoptions,"toolkit");
-
+	_assert_(toolkittype); 
+	char* toolkittype_out = xNew<char>(strlen(toolkittype)+1); 
+	sprintf(toolkittype_out,"%s",toolkittype);
+	return toolkittype_out;
 }/*}}}*/
 char* ToolkitOptions::GetToolkitOptionValue(const char* option){  /*{{{*/
Index: /issm/trunk/src/c/toolkits/ToolkitOptions.h
===================================================================
--- /issm/trunk/src/c/toolkits/ToolkitOptions.h	(revision 22757)
+++ /issm/trunk/src/c/toolkits/ToolkitOptions.h	(revision 22758)
@@ -11,8 +11,9 @@
 
 	private:
+		static char* toolkittype;
 		static char* toolkitoptions;
 
 	public:
-		static void Init(char* options);
+		static void Init(const char* type_in,const char* options);
 		static char* GetToolkitType(void);
 		static char* GetToolkitOptionValue(const char* option);
Index: /issm/trunk/src/c/toolkits/issm/IssmDenseMat.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/IssmDenseMat.h	(revision 22757)
+++ /issm/trunk/src/c/toolkits/issm/IssmDenseMat.h	(revision 22758)
@@ -140,5 +140,5 @@
 			switch(mode){
 				case NORM_INF:
-					norm=0;
+					norm=0.;
 					for(i=0;i<this->M;i++){
 						absolute=0;
@@ -151,8 +151,8 @@
 					break; 
 				case NORM_FROB:
-					norm=0;
+					norm=0.;
 					for(i=0;i<this->M;i++){
 						for(j=0;j<this->N;j++){
-							norm+=pow(this->matrix[N*i+j],2);
+							norm+=this->matrix[N*i+j]*this->matrix[N*i+j];
 						}
 					}
Index: /issm/trunk/src/c/toolkits/issm/IssmMpiDenseMat.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/IssmMpiDenseMat.h	(revision 22757)
+++ /issm/trunk/src/c/toolkits/issm/IssmMpiDenseMat.h	(revision 22758)
@@ -311,5 +311,5 @@
 			switch(mode){
 				case NORM_INF:
-					local_norm=0;
+					local_norm=0.;
 					for(i=0;i<this->m;i++){
 						absolute=0;
@@ -324,8 +324,8 @@
 					break; 
 				case NORM_FROB:
-					local_norm=0;
+					local_norm=0.;
 					for(i=0;i<this->m;i++){
 						for(j=0;j<this->N;j++){
-							local_norm+=pow(this->matrix[N*i+j],2);
+							local_norm+=this->matrix[N*i+j]*this->matrix[N*i+j];
 						}
 					}
Index: /issm/trunk/src/c/toolkits/issm/IssmMpiSparseMat.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/IssmMpiSparseMat.h	(revision 22757)
+++ /issm/trunk/src/c/toolkits/issm/IssmMpiSparseMat.h	(revision 22758)
@@ -24,5 +24,4 @@
 #include "./SparseRow.h"
 #include <math.h>
-
 /*}}}*/
 
Index: /issm/trunk/src/c/toolkits/issm/IssmMpiVec.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/IssmMpiVec.h	(revision 22757)
+++ /issm/trunk/src/c/toolkits/issm/IssmMpiVec.h	(revision 22758)
@@ -141,11 +141,4 @@
 			/*Do a synchronized dump across all the rows: */
 			for(i=0;i<IssmComm::GetSize();i++){
-				if (IssmComm::GetRank()==i){
-					_printf_("cpu " << i << " #rows: " << this->m << "\n");
-					for (j=0;j<this->m;j++){
-						_printf_("row " << j << " " << this->vector[j] << "\n");
-					}
-					_printf_("\n");
-				}
 				ISSM_MPI_Barrier(IssmComm::GetComm());
 			}
@@ -250,5 +243,5 @@
 			for(i=0;i<num_procs;i++){
 				ISSM_MPI_Scatterv( row_indices_forcpu, sendcnts, displs, ISSM_MPI_INT, row_indices_fromcpu[i], numvalues_fromcpu[i], ISSM_MPI_INT, i, comm);
-				ISSM_MPI_Scatterv( values_forcpu, sendcnts, displs, ISSM_MPI_DOUBLE, values_fromcpu[i], numvalues_fromcpu[i], ISSM_MPI_DOUBLE, i, comm);
+				ISSM_MPI_Scatterv( values_forcpu, sendcnts, displs, TypeToMPIType<doubletype>(), values_fromcpu[i], numvalues_fromcpu[i], TypeToMPIType<doubletype>(), i, comm);
 				ISSM_MPI_Scatterv( modes_forcpu, sendcnts, displs, ISSM_MPI_INT, modes_fromcpu[i], numvalues_fromcpu[i], ISSM_MPI_INT, i, comm);
 			}
@@ -402,4 +395,5 @@
 			num_procs=IssmComm::GetSize();
 
+
 			/*Allocate: */
 // AD performance is sensitive to calls to ensurecontiguous.
@@ -424,6 +418,5 @@
 
 			/*All gather:*/
-			ISSM_MPI_Allgatherv(this->vector, this->m, ISSM_MPI_DOUBLE, buffer, recvcounts, displs, ISSM_MPI_DOUBLE,comm);
-
+			ISSM_MPI_Allgatherv(this->vector, this->m, TypeToMPIType<doubletype>(), buffer, recvcounts, displs, TypeToMPIType<doubletype>(),comm);
 			/*free ressources: */
 			xDelete<int>(recvcounts);
@@ -461,6 +454,6 @@
 			switch(mode){
 				case NORM_INF:
-					//local_norm=0; for(i=0;i<this->m;i++)local_norm=max(local_norm,fabs(this->vector[i]));
-					local_norm=0; for(i=0;i<this->m;i++)local_norm=max(local_norm,this->vector[i]);
+					local_norm=0.; for(i=0;i<this->m;i++)local_norm=max(local_norm,fabs(this->vector[i]));
+					//local_norm=0; for(i=0;i<this->m;i++)local_norm=max(local_norm,this->vector[i]);
 					ISSM_MPI_Reduce(&local_norm, &norm, 1, ISSM_MPI_DOUBLE, ISSM_MPI_MAX, 0, IssmComm::GetComm());
 					ISSM_MPI_Bcast(&norm,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
@@ -468,6 +461,6 @@
 					break;
 				case NORM_TWO:
-					local_norm=0; 
-					for(i=0;i<this->m;i++)local_norm+=pow(this->vector[i],2);
+					local_norm=0.; 
+					for(i=0;i<this->m;i++)local_norm+=this->vector[i]*this->vector[i];
 					ISSM_MPI_Reduce(&local_norm, &norm, 1, ISSM_MPI_DOUBLE, ISSM_MPI_SUM, 0, IssmComm::GetComm());
 					ISSM_MPI_Bcast(&norm,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
Index: /issm/trunk/src/c/toolkits/issm/IssmSeqVec.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/IssmSeqVec.h	(revision 22757)
+++ /issm/trunk/src/c/toolkits/issm/IssmSeqVec.h	(revision 22758)
@@ -226,11 +226,11 @@
 			switch(mode){
 				case NORM_INF:
-					//norm=0; for(i=0;i<this->M;i++)norm=max(norm,fabs(this->vector[i]));
-					norm=0; for(i=0;i<this->M;i++)norm=max(norm,this->vector[i]);
+					norm=0.; for(i=0;i<this->M;i++)norm=max(norm,fabs(this->vector[i]));
+					//norm=0.; for(i=0;i<this->M;i++)norm=max(norm,this->vector[i]);
 					return norm;
 					break;
 				case NORM_TWO:
-					norm=0; 
-					for(i=0;i<this->M;i++)norm+=pow(this->vector[i],2);
+					norm=0.; 
+					for(i=0;i<this->M;i++)norm+=this->vector[i]*this->vector[i];
 					return sqrt(norm);
 					break;
Index: /issm/trunk/src/c/toolkits/issm/SparseRow.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/SparseRow.h	(revision 22757)
+++ /issm/trunk/src/c/toolkits/issm/SparseRow.h	(revision 22758)
@@ -102,5 +102,5 @@
 
 			int i;
-			doubletype norm=0;
+			doubletype norm=0.;
 
 			switch(mode){
@@ -113,5 +113,5 @@
 				case NORM_FROB:
 					for(i=0;i<ncols;i++){
-						norm+=pow(values[i],2);
+						norm+=values[i]*values[i];
 					}
 					return norm;
Index: /issm/trunk/src/c/toolkits/mpi/issmmpi.h
===================================================================
--- /issm/trunk/src/c/toolkits/mpi/issmmpi.h	(revision 22757)
+++ /issm/trunk/src/c/toolkits/mpi/issmmpi.h	(revision 22758)
@@ -85,10 +85,15 @@
 	#define ISSM_MPI_ANY_SOURCE    3
 	/*}}}*/
-# endif 
+#endif 
 
+/*Dynamically return ISSM_MPI type from variable type */
 template <class T> ISSM_MPI_Datatype TypeToMPIType(){assert(false);};
 template <> inline ISSM_MPI_Datatype TypeToMPIType<IssmDouble>(){return ISSM_MPI_DOUBLE;};
+#if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_) 
+template <> inline ISSM_MPI_Datatype TypeToMPIType<IssmPDouble>(){return ISSM_MPI_PDOUBLE;};
+#endif
 template <> inline ISSM_MPI_Datatype TypeToMPIType<int>(){return ISSM_MPI_INT;};
 template <> inline ISSM_MPI_Datatype TypeToMPIType<char>(){return ISSM_MPI_CHAR;};
+
 template <class T> int ISSM_MPI_Bcast(T *buffer, int count,int root, ISSM_MPI_Comm comm){  /*{{{*/
 
@@ -117,5 +122,4 @@
 	return rc;
 }/*}}}*/
-
 /* interfaces  {{{*/
 int ISSM_MPI_Allgather(void *sendbuf, int sendcount, ISSM_MPI_Datatype sendtype, void *recvbuf, int recvcount, ISSM_MPI_Datatype recvtype, ISSM_MPI_Comm comm);
Index: /issm/trunk/src/c/toolkits/objects/Matrix.h
===================================================================
--- /issm/trunk/src/c/toolkits/objects/Matrix.h	(revision 22757)
+++ /issm/trunk/src/c/toolkits/objects/Matrix.h	(revision 22758)
@@ -127,6 +127,4 @@
 		void InitCheckAndSetType(void){/*{{{*/
 
-			char* toolkittype=NULL;
-
 			#ifdef _HAVE_PETSC_
 			pmatrix=NULL;
@@ -135,5 +133,5 @@
 
 			/*retrieve toolkittype: */
-			toolkittype=ToolkitOptions::GetToolkitType();
+			char* toolkittype=ToolkitOptions::GetToolkitType();
 
 			/*set matrix type: */
@@ -149,5 +147,7 @@
 				type=IssmMatType;
 			}
-			else _error_("unknow toolkit type ");
+			else{
+				_error_("unknow toolkit type ");
+			}
 
 			/*Free ressources: */
Index: /issm/trunk/src/c/toolkits/objects/Vector.h
===================================================================
--- /issm/trunk/src/c/toolkits/objects/Vector.h	(revision 22757)
+++ /issm/trunk/src/c/toolkits/objects/Vector.h	(revision 22758)
@@ -98,6 +98,4 @@
 		void InitCheckAndSetType(void){ /*{{{*/
 
-			char* toolkittype=NULL;
-
 			#ifdef _HAVE_PETSC_
 			pvector=NULL;
@@ -106,8 +104,9 @@
 
 			/*retrieve toolkittype: */
-			toolkittype=ToolkitOptions::GetToolkitType();
+			char* toolkittype=ToolkitOptions::GetToolkitType();
+			_assert_(toolkittype); 
 
 			/*set vector type: */
-			if (strcmp(toolkittype,"petsc")==0){
+			if(strcmp(toolkittype,"petsc")==0){
 				#ifdef _HAVE_PETSC_
 				type=PetscVecType; 
@@ -120,5 +119,7 @@
 				type=IssmVecType;
 			}
-			else _error_("unknow toolkit type ");
+			else{
+				_error_("unknow toolkit type ");
+			}
 
 			/*Free ressources: */
Index: /issm/trunk/src/c/toolkits/petsc/objects/PetscSolver.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/objects/PetscSolver.cpp	(revision 22757)
+++ /issm/trunk/src/c/toolkits/petsc/objects/PetscSolver.cpp	(revision 22758)
@@ -55,8 +55,5 @@
 	IS         isv=NULL;
 	IS         isp=NULL;
-
-	#if _PETSC_MAJOR_ >= 3 
 	char ksp_type[50];
-	#endif
 
 	/*Display message*/
@@ -80,12 +77,10 @@
 	/*Initial guess */
 	/*Now, check that we are not giving an initial guess to the solver, if we are running a direct solver: */
-	#if _PETSC_MAJOR_ >= 3 
-		#if _PETSC_MINOR_<7
-		PetscOptionsGetString(PETSC_NULL,"-ksp_type",ksp_type,49,&flg);
-		#else
-		PetscOptionsGetString(NULL,PETSC_NULL,"-ksp_type",ksp_type,49,&flg);
-		#endif
+	#if _PETSC_MINOR_<7
+	PetscOptionsGetString(PETSC_NULL,"-ksp_type",ksp_type,49,&flg);
+	#else
+	PetscOptionsGetString(NULL,PETSC_NULL,"-ksp_type",ksp_type,49,&flg);
+	#endif
 	if (strcmp(ksp_type,"preonly")==0)uf0=NULL;
-	#endif
 
 	/*If initial guess for the solution exists, use it to create uf, otherwise, 
@@ -103,8 +98,6 @@
 	/*Check the solver is available*/
 	if(solver_type==MUMPSPACKAGE_LU || solver_type==MUMPSPACKAGE_CHOL){
-		#if _PETSC_MAJOR_ >=3
-			#ifndef _HAVE_MUMPS_
-			_error_("requested MUMPS solver, which was not compiled into ISSM!\n");
-			#endif
+		#ifndef _HAVE_MUMPS_
+		_error_("requested MUMPS solver, which was not compiled into ISSM!\n");
 		#endif
 	}
@@ -119,10 +112,9 @@
 	KSPSetFromOptions(ksp);
 
-	#if _PETSC_MAJOR_==3
 	/*Specific solver?: */
 	KSPGetPC(ksp,&pc);
 	if (solver_type==MUMPSPACKAGE_LU){
-		#if _PETSC_MINOR_==1
-		PCFactorSetMatSolverPackage(pc,MAT_SOLVER_MUMPS);
+		#if defined(_HAVE_PETSCDEV_)
+		PCFactorSetMatSolverType(pc,MATSOLVERMUMPS);
 		#else
 		PCFactorSetMatSolverPackage(pc,MATSOLVERMUMPS);
@@ -147,5 +139,4 @@
 
 	}
-	#endif
 
 	/*If there is an initial guess for the solution, use it
Index: /issm/trunk/src/c/toolkits/petsc/patches/NewMat.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/NewMat.cpp	(revision 22757)
+++ /issm/trunk/src/c/toolkits/petsc/patches/NewMat.cpp	(revision 22758)
@@ -25,5 +25,5 @@
 
 	/*parameters: */
-	double sparsity=.001; //default
+	double sparsity=0.001; //default
 	int    m,n;
 	int    d_nz,o_nz,nnz;
@@ -114,13 +114,7 @@
 	MatGetType(outmatrix,&type);
 
-	#if _PETSC_MAJOR_ == 2 
-	if((strcmp(type,"mpiaij")==0) || (strcmp(type,"aijmumps")==0)){
-		MatMPIAIJSetPreallocation(outmatrix,d_nz,NULL,o_nz,NULL);
-	}
-	#else
 	if((strcmp(type,"mpiaij")==0) || (strcmp(type,"mpidense")==0)){
 		MatMPIAIJSetPreallocation(outmatrix,d_nz,NULL,o_nz,NULL);
 	}
-	#endif
 
 	return outmatrix;
Index: sm/trunk/src/c/toolkits/petsc/patches/PetscOptionsInsertMultipleString.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/PetscOptionsInsertMultipleString.cpp	(revision 22757)
+++ 	(revision )
@@ -1,103 +1,0 @@
-/*!\file PetscOptionsInsertMultipleString.cpp
- * \brief: create distributed Petsc vector.
- */
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-/*Petsc includes: */
-#include <petscmat.h>
-#include <petscvec.h>
-#include <petscksp.h>
-
-#include "./petscpatches.h"
-
-#include "../../../shared/shared.h"
-
-void PetscOptionsInsertMultipleString(char* options_string){
-
-	/*The list of options is going to be pairs of the type "-option option_value"*/
-	#if _PETSC_MAJOR_ == 2
-		PetscToken *token=NULL ;
-	#else
-		PetscToken token=NULL;
-	#endif
-	char* first=NULL;
-	char* second=NULL;
-	size_t len;
-	int first_token=1;
-
-	PetscTokenCreate(options_string,' ',&token);
-	for (;;){
-
-		/*Read next tokens*/
-		if(first_token){
-			PetscTokenFind(token,&first);
-		}
-		PetscTokenFind(token,&second);
-
-		if (!first){
-			/*We are at the end of options*/
-			break;
-		}
-		if(!second){
-			/*We have no second value, just take first
-			 * and set the option, then end the token analysis.*/
-			if(first[0]!='-'){
-				/*This is not good, the option does not have '-'! Get out*/
-				_error_("Option " << first << " should be preceded by '-'!");
-			}
-			/*Reduce first to bare option value*/
-			PetscStrlen(first,&len);
-			while (len > 0 && first[len-1] == ' ') {
-				len--; first[len] = 0;
-			}
-			#if _PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 7
-			PetscOptionsSetValue(first,second);
-			#else
-			PetscOptionsSetValue(NULL,first,second);
-			#endif
-			break;
-		}
-		else{
-			/*Ok, we have a second token coming in. Is it another option, or 'first' option's value?*/
-			if (second[0]=='-'){
-				/*Second is another option, ignore it*/
-				PetscStrlen(first,&len);
-				while (len > 0 && first[len-1] == ' ' ) {
-					len--; first[len] = 0;
-				}
-				#if _PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 7
-				PetscOptionsSetValue(first,NULL);
-				#else
-				PetscOptionsSetValue(NULL,first,NULL);
-				#endif
-				/*Preparing next loop step*/
-				first=second;
-				first_token=0;
-			}
-			else{
-				/*Second is 'first' option's value*/
-				PetscStrlen(second,&len);
-				while (len > 0 && second[len-1] == ' ') {
-					len--; second[len] = 0;
-				}
-				#if _PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 7
-				PetscOptionsSetValue(first,second);
-				#else
-				PetscOptionsSetValue(NULL,first,second);
-				#endif
-				first_token=1;
-			}
-		}
-	}
-
-#if _PETSC_MAJOR_ == 3 && _PETSC_MINOR_ > 2
-	PetscTokenDestroy(&token);
-#else
-	PetscTokenDestroy(token);
-#endif
-}
Index: /issm/trunk/src/c/toolkits/petsc/patches/petscpatches.h
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/petscpatches.h	(revision 22757)
+++ /issm/trunk/src/c/toolkits/petsc/patches/petscpatches.h	(revision 22758)
@@ -29,5 +29,4 @@
 int MatPartition(Mat* poutmatrix,Mat matrixA,double* row_partition_vector,int row_partition_vector_size ,
 		double* col_partition_vector,int col_partition_vector_size);
-void PetscOptionsInsertMultipleString(char* options_string);
 void PetscOptionsDetermineSolverType(int* psolver_type);
 void VecMerge(Vec A, Vec B, double* row_partition_vector,int row_partition_size);
Index: /issm/trunk/src/m/Makefile.am
===================================================================
--- /issm/trunk/src/m/Makefile.am	(revision 22757)
+++ /issm/trunk/src/m/Makefile.am	(revision 22758)
@@ -65,4 +65,5 @@
 					${ISSM_DIR}/src/m/mesh/*.py \
 					${ISSM_DIR}/src/m/mesh/rifts/*.py \
+					${ISSM_DIR}/src/m/mesh/planet/gmsh/*.py \
 					${ISSM_DIR}/src/m/miscellaneous/*.py \
 					${ISSM_DIR}/src/m/modules/*.py \
@@ -83,4 +84,5 @@
 js_scripts =  ${ISSM_DIR}/src/m/array/arrayoperations.js \
 				${ISSM_DIR}/src/m/boundaryconditions/SetIceShelfBC.js \
+				${ISSM_DIR}/src/m/classes/amr.js \
 				${ISSM_DIR}/src/m/classes/autodiff.js \
 				${ISSM_DIR}/src/m/classes/balancethickness.js \
@@ -96,4 +98,5 @@
 				${ISSM_DIR}/src/m/classes/geometry.js \
 				${ISSM_DIR}/src/m/classes/giaivins.js \
+				${ISSM_DIR}/src/m/classes/fourierlove.js \
 				${ISSM_DIR}/src/m/classes/esa.js \
 				${ISSM_DIR}/src/m/classes/groundingline.js \
@@ -106,4 +109,5 @@
 				${ISSM_DIR}/src/m/classes/matice.js \
 				${ISSM_DIR}/src/m/classes/mesh2d.js \
+				${ISSM_DIR}/src/m/classes/mesh3dprisms.js \
 				${ISSM_DIR}/src/m/classes/mesh3dsurface.js \
 				${ISSM_DIR}/src/m/classes/miscellaneous.js \
@@ -117,5 +121,5 @@
 				${ISSM_DIR}/src/m/classes/rifts.js \
 				${ISSM_DIR}/src/m/classes/slr.js \
-				${ISSM_DIR}/src/m/classes/settings.js \
+				${ISSM_DIR}/src/m/classes/issmsettings.js \
 				${ISSM_DIR}/src/m/classes/SMBforcing.js \
 				${ISSM_DIR}/src/m/classes/steadystate.js \
@@ -130,13 +134,8 @@
 				${ISSM_DIR}/src/m/consistency/checkfield.js \
 				${ISSM_DIR}/src/m/consistency/ismodelselfconsistent.js \
+				${ISSM_DIR}/src/m/extrusion/*.js \
 				${ISSM_DIR}/src/m/geometry/FlagElements.js \
 				${ISSM_DIR}/src/m/inversions/marshallcostfunctions.js \
-				${ISSM_DIR}/src/m/io/fileptr.js \
-				${ISSM_DIR}/src/m/io/savemodel.js \
-				${ISSM_DIR}/src/m/io/loadmodel.js \
-				${ISSM_DIR}/src/m/io/saveAsFile.js \
-				${ISSM_DIR}/src/m/io/writetofile.js \
-				${ISSM_DIR}/src/m/io/download.js \
-				${ISSM_DIR}/src/m/io/writetofile.js \
+				${ISSM_DIR}/src/m/io/*.js \
 				${ISSM_DIR}/src/m/materials/paterson.js \
 				${ISSM_DIR}/src/m/mesh/triangle.js \
@@ -146,18 +145,5 @@
 				${ISSM_DIR}/src/m/parameterization/setflowequation.js \
 				${ISSM_DIR}/src/m/parameterization/setmask.js \
-				${ISSM_DIR}/src/m/plot/slider.js \
-				${ISSM_DIR}/src/m/plot/applyoptions.js \
-				${ISSM_DIR}/src/m/plot/checkplotoptions.js \
-				${ISSM_DIR}/src/m/plot/plot_manager.js \
-				${ISSM_DIR}/src/m/plot/plot_mesh.js \
-				${ISSM_DIR}/src/m/plot/plot_overlay.js \
-				${ISSM_DIR}/src/m/plot/plot_unit.js \
-				${ISSM_DIR}/src/m/plot/plot_quiver.js \
-				${ISSM_DIR}/src/m/plot/plotdoc.js \
-				${ISSM_DIR}/src/m/plot/plotmodel.js \
-				${ISSM_DIR}/src/m/plot/processdata.js \
-				${ISSM_DIR}/src/m/plot/processmesh.js \
-				${ISSM_DIR}/src/m/plot/gauge.js \
-				${ISSM_DIR}/src/m/plot/webgl.js \
+				${ISSM_DIR}/src/m/plot/*.js \
 				${ISSM_DIR}/src/m/print/sprintf.js \
 				${ISSM_DIR}/src/m/solve/loadresultsfrombuffer.js \
Index: /issm/trunk/src/m/array/arrayoperations.js
===================================================================
--- /issm/trunk/src/m/array/arrayoperations.js	(revision 22757)
+++ /issm/trunk/src/m/array/arrayoperations.js	(revision 22758)
@@ -1,8 +1,16 @@
 function ArrayMax(array){ //{{{
-	return Math.max.apply(null,array);
+	//Calculate array max using for loop instead of Math.max.apply(null, array) to avoid recursive stack overflow in mobile browsers
+	
+	var max=-Infinity;
+	
+	for (var i=0;i<array.length; i++) {
+		max=Math.max(max,array[i]);
+	}
+	
+	return max;
 } //}}}
 function ArrayMax2D(array){ //{{{
 	
-	var max=0;
+	var max=-Infinity;
 
 	for (var i=0;i<array.length;i++){
@@ -14,5 +22,24 @@
 } //}}}
 function ArrayMin(array){ //{{{
-	return Math.min.apply(null,array);
+	//Calculate array min using for loop instead of Math.min.apply(null, array) to avoid recursive stack overflow in mobile browsers
+	
+	var min=Infinity;
+	
+	for (var i=0;i<array.length; i++) {
+		min=Math.min(min,array[i]);
+	}
+	
+	return min;
+} //}}}
+function ArrayMin2D(array){ //{{{
+	
+	var min=Infinity;
+
+	for (var i=0;i<array.length;i++){
+		var subarray=array[i];
+		min=Math.min(min,ArrayMin(subarray));
+	}
+
+	return min;
 } //}}}
 function ArraySum(array){ //{{{
@@ -67,14 +94,26 @@
 
 } //}}}
-function ArrayMin2D(array){ //{{{
-	
-	var min=ArrayMax2D(array);
-
-	for (var i=0;i<array.length;i++){
-		var subarray=array[i];
-		min=Math.min(min,ArrayMin(subarray));
-	}
-
-	return min;
+function ArrayTranspose(array) { //{{{
+	return Object.keys(array[0]).map(function(column) {
+		return array.map(function(row) { 
+			return row[column]; 
+		});
+	});
+} //}}}
+function ArrayConcat(a, b) { //{{{
+	// Make sure that both typed arrays are of the same type
+	if(Object.prototype.toString.call(a) !== Object.prototype.toString.call(b)) {
+		throw 'The types of the two arguments passed for parameters a and b do not match.';
+	}
+	var c;
+	if(a instanceof Float64Array) {
+		c = new a.constructor(a.length + b.length);
+		c.set(a);
+		c.set(b, a.length);
+	}
+	else {
+		c = clone(a).concat(clone(b));
+	}	
+	return c;
 } //}}}
 function ListToMatrix(list, elementsPerSubArray) { //{{{
@@ -126,5 +165,5 @@
 function ArrayNot(array) { //{{{
 
-	var notarray=array;
+	var notarray=array.slice();
 	for (var i=0;i<array.length;i++)notarray[i]=-array[i];
 	return notarray;
@@ -138,5 +177,5 @@
 function ArrayPow(array,coefficient) { //{{{
 
-	var powarray=array;
+	var powarray=array.slice();
 	for (var i=0;i<array.length;i++)powarray[i]=Math.pow(array[i],coefficient);
 	return powarray;
@@ -144,5 +183,5 @@
 function ArraySqrt(array) { //{{{
 
-	var sqrtarray=array;
+	var sqrtarray=array.slice();
 	for (var i=0;i<array.length;i++)sqrtarray[i]=Math.sqrt(array[i]);
 	return sqrtarray;
@@ -150,6 +189,7 @@
 function ArrayScale(array,alpha) { //{{{
 
-	for (var i=0;i<array.length;i++)array[i]=array[i]*alpha;
-
+	var scalearray=array.slice();
+	for (var i=0;i<array.length;i++)scalearray[i]=array[i]*alpha;
+	return scalearray;
 } //}}}
 function ArrayMag(array1,array2) { //{{{
@@ -164,5 +204,5 @@
         for(var i=0;i<array.length;i++){
             for(var j=0;j<array[0].length;j++){
-                if (isNaN(array[i][j])) return 1;
+                if (Number.isNaN(array[i][j])) return 1;
             }
         }
@@ -170,5 +210,5 @@
     else{
         for(var i=0;i<array.length;i++){
-            if (isNaN(array[i])) return 1;
+            if (Number.isNaN(array[i])) return 1;
         }
     }
@@ -190,5 +230,5 @@
 function ArrayAnyEqual(array,value) { //{{{
 	
-	if(!isNaN(value)){
+	if(!Number.isNaN(value)){
 		for(var i=0;i<array.length;i++){
 			if (array[i]==value)return 1;
@@ -197,5 +237,5 @@
 	else{
 		for(var i=0;i<array.length;i++){
-			if (isNaN(array[i]))return 1;
+			if (Number.isNaN(array[i]))return 1;
 		}
 	}
@@ -250,9 +290,22 @@
 } //}}}
 function NewArrayFill(size,value) { //{{{
-
-	return new Array(size).fill(value);
+	var array = new Array(size);
+	
+	for (var i = 0; i < size; i++) {
+		array[i] = value;
+	}
+	
+	return array;
+} //}}}
+function NewArrayFill2D(rows,cols,value) { //{{{
+	var arr=new Array(rows); 
+
+	for (var i=0;i<rows;i++) {
+		arr[i] = NewArrayFill(cols,value);
+	}
+
+	return arr;
 } //}}}
 function NewArrayFillIncrement(size,start,increment) { //{{{
-
 	var array=new Array(size); 
 
@@ -264,17 +317,24 @@
 } //}}}
 function ArrayFind(array,value) { //{{{
-	
-	//find number of indices
 	var count=0;
-	for (var i=0;i<array.length;i++)if(array[i]==value)count++;
-
-	//allocate:
-	var indices= NewArrayFill(count,0);
-
-	//fill in:
-	count=0;
-	for (var i=0;i<array.length;i++){
-		if(array[i]==value){
-			indices[count]=i;
+	var indices=[];
+
+	for (var i=0;i<array.length;i++){
+		if(array[i]===value){
+			indices.push(count);
+		}
+		count++;
+	}
+	return indices;
+} //}}}
+function ArrayFind2D(array,value) { //{{{
+	var count=0;
+	var indices=[];
+
+	for (var i=0;i<array.length;i++){
+		for (var j=0;j<array[i].length;j++){
+			if(array[i][j]===value){
+				indices.push(count);
+			}
 			count++;
 		}
@@ -283,17 +343,24 @@
 } //}}}
 function ArrayFindNot(array,value) { //{{{
-	
-	//find number of indices
 	var count=0;
-	for (var i=0;i<array.length;i++)if(array[i]!=value)count++;
-
-	//allocate:
-	var indices= NewArrayFill(count,0);
-
-	//fill in:
-	count=0;
-	for (var i=0;i<array.length;i++){
-		if(array[i]!=value){
-			indices[count]=i;
+	var indices=[];
+
+	for (var i=0;i<array.length;i++){
+		if(array[i]!==value){
+			indices.push(count);
+		}
+		count++;
+	}
+	return indices;
+} //}}}
+function ArrayFindNot2D(array,value) { //{{{
+	var count=0;
+	var indices=[];
+
+	for (var i=0;i<array.length;i++){
+		for (var j=0;j<array[i].length;j++){
+			if(array[i][j]!==value){
+				indices.push(count);
+			}
 			count++;
 		}
@@ -302,5 +369,5 @@
 } //}}}
 function Create2DArray(rows,cols) { //{{{
-	var arr = [];
+	var arr=new Array(rows); 
 
 	for (var i=0;i<rows;i++) {
Index: /issm/trunk/src/m/boundaryconditions/SetIceSheetBC.py
===================================================================
--- /issm/trunk/src/m/boundaryconditions/SetIceSheetBC.py	(revision 22757)
+++ /issm/trunk/src/m/boundaryconditions/SetIceSheetBC.py	(revision 22758)
@@ -15,7 +15,7 @@
 	#node on Dirichlet
 	pos=np.nonzero(md.mesh.vertexonboundary)
-	md.stressbalance.spcvx=float('nan')*np.ones(md.mesh.numberofvertices)
-	md.stressbalance.spcvy=float('nan')*np.ones(md.mesh.numberofvertices)
-	md.stressbalance.spcvz=float('nan')*np.ones(md.mesh.numberofvertices)
+	md.stressbalance.spcvx=float('nan')*np.ones((md.mesh.numberofvertices))
+	md.stressbalance.spcvy=float('nan')*np.ones((md.mesh.numberofvertices))
+	md.stressbalance.spcvz=float('nan')*np.ones((md.mesh.numberofvertices))
 	md.stressbalance.spcvx[pos]=0
 	md.stressbalance.spcvy[pos]=0
Index: /issm/trunk/src/m/boundaryconditions/love_numbers.py
===================================================================
--- /issm/trunk/src/m/boundaryconditions/love_numbers.py	(revision 22757)
+++ /issm/trunk/src/m/boundaryconditions/love_numbers.py	(revision 22758)
@@ -7,18 +7,34 @@
 #			   retrieved from: http://www.srosat.com/iag-jsg/loveNb.php
 #    Usage:   series=love_numbers(value) 
+#             series=love_numbers(value,reference_frame) 
+# 
 #             where value is one of 'h','k','l','gamma' and 'lambda'. 
+#	      reference_frame = one of 'CM' (default) and 'CF'.
 #
 #    Example:  
 #          love_k=love_numbers('k');
+#          love_k=love_numbers('k','CF');
 # 
 
-	#some checks:
-	if len(varargin)>0:
-		raise RuntimeError('love_numbers error message: wrong usage')
-
-	if value not in ['h','k','l','gamma','lambda']:
-		raise RuntimeError('value should be one of ''h'',''k'',''l'',''gamma'' and ''lambda''')
-
-	love_numbers=np.array([[    0         , 0          ,0          ,0          ,0          ,0          ,0          ],
+        # some checks:
+        if len(varargin)==0:
+        	frame='CM';
+		print 'Info: computation is done in Center of Mass (CM) reference frame by default'
+        elif len(varargin)==1: 
+		reference_frame = varargin[0]
+		if (reference_frame in ['CF','CM']):
+	            	frame=reference_frame;
+		else:
+			raise RuntimeError('reference_frame should be one of ''CM'' or ''CF''')
+        else:
+            	raise RuntimeError('love_numbers error message: bad usage') 
+        
+        if value not in ['h','k','l','gamma','lambda']:
+        	raise RuntimeError('value should be one of ''h'',''k'',''l'',''gamma'' and ''lambda''') 
+        
+        if len(varargin)>1: 
+            raise RuntimeError('love_numbers error message: wrong usage') 
+        
+        love_numbers=np.array([[    0         , 0          ,0          ,0          ,0          ,0          ,0          ],
 												 [	-1.28740059,-1.00000000,-0.89858519,1.28740059, 0.42519882  ,0.89858519 ,0.00000000 ],
 												 [	-1.00025365, -0.30922675, 0.02060926, 1.69102690, 0.46358648, 0.67016399, 0.61829668],
@@ -10021,7 +10037,6 @@
 												 [	-6.27342771, -0.00030948, 0.00018957, 7.27311822, 0.99905470, 0.99950094, 0.49327205],
 												 [	-6.27342778, -0.00030945, 0.00018956, 7.27311833, 0.99905480, 0.99950099, 0.49327194]]);
-
-
-	if value=='h':
+                                                                                                 
+        if value=='h':
 		series=love_numbers[:,0];
 	elif value=='k':
@@ -10035,4 +10050,14 @@
 	else:
 		raise RuntimeError(['love_numbers error message: unknow value:', value])
-		
-	return series
+	
+	# choose degree 1 term for CF reference system 
+        if frame=='CF': # from Blewitt, 2003, JGR 
+            if value=='h':
+                    series[1] = -0.269; 
+            elif value=='k':
+                    series[1] = 0.021;  
+            elif value=='l':
+                    series[1] = 0.134; 
+
+        return series
+
Index: /issm/trunk/src/m/classes/SMBd18opdd.m
===================================================================
--- /issm/trunk/src/m/classes/SMBd18opdd.m	(revision 22757)
+++ /issm/trunk/src/m/classes/SMBd18opdd.m	(revision 22758)
@@ -17,8 +17,12 @@
 		ismungsm                  = 0;
 		isd18opd                  = 0;
+		issetpddfac               = 0;
+		istemperaturescaled       = 0;
 		delta18o                  = NaN;
 		delta18o_surface          = NaN;
 		temperatures_presentday   = NaN;
 		precipitations_presentday = NaN;
+		pddfac_snow               = NaN;
+		pddfac_ice                = NaN;
 		requested_outputs      = {};
 	end
@@ -35,9 +39,11 @@
 			if(self.isd18opd),self.temperatures_presentday=project3d(md,'vector',self.temperatures_presentday,'type','node');end
 			if(self.isd18opd),self.precipitations_presentday=project3d(md,'vector',self.precipitations_presentday,'type','node');end
+			if(self.issetpddfac), self.pddfac_snow=project3d(md,'vector',self.pddfac_snow,'type','node');end
+			if(self.issetpddfac), self.pddfac_ice=project3d(md,'vector',self.pddfac_ice,'type','node');end
 			self.s0p=project3d(md,'vector',self.s0p,'type','node');
 			self.s0t=project3d(md,'vector',self.s0t,'type','node');
 
 		end % }}}
-			function list = defaultoutputs(self,md) % {{{
+	 function list = defaultoutputs(self,md) % {{{
 
 			list = {''};
@@ -60,4 +66,5 @@
 		  self.ismungsm   = 0;
 		  self.isd18opd   = 1;
+		  self.istemperaturescaled = 1;
 		  self.desfac     = 0.5;
 		  self.rlaps      = 6.5;
@@ -65,4 +72,5 @@
 		  self.dpermil    = 2.4;
 		  self.f          = 0.169;
+		  self.issetpddfac = 0;
                   
 		end % }}}
@@ -76,9 +84,17 @@
 				md = checkfield(md,'fieldname','smb.rlapslgm','>=',0,'numel',1);
 				if(self.isd18opd==1) 
-					md = checkfield(md,'fieldname','smb.temperatures_presentday','size',[md.mesh.numberofvertices+1 12],'NaN',1,'Inf',1,'timeseries',1);
-					md = checkfield(md,'fieldname','smb.precipitations_presentday','size',[md.mesh.numberofvertices+1 12],'NaN',1,'Inf',1,'timeseries',1);
+					lent=size(self.temperatures_presentday,2);
+					lenp=size(self.precipitations_presentday,2);
+					multt=ceil(lent/12)*12;
+					multp=ceil(lenp/12)*12;
+					md = checkfield(md,'fieldname','smb.temperatures_presentday','size',[md.mesh.numberofvertices+1 multt],'NaN',1,'Inf',1,'timeseries',1);
+					md = checkfield(md,'fieldname','smb.precipitations_presentday','size',[md.mesh.numberofvertices+1 multp],'NaN',1,'Inf',1,'timeseries',1);
 					md = checkfield(md,'fieldname','smb.delta18o','NaN',1,'Inf',1,'size',[2,NaN],'singletimeseries',1);
 					md = checkfield(md,'fieldname','smb.dpermil','>=',0,'numel',1);
 				   md = checkfield(md,'fieldname','smb.f','>=',0,'numel',1);
+				end
+				if(self.issetpddfac==1)
+					md = checkfield(md,'fieldname','smb.pddfac_snow','>=',0,'NaN',1,'Inf',1);
+					md = checkfield(md,'fieldname','smb.pddfac_ice','>=',0,'NaN',1,'Inf',1);
 				end
 			end
@@ -90,4 +106,5 @@
 			disp(sprintf('\n   PDD and deltaO18 parameters:'));
 			fielddisplay(self,'isd18opd','is delta18o parametrisation from present day temperature and precipitation activated (0 or 1, default is 0)');
+			fielddisplay(self,'issetpddfac','is user passing in defined pdd factors at each vertex (0 or 1, default is 0)');
 			fielddisplay(self,'desfac','desertification elevation factor (between 0 and 1, default is 0.5) [m]');
 			fielddisplay(self,'s0p','should be set to elevation from precip source (between 0 and a few 1000s m, default is 0) [m]');
@@ -97,7 +114,12 @@
 				fielddisplay(self,'temperatures_presentday','monthly present day surface temperatures [K], required if delta18o/mungsm/d18opd is activated');
 				fielddisplay(self,'precipitations_presentday','monthly surface precipitation [m/yr water eq], required if delta18o/mungsm/d18opd is activated');
+				fielddisplay(self,'istemperaturescaled','if delta18o parametrisation from present day temperature and precipitation is activated, is temperature scaled to delta18o value? (0 or 1, default is 0)');
 				fielddisplay(self,'delta18o','delta18o [per mil], required if pdd is activated and d18opd activated');  
 				fielddisplay(self,'dpermil','degree per mil, required if d18opd is activated');                            
 			   fielddisplay(self,'f','precip/temperature scaling factor, required if d18opd is activated');
+			end
+			if(self.issetpddfac==1)
+				fielddisplay(self,'pddfac_snow','Pdd factor for snow, at each vertex [mm ice equiv/day/degree C]');
+				fielddisplay(self,'pddfac_ice','Pdd factor for ice, at each vertex [mm ice equiv/day/degree C]');
 			end
 			fielddisplay(self,'requested_outputs','additional outputs requested');
@@ -114,4 +136,5 @@
 			WriteData(fid,prefix,'object',self,'class','smb','fieldname','ismungsm','format','Boolean');
 			WriteData(fid,prefix,'object',self,'class','smb','fieldname','isd18opd','format','Boolean');
+			WriteData(fid,prefix,'object',self,'class','smb','fieldname','issetpddfac','format','Boolean');
 			WriteData(fid,prefix,'object',self,'class','smb','fieldname','desfac','format','Double');
 			WriteData(fid,prefix,'object',self,'class','smb','fieldname','s0p','format','DoubleMat','mattype',1);
@@ -125,7 +148,12 @@
 				WriteData(fid,prefix,'object',self,'class','smb','fieldname','temperatures_presentday','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
 				WriteData(fid,prefix,'object',self,'class','smb','fieldname','precipitations_presentday','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
+				WriteData(fid,prefix,'object',self,'class','smb','fieldname','istemperaturescaled','format','Boolean');
 				WriteData(fid,prefix,'object',self,'class','smb','fieldname','delta18o','format','DoubleMat','mattype',1,'timeserieslength',2,'yts',md.constants.yts);
 				WriteData(fid,prefix,'object',self,'class','smb','fieldname','dpermil','format','Double');
 			   WriteData(fid,prefix,'object',self,'class','smb','fieldname','f','format','Double');
+			end
+			if self.issetpddfac==1
+				WriteData(fid,prefix,'object',self,'class','smb','fieldname','pddfac_snow','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
+				WriteData(fid,prefix,'object',self,'class','smb','fieldname','pddfac_ice','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
 			end
 			
Index: /issm/trunk/src/m/classes/SMBd18opdd.py
===================================================================
--- /issm/trunk/src/m/classes/SMBd18opdd.py	(revision 22757)
+++ /issm/trunk/src/m/classes/SMBd18opdd.py	(revision 22758)
@@ -25,8 +25,12 @@
 		self.ismungsm                  = 0
 		self.isd18opd                  = 0
+		self.issetpddfac               = 0
+		self.istemperaturescaled       = 0
 		self.delta18o                  = float('NaN')
 		self.delta18o_surface          = float('NaN')
 		self.temperatures_presentday   = float('NaN')
 		self.precipitations_presentday = float('NaN')
+		self.pddfac_snow               = float('NaN')
+		self.pddfac_ice                = float('NaN')
 
 		#set defaults
@@ -38,4 +42,5 @@
 
 		string="%s\n%s"%(string,fielddisplay(self,'isd18opd','is delta18o parametrisation from present day temperature and precipitation activated (0 or 1, default is 0)'))
+		string="%s\n%s"%(string,fielddisplay(self,'issetpddfac','is user passing in defined pdd factors at each vertex (0 or 1, default is 0)'))
 		string="%s\n%s"%(string,fielddisplay(self,'desfac','desertification elevation factor (between 0 and 1, default is 0.5) [m]'))
 		string="%s\n%s"%(string,fielddisplay(self,'s0p','should be set to elevation from precip source (between 0 and a few 1000s m, default is 0) [m]'))
@@ -45,6 +50,12 @@
 			string="%s\n%s"%(string,fielddisplay(self,'temperatures_presentday','monthly present day surface temperatures [K], required if delta18o/mungsm is activated'))
 			string="%s\n%s"%(string,fielddisplay(self,'precipitations_presentday','monthly surface precipitation [m/yr water eq], required if delta18o or mungsm is activated'))
+			string="%s\n%s"%(string,fielddisplay(self,'istemperaturescaled','if delta18o parametrisation from present day temperature and precipitation is activated, is temperature scaled to delta18o value? (0 or 1, default is 0)'))
 			string="%s\n%s"%(string,fielddisplay(self,'delta18o','delta18o [per mil], required if pdd is activated and delta18o activated'))
 			string="%s\n%s"%(string,fielddisplay(self,'dpermil','degree per mil, required if d18opd is activated'))
+			string="%s\n%s"%(string,fielddisplay(self,'f','precip/temperature scaling factor, required if d18opd is activated'))
+
+		if self.issetpddfac==1:
+			string="%s\n%s"%(string,fielddisplay(self,'pddfac_snow','Pdd factor for snow, at each vertex [mm ice equiv/day/degree C]'))
+			string="%s\n%s"%(string,fielddisplay(self,'pddfac_ice','Pdd factor for ice, at each vertex [mm ice equiv/day/degree C]'))
 		string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','additional outputs requested'))
 
@@ -55,4 +66,6 @@
 		if self.isd18opd: self.temperatures_presentday=project3d(md,'vector',self.temperatures_presentday,'type','node')
 		if self.isd18opd: self.precipitations_presentday=project3d(md,'vector',self.precipitations_presentday,'type','node')
+		if self.issetpddfac: self.pddfac_snow=project3d(md,'vector',self.pddfac_snow,'type','node')
+		if self.issetpddfac: self.pddfac_ice=project3d(md,'vector',self.pddfac_ice,'type','node')
 		self.s0p=project3d(md,'vector',self.s0p,'type','node')
 		self.s0t=project3d(md,'vector',self.s0t,'type','node')
@@ -80,4 +93,5 @@
 		self.ismungsm   = 0
 		self.isd18opd   = 1
+		self.istemperaturescaled = 1
 		self.desfac     = 0.5
 		self.rlaps      = 6.5 
@@ -85,4 +99,5 @@
 		self.dpermil    = 2.4
 		self.f          = 0.169
+		self.issetpddfac = 0
 		return self
 	#}}}
@@ -97,9 +112,17 @@
 
 			if self.isd18opd:
-				md = checkfield(md,'fieldname','smb.temperatures_presentday','size',[md.mesh.numberofvertices+1,12],'NaN',1,'Inf',1,'timeseries',1)
-				md = checkfield(md,'fieldname','smb.precipitations_presentday','size',[md.mesh.numberofvertices+1,12],'NaN',1,'Inf',1,'timeseries',1)
+				lent=float(np.size(self.temperatures_presentday,1))
+				lenp=float(np.size(self.precipitations_presentday,1))
+				multt=np.ceil(lent/12.)*12.
+				multp=np.ceil(lenp/12.)*12.
+				md = checkfield(md,'fieldname','smb.temperatures_presentday','size',[md.mesh.numberofvertices+1,multt],'NaN',1,'Inf',1,'timeseries',1)
+				md = checkfield(md,'fieldname','smb.precipitations_presentday','size',[md.mesh.numberofvertices+1,multp],'NaN',1,'Inf',1,'timeseries',1)
 				md = checkfield(md,'fieldname','smb.delta18o','NaN',1,'Inf',1,'size',[2,np.nan],'singletimeseries',1)
 				md = checkfield(md,'fieldname','smb.dpermil','>=',0,'numel',[1])
 				md = checkfield(md,'fieldname','smb.f','>=',0,'numel',[1])
+
+			if self.issetpddfac:
+				md = checkfield(md,'fieldname','smb.pddfac_snow','>=',0,'NaN',1,'Inf',1)
+				md = checkfield(md,'fieldname','smb.pddfac_ice','>=',0,'NaN',1,'Inf',1)
 
 		md = checkfield(md,'fieldname','masstransport.requested_outputs','stringrow',1)
@@ -115,4 +138,5 @@
 		WriteData(fid,prefix,'object',self,'class','smb','fieldname','ismungsm','format','Boolean')
 		WriteData(fid,prefix,'object',self,'class','smb','fieldname','isd18opd','format','Boolean')
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','issetpddfac','format','Boolean');
 		WriteData(fid,prefix,'object',self,'class','smb','fieldname','desfac','format','Double')
 		WriteData(fid,prefix,'object',self,'class','smb','fieldname','s0p','format','DoubleMat','mattype',1);
@@ -126,7 +150,13 @@
 			WriteData(fid,prefix,'object',self,'class','smb','fieldname','temperatures_presentday','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
 			WriteData(fid,prefix,'object',self,'class','smb','fieldname','precipitations_presentday','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
+			WriteData(fid,prefix,'object',self,'class','smb','fieldname','istemperaturescaled','format','Boolean')
 			WriteData(fid,prefix,'object',self,'class','smb','fieldname','delta18o','format','DoubleMat','mattype',1,'timeserieslength',2,'yts',md.constants.yts)
 			WriteData(fid,prefix,'object',self,'class','smb','fieldname','dpermil','format','Double')
 			WriteData(fid,prefix,'object',self,'class','smb','fieldname','f','format','Double')
+
+		if self.issetpddfac:
+			WriteData(fid,prefix,'object',self,'class','smb','fieldname','pddfac_snow','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
+			WriteData(fid,prefix,'object',self,'class','smb','fieldname','pddfac_ice','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
+
 		#process requested outputs
 		outputs = self.requested_outputs
Index: /issm/trunk/src/m/classes/SMBgemb.m
===================================================================
--- /issm/trunk/src/m/classes/SMBgemb.m	(revision 22757)
+++ /issm/trunk/src/m/classes/SMBgemb.m	(revision 22758)
@@ -36,4 +36,8 @@
 		Tz    = NaN; %height above ground at which temperature (T) was sampled [m]
 		Vz    = NaN; %height above ground at which wind (V) eas sampled [m]
+
+		%optional inputs:
+		aValue = NaN; %Albedo forcing at every element.  Used only if aIdx == 0.
+		teValue = NaN; %Outward longwave radiation thermal emissivity forcing at every element (default in code is 1)
         
 		% Initialization of snow properties
@@ -51,8 +55,10 @@
 		%settings: 
 		aIdx   = NaN; %method for calculating albedo and subsurface absorption (default is 1)
-		              % 1: effective grain radius [Gardner & Sharp, 2009]
+		           % 0: direct input from aValue parameter
+		           % 1: effective grain radius [Gardner & Sharp, 2009]
 					  % 2: effective grain radius [Brun et al., 2009]
 					  % 3: density and cloud amount [Greuell & Konzelmann, 1994]
 					  % 4: exponential time decay & wetness [Bougamont & Bamber, 2005]
+
 		swIdx  = NaN; % apply all SW to top grid cell (0) or allow SW to penetrate surface (1) (default 1)
 
@@ -82,7 +88,13 @@
 		t0dry = NaN; % warm snow timescale (30) 
 		K     = NaN; % time scale temperature coef. (7) 
+		adThresh = NaN; %Apply aIdx method to all areas with densities below this value,
+		                %or else apply direct input value from aValue, allowing albedo to be altered.
+							 %Default value is rho water (1023 kg m-3).
 
 		%densities:
 		InitDensityScaling= NaN; %initial scaling factor multiplying the density of ice, which describes the density of the snowpack.
+
+		%thermal:
+		ThermoDeltaTScaling= NaN; %scaling factor to multiply the thermal diffusion timestep (delta t)
 		
 		requested_outputs      = {};
@@ -114,4 +126,12 @@
 			self.eAir=project3d(md,'vector',self.eAir,'type','node');
 			self.pAir=project3d(md,'vector',self.pAir,'type','node');
+
+			if (aIdx == 0) & ~isnan(self.aValue)
+				self.aValue=project3d(md,'vector',self.aValue,'type','node');
+			end
+			if ~isnan(self.teValue)
+				self.teValue=project3d(md,'vector',self.teValue,'type','node');
+			end
+
 
 		end % }}}
@@ -137,4 +157,5 @@
 		self.dzMin = self.dzTop/2;
 		self.InitDensityScaling = 1.0;
+		self.ThermoDeltaTScaling = 1/11;
 		
 		self.zMax=250*ones(mesh.numberofelements,1);
@@ -150,4 +171,8 @@
 		self.t0dry = 30;
 		self.K = 7;
+		self.adThresh = 1023;
+
+		self.teValue = ones(mesh.numberofelements,1);
+		self.aValue = self.aSnow*ones(mesh.numberofelements,1);
         
 		self.Dzini=0.05*ones(mesh.numberofelements,2);
@@ -167,5 +192,4 @@
 		function md = checkconsistency(self,md,solution,analyses) % {{{
 
-
 			md = checkfield(md,'fieldname','smb.isgraingrowth','values',[0 1]);
 			md = checkfield(md,'fieldname','smb.isalbedo','values',[0 1]);
@@ -189,5 +213,7 @@
 			md = checkfield(md,'fieldname','smb.Vz','size',[md.mesh.numberofelements 1],'NaN',1,'Inf',1,'>=',0,'<=',5000); 
 
-			md = checkfield(md,'fieldname','smb.aIdx','NaN',1,'Inf',1,'values',[1,2,3,4]);
+			md = checkfield(md,'fieldname','smb.teValue','timeseries',1,'NaN',1,'Inf',1,'>=',0,'<=',1);
+
+			md = checkfield(md,'fieldname','smb.aIdx','NaN',1,'Inf',1,'values',[0,1,2,3,4]);
 			md = checkfield(md,'fieldname','smb.swIdx','NaN',1,'Inf',1,'values',[0,1]);
 			md = checkfield(md,'fieldname','smb.denIdx','NaN',1,'Inf',1,'values',[1,2,3,4,5]);
@@ -199,6 +225,10 @@
 			md = checkfield(md,'fieldname','smb.outputFreq','NaN',1,'Inf',1,'>',0,'<',10*365); %10 years max 
 			md = checkfield(md,'fieldname','smb.InitDensityScaling','NaN',1,'Inf',1,'>=',0,'<=',1);
+			md = checkfield(md,'fieldname','smb.ThermoDeltaTScaling','NaN',1,'Inf',1,'>=',0,'<=',1);
+			md = checkfield(md,'fieldname','smb.adThresh','NaN',1,'Inf',1,'>=',0);
 
 			switch self.aIdx,
+				case 0
+					md = checkfield(md,'fieldname','smb.aValue','timeseries',1,'NaN',1,'Inf',1,'>=',0,'<=',1);
 				case {1 2}
 					md = checkfield(md,'fieldname','smb.aSnow','NaN',1,'Inf',1,'>=',.64,'<=',.89);
@@ -250,13 +280,18 @@
 			fielddisplay(self,'zY','strech grid cells bellow top_z by a [top_dz * y ^ (cells bellow top_z)]');
 			fielddisplay(self,'InitDensityScaling',{'initial scaling factor multiplying the density of ice','which describes the density of the snowpack.'});
+			fielddisplay(self,'ThermoDeltaTScaling',{'scaling factor to multiply the thermal diffusion timestep (delta t)'});
 			fielddisplay(self,'outputFreq','output frequency in days (default is monthly, 30)');
+			fielddisplay(self,'adThresh',{'Apply aIdx method to all areas with densities below this value,','or else apply direct input value from aValue, allowing albedo to be altered.'});
 			fielddisplay(self,'aIdx',{'method for calculating albedo and subsurface absorption (default is 1)',...
-									'1: effective grain radius [Gardner & Sharp, 2009]',...
-									'2: effective grain radius [Brun et al., 2009]',...
-									'3: density and cloud amount [Greuell & Konzelmann, 1994]',...
-									'4: exponential time decay & wetness [Bougamont & Bamber, 2005]'});
+				'0: direct input from aValue parameter',...
+				'1: effective grain radius [Gardner & Sharp, 2009]',...
+				'2: effective grain radius [Brun et al., 2009]',...
+				'3: density and cloud amount [Greuell & Konzelmann, 1994]',...
+				'4: exponential time decay & wetness [Bougamont & Bamber, 2005]'})
+
+			fielddisplay(self,'teValue','Outward longwave radiation thermal emissivity forcing at every element (default in code is 1)');
                                 
 			%snow properties init
-			fielddisplay(self,'Dzini','Initial cel depth when restart [m]');
+			fielddisplay(self,'Dzini','Initial cell depth when restart [m]');
 			fielddisplay(self,'Dini','Initial snow density when restart [kg m-3]');
 			fielddisplay(self,'Reini','Initial grain size when restart [mm]');
@@ -272,4 +307,6 @@
 			%additional albedo parameters: 
 			switch self.aIdx
+			case {0 5}
+				fielddisplay(self,'aValue','Albedo forcing at every element.  Used only if aIdx == {0,5}.');
 			case {1 2}
 				fielddisplay(self,'aSnow','new snow albedo (0.64 - 0.89)');
@@ -332,4 +369,5 @@
 			WriteData(fid,prefix,'object',self,'class','smb','fieldname','denIdx','format','Integer');
 			WriteData(fid,prefix,'object',self,'class','smb','fieldname','InitDensityScaling','format','Double');
+			WriteData(fid,prefix,'object',self,'class','smb','fieldname','ThermoDeltaTScaling','format','Double');
 			WriteData(fid,prefix,'object',self,'class','smb','fieldname','outputFreq','format','Double');
 			WriteData(fid,prefix,'object',self,'class','smb','fieldname','aSnow','format','Double');
@@ -339,4 +377,8 @@
 			WriteData(fid,prefix,'object',self,'class','smb','fieldname','t0dry','format','Double');
 			WriteData(fid,prefix,'object',self,'class','smb','fieldname','K','format','Double');
+			WriteData(fid,prefix,'object',self,'class','smb','fieldname','adThresh','format','Double');
+
+			WriteData(fid,prefix,'object',self,'class','smb','fieldname','aValue','format','DoubleMat','mattype',2,'timeserieslength',md.mesh.numberofelements+1,'yts',md.constants.yts);
+			WriteData(fid,prefix,'object',self,'class','smb','fieldname','teValue','format','DoubleMat','mattype',2,'timeserieslength',md.mesh.numberofelements+1,'yts',md.constants.yts);
             
 			%snow properties init
@@ -358,5 +400,5 @@
             
 			WriteData(fid,prefix,'data',dt,'name','md.smb.dt','format','Double','scale',yts);
-            
+
 			% Check if smb_dt goes evenly into transient core time step
 			if (mod(md.timestepping.time_step,dt) >= 1e-10)
Index: /issm/trunk/src/m/classes/SMBgemb.py
===================================================================
--- /issm/trunk/src/m/classes/SMBgemb.py	(revision 22758)
+++ /issm/trunk/src/m/classes/SMBgemb.py	(revision 22758)
@@ -0,0 +1,412 @@
+import numpy as np
+from fielddisplay import fielddisplay
+from checkfield import checkfield
+from WriteData import WriteData
+from project3d import project3d
+
+class SMBgemb(object):
+	"""
+	SMBgemb Class definition
+
+	   Usage:
+	      SMB = SMBgemb()
+	"""
+
+	def __init__(self): # {{{
+		#each one of these properties is a transient forcing to the GEMB model, loaded from meteorological data derived 
+		#from an automatic weather stations (AWS). Each property is therefore a matrix, of size (numberofvertices x number 
+		#of time steps. )
+
+		#solution choices
+		#check these:
+		#isgraingrowth
+		#isalbedo
+		#isshortwave
+		#isthermal
+		#isaccumulation
+		#ismelt
+		#isdensification
+		#isturbulentflux    
+
+		#inputs: 
+		Ta    = float('NaN')	#2 m air temperature, in Kelvin
+		V     = float('NaN')	#wind speed (m/s-1)
+		dswrf = float('NaN')	#downward shortwave radiation flux [W/m^2]
+		dlwrf = float('NaN')	#downward longwave radiation flux [W/m^2]
+		P     = float('NaN')	#precipitation [mm w.e. / m^2]
+		eAir  = float('NaN')	#screen level vapor pressure [Pa]
+		pAir  = float('NaN')	#surface pressure [Pa]
+		
+		Tmean = float('NaN')	#mean annual temperature [K]
+		C     = float('NaN')	#mean annual snow accumulation [kg m-2 yr-1]
+		Tz    = float('NaN')	#height above ground at which temperature (T) was sampled [m]
+		Vz    = float('NaN')	#height above ground at which wind (V) eas sampled [m]
+
+		#optional inputs:
+		aValue  = float('NaN') #Albedo forcing at every element.  Used only if aIdx == 0.
+		teValue = float('NaN') #Outward longwave radiation thermal emissivity forcing at every element (default in code is 1)
+        
+		# Initialization of snow properties
+		Dzini = float('NaN')	#cell depth (m)
+		Dini = float('NaN')	#snow density (kg m-3)
+		Reini = float('NaN')	#effective grain size (mm)
+		Gdnini = float('NaN')	#grain dricity (0-1)
+		Gspini = float('NaN')	#grain sphericity (0-1)
+		ECini = float('NaN')	#evaporation/condensation (kg m-2)
+		Wini = float('NaN')	#Water content (kg m-2)
+		Aini = float('NaN')	#albedo (0-1)
+		Tini = float('NaN')	#snow temperature (K)
+		Sizeini = float('NaN')	#Number of layers
+
+		#settings: 
+		aIdx   = float('NaN')	#method for calculating albedo and subsurface absorption (default is 1)
+		           # 0: direct input from aValue parameter
+					  # 1: effective grain radius [Gardner & Sharp, 2009]
+					  # 2: effective grain radius [Brun et al., 2009]
+					  # 3: density and cloud amount [Greuell & Konzelmann, 1994]
+					  # 4: exponential time decay & wetness [Bougamont & Bamber, 2005]
+					  # 5: ingest MODIS mode, direct input from aValue parameter applied to surface ice only
+
+		swIdx  = float('NaN')	# apply all SW to top grid cell (0) or allow SW to penetrate surface (1) (default 1)
+
+		denIdx = float('NaN')	#densification model to use (default is 2):
+					# 1 = emperical model of Herron and Langway (1980)
+					# 2 = semi-emerical model of Anthern et al. (2010)
+					# 3 = DO NOT USE: physical model from Appix B of Anthern et al. (2010)
+					# 4 = DO NOT USE: emperical model of Li and Zwally (2004)
+					# 5 = DO NOT USE: modified emperical model (4) by Helsen et al. (2008)
+
+		zTop  = float('NaN')	# depth over which grid length is constant at the top of the snopack (default 10) [m]
+		dzTop = float('NaN')	# initial top vertical grid spacing (default .05) [m] 
+		dzMin = float('NaN')	# initial min vertical allowable grid spacing (default dzMin/2) [m] 
+		zY    = float('NaN')	# strech grid cells bellow top_z by a [top_dz * y ^ (cells bellow top_z)]
+		zMax = float('NaN')	#initial max model depth (default is min(thickness,500)) [m]
+		zMin = float('NaN')	#initial min model depth (default is min(thickness,30)) [m]
+		outputFreq = float('NaN')	#output frequency in days (default is monthly, 30)
+
+		#specific albedo parameters: 
+		#Method 1 and 2: 
+		aSnow = float('NaN')	# new snow albedo (0.64 - 0.89)
+		aIce  = float('NaN')	# range 0.27-0.58 for old snow
+			#Method 3: Radiation Correction Factors -> only used for met station data and Greuell & Konzelmann, 1994 albedo
+		cldFrac = float('NaN')	# average cloud amount
+			#Method 4: additonal tuning parameters albedo as a funtion of age and water content (Bougamont et al., 2005)
+		t0wet = float('NaN')	# time scale for wet snow (15-21.9) 
+		t0dry = float('NaN')	# warm snow timescale (30) 
+		K     = float('NaN')	# time scale temperature coef. (7) 
+		adThresh = float('NaN') # Apply aIdx method to all areas with densities below this value,
+		                        # or else apply direct input value from aValue, allowing albedo to be altered.
+										# Default value is rho water (1023 kg m-3).
+
+		#densities:
+		InitDensityScaling =  float('NaN')	#initial scaling factor multiplying the density of ice, which describes the density of the snowpack.
+
+		#thermo:
+		ThermoDeltaTScaling = float('NaN') #scaling factor to multiply the thermal diffusion timestep (delta t)
+		
+		requested_outputs      = []
+
+		#Several fields are missing from the standard GEMB model, which are capture intrinsically by ISSM. 
+		#dateN: that's the last row of the above fields. 
+		#dt:    included in dateN. Not an input.  
+		#elev:  this is taken from the ISSM surface itself.
+
+		#}}}
+	def __repr__(self): # {{{
+		#string = "   surface forcings parameters:"
+		#string = "#s\n#s"%(string,fielddisplay(self,'mass_balance','surface mass balance [m/yr ice eq]'))
+		#string = "#s\n#s"%(string,fielddisplay(self,'requested_outputs','additional outputs requested'))
+		string = '   surface forcings for SMB GEMB model :'
+			
+		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,'isgraingrowth','run grain growth module (default true)'))
+		string = "%s\n%s"%(string,fielddisplay(self,'isalbedo','run albedo module (default true)'))
+		string = "%s\n%s"%(string,fielddisplay(self,'isshortwave','run short wave module (default true)'))
+		string = "%s\n%s"%(string,fielddisplay(self,'isthermal','run thermal module (default true)'))
+		string = "%s\n%s"%(string,fielddisplay(self,'isaccumulation','run accumulation module (default true)'))
+		string = "%s\n%s"%(string,fielddisplay(self,'ismelt','run melting  module (default true)'))
+		string = "%s\n%s"%(string,fielddisplay(self,'isdensification','run densification module (default true)'))
+		string = "%s\n%s"%(string,fielddisplay(self,'isturbulentflux','run turbulant heat fluxes module (default true)'))
+		string = "%s\n%s"%(string,fielddisplay(self,'Ta','2 m air temperature, in Kelvin'))
+		string = "%s\n%s"%(string,fielddisplay(self,'V','wind speed (m/s-1)'))
+		string = "%s\n%s"%(string,fielddisplay(self,'dlwrf','downward shortwave radiation flux [W/m^2]'))
+		string = "%s\n%s"%(string,fielddisplay(self,'dswrf','downward longwave radiation flux [W/m^2]'))
+		string = "%s\n%s"%(string,fielddisplay(self,'P','precipitation [mm w.e. / m^2]'))
+		string = "%s\n%s"%(string,fielddisplay(self,'eAir','screen level vapor pressure [Pa]'))
+		string = "%s\n%s"%(string,fielddisplay(self,'pAir','surface pressure [Pa]'))
+		string = "%s\n%s"%(string,fielddisplay(self,'Tmean','mean annual temperature [K]'))
+		string = "%s\n%s"%(string,fielddisplay(self,'C','mean annual snow accumulation [kg m-2 yr-1]'))
+		string = "%s\n%s"%(string,fielddisplay(self,'Tz','height above ground at which temperature (T) was sampled [m]'))
+		string = "%s\n%s"%(string,fielddisplay(self,'Vz','height above ground at which wind (V) eas sampled [m]'))
+		string = "%s\n%s"%(string,fielddisplay(self,'zTop','depth over which grid length is constant at the top of the snopack (default 10) [m]'))
+		string = "%s\n%s"%(string,fielddisplay(self,'dzTop','initial top vertical grid spacing (default .05) [m] '))
+		string = "%s\n%s"%(string,fielddisplay(self,'dzMin','initial min vertical allowable grid spacing (default dzMin/2) [m] '))
+		string = "%s\n%s"%(string,fielddisplay(self,'zMax','initial max model depth (default is min(thickness,500)) [m]'))
+		string = "%s\n%s"%(string,fielddisplay(self,'zMin','initial min model depth (default is min(thickness,30)) [m]'))
+		string = "%s\n%s"%(string,fielddisplay(self,'zY','strech grid cells bellow top_z by a [top_dz * y ^ (cells bellow top_z)]'))
+		string = "%s\n%s"%(string,fielddisplay(self,'InitDensityScaling',['initial scaling factor multiplying the density of ice','which describes the density of the snowpack.']))
+		string = "%s\n%s"%(string,fielddisplay(self,'ThermoDeltaTScaling','scaling factor to multiply the thermal diffusion timestep (delta t)'))
+		string = "%s\n%s"%(string,fielddisplay(self,'outputFreq','output frequency in days (default is monthly, 30)'))
+		string = "%s\n%s"%(string,fielddisplay(self,'adThresh','Apply aIdx method to all areas with densities below this value,','or else apply direct input value from aValue, allowing albedo to be altered.'))
+		string = "%s\n%s"%(string,fielddisplay(self,'aIdx',['method for calculating albedo and subsurface absorption (default is 1)',
+			         '0: direct input from aValue parameter',
+						'1: effective grain radius [Gardner & Sharp, 2009]',
+						'2: effective grain radius [Brun et al., 2009]',
+						'3: density and cloud amount [Greuell & Konzelmann, 1994]',
+						'4: exponential time decay & wetness [Bougamont & Bamber, 2005]']))
+
+		string = "%s\n%s"%(string,fielddisplay(self,'teValue','Outward longwave radiation thermal emissivity forcing at every element (default in code is 1)'))
+                               
+		#snow properties init
+		string = "%s\n%s"%(string,fielddisplay(self,'Dzini','Initial cell depth when restart [m]'))
+		string = "%s\n%s"%(string,fielddisplay(self,'Dini','Initial snow density when restart [kg m-3]'))
+		string = "%s\n%s"%(string,fielddisplay(self,'Reini','Initial grain size when restart [mm]'))
+		string = "%s\n%s"%(string,fielddisplay(self,'Gdnini','Initial grain dricity when restart [-]'))
+		string = "%s\n%s"%(string,fielddisplay(self,'Gspini','Initial grain sphericity when restart [-]'))
+		string = "%s\n%s"%(string,fielddisplay(self,'ECini','Initial evaporation/condensation when restart [kg m-2]'))
+		string = "%s\n%s"%(string,fielddisplay(self,'Wini','Initial snow water content when restart [kg m-2]'))
+		string = "%s\n%s"%(string,fielddisplay(self,'Aini','Initial albedo when restart [-]'))
+		string = "%s\n%s"%(string,fielddisplay(self,'Tini','Initial snow temperature when restart [K]'))
+		string = "%s\n%s"%(string,fielddisplay(self,'Sizeini','Initial number of layers when restart [K]'))
+                        
+		#additional albedo parameters: 
+		if type(self.aIdx) == list or type(self.aIdx) == type(np.array([1,2])) and (self.aIdx == [1,2] or (1 in self.aIdx and 2 in self.aIdx)):
+			string = "%s\n%s"%(string,fielddisplay(self,'aSnow','new snow albedo (0.64 - 0.89)'))
+			string = "%s\n%s"%(string,fielddisplay(self,'aIce','albedo of ice (0.27-0.58)'))
+		elif elf.aIdx == 0:
+			string = "%s\n%s"%(string,fielddisplay(self,'aValue','Albedo forcing at every element.  Used only if aIdx == {0,5}'))
+		elif elf.aIdx == 5:
+			string = "%s\n%s"%(string,fielddisplay(self,'aValue','Albedo forcing at every element.  Used only if aIdx == {0,5}'))
+		elif self.aIdx == 3:
+			string = "%s\n%s"%(string,fielddisplay(self,'cldFrac','average cloud amount'))
+		elif self.aIdx == 4:
+			string = "%s\n%s"%(string,fielddisplay(self,'t0wet','time scale for wet snow (15-21.9) [d]'))
+			string = "%s\n%s"%(string,fielddisplay(self,'t0dry','warm snow timescale (30) [d]'))
+			string = "%s\n%s"%(string,fielddisplay(self,'K','time scale temperature coef. (7) [d]'))
+		
+		string = "%s\n%s"%(string,fielddisplay(self,'swIdx','apply all SW to top grid cell (0) or allow SW to penetrate surface (1) [default 1]'))
+		string = "%s\n%s"%(string,fielddisplay(self,'denIdx',['densification model to use (default is 2):',
+						'1 = emperical model of Herron and Langway (1980)',
+						'2 = semi-emerical model of Anthern et al. (2010)',
+						'3 = DO NOT USE: physical model from Appix B of Anthern et al. (2010)',
+						'4 = DO NOT USE: emperical model of Li and Zwally (2004)',
+						'5 = DO NOT USE: modified emperical model (4) by Helsen et al. (2008)']))
+		string = "%s\n%s"%(string,fielddisplay(self,'requested_outputs','additional outputs requested'))
+		return string
+	#}}}
+
+	def extrude(self,md): # {{{
+
+		self.Ta = project3d(md,'vector',self.Ta,'type','node')
+		self.V = project3d(md,'vector',self.V,'type','node')
+		self.dswrf = project3d(md,'vector',self.dswrf,'type','node')
+		self.dswrf = project3d(md,'vector',self.dswrf,'type','node')
+		self.P = project3d(md,'vector',self.P,'type','node')
+		self.eAir = project3d(md,'vector',self.eAir,'type','node')
+		self.pAir = project3d(md,'vector',self.pAir,'type','node')
+
+		if (aIdx == 0) and np.isnan(self.aValue):
+			self.aValue=project3d(md,'vector',self.aValue,'type','node');
+		if np.isnan(self.teValue):
+			self.teValue=project3d(md,'vector',self.teValue,'type','node');
+
+		return self
+	#}}}
+	def defaultoutputs(self,md): # {{{
+		return ['SmbMassBalance']
+	#}}}
+
+	def setdefaultparameters(self,mesh,geometry): # {{{
+		self.isgraingrowth = 1
+		self.isalbedo = 1
+		self.isshortwave = 1
+		self.isthermal = 1
+		self.isaccumulation = 1
+		self.ismelt = 1
+		self.isdensification = 1
+		self.isturbulentflux = 1
+	
+		self.aIdx = 1
+		self.swIdx = 1
+		self.denIdx = 2
+		self.zTop = 10*np.ones((mesh.numberofelements,))
+		self.dzTop = .05* np.ones((mesh.numberofelements,))
+		self.dzMin = self.dzTop/2
+		self.InitDensityScaling = 1.0
+		self.ThermoDeltaTScaling = 1/11.0
+		
+		self.zMax = 250*np.ones((mesh.numberofelements,))
+		self.zMin = 130*np.ones((mesh.numberofelements,))
+		self.zY = 1.10*np.ones((mesh.numberofelements,))
+		self.outputFreq = 30
+
+		#additional albedo parameters
+		self.aSnow = 0.85
+		self.aIce = 0.48
+		self.cldFrac = 0.1 
+		self.t0wet = 15
+		self.t0dry = 30
+		self.K = 7
+		self.adThresh = 1023
+
+		self.teValue = np.ones((mesh.numberofelements,));
+		self.aValue = self.aSnow*np.ones(mesh.numberofelements,);
+        
+		self.Dzini = 0.05*np.ones((mesh.numberofelements,2))
+		self.Dini = 910.0*np.ones((mesh.numberofelements,2)) 
+		self.Reini = 2.5*np.ones((mesh.numberofelements,2))
+		self.Gdnini = 0.0*np.ones((mesh.numberofelements,2))
+		self.Gspini = 0.0*np.ones((mesh.numberofelements,2))
+		self.ECini = 0.0*np.ones((mesh.numberofelements,))
+		self.Wini = 0.0*np.ones((mesh.numberofelements,2))
+		self.Aini = self.aSnow*np.ones((mesh.numberofelements,2))
+		self.Tini = 273.15*np.ones((mesh.numberofelements,2))
+# 		/!\ Default value of Tini must be equal to Tmean but don't know Tmean yet (computed when atmospheric forcings are interpolated on mesh). 
+# 		If initialization without restart, this value will be overwritten when snow parameters are retrieved in Element.cpp 
+		self.Sizeini = 2*np.ones((mesh.numberofelements,))
+	#}}}
+
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		md = checkfield(md,'fieldname','smb.isgraingrowth','values',[0,1])
+		md = checkfield(md,'fieldname','smb.isalbedo','values',[0,1])
+		md = checkfield(md,'fieldname','smb.isshortwave','values',[0,1])
+		md = checkfield(md,'fieldname','smb.isthermal','values',[0,1])
+		md = checkfield(md,'fieldname','smb.isaccumulation','values',[0,1])
+		md = checkfield(md,'fieldname','smb.ismelt','values',[0,1])
+		md = checkfield(md,'fieldname','smb.isdensification','values',[0,1])
+		md = checkfield(md,'fieldname','smb.isturbulentflux','values',[0,1])
+
+		md = checkfield(md,'fieldname','smb.Ta','timeseries',1,'NaN',1,'Inf',1,'>',273-100,'<',273+100) #-100/100 celsius min/max value
+		md = checkfield(md,'fieldname','smb.V','timeseries',1,'NaN',1,'Inf',1,'> = ',0,'<',45) #max 500 km/h
+		md = checkfield(md,'fieldname','smb.dswrf','timeseries',1,'NaN',1,'Inf',1,'> = ',0,'< = ',1400)
+		md = checkfield(md,'fieldname','smb.dlwrf','timeseries',1,'NaN',1,'Inf',1,'> = ',0)
+		md = checkfield(md,'fieldname','smb.P','timeseries',1,'NaN',1,'Inf',1,'> = ',0,'< = ',100)
+		md = checkfield(md,'fieldname','smb.eAir','timeseries',1,'NaN',1,'Inf',1)
+
+		md = checkfield(md,'fieldname','smb.Tmean','size',[md.mesh.numberofelements],'NaN',1,'Inf',1,'>',273-100,'<',273+100) #-100/100 celsius min/max value
+		md = checkfield(md,'fieldname','smb.C','size',[md.mesh.numberofelements],'NaN',1,'Inf',1,'> = ',0) 
+		md = checkfield(md,'fieldname','smb.Tz','size',[md.mesh.numberofelements],'NaN',1,'Inf',1,'> = ',0,'< = ',5000) 
+		md = checkfield(md,'fieldname','smb.Vz','size',[md.mesh.numberofelements],'NaN',1,'Inf',1,'> = ',0,'< = ',5000) 
+
+		md = checkfield(md,'fieldname','smb.teValue','timeseries',1,'NaN',1,'Inf',1,'>=',0,'<=',1);
+
+		md = checkfield(md,'fieldname','smb.aIdx','NaN',1,'Inf',1,'values',[0,1,2,3,4])
+		md = checkfield(md,'fieldname','smb.swIdx','NaN',1,'Inf',1,'values',[0,1])
+		md = checkfield(md,'fieldname','smb.denIdx','NaN',1,'Inf',1,'values',[1,2,3,4,5])
+
+		md = checkfield(md,'fieldname','smb.zTop','NaN',1,'Inf',1,'> = ',0)
+		md = checkfield(md,'fieldname','smb.dzTop','NaN',1,'Inf',1,'>',0)
+		md = checkfield(md,'fieldname','smb.dzMin','NaN',1,'Inf',1,'>',0)
+		md = checkfield(md,'fieldname','smb.zY','NaN',1,'Inf',1,'> = ',1)
+		md = checkfield(md,'fieldname','smb.outputFreq','NaN',1,'Inf',1,'>',0,'<',10*365) #10 years max 
+		md = checkfield(md,'fieldname','smb.InitDensityScaling','NaN',1,'Inf',1,'> = ',0,'< = ',1)
+		md = checkfield(md,'fieldname','smb.ThermoDeltaTScaling','NaN',1,'Inf',1,'> = ',0,'< = ',1)
+		md = checkfield(md,'fieldname','smb.adThresh','NaN',1,'Inf',1,'>=',0)
+
+		if type(self.aIdx) == list or type(self.aIdx) == type(np.array([1,2])) and (self.aIdx == [1,2] or (1 in self.aIdx and 2 in self.aIdx)):
+			md = checkfield(md,'fieldname','smb.aSnow','NaN',1,'Inf',1,'> = ',.64,'< = ',.89)
+			md = checkfield(md,'fieldname','smb.aIce','NaN',1,'Inf',1,'> = ',.27,'< = ',.58)
+		elif self.aIdx == 0:
+			md = checkfield(md,'fieldname','smb.aValue','timeseries',1,'NaN',1,'Inf',1,'>=',0,'<=',1);
+		elif self.aIdx == 3:
+			md = checkfield(md,'fieldname','smb.cldFrac','NaN',1,'Inf',1,'> = ',0,'< = ',1)
+		elif self.aIdx == 4:
+			md = checkfield(md,'fieldname','smb.t0wet','NaN',1,'Inf',1,'> = ',15,'< = ',21.9)
+			md = checkfield(md,'fieldname','smb.t0dry','NaN',1,'Inf',1,'> = ',30,'< = ',30)
+			md = checkfield(md,'fieldname','smb.K','NaN',1,'Inf',1,'> = ',7,'< = ',7)
+			
+
+		#check zTop is < local thickness:
+		he = np.sum(md.geometry.thickness[md.mesh.elements-1],axis=1)/np.size(md.mesh.elements,1)
+		if np.any(he<self.zTop):
+			error('SMBgemb consistency check error: zTop should be smaller than local ice thickness')
+		
+		md = checkfield(md,'fieldname','smb.requested_outputs','stringrow',1)
+		return md
+	# }}}
+
+	def marshall(self,prefix,md,fid):    # {{{
+
+		yts = md.constants.yts
+
+		WriteData(fid,prefix,'name','md.smb.model','data',8,'format','Integer')
+			
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','isgraingrowth','format','Boolean')
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','isalbedo','format','Boolean')
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','isshortwave','format','Boolean')
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','isthermal','format','Boolean')
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','isaccumulation','format','Boolean')
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','ismelt','format','Boolean')
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','isdensification','format','Boolean')
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','isturbulentflux','format','Boolean')
+            
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','Ta','format','DoubleMat','mattype',2,'timeserieslength',md.mesh.numberofelements+1,'yts',md.constants.yts)
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','V','format','DoubleMat','mattype',2,'timeserieslength',md.mesh.numberofelements+1,'yts',md.constants.yts)
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','dswrf','format','DoubleMat','mattype',2,'timeserieslength',md.mesh.numberofelements+1,'yts',md.constants.yts)
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','dlwrf','format','DoubleMat','mattype',2,'timeserieslength',md.mesh.numberofelements+1,'yts',md.constants.yts)
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','P','format','DoubleMat','mattype',2,'timeserieslength',md.mesh.numberofelements+1,'yts',md.constants.yts)
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','eAir','format','DoubleMat','mattype',2,'timeserieslength',md.mesh.numberofelements+1,'yts',md.constants.yts)
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','pAir','format','DoubleMat','mattype',2,'timeserieslength',md.mesh.numberofelements+1,'yts',md.constants.yts)         
+
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','Tmean','format','DoubleMat','mattype',2)
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','C','format','DoubleMat','mattype',2)
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','Tz','format','DoubleMat','mattype',2)
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','Vz','format','DoubleMat','mattype',2)
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','zTop','format','DoubleMat','mattype',2)
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','dzTop','format','DoubleMat','mattype',2)
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','dzMin','format','DoubleMat','mattype',2)
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','zY','format','DoubleMat','mattype',2)
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','zMax','format','DoubleMat','mattype',2)
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','zMin','format','DoubleMat','mattype',2)
+		
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','aIdx','format','Integer')
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','swIdx','format','Integer')
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','denIdx','format','Integer')
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','InitDensityScaling','format','Double')
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','ThermoDeltaTScaling','format','Double')
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','outputFreq','format','Double')
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','aSnow','format','Double')
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','aIce','format','Double')
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','cldFrac','format','Double')
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','t0wet','format','Double')
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','t0dry','format','Double')
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','K','format','Double')
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','adThresh','format','Double');
+
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','aValue','format','DoubleMat','mattype',2,'timeserieslength',md.mesh.numberofelements+1,'yts',md.constants.yts);
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','teValue','format','DoubleMat','mattype',2,'timeserieslength',md.mesh.numberofelements+1,'yts',md.constants.yts);
+            
+		#snow properties init
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','Dzini','format','DoubleMat','mattype',3)
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','Dini','format','DoubleMat','mattype',3)
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','Reini','format','DoubleMat','mattype',3)
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','Gdnini','format','DoubleMat','mattype',3)
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','Gspini','format','DoubleMat','mattype',3)
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','ECini','format','DoubleMat','mattype',2)
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','Wini','format','DoubleMat','mattype',3)
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','Aini','format','DoubleMat','mattype',3)
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','Tini','format','DoubleMat','mattype',3)
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','Sizeini','format','IntMat','mattype',2)
+
+		#figure out dt from forcings: 
+		time = self.Ta[-1] #assume all forcings are on the same time step
+		dtime = np.diff(time,n=1,axis=0)
+		dt = min(dtime) / yts
+            
+		WriteData(fid,prefix,'data',dt,'name','md.smb.dt','format','Double','scale',yts)
+
+		# Check if smb_dt goes evenly into transient core time step
+		if (md.timestepping.time_step % dt >=  1e-10):
+	                error('smb_dt/dt = #f. The number of SMB time steps in one transient core time step has to be an an integer',md.timestepping.time_step/dt)
+			
+		#process requested outputs
+		outputs = self.requested_outputs
+		indices = [i for i, x in enumerate(outputs) if x == 'default']
+		if len(indices) > 0:
+			outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:]
+			outputs    =outputscopy
+		
+		WriteData(fid,prefix,'data',outputs,'name','md.smb.requested_outputs','format','StringArray')
+	# }}}
+
Index: /issm/trunk/src/m/classes/SMBgradientsela.py
===================================================================
--- /issm/trunk/src/m/classes/SMBgradientsela.py	(revision 22757)
+++ /issm/trunk/src/m/classes/SMBgradientsela.py	(revision 22758)
@@ -9,5 +9,5 @@
 
 	   Usage:
-	      SMBgradientsela=SMBgradientsela();
+	      SMBgradientsela=SMBgradientsela()
 	"""
 
@@ -19,9 +19,10 @@
 		self.b_min   = float('NaN')
 		self.requested_outputs      = []
+		self.setdefaultparameters()
 		#}}}
 	def __repr__(self): # {{{
-		string="   surface forcings parameters:"
+		string = "   surface forcings parameters:"
+		string+= '\n   SMB gradients ela parameters:'
 
-		string="%s\n%s"%(string,fielddisplay(self,'issmbgradientsela','is smb gradients ela method activated (0 or 1, default is 0)'))
 		string="%s\n%s"%(string,fielddisplay(self,'ela',' equilibrium line altitude from which deviation is used to calculate smb using the smb gradients ela method [m a.s.l.]'))
 		string="%s\n%s"%(string,fielddisplay(self,'b_pos',' vertical smb gradient (dB/dz) above ela'))
@@ -47,4 +48,9 @@
 		return self
 	#}}}
+	def setdefaultparameters(self): # {{{
+		self.b_max=9999.
+		self.b_min=-9999.
+		return self
+	#}}}
 	def checkconsistency(self,md,solution,analyses):    # {{{
 
@@ -56,5 +62,5 @@
 			md = checkfield(md,'fieldname','smb.b_min','timeseries',1,'NaN',1,'Inf',1)
 
-		md = checkfield(md,'fieldname','masstransport.requested_outputs','stringrow',1)
+		md = checkfield(md,'fieldname','smb.requested_outputs','stringrow',1)
 		return md
 	# }}}
Index: /issm/trunk/src/m/classes/SMBpdd.m
===================================================================
--- /issm/trunk/src/m/classes/SMBpdd.m	(revision 22757)
+++ /issm/trunk/src/m/classes/SMBpdd.m	(revision 22758)
@@ -18,4 +18,5 @@
 		isdelta18o                = 0;
 		ismungsm                  = 0;
+		issetpddfac               = 0;
 		delta18o                  = NaN;
 		delta18o_surface          = NaN;
@@ -148,4 +149,5 @@
 
 			WriteData(fid,prefix,'object',self,'class','smb','fieldname','isdelta18o','format','Boolean');
+			WriteData(fid,prefix,'object',self,'class','smb','fieldname','issetpddfac','format','Boolean');
 			WriteData(fid,prefix,'object',self,'class','smb','fieldname','ismungsm','format','Boolean');
 			WriteData(fid,prefix,'object',self,'class','smb','fieldname','desfac','format','Double');
Index: /issm/trunk/src/m/classes/SMBpdd.py
===================================================================
--- /issm/trunk/src/m/classes/SMBpdd.py	(revision 22757)
+++ /issm/trunk/src/m/classes/SMBpdd.py	(revision 22758)
@@ -26,4 +26,5 @@
 		self.isdelta18o                = 0
 		self.ismungsm                  = 0
+		self.issetpddfac               = 0
 		self.delta18o                  = float('NaN')
 		self.delta18o_surface          = float('NaN')
@@ -156,4 +157,5 @@
 		WriteData(fid,prefix,'object',self,'class','smb','fieldname','isdelta18o','format','Boolean')
 		WriteData(fid,prefix,'object',self,'class','smb','fieldname','ismungsm','format','Boolean')
+		WriteData(fid,prefix,'object',self,'class','smb','fieldname','issetpddfac','format','Boolean');
 		WriteData(fid,prefix,'object',self,'class','smb','fieldname','desfac','format','Double')
 		WriteData(fid,prefix,'object',self,'class','smb','fieldname','s0p','format','DoubleMat','mattype',1);
Index: sm/trunk/src/m/classes/adinversion.m
===================================================================
--- /issm/trunk/src/m/classes/adinversion.m	(revision 22757)
+++ 	(revision )
@@ -1,188 +1,0 @@
-%ADINVERSION class definition
-%
-%   Usage:
-%      adinversion=adinversion();
-
-classdef adinversion
-	properties (SetAccess=public) 
-		iscontrol                   = 0
-		control_parameters          = NaN
-		control_scaling_factors     = NaN
-		maxsteps                    = 0
-		maxiter                     = 0
-		dxmin                       = 0
-		gttol                       = 0
-		cost_functions              = NaN
-		cost_functions_coefficients = NaN
-		min_parameters              = NaN
-		max_parameters              = NaN
-		vx_obs                      = NaN
-		vy_obs                      = NaN
-		vz_obs                      = NaN
-		vel_obs                     = NaN
-		thickness_obs               = NaN
-		surface_obs                 = NaN
-
-	end
-	methods
-		function self = adinversion(varargin) % {{{
-			switch nargin
-				case 0
-					self=setdefaultparameters(self);
-				case 1
-					self=structtoobj(adinversion(),varargin{1});
-				otherwise
-					error('constructor not supported');
-			end
-		end % }}}
-		function self = setdefaultparameters(self) % {{{
-
-			%parameter to be inferred by control methods (only
-			%drag and B are supported yet)
-			self.control_parameters={'FrictionCoefficient'};
-
-			%Scaling factor for each control
-			self.control_scaling_factors=1;
-
-			%number of iterations
-			self.maxsteps=20;
-			self.maxiter=40;
-
-			%several responses can be used:
-			self.cost_functions={'FrictionCoefficient'};
-
-			%m1qn3 parameters
-			self.dxmin  = 0.1;
-			self.gttol = 1e-4;
-
-		end % }}}
-		function md = checkconsistency(self,md,solution,analyses) % {{{
-
-			%Early return
-			if ~self.iscontrol, return; end
-
-			if ~IssmConfig('_HAVE_M1QN3_'),
-				md = checkmessage(md,['M1QN3 has not been installed, ISSM needs to be reconfigured and recompiled with AD']);
-			end
-
-			num_controls=numel(md.inversion.control_parameters);
-			num_costfunc=size(md.inversion.cost_functions,2);
-
-			md = checkfield(md,'fieldname','inversion.iscontrol','values',[0 1]);
-			md = checkfield(md,'fieldname','inversion.control_parameters','cell',1,'values',...
-				{'BalancethicknessThickeningRate' 'FrictionCoefficient' 'MaterialsRheologyBbar' 'DamageDbar',...
-				'Vx' 'Vy' 'Thickness' 'BalancethicknessOmega' 'BalancethicknessApparentMassbalance'});
-			md = checkfield(md,'fieldname','inversion.control_scaling_factors','size',[1 num_controls],'>',0,'NaN',1,'Inf',1);
-			md = checkfield(md,'fieldname','inversion.maxsteps','numel',1,'>=',0);
-			md = checkfield(md,'fieldname','inversion.maxiter','numel',1,'>=',0);
-			md = checkfield(md,'fieldname','inversion.dxmin','numel',1,'>',0);
-			md = checkfield(md,'fieldname','inversion.gttol','numel',1,'>',0);
-			md = checkfield(md,'fieldname','inversion.cost_functions','size',[1 num_costfunc],'values',[101:105 201 501:506 601:604 1001:1010]);
-			md = checkfield(md,'fieldname','inversion.cost_functions_coefficients','size',[md.mesh.numberofvertices num_costfunc],'>=',0);
-			md = checkfield(md,'fieldname','inversion.min_parameters','size',[md.mesh.numberofvertices num_controls]);
-			md = checkfield(md,'fieldname','inversion.max_parameters','size',[md.mesh.numberofvertices num_controls]);
-
-			if strcmp(solution,'BalancethicknessSolution')
-				md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1,'Inf',1);
-				md = checkfield(md,'fieldname','inversion.surface_obs','size',[md.mesh.numberofvertices 1],'NaN',1,'Inf',1);
-			elseif strcmp(solution,'BalancethicknessSoftSolution')
-				md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1,'Inf',1);
-			else
-				md = checkfield(md,'fieldname','inversion.vx_obs','size',[md.mesh.numberofvertices 1],'NaN',1,'Inf',1);
-				if ~strcmp(domaintype(md.mesh),'2Dvertical'),
-					md = checkfield(md,'fieldname','inversion.vy_obs','size',[md.mesh.numberofvertices 1],'NaN',1,'Inf',1);
-				end
-			end
-		end % }}}
-		function disp(self) % {{{
-			disp(sprintf('   adinversion parameters:'));
-			fielddisplay(self,'iscontrol','is inversion activated?');
-			fielddisplay(self,'control_parameters','ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''}');
-			fielddisplay(self,'control_scaling_factors','order of magnitude of each control (useful for multi-parameter optimization)');
-			fielddisplay(self,'maxsteps','maximum number of iterations (gradient computation)');
-			fielddisplay(self,'maxiter','maximum number of Function evaluation (forward run)');
-			fielddisplay(self,'dxmin','convergence criterion: two points less than dxmin from eachother (sup-norm) are considered identical');
-			fielddisplay(self,'gttol','convergence criterion: ||g(X)||/||g(X0)|| (g(X0): gradient at initial guess X0)');
-			fielddisplay(self,'cost_functions','indicate the type of response for each optimization step');
-			fielddisplay(self,'cost_functions_coefficients','cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter');
-			fielddisplay(self,'min_parameters','absolute minimum acceptable value of the inversed parameter on each vertex');
-			fielddisplay(self,'max_parameters','absolute maximum acceptable value of the inversed parameter on each vertex');
-			fielddisplay(self,'vx_obs','observed velocity x component [m/yr]');
-			fielddisplay(self,'vy_obs','observed velocity y component [m/yr]');
-			fielddisplay(self,'vel_obs','observed velocity magnitude [m/yr]');
-			fielddisplay(self,'thickness_obs','observed thickness [m]');
-			fielddisplay(self,'surface_obs','observed surface elevation [m]');
-			
-			disp('Available cost functions:');
-			disp('   101: SurfaceAbsVelMisfit');
-			disp('   102: SurfaceRelVelMisfit');
-			disp('   103: SurfaceLogVelMisfit');
-			disp('   104: SurfaceLogVxVyMisfit');
-			disp('   105: SurfaceAverageVelMisfit');
-			disp('   201: ThicknessAbsMisfit');
-			disp('   501: DragCoefficientAbsGradient');
-			disp('   502: RheologyBbarAbsGradient');
-			disp('   503: ThicknessAbsGradient');
-		end % }}}
-		function marshall(self,prefix,md,fid) % {{{
-
-			yts=md.constants.yts;
-
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','iscontrol','format','Boolean');
-			WriteData(fid,prefix,'name','md.inversion.type','data',4,'format','Integer');
-			if ~self.iscontrol, return; end
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','control_scaling_factors','format','DoubleMat','mattype',3);
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','maxsteps','format','Integer');
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','maxiter','format','Integer');
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','dxmin','format','Double');
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','gttol','format','Double');
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1);
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','min_parameters','format','DoubleMat','mattype',3);
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','max_parameters','format','DoubleMat','mattype',3);
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts);
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts);
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts);
-			if(numel(self.thickness_obs)==md.mesh.numberofelements),
-				mattype=2;
-			else
-				mattype=1;
-			end
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','thickness_obs','format','DoubleMat','mattype',mattype);
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','surface_obs','format','DoubleMat','mattype',mattype);
-
-			%process control parameters
-			num_control_parameters=numel(self.control_parameters);
-			WriteData(fid,prefix,'object',self,'fieldname','control_parameters','format','StringArray');
-			WriteData(fid,prefix,'data',num_control_parameters,'name','md.inversion.num_control_parameters','format','Integer');
-
-			%process cost functions
-			num_cost_functions=size(self.cost_functions,2);
-			data=self.cost_functions;
-			pos=find(self.cost_functions==101); data(pos)={'SurfaceAbsVelMisfit'};
-			pos=find(self.cost_functions==102); data(pos)={'SurfaceRelVelMisfit'};
-			pos=find(self.cost_functions==103); data(pos)={'SurfaceLogVelMisfit'};
-			pos=find(self.cost_functions==104); data(pos)={'SurfaceLogVxVyMisfit'};
-			pos=find(self.cost_functions==105); data(pos)={'SurfaceAverageVelMisfit'};
-			pos=find(self.cost_functions==201); data(pos)={'ThicknessAbsMisfit'};
-			pos=find(self.cost_functions==501); data(pos)={'DragCoefficientAbsGradient'};
-			pos=find(self.cost_functions==502); data(pos)={'RheologyBbarAbsGradient'};
-			pos=find(self.cost_functions==503); data(pos)={'ThicknessAbsGradient'};
-			pos=find(self.cost_functions==504); data(pos)={'ThicknessAlongGradient'};
-			pos=find(self.cost_functions==505); data(pos)={'ThicknessAcrossGradient'};
-			pos=find(self.cost_functions==506); data(pos)={'BalancethicknessMisfit'};
-			pos=find(self.cost_functions==601); data(pos)={'SurfaceAbsMisfit'};
-			pos=find(self.cost_functions==1001); data(pos)={'Outputdefinition1'};
-			pos=find(self.cost_functions==1002); data(pos)={'Outputdefinition2'};
-			pos=find(self.cost_functions==1003); data(pos)={'Outputdefinition3'};
-			pos=find(self.cost_functions==1004); data(pos)={'Outputdefinition4'};
-			pos=find(self.cost_functions==1005); data(pos)={'Outputdefinition5'};
-			pos=find(self.cost_functions==1006); data(pos)={'Outputdefinition6'};
-			pos=find(self.cost_functions==1007); data(pos)={'Outputdefinition7'};
-			pos=find(self.cost_functions==1008); data(pos)={'Outputdefinition8'};
-			pos=find(self.cost_functions==1009); data(pos)={'Outputdefinition8'};
-			pos=find(self.cost_functions==1010); data(pos)={'Outputdefinition10'};
-			WriteData(fid,prefix,'data',data,'name','md.inversion.cost_functions','format','StringArray');
-			WriteData(fid,prefix,'data',num_cost_functions,'name','md.inversion.num_cost_functions','format','Integer');
-		end % }}}
-	end
-end
Index: sm/trunk/src/m/classes/adinversion.py
===================================================================
--- /issm/trunk/src/m/classes/adinversion.py	(revision 22757)
+++ 	(revision )
@@ -1,193 +1,0 @@
-"""
-== == == == == == == == == == == == == == == == == == ==
-Auto generated python script for ISSM:   /home/andrei/issm/trunk-jpl/src/m/classes/adinversion.m
-Created on 2015-05-15 via translateToPy.py Ver 1.0 by andrei
-== == == == == == == == == == == == == == == == == == ==
-
-Matlab script conversion into python
-translateToPy.py Author: Michael Pellegrin
-translateToPy.py Date: 09/24/12
-== == == == == == == == == == == == == == == == == == ==
-"""
-
-from MatlabFuncs import *
-from np.import *
-
-# ADINVERSION class definition
-# 
-#    Usage:
-#       adinversion=adinversion();
-
-class adinversion:
-	def __init__(self): 
-		iscontrol                   = 0
-		control_parameters          = float('Nan')
-		control_scaling_factors     = float('Nan')
-		maxsteps                    = 0
-		maxiter                     = 0
-		dxmin                       = 0
-		gttol                       = 0
-		cost_functions              = float('Nan')
-		cost_functions_coefficients = float('Nan')
-		min_parameters              = float('Nan')
-		max_parameters              = float('Nan')
-		vx_obs                      = float('Nan')
-		vy_obs                      = float('Nan')
-		vz_obs                      = float('Nan')
-		vel_obs                     = float('Nan')
-		thickness_obs               = float('Nan')
-		surface_obs                 = float('Nan')
-
-	def setdefaultparameters(self):
-
-		self.control_parameters=['FrictionCoefficient']
-
-
-# 		Scaling factor for each control
-		self.control_scaling_factors=1
-
-# 		number of iterations
-		self.maxsteps=20
-		self.maxiter=40
-
-#		several responses can be used:
-		self.cost_functions=['FrictionCoefficient']
-
-# 		m1qn3 parameters
-		self.dxmin  = 0.1
-		self.gttol = 1e-4
-
-		return self
-	
-	def checkconsistency(self, md, solution, analyses): 
-
-# 			Early return
-		if not self.iscontrol:
-			return
-
-		if not IssmConfig('_HAVE_M1QN3_')[0]:
-			md = checkmessage(md,['M1QN3 has not been installed, ISSM needs to be reconfigured and recompiled with AD'])
-
-
-		num_controls=np.numel(md.inversion.control_parameters)
-		num_costfunc=np.size(md.inversion.cost_functions,2)
-
-
-		md = checkfield(md,'fieldname','inversion.iscontrol','values',[0, 1])
-		md = checkfield(md,'fieldname','inversion.control_parameters','cell',1,'values',\
-			['BalancethicknessThickeningRate' 'FrictionCoefficient' 'MaterialsRheologyBbar' 'DamageDbar',\
-			'Vx' 'Vy' 'Thickness' 'BalancethicknessOmega' 'BalancethicknessApparentMassbalance'])
-		md = checkfield(md,'fieldname','inversion.control_scaling_factors','size',[1, num_controls],'>',0,float('Nan'),1)
-		md = checkfield(md,'fieldname','inversion.maxsteps','numel',1,'>=',0)
-		md = checkfield(md,'fieldname','inversion.maxiter','numel',1,'>=',0)
-		md = checkfield(md,'fieldname','inversion.dxmin','numel',1,'>',0)
-		md = checkfield(md,'fieldname','inversion.gttol','numel',1,'>',0)
-		md = checkfield(md,'fieldname','inversion.cost_functions','size',[1, num_costfunc],'values', [i for i in range(101,106)]+[201]+[i for i in range(501,507)]+[i for i in range(601,605)]+[i for i in range(1001, 1011)])
-		md = checkfield(md,'fieldname','inversion.cost_functions_coefficients','size',[md.mesh.numberofvertices, num_costfunc],'>=',0)
-		md = checkfield(md,'fieldname','inversion.min_parameters','size',[md.mesh.numberofvertices, num_controls])
-		md = checkfield(md,'fieldname','inversion.max_parameters','size',[md.mesh.numberofvertices, num_controls])
-
-
-		if solution=='BalancethicknessSolution':
-			md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices],float('Nan'),1)
-			md = checkfield(md,'fieldname','inversion.surface_obs','size',[md.mesh.numberofvertices], float('Nan'),1)
-		elif solution=='BalancethicknessSoftSolution':
-			md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices],float('Nan'),1)
-		else:
-			md = checkfield(md,'fieldname','inversion.vx_obs','size',[md.mesh.numberofvertices],float('Nan'),1)
-			if not np.strcmp(domaintype(md.mesh),'2Dvertical'):
-				md = checkfield(md,'fieldname','inversion.vy_obs','size',[md.mesh.numberofvertices],float('Nan'),1)
-		return md
-
-	def __repr__(self):
-		string = '   adinversion parameters:'
-		string ="%s\n\%s"%(string, fielddisplay(self,'iscontrol','is inversion activated?'))
-		string ="%s\n\%s"%(string, fielddisplay(self,'control_parameters','ex: [''FrictionCoefficient''], or [''MaterialsRheologyBbar'']'))
-		string ="%s\n\%s"%(string, fielddisplay(self,'control_scaling_factors','order of magnitude of each control (useful for multi-parameter optimization)'))
-		string ="%s\n\%s"%(string, fielddisplay(self,'maxsteps','maximum number of iterations (gradient computation)'))
-		string ="%s\n\%s"%(string, fielddisplay(self,'maxiter','maximum number of Function evaluation (forward run)'))
-		string ="%s\n\%s"%(string, fielddisplay(self,'dxmin','convergence criterion: two points less than dxmin from eachother (sup-norm) are considered identical'))
-		string ="%s\n\%s"%(string, fielddisplay(self,'gttol','convergence criterion: ||g(X)||/||g(X0)|| (g(X0): gradient at initial guess X0)'))
-		string ="%s\n\%s"%(string, fielddisplay(self,'cost_functions','indicate the type of response for each optimization step'))
-		string ="%s\n\%s"%(string, fielddisplay(self,'cost_functions_coefficients','cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter'))
-		string ="%s\n\%s"%(string, fielddisplay(self,'min_parameters','absolute minimum acceptable value of the inversed parameter on each vertex'))
-		string ="%s\n\%s"%(string, fielddisplay(self,'max_parameters','absolute maximum acceptable value of the inversed parameter on each vertex'))
-		string ="%s\n\%s"%(string, fielddisplay(self,'vx_obs','observed velocity x component [m/yr]'))
-		string ="%s\n\%s"%(string, fielddisplay(self,'vy_obs','observed velocity y component [m/yr]'))
-		string ="%s\n\%s"%(string, fielddisplay(self,'vel_obs','observed velocity magnitude [m/yr]'))
-		string ="%s\n\%s"%(string, fielddisplay(self,'thickness_obs','observed thickness [m]'))
-		string ="%s\n\%s"%(string, fielddisplay(self,'surface_obs','observed surface elevation [m]'))
-		string ="%s\n%s"%(string,'Available cost functions:');
-		string ="%s\n%s"%(string,'   101: SurfaceAbsVelMisfit');
-		string ="%s\n%s"%(string,'   102: SurfaceRelVelMisfit');
-		string ="%s\n%s"%(string,'   103: SurfaceLogVelMisfit');
-		string ="%s\n%s"%(string,'   104: SurfaceLogVxVyMisfit');
-		string ="%s\n%s"%(string,'   105: SurfaceAverageVelMisfit');
-		string ="%s\n%s"%(string,'   201: ThicknessAbsMisfit');
-		string ="%s\n%s"%(string,'   501: DragCoefficientAbsGradient');
-		string ="%s\n%s"%(string,'   502: RheologyBbarAbsGradient');
-		string ="%s\n%s"%(string,'   503: ThicknessAbsGradient');
-		
-		return string
-
-	def marshall(self):
-
-		yts=md.constants.yts;
-
-		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','iscontrol','format','Boolean');
-		WriteData(fid,prefix,'name','md.inversion.type','data',4,'format','Integer');
-		if not self.iscontrol:
-			return
-		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','control_scaling_factors','format','DoubleMat','mattype',3);
-		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','maxsteps','format','Integer');
-		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','maxiter','format','Integer');
-		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','dxmin','format','Double');
-		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','gttol','format','Double');
-		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1);
-		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','min_parameters','format','DoubleMat','mattype',3);
-		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','max_parameters','format','DoubleMat','mattype',3);
-		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts);
-		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts);
-		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts);
-		if(numel(self.thickness_obs)==md.mesh.numberofelements):
-			mattype=2;
-		else:
-			mattype=1;
-		
-		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','thickness_obs','format','DoubleMat','mattype',mattype);
-		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','surface_obs','format','DoubleMat','mattype',mattype);
-
-		#process control parameters
-		num_control_parameters = np.numel(self.control_parameters);
-		WriteData(fid,prefix,'object',self,'fieldname','control_parameters','format','StringArray');
-		WriteData(fid,prefix,'data',num_control_parameters,'name','md.inversion.num_control_parameters','format','Integer');
-
-		#process cost functions
-		num_cost_functions=np.size(self.cost_functions,2);
-		data=copy.deepcopy(self.cost_functions)
-		data[np.nonzero(self.cost_functions==101)] =['SurfaceAbsVelMisfit'];
-		data[np.nonzero(self.cost_functions==102)]=['SurfaceRelVelMisfit'];
-		data[np.nonzero(self.cost_functions==103)]=['SurfaceLogVelMisfit'];
-		data[np.nonzero(self.cost_functions==104)]=['SurfaceLogVxVyMisfit'];
-		data[np.nonzero(self.cost_functions==105)]=['SurfaceAverageVelMisfit'];
-		data[np.nonzero(self.cost_functions==201)]=['ThicknessAbsMisfit'];
-		data[np.nonzero(self.cost_functions==501)]=['DragCoefficientAbsGradient'];
-		data[np.nonzero(self.cost_functions==502)]=['RheologyBbarAbsGradient'];
-		data[np.nonzero(self.cost_functions==503)]=['ThicknessAbsGradient'];
-		data[np.nonzero(self.cost_functions==504)]=['ThicknessAlongGradient'];
-		data[np.nonzero(self.cost_functions==505)]=['ThicknessAcrossGradient'];
-		data[np.nonzero(self.cost_functions==506)]=['BalancethicknessMisfit'];
-		data[np.nonzero(self.cost_functions==601)]=['SurfaceAbsMisfit'];
-		data[np.nonzero(self.cost_functions==1001)]=['Outputdefinition1'];
-		data[np.nonzero(self.cost_functions==1002)]=['Outputdefinition2'];
-		data[np.nonzero(self.cost_functions==1003)]=['Outputdefinition3'];
-		data[np.nonzero(self.cost_functions==1004)]=['Outputdefinition4'];
-		data[np.nonzero(self.cost_functions==1005)]=['Outputdefinition5'];
-		data[np.nonzero(self.cost_functions==1006)]=['Outputdefinition6'];
-		data[np.nonzero(self.cost_functions==1007)]=['Outputdefinition7'];
-		data[np.nonzero(self.cost_functions==1008)]=['Outputdefinition8'];
-		data[np.nonzero(self.cost_functions==1009)]=['Outputdefinition8'];
-		data[np.nonzero(self.cost_functions==1010)]=['Outputdefinition10'];
-		WriteData(fid,prefix,'data',data,'name','md.inversion.cost_functions','format','StringArray');
-		WriteData(fid,prefix,'data',num_cost_functions,'name','md.inversion.num_cost_functions','format','Integer');
-		
Index: /issm/trunk/src/m/classes/adm1qn3inversion.m
===================================================================
--- /issm/trunk/src/m/classes/adm1qn3inversion.m	(revision 22758)
+++ /issm/trunk/src/m/classes/adm1qn3inversion.m	(revision 22758)
@@ -0,0 +1,91 @@
+%ADM1QN3INVERSION class definition
+%
+%   Usage:
+%      adm1qn3inversion=adm1qn3inversion();
+
+classdef adm1qn3inversion
+	properties (SetAccess=public) 
+		iscontrol                   = 0
+		maxsteps                    = 0
+		maxiter                     = 0
+		dxmin                       = 0
+		gttol                       = 0
+
+	end
+	methods
+		function self = adm1qn3inversion(varargin) % {{{
+			switch nargin
+				case 0
+					self=setdefaultparameters(self);
+				case 1
+					self=structtoobj(adm1qn3inversion(),varargin{1});
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function self = extrude(self,md) % {{{
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
+
+
+			%parameter to be inferred by control methods (only
+			%drag and B are supported yet)
+			%self.control_parameters={'FrictionCoefficient'};
+
+			%number of iterations
+			self.maxsteps=20;
+			self.maxiter=40;
+
+			%m1qn3 parameters
+			self.dxmin  = 0.1;
+			self.gttol = 1e-4;
+
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
+
+			%Early return
+			if ~self.iscontrol, return; end
+
+			if ~IssmConfig('_HAVE_M1QN3_'),
+				md = checkmessage(md,['M1QN3 has not been installed, ISSM needs to be reconfigured and recompiled with M1QN3']);
+			end
+
+			md = checkfield(md,'fieldname','inversion.iscontrol','values',[0 1]);
+			md = checkfield(md,'fieldname','inversion.maxsteps','numel',1,'>=',0);
+			md = checkfield(md,'fieldname','inversion.maxiter','numel',1,'>=',0);
+			md = checkfield(md,'fieldname','inversion.dxmin','numel',1,'>',0);
+			md = checkfield(md,'fieldname','inversion.gttol','numel',1,'>',0);
+
+	end % }}}
+		function disp(self) % {{{
+			disp(sprintf('   adm1qn3inversion parameters:'));
+			fielddisplay(self,'iscontrol','is inversion activated?');
+			fielddisplay(self,'maxsteps','maximum number of iterations (gradient computation)');
+			fielddisplay(self,'maxiter','maximum number of Function evaluation (forward run)');
+			fielddisplay(self,'dxmin','convergence criterion: two points less than dxmin from eachother (sup-norm) are considered identical');
+			fielddisplay(self,'gttol','convergence criterion: ||g(X)||/||g(X0)|| (g(X0): gradient at initial guess X0)');
+		end % }}}
+		function marshall(self,prefix,md,fid) % {{{
+
+			yts=md.constants.yts;
+
+			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','iscontrol','format','Boolean');
+			WriteData(fid,prefix,'name','md.inversion.type','data',4,'format','Integer');
+			if ~self.iscontrol, return; end
+			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','maxsteps','format','Integer');
+			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','maxiter','format','Integer');
+			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','dxmin','format','Double');
+			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','gttol','format','Double');
+
+		end % }}}
+		function savemodeljs(self,fid,modelname) % {{{
+		
+			writejsdouble(fid,[modelname '.inversion.iscontrol'],self.iscontrol);
+			writejsdouble(fid,[modelname '.inversion.maxsteps'],self.maxsteps);
+			writejsdouble(fid,[modelname '.inversion.maxiter'],self.maxiter);
+			writejsdouble(fid,[modelname '.inversion.dxmin'],self.dxmin);
+			writejsdouble(fid,[modelname '.inversion.gttol'],self.gttol);
+
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/amr.js
===================================================================
--- /issm/trunk/src/m/classes/amr.js	(revision 22757)
+++ /issm/trunk/src/m/classes/amr.js	(revision 22758)
@@ -7,20 +7,42 @@
 	//methods
 	this.setdefaultparameters = function(){// {{{
-		//level_max: 2 to 4
-		this.level_max=2;
-
-		//region_level_1: region around (m) the discontinuity (grounding line or ice front) where the mesh will be refined once (h=1).
-		this.region_level_1=20000.;
-
-		//region_level_max: region around (m) the discontinuity (grounding line or ice front) where the mesh will be refined with max level of refinement (h=level_max).
-		this.region_level_max=15000.;
+		this.hmin								= 100.;
+		this.hmax								= 100.e3;
+		this.fieldname							= "Vel";
+		this.err								= 3.;
+		this.keepmetric							= 1;
+		this.gradation							= 1.5;
+		this.groundingline_resolution			= 500.;
+		this.groundingline_distance				= 0;
+		this.icefront_resolution				= 500;
+		this.icefront_distance					= 0;
+		this.thicknesserror_resolution			= 500;
+		this.thicknesserror_threshold			= 0;
+		this.thicknesserror_groupthreshold 		= 0;
+		this.thicknesserror_maximum				= 0;
+		this.deviatoricerror_resolution			= 500;	
+		this.deviatoricerror_threshold			= 0;	
+		this.deviatoricerror_groupthreshold		= 0;	
+		this.deviatoricerror_maximum			= 0;	
 	}// }}}
 	this.disp= function(){// {{{
-
 		console.log(sprintf('   amr parameters:'));
-		fielddisplay(this,'level_max','maximum refinement level (1, 2, 3 or 4)');
-		fielddisplay(this,'region_level_1','region which will be refined once (level 1) [ m ]');
-		fielddisplay(this,'region_level_max','region which will be refined with level_max [ m ]');
-
+		fielddisplay(this,'hmin','minimum element length');
+		fielddisplay(this,'hmax','maximum element length');
+		fielddisplay(this,'fieldname','name of input that will be used to compute the metric (should be an input of FemModel)');
+		fielddisplay(this,'keepmetric','indicates whether the metric should be kept every remeshing time');
+		fielddisplay(this,'gradation','maximum ratio between two adjacent edges');
+		fielddisplay(this,'groundingline_resolution','element length near the grounding line');
+		fielddisplay(this,'groundingline_distance','distance around the grounding line which elements will be refined');
+		fielddisplay(this,'icefront_resolution','element length near the ice front');
+		fielddisplay(this,'icefront_distance','distance around the ice front which elements will be refined');
+		fielddisplay(this,'thicknesserror_resolution','element length when thickness error estimator is used');
+		fielddisplay(this,'thicknesserror_threshold','maximum threshold thickness error permitted');
+		fielddisplay(this,'thicknesserror_groupthreshold','maximum group threshold thickness error permitted');
+		fielddisplay(this,'thicknesserror_maximum','maximum thickness error permitted');
+		fielddisplay(this,'deviatoricerror_resolution','element length when deviatoric stress error estimator is used');
+		fielddisplay(this,'deviatoricerror_threshold','maximum threshold deviatoricstress error permitted');
+		fielddisplay(this,'deviatoricerror_groupthreshold','maximum group threshold deviatoricstress error permitted');
+		fielddisplay(this,'deviatoricerror_maximum','maximum deviatoricstress error permitted');
 	}// }}}
 	this.classname= function(){// {{{
@@ -28,27 +50,65 @@
 
 	}// }}}
-		this.checkconsistency = function(md,solution,analyses) { //{{{
-			
-			checkfield(md,'fieldname','amr.level_max','numel',[1],'>=',0,'<=',4);
-			checkfield(md,'fieldname','amr.region_level_1','numel',[1],'>',0,'NaN',1,'Inf',1);
-			checkfield(md,'fieldname','amr.region_level_max','numel',[1],'>',0,'NaN',1,'Inf',1);
-			if (this.region_level_1-this.region_level_max<0.2*this.region_level_1){
-				md.checkmessage('region_level_max should be lower than 80% of region_level_1');
-			}
-		} // }}}
-		this.marshall=function(md,prefix,fid) { //{{{
-
-			WriteData(fid,prefix,'object',this,'fieldname','level_max','format','Integer');
-			WriteData(fid,prefix,'object',this,'fieldname','region_level_1','format','Double');
-			WriteData(fid,prefix,'object',this,'fieldname','region_level_max','format','Double');
-
-		}//}}}
-		this.fix=function() { //{{{
-		}//}}}
+	this.checkconsistency = function(md,solution,analyses) { //{{{
+		checkfield(md,'fieldname','amr.hmax','numel',[1],'>',0,'NaN',1);
+		checkfield(md,'fieldname','amr.hmin','numel',[1],'>',0,'<',this.hmax,'NaN',1);
+		checkfield(md,'fieldname','amr.keepmetric','numel',[1],'>=',0,'<=',1,'NaN',1);
+		checkfield(md,'fieldname','amr.gradation','numel',[1],'>=',1.1,'<=',5,'NaN',1);
+		checkfield(md,'fieldname','amr.groundingline_resolution','numel',[1],'>',0,'<',this.hmax,'NaN',1);
+		checkfield(md,'fieldname','amr.groundingline_distance','numel',[1],'>=',0,'NaN',1,'Inf',1);
+		checkfield(md,'fieldname','amr.icefront_resolution','numel',[1],'>',0,'<',this.hmax,'NaN',1);
+		checkfield(md,'fieldname','amr.icefront_distance','numel',[1],'>=',0,'NaN',1,'Inf',1);
+		checkfield(md,'fieldname','amr.thicknesserror_resolution','numel',[1],'>',0,'<',this.hmax,'NaN',1);
+		checkfield(md,'fieldname','amr.thicknesserror_threshold','numel',[1],'>=',0,'<=',1,'NaN',1);
+		checkfield(md,'fieldname','amr.thicknesserror_groupthreshold','numel',[1],'>=',0,'<=',1,'NaN',1);
+		checkfield(md,'fieldname','amr.thicknesserror_maximum','numel',[1],'>=',0,'NaN',1,'Inf',1);
+		checkfield(md,'fieldname','amr.deviatoricerror_resolution','numel',[1],'>',0,'<',this.hmax,'NaN',1);
+		checkfield(md,'fieldname','amr.deviatoricerror_threshold','numel',[1],'>=',0,'<=',1,'NaN',1);
+		checkfield(md,'fieldname','amr.deviatoricerror_groupthreshold','numel',[1],'>=',0,'<=',1,'NaN',1);
+		checkfield(md,'fieldname','amr.deviatoricerror_maximum','numel',[1],'>=',0,'NaN',1,'Inf',1);
+	} // }}}
+	this.marshall=function(md,prefix,fid) { //{{{
+		WriteData(fid,prefix,'name','md.amr.type','data',1,'format','Integer');
+		WriteData(fid,prefix,'object',this,'fieldname','hmin','format','Double');
+		WriteData(fid,prefix,'object',this,'fieldname','hmax','format','Double');
+		WriteData(fid,prefix,'object',this,'fieldname','fieldname','format','String');
+		WriteData(fid,prefix,'object',this,'fieldname','err','format','Double');
+		WriteData(fid,prefix,'object',this,'fieldname','keepmetric','format','Integer');
+		WriteData(fid,prefix,'object',this,'fieldname','gradation','format','Double');
+		WriteData(fid,prefix,'object',this,'fieldname','groundingline_resolution','format','Double');
+		WriteData(fid,prefix,'object',this,'fieldname','groundingline_distance','format','Double');
+		WriteData(fid,prefix,'object',this,'fieldname','icefront_resolution','format','Double');
+		WriteData(fid,prefix,'object',this,'fieldname','icefront_distance','format','Double');
+		WriteData(fid,prefix,'object',this,'fieldname','thicknesserror_resolution','format','Double');
+		WriteData(fid,prefix,'object',this,'fieldname','thicknesserror_threshold','format','Double');
+		WriteData(fid,prefix,'object',this,'fieldname','thicknesserror_groupthreshold','format','Double');
+		WriteData(fid,prefix,'object',this,'fieldname','thicknesserror_maximum','format','Double');
+		WriteData(fid,prefix,'object',this,'fieldname','deviatoricerror_resolution','format','Double');
+		WriteData(fid,prefix,'object',this,'fieldname','deviatoricerror_threshold','format','Double');
+		WriteData(fid,prefix,'object',this,'fieldname','deviatoricerror_groupthreshold','format','Double');
+		WriteData(fid,prefix,'object',this,'fieldname','deviatoricerror_maximum','format','Double');
+	}//}}}
+	this.fix=function() { //{{{
+	}//}}}
 	//properties 
 	// {{{
-	this.level_max				= 0;
-	this.region_level_1     = 0.;
-	this.region_level_max   = 0.;
+	this.hmin								= 0.;
+	this.hmax								= 0.;
+	this.fieldname							= "";
+	this.err								= 0.;
+	this.keepmetric							= 0;
+	this.gradation							= 0.;
+	this.groundingline_resolution			= 0.;
+	this.groundingline_distance				= 0.;
+	this.icefront_resolution				= 0.;
+	this.icefront_distance					= 0.;
+	this.thicknesserror_resolution			= 0.;
+	this.thicknesserror_threshold			= 0.;
+	this.thicknesserror_groupthreshold		= 0.;
+	this.thicknesserror_maximum				= 0.;
+	this.deviatoricerror_resolution			= 0.;
+	this.deviatoricerror_threshold			= 0.;
+	this.deviatoricerror_groupthreshold		= 0.;
+	this.deviatoricerror_maximum			= 0.;
 
 	this.setdefaultparameters();
Index: /issm/trunk/src/m/classes/amr.m
===================================================================
--- /issm/trunk/src/m/classes/amr.m	(revision 22757)
+++ /issm/trunk/src/m/classes/amr.m	(revision 22758)
@@ -2,11 +2,60 @@
 %
 %   Usage:
-%      amr=amr();
+%      md.amr=amr();
 
 classdef amr
 	properties (SetAccess=public) 
-		level_max			= 0; 
-		region_level_1		= 0;
-		region_level_max	= 0;
+		hmin = 0.; 
+		hmax = 0.;
+		fieldname = '';
+		err = 0.;
+		keepmetric = 0;
+		gradation = 0.;
+		groundingline_resolution = 0.;
+		groundingline_distance = 0.;
+		icefront_resolution = 0.;
+		icefront_distance = 0.;
+		thicknesserror_resolution = 0.;
+		thicknesserror_threshold = 0.;
+		thicknesserror_groupthreshold = 0.;
+		thicknesserror_maximum = 0.;
+		deviatoricerror_resolution = 0.;
+		deviatoricerror_threshold = 0.;
+		deviatoricerror_groupthreshold = 0.;
+		deviatoricerror_maximum = 0.;
+		restart=0.;
+	end
+	methods (Static)
+ 		function self = loadobj(self) % {{{
+         % This function is directly called by matlab when a model object is
+         % loaded. Update old properties here
+
+         if verLessThan('matlab','7.9'),
+            disp('Warning: your matlab version is old and there is a risk that load does not work correctly');
+            disp('         if the model is not loaded correctly, rename temporarily loadobj so that matlab does not use it');
+
+            % This is a Matlab bug: all the fields of md have their default value
+            % Example of error message:
+            % Warning: Error loading an object of class 'model':
+            % Undefined function or method 'exist' for input arguments of type 'cell'
+            %
+            % This has been fixed in MATLAB 7.9 (R2009b) and later versions
+         end
+
+         %2017 September 15th
+         if isstruct(self),
+            disp('WARNING: updating amr. Now the default is amr with bamg');
+            disp('         some old fields were not converted');
+            disp('         see the new fields typing md.amr and modify them properly');
+            obj2 = self;
+            self = amr();
+            %Converting region_level_max to groundingline_distance
+            if(obj2.region_level_max>0 && obj2.region_level_1>obj2.region_level_max)
+               self.groundingline_distance	= obj2.region_level_max;
+					self.keepmetric					= 0;
+					self.fieldname						= 'None';
+            end
+         end
+      end% }}}
 	end
 	methods
@@ -21,43 +70,101 @@
 		function self = setdefaultparameters(self) % {{{
 
-			%level_max: 2 to 4
-			self.level_max=2;
+			%hmin and hmax
+			self.hmin=100.;
+			self.hmax=100.e3;
 
-			%region_level_1: region around (m) the discontinuity (grounding line or ice front) where the mesh will be refined once (h=1).
-			self.region_level_1=20000.;
+			%fields
+			self.fieldname ='Vel';
+			self.err=3.;
+
+			%keep metric?
+			self.keepmetric=1;
+
+			%control of element lengths
+			self.gradation=1.5;
+
+			%other criterias
+			self.groundingline_resolution=500.;
+			self.groundingline_distance=0.;
+			self.icefront_resolution=500.;
+			self.icefront_distance=0.;
+			self.thicknesserror_resolution=500.;
+			self.thicknesserror_threshold=0.;
+			self.thicknesserror_groupthreshold=0.;
+			self.thicknesserror_maximum=0.;
+			self.deviatoricerror_resolution=500.;
+			self.deviatoricerror_threshold=0.;
+			self.deviatoricerror_groupthreshold=0.;
+			self.deviatoricerror_maximum=0.;
 			
-			%region_level_max: region around (m) the discontinuity (grounding line or ice front) where the mesh will be refined with max level of refinement (h=level_max). 
-			self.region_level_max=15000.;
+			%is restart? This calls femmodel->ReMesh() before first time step. 
+			self.restart=0;
 
 		end % }}}
 		function md = checkconsistency(self,md,solution,analyses) % {{{
 
-			md = checkfield(md,'fieldname','amr.level_max','numel',[1],'>=',0,'<=',4);
-			md = checkfield(md,'fieldname','amr.region_level_1','numel',[1],'>',0,'NaN',1,'Inf',1);
-			md = checkfield(md,'fieldname','amr.region_level_max','numel',[1],'>',0,'NaN',1,'Inf',1);
-			if self.region_level_1-self.region_level_max<0.2*self.region_level_1, %it was adopted 20% of the region_level_1
-				md = checkmessage(md,'region_level_max should be lower than 80% of region_level_1');
-			end 
+			md = checkfield(md,'fieldname','amr.hmax','numel',[1],'>',0,'NaN',1);
+			md = checkfield(md,'fieldname','amr.hmin','numel',[1],'>',0,'<',self.hmax,'NaN',1);
+			%md = checkfield(md,'fieldname','amr.fieldname','string',[1]);
+			md = checkfield(md,'fieldname','amr.keepmetric','numel',[1],'>=',0,'<=',1,'NaN',1);
+			md = checkfield(md,'fieldname','amr.gradation','numel',[1],'>=',1.1,'<=',5,'NaN',1);
+			md = checkfield(md,'fieldname','amr.groundingline_resolution','numel',[1],'>',0,'<',self.hmax,'NaN',1);
+			md = checkfield(md,'fieldname','amr.groundingline_distance','numel',[1],'>=',0,'NaN',1,'Inf',1);
+			md = checkfield(md,'fieldname','amr.icefront_resolution','numel',[1],'>',0,'<',self.hmax,'NaN',1);
+			md = checkfield(md,'fieldname','amr.icefront_distance','numel',[1],'>=',0,'NaN',1,'Inf',1);
+			md = checkfield(md,'fieldname','amr.thicknesserror_resolution','numel',[1],'>',0,'<',self.hmax,'NaN',1);
+			md = checkfield(md,'fieldname','amr.thicknesserror_threshold','numel',[1],'>=',0,'<=',1,'NaN',1);
+			md = checkfield(md,'fieldname','amr.thicknesserror_groupthreshold','numel',[1],'>=',0,'<=',1,'NaN',1);
+			md = checkfield(md,'fieldname','amr.thicknesserror_maximum','numel',[1],'>=',0,'NaN',1,'Inf',1);
+			md = checkfield(md,'fieldname','amr.deviatoricerror_resolution','numel',[1],'>',0,'<',self.hmax,'NaN',1);
+			md = checkfield(md,'fieldname','amr.deviatoricerror_threshold','numel',[1],'>=',0,'<=',1,'NaN',1);
+			md = checkfield(md,'fieldname','amr.deviatoricerror_groupthreshold','numel',[1],'>=',0,'<=',1,'NaN',1);
+			md = checkfield(md,'fieldname','amr.deviatoricerror_maximum','numel',[1],'>=',0,'NaN',1,'Inf',1);
+			md = checkfield(md,'fieldname','amr.restart','numel',[1],'>=',0,'<=',1,'NaN',1);
 		end % }}}
 		function disp(self) % {{{
 			disp(sprintf('   amr parameters:'));
 
-			fielddisplay(self,'level_max',['maximum refinement level (1, 2, 3 or 4)']);
-			fielddisplay(self,'region_level_1',['region which will be refined once (level 1) [ m ]']);
-			fielddisplay(self,'region_level_max',['region which will be refined with level_max [ m ]']);
-
+			fielddisplay(self,'hmin',['minimum element length']);
+			fielddisplay(self,'hmax',['maximum element length']);
+			fielddisplay(self,'fieldname',['name of input that will be used to compute the metric (should be an input of FemModel)']);
+			fielddisplay(self,'keepmetric',['indicates whether the metric should be kept every remeshing time']);
+			fielddisplay(self,'gradation',['maximum ratio between two adjacent edges']);
+			fielddisplay(self,'groundingline_resolution',['element length near the grounding line']);
+			fielddisplay(self,'groundingline_distance',['distance around the grounding line which elements will be refined']);
+			fielddisplay(self,'icefront_resolution',['element length near the ice front']);
+			fielddisplay(self,'icefront_distance',['distance around the ice front which elements will be refined']);
+			fielddisplay(self,'thicknesserror_resolution',['element length when thickness error estimator is used']);
+			fielddisplay(self,'thicknesserror_threshold',['maximum threshold thickness error permitted']);
+			fielddisplay(self,'thicknesserror_groupthreshold',['maximum group threshold thickness error permitted']);
+			fielddisplay(self,'thicknesserror_maximum',['maximum thickness error permitted']);
+			fielddisplay(self,'deviatoricerror_resolution',['element length when deviatoric stress error estimator is used']);
+			fielddisplay(self,'deviatoricerror_threshold',['maximum threshold deviatoricstress error permitted']);
+			fielddisplay(self,'deviatoricerror_groupthreshold',['maximum group threshold deviatoricstress error permitted']);
+			fielddisplay(self,'deviatoricerror_maximum',['maximum deviatoricstress error permitted']);
+			fielddisplay(self,'restart',['indicates if ReMesh() will call before first time step']);
 		end % }}}
 		function marshall(self,prefix,md,fid) % {{{
 
-			scale = md.constants.yts;
-			WriteData(fid,prefix,'object',self,'fieldname','level_max','format','Integer');
-			WriteData(fid,prefix,'object',self,'fieldname','region_level_1','format','Double');
-			WriteData(fid,prefix,'object',self,'fieldname','region_level_max','format','Double');
-		end % }}}
-		function savemodeljs(self,fid,modelname) % {{{
-		
-			writejsdouble(fid,[modelname '.amr.level_max'],self.level_max);
-			writejsdouble(fid,[modelname '.amr.region_level_1'],self.region_level_1);
-			writejsdouble(fid,[modelname '.amr.region_level_max'],self.region_level_max);
+			WriteData(fid,prefix,'name','md.amr.type','data',1,'format','Integer');
+			WriteData(fid,prefix,'object',self,'class','amr','fieldname','hmin','format','Double');
+			WriteData(fid,prefix,'object',self,'class','amr','fieldname','hmax','format','Double');
+			WriteData(fid,prefix,'object',self,'class','amr','fieldname','fieldname','format','String');
+			WriteData(fid,prefix,'object',self,'class','amr','fieldname','err','format','Double');
+			WriteData(fid,prefix,'object',self,'class','amr','fieldname','keepmetric','format','Integer');
+			WriteData(fid,prefix,'object',self,'class','amr','fieldname','gradation','format','Double');
+			WriteData(fid,prefix,'object',self,'class','amr','fieldname','groundingline_resolution','format','Double');
+			WriteData(fid,prefix,'object',self,'class','amr','fieldname','groundingline_distance','format','Double');
+			WriteData(fid,prefix,'object',self,'class','amr','fieldname','icefront_resolution','format','Double');
+			WriteData(fid,prefix,'object',self,'class','amr','fieldname','icefront_distance','format','Double');
+			WriteData(fid,prefix,'object',self,'class','amr','fieldname','thicknesserror_resolution','format','Double');
+			WriteData(fid,prefix,'object',self,'class','amr','fieldname','thicknesserror_threshold','format','Double');
+			WriteData(fid,prefix,'object',self,'class','amr','fieldname','thicknesserror_groupthreshold','format','Double');
+			WriteData(fid,prefix,'object',self,'class','amr','fieldname','thicknesserror_maximum','format','Double');
+			WriteData(fid,prefix,'object',self,'class','amr','fieldname','deviatoricerror_resolution','format','Double');
+			WriteData(fid,prefix,'object',self,'class','amr','fieldname','deviatoricerror_threshold','format','Double');
+			WriteData(fid,prefix,'object',self,'class','amr','fieldname','deviatoricerror_groupthreshold','format','Double');
+			WriteData(fid,prefix,'object',self,'class','amr','fieldname','deviatoricerror_maximum','format','Double');
+			WriteData(fid,prefix,'object',self,'class','amr','fieldname','restart','format','Integer');
 
 		end % }}}
Index: /issm/trunk/src/m/classes/amr.py
===================================================================
--- /issm/trunk/src/m/classes/amr.py	(revision 22757)
+++ /issm/trunk/src/m/classes/amr.py	(revision 22758)
@@ -12,8 +12,23 @@
 
     def __init__(self): # {{{
-        self.level_max        = 0.
-        self.region_level_1   = 0.
-        self.region_level_max = 0.
-
+        self.hmin										= 0.
+        self.hmax										= 0.
+        self.fieldname								=''
+        self.err 										= 0.
+        self.keepmetric								= 0.
+        self.gradation 								= 0.
+        self.groundingline_resolution 			= 0.
+        self.groundingline_distance 			= 0.
+        self.icefront_resolution 				= 0.
+        self.icefront_distance 					= 0.
+        self.thicknesserror_resolution 		= 0.
+        self.thicknesserror_threshold 			= 0.
+        self.thicknesserror_groupthreshold	= 0.
+        self.thicknesserror_maximum				= 0.
+        self.deviatoricerror_resolution		= 0.
+        self.deviatoricerror_threshold			= 0.
+        self.deviatoricerror_groupthreshold	= 0.
+        self.deviatoricerror_maximum			= 0.
+        self.restart                         = 0.
         #set defaults
         self.setdefaultparameters()
@@ -21,35 +36,86 @@
     def __repr__(self): # {{{
         string="   amr parameters:"
-        string="%s\n%s"%(string,fielddisplay(self,"level_max","maximum refinement level (1, 2, 3 or 4)"))
-        string="%s\n%s"%(string,fielddisplay(self,"region_level_1","region which will be refined once (level 1) [ m ]"))
-        string="%s\n%s"%(string,fielddisplay(self,"region_level_max","region which will be refined with level_max [ m ]"))
+        string="%s\n%s"%(string,fielddisplay(self,"hmin","minimum element length"))
+        string="%s\n%s"%(string,fielddisplay(self,"hmax","maximum element length"))
+        string="%s\n%s"%(string,fielddisplay(self,"fieldname","name of input that will be used to compute the metric (should be an input of FemModel)"))
+        string="%s\n%s"%(string,fielddisplay(self,"keepmetric","indicates whether the metric should be kept every remeshing time"))
+        string="%s\n%s"%(string,fielddisplay(self,"gradation","maximum ratio between two adjacent edges"))
+        string="%s\n%s"%(string,fielddisplay(self,"groundingline_resolution","element length near the grounding line"))
+        string="%s\n%s"%(string,fielddisplay(self,"groundingline_distance","distance around the grounding line which elements will be refined"))
+        string="%s\n%s"%(string,fielddisplay(self,"icefront_resolution","element length near the ice front"))
+        string="%s\n%s"%(string,fielddisplay(self,"icefront_distance","distance around the ice front which elements will be refined"))
+        string="%s\n%s"%(string,fielddisplay(self,"thicknesserror_resolution","element length when thickness error estimator is used"))
+        string="%s\n%s"%(string,fielddisplay(self,"thicknesserror_threshold","maximum threshold thickness error permitted"))
+        string="%s\n%s"%(string,fielddisplay(self,"thicknesserror_groupthreshold","maximum group threshold thickness error permitted"))
+        string="%s\n%s"%(string,fielddisplay(self,"thicknesserror_maximum","maximum thickness error permitted"))
+        string="%s\n%s"%(string,fielddisplay(self,"deviatoricerror_resolution","element length when deviatoric stress error estimator is used"))
+        string="%s\n%s"%(string,fielddisplay(self,"deviatoricerror_threshold","maximum threshold deviatoricstress error permitted"))
+        string="%s\n%s"%(string,fielddisplay(self,"deviatoricerror_groupthreshold","maximum group threshold deviatoric stress error permitted"))
+        string="%s\n%s"%(string,fielddisplay(self,"deviatoricerror_maximum","maximum deviatoricstress error permitted"))
+        string="%s\n%s"%(string,fielddisplay(self,"restart","indicates if ReMesh() will call before first time step"))
         return string
     #}}}
     def setdefaultparameters(self): # {{{
-
-        #level_max: 2 to 4
-        self.level_max=2
-
-        #region_level_1: region around (m) the discontinuity (grounding line or ice front) where the mesh will be refined once (h=1).
-        self.region_level_1=20000.
-
-        #region_level_max: region around (m) the discontinuity (grounding line or ice front) where the mesh will be refined with max level of refinement (h=level_max).
-        self.region_level_max=15000.
-
+        self.hmin										= 100.
+        self.hmax										= 100.e3
+        self.fieldname								= 'Vel'
+        self.err 										= 3.
+        self.keepmetric								= 1
+        self.gradation 								= 1.5
+        self.groundingline_resolution 			= 500.
+        self.groundingline_distance 			= 0
+        self.icefront_resolution 				= 500.
+        self.icefront_distance 					= 0
+        self.thicknesserror_resolution 		= 500.
+        self.thicknesserror_threshold 			= 0
+        self.thicknesserror_groupthreshold 	= 0
+        self.thicknesserror_maximum				= 0
+        self.deviatoricerror_resolution		= 500.
+        self.deviatoricerror_threshold			= 0
+        self.deviatoricerror_groupthreshold	= 0
+        self.deviatoricerror_maximum			= 0
+        self.restart									= 0.
         return self
-        #}}}
+    #}}}
     def checkconsistency(self,md,solution,analyses):    # {{{
-        md = checkfield(md,'fieldname','amr.level_max','numel',[1],'>=',0,'<=',4)
-        md = checkfield(md,'fieldname','amr.region_level_1','numel',[1],'>',0,'NaN',1,'Inf',1)
-        md = checkfield(md,'fieldname','amr.region_level_max','numel',[1],'>',0,'NaN',1,'Inf',1)
-                #it was adopted 20% of the region_level_1
-        if self.region_level_1-self.region_level_max<0.2*self.region_level_1:
-            md.checkmessage("region_level_max should be lower than 80% of region_level_1")
-
+        md = checkfield(md,'fieldname','amr.hmax','numel',[1],'>',0,'NaN',1)
+        md = checkfield(md,'fieldname','amr.hmin','numel',[1],'>',0,'<',self.hmax,'NaN',1)
+        md = checkfield(md,'fieldname','amr.keepmetric','numel',[1],'>=',0,'<=',1,'NaN',1);
+        md = checkfield(md,'fieldname','amr.gradation','numel',[1],'>=',1.1,'<=',5,'NaN',1);
+        md = checkfield(md,'fieldname','amr.groundingline_resolution','numel',[1],'>',0,'<',self.hmax,'NaN',1);
+        md = checkfield(md,'fieldname','amr.groundingline_distance','numel',[1],'>=',0,'NaN',1,'Inf',1);
+        md = checkfield(md,'fieldname','amr.icefront_resolution','numel',[1],'>',0,'<',self.hmax,'NaN',1);
+        md = checkfield(md,'fieldname','amr.icefront_distance','numel',[1],'>=',0,'NaN',1,'Inf',1);
+        md = checkfield(md,'fieldname','amr.thicknesserror_resolution','numel',[1],'>',0,'<',self.hmax,'NaN',1);
+        md = checkfield(md,'fieldname','amr.thicknesserror_threshold','numel',[1],'>=',0,'<=',1,'NaN',1);
+        md = checkfield(md,'fieldname','amr.thicknesserror_groupthreshold','numel',[1],'>=',0,'<=',1,'NaN',1);
+        md = checkfield(md,'fieldname','amr.thicknesserror_maximum','numel',[1],'>=',0,'NaN',1,'Inf',1);
+        md = checkfield(md,'fieldname','amr.deviatoricerror_resolution','numel',[1],'>',0,'<',self.hmax,'NaN',1);
+        md = checkfield(md,'fieldname','amr.deviatoricerror_threshold','numel',[1],'>=',0,'<=',1,'NaN',1);        
+        md = checkfield(md,'fieldname','amr.deviatoricerror_groupthreshold','numel',[1],'>=',0,'<=',1,'NaN',1);        
+        md = checkfield(md,'fieldname','amr.deviatoricerror_maximum','numel',[1],'>=',0,'NaN',1,'Inf',1);
+        md = checkfield(md,'fieldname','amr.restart','numel',[1],'>=',0,'<=',1,'NaN',1)
         return md
     # }}}
     def marshall(self,prefix,md,fid):    # {{{
-        WriteData(fid,prefix,'object',self,'fieldname','level_max','format','Integer')
-        WriteData(fid,prefix,'object',self,'fieldname','region_level_1','format','Double')
-        WriteData(fid,prefix,'object',self,'fieldname','region_level_max','format','Double')
+        WriteData(fid,prefix,'name','md.amr.type','data',1,'format','Integer')
+        WriteData(fid,prefix,'object',self,'fieldname','hmin','format','Double');
+        WriteData(fid,prefix,'object',self,'fieldname','hmax','format','Double');
+        WriteData(fid,prefix,'object',self,'fieldname','fieldname','format','String');
+        WriteData(fid,prefix,'object',self,'fieldname','err','format','Double');
+        WriteData(fid,prefix,'object',self,'fieldname','keepmetric','format','Integer');
+        WriteData(fid,prefix,'object',self,'fieldname','gradation','format','Double');
+        WriteData(fid,prefix,'object',self,'fieldname','groundingline_resolution','format','Double');
+        WriteData(fid,prefix,'object',self,'fieldname','groundingline_distance','format','Double');
+        WriteData(fid,prefix,'object',self,'fieldname','icefront_resolution','format','Double');
+        WriteData(fid,prefix,'object',self,'fieldname','icefront_distance','format','Double');
+        WriteData(fid,prefix,'object',self,'fieldname','thicknesserror_resolution','format','Double');
+        WriteData(fid,prefix,'object',self,'fieldname','thicknesserror_threshold','format','Double');
+        WriteData(fid,prefix,'object',self,'fieldname','thicknesserror_groupthreshold','format','Double');
+        WriteData(fid,prefix,'object',self,'fieldname','thicknesserror_maximum','format','Double');
+        WriteData(fid,prefix,'object',self,'fieldname','deviatoricerror_resolution','format','Double');
+        WriteData(fid,prefix,'object',self,'fieldname','deviatoricerror_threshold','format','Double'); 
+        WriteData(fid,prefix,'object',self,'fieldname','deviatoricerror_groupthreshold','format','Double'); 
+        WriteData(fid,prefix,'object',self,'fieldname','deviatoricerror_maximum','format','Double'); 
+        WriteData(fid,prefix,'object',self,'class','amr','fieldname','restart','format','Integer')
     # }}}
Index: /issm/trunk/src/m/classes/amrneopz.m
===================================================================
--- /issm/trunk/src/m/classes/amrneopz.m	(revision 22758)
+++ /issm/trunk/src/m/classes/amrneopz.m	(revision 22758)
@@ -0,0 +1,159 @@
+%AMRNEOPZ Class definition
+%
+%   Usage:
+%      md.amr=amrneopz();
+
+classdef amrneopz
+	properties (SetAccess=public) 
+		level_max								= 0; 
+		gradation								= 0;
+      lag										= 0;
+		groundingline_distance				= 0;
+      icefront_distance						= 0;
+      thicknesserror_threshold			= 0;
+      thicknesserror_groupthreshold 	= 0;
+      thicknesserror_maximum				= 0;
+		deviatoricerror_threshold			= 0;
+		deviatoricerror_groupthreshold	= 0;
+		deviatoricerror_maximum				= 0;
+		restart									= 0;
+	end
+   methods (Static)
+      %function self = loadobj(self) % {{{
+         % This function is directly called by matlab when a model object is
+         % loaded. Update old properties here
+
+			%if verLessThan('matlab','7.9'),
+         %   disp('Warning: your matlab version is old and there is a risk that load does not work correctly');
+         %   disp('         if the model is not loaded correctly, rename temporarily loadobj so that matlab does not use it');
+
+            % This is a Matlab bug: all the fields of md have their default value
+            % Example of error message:
+            % Warning: Error loading an object of class 'model':
+            % Undefined function or method 'exist' for input arguments of type 'cell'
+            %
+            % This has been fixed in MATLAB 7.9 (R2009b) and later versions
+			%end
+
+         %2017 September 15th
+         %if isstruct(self),
+         %   disp('WARNING: updating amr');
+         %   disp('         md.amr.region_level_max is now md.amr.radius_level_max');
+         %   disp('         md.amr.region_level_1 is not being used; now gradation is used instead');
+         %   obj2 						= self;
+         %   self 						= amr();
+         %   %Converting region_level_1 to gradation
+			%	if(obj2.region_level_max>0 && obj2.region_level_1>obj2.region_level_max) 
+			%		alpha=0;
+			%		if(obj2.level_max>1) alpha=log(obj2.region_level_1/obj2.region_level_max)/(obj2.level_max-1);end
+			%		self.radius_level_max			= obj2.region_level_max;
+			%		self.level_max						= obj2.level_max;
+			%		self.gradation						= exp(alpha);
+         %   	self.lag								= 1.0;
+			%		self.groundingline_distance 	= 0;
+			%		self.icefront_distance 			= 0;
+			%		self.thicknesserror_threshold = 0;
+			%		self.deviatoricerror_threshold= 0;
+			%	end
+         %end
+
+			%2017 November 24th
+			%radius_level_max was deleted!
+
+			%2017 December 18th
+			%group threshold was inserted
+
+      %end% }}}
+   end
+	methods
+		function self = amrneopz(varargin) % {{{
+			switch nargin
+				case 0
+					self=setdefaultparameters(self);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
+
+			%filter parameters:
+			self.level_max								= 2;
+			self.gradation								= 1.5;
+			self.lag										= 1.1;
+		
+ 			%other criterias
+         self.groundingline_distance			= 10000;
+         self.icefront_distance					= 0;
+         self.thicknesserror_threshold			= 0;
+         self.thicknesserror_groupthreshold	= 0;
+			self.thicknesserror_maximum			= 0; 
+			self.deviatoricerror_threshold		= 0;
+			self.deviatoricerror_groupthreshold = 0;
+			self.deviatoricerror_maximum			= 0;
+			self.restart								= 0;
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
+
+			md = checkfield(md,'fieldname','amr.level_max','numel',[1],'>=',0,'<=',5);
+   		md = checkfield(md,'fieldname','amr.gradation','numel',[1],'>=',1.1,'<=',5.0,'NaN',1);
+   		md = checkfield(md,'fieldname','amr.lag','numel',[1],'>=',1.0,'<=',3.0,'NaN',1);
+         md = checkfield(md,'fieldname','amr.groundingline_distance','numel',[1],'>=',0,'NaN',1,'Inf',1);
+         md = checkfield(md,'fieldname','amr.icefront_distance','numel',[1],'>=',0,'NaN',1,'Inf',1);
+         md = checkfield(md,'fieldname','amr.thicknesserror_threshold','numel',[1],'>=',0,'<=',1,'NaN',1);
+         md = checkfield(md,'fieldname','amr.thicknesserror_groupthreshold','numel',[1],'>=',0,'<=',1,'NaN',1);
+         md = checkfield(md,'fieldname','amr.thicknesserror_maximum','numel',[1],'>=',0,'NaN',1,'Inf',1);
+			md = checkfield(md,'fieldname','amr.deviatoricerror_threshold','numel',[1],'>=',0,'<=',1,'NaN',1);			
+			md = checkfield(md,'fieldname','amr.deviatoricerror_groupthreshold','numel',[1],'>=',0,'<=',1,'NaN',1);			
+         md = checkfield(md,'fieldname','amr.deviatoricerror_maximum','numel',[1],'>=',0,'NaN',1,'Inf',1);		
+		   md = checkfield(md,'fieldname','amr.restart','numel',[1],'>=',0,'<=',1,'NaN',1);
+		end % }}}
+		function disp(self) % {{{
+			disp(sprintf('   amrneopz parameters:'));
+
+			fielddisplay(self,'level_max',['maximum refinement level (1, 2, 3, 4 or 5)']);
+			fielddisplay(self,'gradation',['maximum ratio between two adjacent edges']);
+			fielddisplay(self,'lag',['lag used to unrefine the elements']);
+         fielddisplay(self,'groundingline_distance',['distance around the grounding line which elements will be refined']);
+         fielddisplay(self,'icefront_distance',['distance around the ice front which elements will be refined']);
+         fielddisplay(self,'thicknesserror_threshold',['maximum threshold thickness error permitted']);
+         fielddisplay(self,'thicknesserror_groupthreshold',['maximum group threshold thickness error permitted']);
+         fielddisplay(self,'thicknesserror_maximum',['maximum thickness error permitted']);
+			fielddisplay(self,'deviatoricerror_threshold',['maximum threshold deviatoricstress error permitted']);
+			fielddisplay(self,'deviatoricerror_groupthreshold',['maximum group threshold deviatoricstress error permitted']);
+			fielddisplay(self,'deviatoricerror_maximum',['maximum deviatoricstress error permitted']);
+         fielddisplay(self,'restart',['indicates if ReMesh() will call before first time step']);
+		end % }}}
+		function marshall(self,prefix,md,fid) % {{{
+
+			WriteData(fid,prefix,'name','md.amr.type','data',2,'format','Integer');
+			WriteData(fid,prefix,'object',self,'class','amr','fieldname','level_max','format','Integer');
+			WriteData(fid,prefix,'object',self,'class','amr','fieldname','gradation','format','Double');
+			WriteData(fid,prefix,'object',self,'class','amr','fieldname','lag','format','Double');
+         WriteData(fid,prefix,'object',self,'class','amr','fieldname','groundingline_distance','format','Double');
+         WriteData(fid,prefix,'object',self,'class','amr','fieldname','icefront_distance','format','Double');
+         WriteData(fid,prefix,'object',self,'class','amr','fieldname','thicknesserror_threshold','format','Double');
+         WriteData(fid,prefix,'object',self,'class','amr','fieldname','thicknesserror_groupthreshold','format','Double');
+         WriteData(fid,prefix,'object',self,'class','amr','fieldname','thicknesserror_maximum','format','Double');
+			WriteData(fid,prefix,'object',self,'class','amr','fieldname','deviatoricerror_threshold','format','Double');
+			WriteData(fid,prefix,'object',self,'class','amr','fieldname','deviatoricerror_groupthreshold','format','Double');
+			WriteData(fid,prefix,'object',self,'class','amr','fieldname','deviatoricerror_maximum','format','Double');
+		   WriteData(fid,prefix,'object',self,'class','amr','fieldname','restart','format','Integer');
+		end % }}}
+		function savemodeljs(self,fid,modelname) % {{{
+		
+			writejsdouble(fid,[modelname '.amr.level_max'],self.level_max);
+			writejsdouble(fid,[modelname '.amr.gradation'],self.gradation);
+			writejsdouble(fid,[modelname '.amr.lag'],self.lag);
+			writejsdouble(fid,[modelname '.amr.groundingline_distance'],self.groundingline_distance);
+			writejsdouble(fid,[modelname '.amr.icefront_distance'],self.icefront_distance);
+			writejsdouble(fid,[modelname '.amr.thicknesserror_threshold'],self.thicknesserror_threshold);
+			writejsdouble(fid,[modelname '.amr.thicknesserror_groupthreshold'],self.thicknesserror_threshold);
+			writejsdouble(fid,[modelname '.amr.thicknesserror_maximum'],self.thicknesserror_maximum);
+			writejsdouble(fid,[modelname '.amr.deviatoricerror_threshold'],self.deviatoricerror_threshold);
+			writejsdouble(fid,[modelname '.amr.deviatoricerror_groupthreshold'],self.deviatoricerror_threshold);
+			writejsdouble(fid,[modelname '.amr.deviatoricerror_maximum'],self.deviatoricerror_maximum);
+			writejsdouble(fid,[modelname '.amr.restart'],self.restart);
+
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/autodiff.m
===================================================================
--- /issm/trunk/src/m/classes/autodiff.m	(revision 22757)
+++ /issm/trunk/src/m/classes/autodiff.m	(revision 22758)
@@ -130,7 +130,17 @@
 					names{i}=indep.name;
 					types(i)=indep.typetoscalar();
+					min_parameters(:,:,i)=indep.min_parameters;
+					max_parameters(:,:,i)=indep.max_parameters;
+					scaling_factors(i)=indep.control_scaling_factor;
+					control_sizes(i) = indep.control_size;
+
 				end
 				WriteData(fid,prefix,'data',names,'name','md.autodiff.independent_object_names','format','StringArray');
 				WriteData(fid,prefix,'data',types,'name','md.autodiff.independent_object_types','format','IntMat','mattype',3);
+				WriteData(fid,prefix,'data',min_parameters,'name','md.autodiff.independent_min_parameters','format','DoubleMat','mattype',3);
+	         WriteData(fid,prefix,'data',max_parameters,'name','md.autodiff.independent_max_parameters','format','DoubleMat','mattype',3);
+	         WriteData(fid,prefix,'data',scaling_factors,'name','md.autodiff.independent_scaling_factors','format','IntMat','mattype',3);
+				WriteData(fid,prefix,'data',control_sizes,'name','md.autodiff.independent_control_sizes','format','IntMat','mattype',3);
+
 			end
 			%}}}
Index: /issm/trunk/src/m/classes/balancethickness.m
===================================================================
--- /issm/trunk/src/m/classes/balancethickness.m	(revision 22757)
+++ /issm/trunk/src/m/classes/balancethickness.m	(revision 22758)
@@ -11,4 +11,6 @@
 
 		omega             = NaN;
+		slopex            = NaN;
+		slopey            = NaN;
 	end
 	methods
@@ -53,4 +55,6 @@
 			WriteData(fid,prefix,'object',self,'fieldname','stabilization','format','Integer');
 
+			WriteData(fid,prefix,'object',self,'fieldname','slopex','format','DoubleMat','mattype',1);
+			WriteData(fid,prefix,'object',self,'fieldname','slopey','format','DoubleMat','mattype',1);
 			WriteData(fid,prefix,'object',self,'fieldname','omega','format','DoubleMat','mattype',1);
 		end % }}}
Index: /issm/trunk/src/m/classes/balancethickness.py
===================================================================
--- /issm/trunk/src/m/classes/balancethickness.py	(revision 22757)
+++ /issm/trunk/src/m/classes/balancethickness.py	(revision 22758)
@@ -15,4 +15,6 @@
 		self.thickening_rate   = float('NaN')
 		self.stabilization     = 0
+		
+		self.omega	       = float('NaN')
 
 		#set defaults
@@ -44,5 +46,5 @@
 		md = checkfield(md,'fieldname','balancethickness.thickening_rate','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1)
 		md = checkfield(md,'fieldname','balancethickness.stabilization','size',[1],'values',[0,1,2,3])
-
+		#md = checkfield(md,'fieldname','balancethickness.omega','size', [md.mesh.numberofvertices],'NaN',1,'Inf',1,'>=',0);
 		return md
 	# }}}
@@ -54,3 +56,4 @@
 		WriteData(fid,prefix,'object',self,'fieldname','thickening_rate','format','DoubleMat','mattype',1,'scale',1./yts)
 		WriteData(fid,prefix,'object',self,'fieldname','stabilization','format','Integer')
+		WriteData(fid,prefix,'object',self,'fieldname','omega','format','DoubleMat','mattype',1);
 	# }}}
Index: /issm/trunk/src/m/classes/basalforcings.py
===================================================================
--- /issm/trunk/src/m/classes/basalforcings.py	(revision 22757)
+++ /issm/trunk/src/m/classes/basalforcings.py	(revision 22758)
@@ -45,4 +45,7 @@
 			self.floatingice_melting_rate=np.zeros((md.mesh.numberofvertices))
 			print "      no basalforcings.floatingice_melting_rate specified: values set as zero"
+		#if np.all(np.isnan(self.geothermalflux)):
+			#self.geothermalflux=np.zeros((md.mesh.numberofvertices))
+			#print "      no basalforcings.geothermalflux specified: values set as zero"
 
 		return self
Index: /issm/trunk/src/m/classes/basalforcingspico.m
===================================================================
--- /issm/trunk/src/m/classes/basalforcingspico.m	(revision 22758)
+++ /issm/trunk/src/m/classes/basalforcingspico.m	(revision 22758)
@@ -0,0 +1,107 @@
+%PICO BASAL FORCINGS class definition
+%
+%   Usage:
+%      basalforcingspico=basalforcingspico();
+
+classdef basalforcingspico
+	properties (SetAccess=public) 
+		num_basins                = 0;
+		basin_id                  = NaN;
+		maxboxcount               = 0;
+		overturning_coeff         = 0.;
+		gamma_T                   = 0.;
+		farocean_temperature      = NaN;
+		farocean_salinity         = NaN;
+		geothermalflux            = NaN;
+		groundedice_melting_rate  = NaN;
+	end
+	methods
+		function self = extrude(self,md) % {{{
+			self.basin_id=project3d(md,'vector',self.basin_id,'type','element','layer',1);
+			self.geothermalflux=project3d(md,'vector',self.geothermalflux,'type','element','layer',1); %bedrock only gets geothermal flux
+			self.groundedice_melting_rate=project3d(md,'vector',self.groundedice_melting_rate,'type','node','layer',1);
+		end % }}}
+		function self = basalforcingspico(varargin) % {{{
+			switch nargin
+				case 0
+					self=setdefaultparameters(self);
+				case 1
+					self=setdefaultparameters(self);
+					self=structtoobj(self,varargin{1});
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function self = initialize(self,md) % {{{
+			if isnan(self.maxboxcount),
+	            self.maxboxcount = 5;
+		   			disp('      no maximum number of boxes set, setting value to 5');
+		   end
+
+			if isnan(self.overturning_coeff)
+				self.overturning_coeff = 1e6; %m^3/s
+				disp('      no overturning strength set, setting value to 1e6');
+			end
+
+			if isnan(self.gamma_T)
+				self.gamma_T = 2e-5; %m/s
+				disp('      no turbulent temperature exchange velocity set, setting value to 2e-5');
+			end
+			if isnan(self.groundedice_melting_rate),
+				self.groundedice_melting_rate=zeros(md.mesh.numberofvertices,1);
+				disp('      no basalforcings.groundedice_melting_rate specified: values set as zero');
+			end
+
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
+
+			self.maxboxcount = 5;
+			self.overturning_coeff = 1e6; %m^3/s
+			self.gamma_T = 2e-5; %m/s
+
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
+
+				md = checkfield(md,'fieldname','basalforcings.num_basins','numel',1,'NaN',1,'Inf',1,'>',0);
+				md = checkfield(md,'fieldname','basalforcings.basin_id','Inf',1,'>=',0,'<=',md.basalforcings.num_basins,'size',[md.mesh.numberofelements 1]);
+				md = checkfield(md,'fieldname','basalforcings.maxboxcount','numel',1,'NaN',1,'Inf',1,'>',0);
+				md = checkfield(md,'fieldname','basalforcings.overturning_coeff','numel',1,'NaN',1,'Inf',1,'>',0);
+				md = checkfield(md,'fieldname','basalforcings.gamma_T','numel',1,'NaN',1,'Inf',1,'>',0);
+				md = checkfield(md,'fieldname','basalforcings.farocean_temperature','NaN',1,'Inf',1,'>',0,'size',[md.basalforcings.num_basins+1 NaN]);
+				md = checkfield(md,'fieldname','basalforcings.farocean_salinity','NaN',1,'Inf',1,'>',0,'size',[md.basalforcings.num_basins+1 NaN]);
+				md = checkfield(md,'fieldname','basalforcings.geothermalflux','NaN',1,'Inf',1,'>=',0,'timeseries',1);
+				md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'Inf',1,'timeseries',1);
+
+		end % }}}
+		function disp(self) % {{{
+			disp(sprintf('   PICO basal melt rate parameterization:'));
+			fielddisplay(self,'num_basins','number of basins the model domain is partitioned into [unitless]');
+			fielddisplay(self,'basin_id','basin number assigned to each node [unitless]');
+			fielddisplay(self,'maxboxcount','maximum number of boxes initialized under all ice shelves');
+			fielddisplay(self,'overturning_coeff','Overturning strength [m^3/s]');
+			fielddisplay(self,'gamma_T','Turbulent temperature exchange velocity [m/s]');
+			fielddisplay(self,'farocean_temperature','depth averaged ocean temperature in front of the ice shelf for basin i [K]');
+			fielddisplay(self,'farocean_salinity','depth averaged ocean salinity in front of the ice shelf for basin i [psu]');
+			fielddisplay(self,'geothermalflux','geothermal heat flux [W/m^2]');
+			fielddisplay(self,'groundedice_melting_rate','basal melting rate (positive if melting) [m/yr]');
+
+		end % }}}
+		function marshall(self,prefix,md,fid) % {{{
+
+			yts=md.constants.yts;
+
+			WriteData(fid,prefix,'name','md.basalforcings.model','data',5,'format','Integer');
+			WriteData(fid,prefix,'object',self,'fieldname','num_basins','format','Integer');
+			WriteData(fid,prefix,'object',self,'fieldname','maxboxcount','format','Integer');
+			WriteData(fid,prefix,'object',self,'fieldname','overturning_coeff','format','Double');
+			WriteData(fid,prefix,'object',self,'fieldname','gamma_T','format','Double');
+			WriteData(fid,prefix,'object',self,'fieldname','farocean_temperature','format','DoubleMat','name','md.basalforcings.farocean_temperature','timeserieslength',md.basalforcings.num_basins+1,'yts',md.constants.yts);
+			WriteData(fid,prefix,'object',self,'fieldname','farocean_salinity','format','DoubleMat','name','md.basalforcings.farocean_salinity','timeserieslength',md.basalforcings.num_basins+1,'yts',md.constants.yts);
+			%WriteData(fid,prefix,'object',self,'fieldname','basin_id','format','DoubleMat','name','md.basalforcings.basin_id','mattype',2);
+			WriteData(fid,prefix,'object',self,'fieldname','basin_id','data',self.basin_id-1,'name','md.basalforcings.basin_id','format','IntMat','mattype',2);   %Change to 0-indexing
+			WriteData(fid,prefix,'object',self,'fieldname','geothermalflux','format','DoubleMat','name','md.basalforcings.geothermalflux','mattype',1,'timeserieslength',md.mesh.numberofelements+1,'yts',md.constants.yts);
+			WriteData(fid,prefix,'object',self,'fieldname','groundedice_melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
+
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/calvingcrevassedepth.m
===================================================================
--- /issm/trunk/src/m/classes/calvingcrevassedepth.m	(revision 22758)
+++ /issm/trunk/src/m/classes/calvingcrevassedepth.m	(revision 22758)
@@ -0,0 +1,63 @@
+%CALVINCREVASSEDEPTH class definition
+%
+%   Usage:
+%      calvingcrevassedepth=calvingcrevassedepth();
+
+classdef calvingcrevassedepth
+	properties (SetAccess=public) 
+		critical_fraction = 0.;
+		water_height = 0.;
+		meltingrate   = NaN;
+	end
+	methods
+		function self = calvingcrevassedepth(varargin) % {{{
+			switch nargin
+				case 0
+					self=setdefaultparameters(self);
+				case 1
+					inputstruct=varargin{1};
+					list1 = properties('calvingcrevassedepth');
+					list2 = fieldnames(inputstruct);
+					for i=1:length(list1)
+						fieldname = list1{i};
+						if ismember(fieldname,list2),
+							self.(fieldname) = inputstruct.(fieldname);
+						end
+					end
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function self = extrude(self,md) % {{{
+			self.meltingrate=project3d(md,'vector',self.meltingrate,'type','node');
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
+
+			% crticial fraction of thickness that surface and basal crevasses penetrate for calving onset
+			self.critical_fraction = 1.;
+			self.water_height = 0.;
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
+			%Early return
+			if (~strcmp(solution,'TransientSolution') | md.transient.ismovingfront==0), return; end
+
+			md = checkfield(md,'fieldname','calving.critical_fraction','>',0,'NaN',1,'Inf',1);
+			md = checkfield(md,'fieldname','calving.water_height','NaN',1,'Inf',1,'timeseries',1,'>=',0);
+			md = checkfield(md,'fieldname','calving.meltingrate','NaN',1,'Inf',1,'timeseries',1,'>=',0);
+		end % }}}
+		function disp(self) % {{{
+			disp(sprintf('   Calving Pi parameters:'));
+			fielddisplay(self,'critical_fraction','critical fraction of thickness that surface and basal crevasses penetrate for calving onset');
+			fielddisplay(self,'water_height','water height in the crevasse [m]');
+			fielddisplay(self,'meltingrate','melting rate at given location [m/a]');
+
+		end % }}}
+		function marshall(self,prefix,md,fid) % {{{
+			yts=md.constants.yts;
+			WriteData(fid,prefix,'name','md.calving.law','data',6,'format','Integer');
+			WriteData(fid,prefix,'object',self,'fieldname','critical_fraction','format','Double');
+			WriteData(fid,prefix,'object',self,'fieldname','water_height','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
+			WriteData(fid,prefix,'object',self,'fieldname','meltingrate','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts,'scale',1./yts);
+		end % }}}
+	end
+end
Index: sm/trunk/src/m/classes/calvingdev.m
===================================================================
--- /issm/trunk/src/m/classes/calvingdev.m	(revision 22757)
+++ 	(revision )
@@ -1,63 +1,0 @@
-%CALVINGDEV class definition
-%
-%   Usage:
-%      calvingdev=calvingdev();
-
-classdef calvingdev
-	properties (SetAccess=public) 
-		stress_threshold_groundedice = 0.;
-		stress_threshold_floatingice = 0.;
-		meltingrate   = NaN;
-	end
-	methods
-		function self = calvingdev(varargin) % {{{
-			switch nargin
-				case 0
-					self=setdefaultparameters(self);
-				case 1
-					inputstruct=varargin{1};
-					list1 = properties('calvingdev');
-					list2 = fieldnames(inputstruct);
-					for i=1:length(list1)
-						fieldname = list1{i};
-						if ismember(fieldname,list2),
-							self.(fieldname) = inputstruct.(fieldname);
-						end
-					end
-				otherwise
-					error('constructor not supported');
-			end
-		end % }}}
-		function self = extrude(self,md) % {{{
-			self.meltingrate=project3d(md,'vector',self.meltingrate,'type','node');
-		end % }}}
-		function self = setdefaultparameters(self) % {{{
-
-			%Default sigma max
-			self.stress_threshold_groundedice = 1e6;
-			self.stress_threshold_floatingice = 150e3;
-		end % }}}
-		function md = checkconsistency(self,md,solution,analyses) % {{{
-			%Early return
-			if (~strcmp(solution,'TransientSolution') | md.transient.ismovingfront==0), return; end
-
-			md = checkfield(md,'fieldname','calving.stress_threshold_groundedice','>',0,'numel',1,'nan',1,'Inf',1);
-			md = checkfield(md,'fieldname','calving.stress_threshold_floatingice','>',0,'numel',1,'nan',1,'Inf',1);
-			md = checkfield(md,'fieldname','calving.meltingrate','NaN',1,'Inf',1,'timeseries',1,'>=',0);
-		end % }}}
-		function disp(self) % {{{
-			disp(sprintf('   Calving Pi parameters:'));
-			fielddisplay(self,'stress_threshold_groundedice','sigma_max applied to grounded ice only [Pa]');
-			fielddisplay(self,'stress_threshold_floatingice','sigma_max applied to floating ice only [Pa]');
-			fielddisplay(self,'meltingrate','melting rate at given location [m/a]');
-
-		end % }}}
-		function marshall(self,prefix,md,fid) % {{{
-			yts=md.constants.yts;
-			WriteData(fid,prefix,'name','md.calving.law','data',2,'format','Integer');
-			WriteData(fid,prefix,'object',self,'fieldname','stress_threshold_groundedice','format','Double');
-			WriteData(fid,prefix,'object',self,'fieldname','stress_threshold_floatingice','format','Double');
-			WriteData(fid,prefix,'object',self,'fieldname','meltingrate','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts,'scale',1./yts);
-		end % }}}
-	end
-end
Index: /issm/trunk/src/m/classes/calvingdev.py
===================================================================
--- /issm/trunk/src/m/classes/calvingdev.py	(revision 22758)
+++ /issm/trunk/src/m/classes/calvingdev.py	(revision 22758)
@@ -0,0 +1,60 @@
+from fielddisplay import fielddisplay
+from project3d import project3d
+from checkfield import checkfield
+from WriteData import WriteData
+
+class calvingdev(object):
+	"""
+	CALVINGDEV class definition
+
+	   Usage:
+	      calvingdev=calvingdev();
+	"""
+
+	def __init__(self): # {{{
+
+		self.stress_threshold_groundedice = 0.
+		self.stress_threshold_floatingice = 0.
+		self.meltingrate   = float('NaN')
+
+		#set defaults
+		self.setdefaultparameters()
+
+	#}}}
+	def __repr__(self): # {{{
+		string='   Calving Pi parameters:'
+		string="%s\n%s"%(string,fielddisplay(self,'stress_threshold_groundedice','sigma_max applied to grounded ice only [Pa]'))
+		string="%s\n%s"%(string,fielddisplay(self,'stress_threshold_floatingice','sigma_max applied to floating ice only [Pa]'))
+
+		string="%s\n%s"%(string,fielddisplay(self,'meltingrate','melting rate at given location [m/a]'))
+		return string
+	#}}}
+	def extrude(self,md): # {{{
+		self.meltingrate=project3d(md,'vector',self.meltingrate,'type','node')
+		return self
+	#}}}
+	def setdefaultparameters(self): # {{{
+		#Default sigma max
+		self.stress_threshold_groundedice = 1e6
+		self.stress_threshold_floatingice = 150e3
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		#Early return
+		if solution == 'TransientSolution' or md.transient.ismovingfront == 0:
+			return
+
+		md = checkfield(md,'fieldname','calving.stress_threshold_groundedice','>',0,'nan',1,'Inf',1)
+		md = checkfield(md,'fieldname','calving.stress_threshold_floatingice','>',0,'nan',1,'Inf',1)
+		md = checkfield(md,'fieldname','calving.meltingrate','NaN',1,'Inf',1,'timeseries',1,'>=',0)
+
+		return md
+	# }}}
+	def marshall(self,prefix,md,fid):    # {{{
+		yts=md.constants.yts
+
+		WriteData(fid,prefix,'name','md.calving.law','data',2,'format','Integer')
+		WriteData(fid,prefix,'object',self,'fieldname','stress_threshold_groundedice','format','DoubleMat','mattype',1)
+		WriteData(fid,prefix,'object',self,'fieldname','stress_threshold_floatingice','format','DoubleMat','mattype',1)
+		WriteData(fid,prefix,'object',self,'fieldname','meltingrate','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts,'scale',1./yts)
+	# }}}
Index: /issm/trunk/src/m/classes/calvingdev2.m
===================================================================
--- /issm/trunk/src/m/classes/calvingdev2.m	(revision 22758)
+++ /issm/trunk/src/m/classes/calvingdev2.m	(revision 22758)
@@ -0,0 +1,68 @@
+%CALVINGDEV2 class definition
+%
+%   Usage:
+%      calvingdev2=calvingdev2();
+
+classdef calvingdev2
+	properties (SetAccess=public) 
+		stress_threshold_groundedice = 0.;
+		stress_threshold_floatingice = 0.;
+		height_above_floatation = 0.;
+		meltingrate   = NaN;
+	end
+	methods
+		function self = calvingdev2(varargin) % {{{
+			switch nargin
+				case 0
+					self=setdefaultparameters(self);
+				case 1
+					inputstruct=varargin{1};
+					list1 = properties('calvingdev2');
+					list2 = fieldnames(inputstruct);
+					for i=1:length(list1)
+						fieldname = list1{i};
+						if ismember(fieldname,list2),
+							self.(fieldname) = inputstruct.(fieldname);
+						end
+					end
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function self = extrude(self,md) % {{{
+			self.meltingrate=project3d(md,'vector',self.meltingrate,'type','node');
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
+
+			%Default sigma max
+			self.stress_threshold_groundedice = 1.e6;
+			self.stress_threshold_floatingice = 150.e3;
+			self.height_above_floatation= 0.;
+			self.meltingrate= 0.;
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
+			%Early return
+			if (~strcmp(solution,'TransientSolution') | md.transient.ismovingfront==0), return; end
+
+			md = checkfield(md,'fieldname','calving.stress_threshold_groundedice','>',0,'nan',1,'Inf',1);
+			md = checkfield(md,'fieldname','calving.stress_threshold_floatingice','>',0,'nan',1,'Inf',1);
+			md = checkfield(md,'fieldname','calving.height_above_floatation','<=',0);
+			md = checkfield(md,'fieldname','calving.meltingrate','NaN',1,'Inf',1,'timeseries',1,'>=',0);
+		end % }}}
+		function disp(self) % {{{
+			disp(sprintf('   Calving Dev2 parameters:'));
+			fielddisplay(self,'stress_threshold_groundedice','sigma_max applied to grounded ice only [Pa]');
+			fielddisplay(self,'stress_threshold_floatingice','sigma_max applied to floating ice only [Pa]');
+			fielddisplay(self,'height_above_floatation','height above floatation that the ice tongue must reach before it can calve [m]');
+			fielddisplay(self,'meltingrate','frontal undercutting melting rate at given location [m/a]');
+		end % }}}
+		function marshall(self,prefix,md,fid) % {{{
+			yts=md.constants.yts;
+			WriteData(fid,prefix,'name','md.calving.law','data',7,'format','Integer');
+			WriteData(fid,prefix,'object',self,'fieldname','stress_threshold_groundedice','format','DoubleMat','mattype',1);
+			WriteData(fid,prefix,'object',self,'fieldname','stress_threshold_floatingice','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1, 'yts', md.constants.yts);
+			WriteData(fid,prefix,'object',self,'fieldname','height_above_floatation', 'format','Double');
+			WriteData(fid,prefix,'object',self,'fieldname','meltingrate','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts,'scale',1./yts);
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/calvinghab.m
===================================================================
--- /issm/trunk/src/m/classes/calvinghab.m	(revision 22758)
+++ /issm/trunk/src/m/classes/calvinghab.m	(revision 22758)
@@ -0,0 +1,58 @@
+%CALVINGHAB class definition
+%
+%   Usage:
+%      calvinghab=calvinghab();
+
+classdef calvinghab
+	properties (SetAccess=public) 
+		flotation_fraction = 0.;
+		meltingrate   = NaN;
+	end
+	methods
+		function self = calvinghab(varargin) % {{{
+			switch nargin
+				case 0
+					self=setdefaultparameters(self);
+				case 1
+					inputstruct=varargin{1};
+					list1 = properties('calvinghab');
+					list2 = fieldnames(inputstruct);
+					for i=1:length(list1)
+						fieldname = list1{i};
+						if ismember(fieldname,list2),
+							self.(fieldname) = inputstruct.(fieldname);
+						end
+					end
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function self = extrude(self,md) % {{{
+			self.meltingrate=project3d(md,'vector',self.meltingrate,'type','node');
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
+
+			%fraction q = .15 of the flotation thickness at the terminus by default
+			self.flotation_fraction = 0.15;
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
+			%Early return
+			if (~strcmp(solution,'TransientSolution') | md.transient.ismovingfront==0), return; end
+
+			md = checkfield(md,'fieldname','calving.flotation_fraction','>=',0,'NaN',1,'Inf',1);
+			md = checkfield(md,'fieldname','calving.meltingrate','NaN',1,'Inf',1,'timeseries',1,'>=',0);
+		end % }}}
+		function disp(self) % {{{
+			disp(sprintf('   Calving Pi parameters:'));
+			fielddisplay(self,'flotation_fraction','fraction of flotation thickness at the terminus');
+			fielddisplay(self,'meltingrate','melting rate at given location [m/a]');
+
+		end % }}}
+		function marshall(self,prefix,md,fid) % {{{
+			yts=md.constants.yts;
+			WriteData(fid,prefix,'name','md.calving.law','data',5,'format','Integer');
+			WriteData(fid,prefix,'object',self,'fieldname','flotation_fraction','format','DoubleMat','mattype',1);
+			WriteData(fid,prefix,'object',self,'fieldname','meltingrate','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts,'scale',1./yts);
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/calvinglevermann.m
===================================================================
--- /issm/trunk/src/m/classes/calvinglevermann.m	(revision 22757)
+++ /issm/trunk/src/m/classes/calvinglevermann.m	(revision 22758)
@@ -54,5 +54,5 @@
 			WriteData(fid,prefix,'name','md.calving.law','data',3,'format','Integer');
 			WriteData(fid,prefix,'object',self,'fieldname','coeff','format','DoubleMat','mattype',1);
-			WriteData(fid,prefix,'object',self,'fieldname','meltingrate','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'scale',1./yts);
+			WriteData(fid,prefix,'object',self,'fieldname','meltingrate','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts,'scale',1./yts);
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/calvingminthickness.m
===================================================================
--- /issm/trunk/src/m/classes/calvingminthickness.m	(revision 22757)
+++ /issm/trunk/src/m/classes/calvingminthickness.m	(revision 22758)
@@ -44,6 +44,6 @@
 		end % }}}
 		function disp(self) % {{{
-			disp(sprintf('   Calving Pi parameters:'));
-			fielddisplay(self,'coeff','proportionality coefficient in Pi model');
+			disp(sprintf('   Calving Minimum thickness:'));
+			fielddisplay(self,'min_thickness','minimum thickness below which no ice is allowed');
 			fielddisplay(self,'meltingrate','melting rate at given location [m/a]');
 
Index: /issm/trunk/src/m/classes/calvingminthickness.py
===================================================================
--- /issm/trunk/src/m/classes/calvingminthickness.py	(revision 22758)
+++ /issm/trunk/src/m/classes/calvingminthickness.py	(revision 22758)
@@ -0,0 +1,52 @@
+from fielddisplay import fielddisplay
+from checkfield import checkfield
+from WriteData import WriteData
+
+class calvingminthickness(object):
+	"""
+	CALVINGMINTHICKNESS class definition
+
+	   Usage:
+	      calvingminthickness=calvingminthickness()
+	"""
+
+	def __init__(self): # {{{
+
+		self.min_thickness = 0.
+		self.meltingrate   = float('NaN')
+
+		#set defaults
+		self.setdefaultparameters()
+
+	#}}}
+	def __repr__(self): # {{{
+		string='   Calving Minimum thickness:'
+		string="%s\n%s"%(string,fielddisplay(self,'min_thickness','minimum thickness below which no ice is allowed'))
+		string="%s\n%s"%(string,fielddisplay(self,'meltingrate','melting rate at given location [m/a]'))
+		return string
+	#}}}
+	def extrude(self,md): # {{{
+		self.meltingrate=project3d(md,'vector',self.meltingrate,'type','node')
+		return self
+	#}}}
+	def setdefaultparameters(self): # {{{
+
+		#minimum thickness is 100 m by default
+		self.min_thickness = 100.
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if solution == 'TransientSolution' or md.transient.ismovingfront == 0:
+			return
+
+		md = checkfield(md,'fieldname','calving.min_thickness','>',0,'NaN',1,'Inf',1)
+		md = checkfield(md,'fieldname','calving.meltingrate','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices],'>=',0)
+		return md
+	# }}}
+	def marshall(self,prefix,md,fid):    # {{{
+		yts=md.constants.yts
+		WriteData(fid,prefix,'name','md.calving.law','data',4,'format','Integer')
+		WriteData(fid,prefix,'object',self,'fieldname','min_thickness','format','Double')
+		WriteData(fid,prefix,'object',self,'fieldname','meltingrate','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'scale',1./yts)
+	# }}}
Index: /issm/trunk/src/m/classes/calvingvonmises.m
===================================================================
--- /issm/trunk/src/m/classes/calvingvonmises.m	(revision 22758)
+++ /issm/trunk/src/m/classes/calvingvonmises.m	(revision 22758)
@@ -0,0 +1,63 @@
+%CALVINGVONMISES class definition
+%
+%   Usage:
+%      calvingvonmises=calvingvonmises();
+
+classdef calvingvonmises
+	properties (SetAccess=public) 
+		stress_threshold_groundedice = 0.;
+		stress_threshold_floatingice = 0.;
+		meltingrate   = NaN;
+	end
+	methods
+		function self = calvingvonmises(varargin) % {{{
+			switch nargin
+				case 0
+					self=setdefaultparameters(self);
+				case 1
+					inputstruct=varargin{1};
+					list1 = properties('calvingvonmises');
+					list2 = fieldnames(inputstruct);
+					for i=1:length(list1)
+						fieldname = list1{i};
+						if ismember(fieldname,list2),
+							self.(fieldname) = inputstruct.(fieldname);
+						end
+					end
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function self = extrude(self,md) % {{{
+			self.meltingrate=project3d(md,'vector',self.meltingrate,'type','node');
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
+
+			%Default sigma max
+			self.stress_threshold_groundedice = 1e6;
+			self.stress_threshold_floatingice = 150e3;
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
+			%Early return
+			if (~strcmp(solution,'TransientSolution') | md.transient.ismovingfront==0), return; end
+
+			md = checkfield(md,'fieldname','calving.stress_threshold_groundedice','>',0,'nan',1,'Inf',1);
+			md = checkfield(md,'fieldname','calving.stress_threshold_floatingice','>',0,'nan',1,'Inf',1);
+			md = checkfield(md,'fieldname','calving.meltingrate','NaN',1,'Inf',1,'timeseries',1,'>=',0);
+		end % }}}
+		function disp(self) % {{{
+			disp(sprintf('   Calving VonMises parameters:'));
+			fielddisplay(self,'stress_threshold_groundedice','sigma_max applied to grounded ice only [Pa]');
+			fielddisplay(self,'stress_threshold_floatingice','sigma_max applied to floating ice only [Pa]');
+			fielddisplay(self,'meltingrate','melting rate at given location [m/a]');
+
+		end % }}}
+		function marshall(self,prefix,md,fid) % {{{
+			yts=md.constants.yts;
+			WriteData(fid,prefix,'name','md.calving.law','data',2,'format','Integer');
+			WriteData(fid,prefix,'object',self,'fieldname','stress_threshold_groundedice','format','DoubleMat','mattype',1);
+			WriteData(fid,prefix,'object',self,'fieldname','stress_threshold_floatingice','format','DoubleMat','mattype',1);
+			WriteData(fid,prefix,'object',self,'fieldname','meltingrate','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts,'scale',1./yts);
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/calvingvonmises.py
===================================================================
--- /issm/trunk/src/m/classes/calvingvonmises.py	(revision 22758)
+++ /issm/trunk/src/m/classes/calvingvonmises.py	(revision 22758)
@@ -0,0 +1,60 @@
+from fielddisplay import fielddisplay
+from project3d import project3d
+from checkfield import checkfield
+from WriteData import WriteData
+
+class calvingvonmises(object):
+	"""
+	CALVINGVONMISES class definition
+
+	   Usage:
+	      calvingvonmises=calvingvonmises()
+	"""
+
+	def __init__(self): # {{{
+
+		self.stress_threshold_groundedice = 0.
+		self.stress_threshold_floatingice = 0.
+		self.meltingrate   = float('NaN')
+
+		#set defaults
+		self.setdefaultparameters()
+
+	#}}}
+	def __repr__(self): # {{{
+		string='   Calving VonMises parameters:'
+		string="%s\n%s"%(string,fielddisplay(self,'stress_threshold_groundedice','sigma_max applied to grounded ice only [Pa]'))
+		string="%s\n%s"%(string,fielddisplay(self,'stress_threshold_floatingice','sigma_max applied to floating ice only [Pa]'))
+
+		string="%s\n%s"%(string,fielddisplay(self,'meltingrate','melting rate at given location [m/a]'))
+		return string
+	#}}}
+	def extrude(self,md): # {{{
+		self.meltingrate=project3d(md,'vector',self.meltingrate,'type','node')
+		return self
+	#}}}
+	def setdefaultparameters(self): # {{{
+		#Default sigma max
+		self.stress_threshold_groundedice = 1e6
+		self.stress_threshold_floatingice = 150e3
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		#Early return
+		if solution == 'TransientSolution' or md.transient.ismovingfront == 0:
+			return
+
+		md = checkfield(md,'fieldname','calving.stress_threshold_groundedice','>',0,'nan',1,'Inf',1)
+		md = checkfield(md,'fieldname','calving.stress_threshold_floatingice','>',0,'nan',1,'Inf',1)
+		md = checkfield(md,'fieldname','calving.meltingrate','NaN',1,'Inf',1,'timeseries',1,'>=',0)
+
+		return md
+	# }}}
+	def marshall(self,prefix,md,fid):    # {{{
+		yts=md.constants.yts
+
+		WriteData(fid,prefix,'name','md.calving.law','data',2,'format','Integer')
+		WriteData(fid,prefix,'object',self,'fieldname','stress_threshold_groundedice','format','DoubleMat','mattype',1)
+		WriteData(fid,prefix,'object',self,'fieldname','stress_threshold_floatingice','format','DoubleMat','mattype',1)
+		WriteData(fid,prefix,'object',self,'fieldname','meltingrate','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts,'scale',1./yts)
+	# }}}
Index: /issm/trunk/src/m/classes/cfsurfacelogvel.m
===================================================================
--- /issm/trunk/src/m/classes/cfsurfacelogvel.m	(revision 22758)
+++ /issm/trunk/src/m/classes/cfsurfacelogvel.m	(revision 22758)
@@ -0,0 +1,104 @@
+%MISFIT class definition
+%
+%   Usage:
+%      cfsurfacelogvel=cfsurfacelogvel();
+%      cfsurfacelogvel=cfsurfacelogvel('name','SurfaceAltimetry',...
+%                    'definitionstring','Outputdefinition1',... 
+%                    'observation_string','SurfaceObservations',...
+%                    'observation',md.geometry.surface,...
+%                    'weights',ones(md.mesh.numberofvertices,1),...
+%                    'weights_string','WeightsSurfaceObservations',...
+%							'datatime',time);
+%
+%
+
+classdef cfsurfacelogvel
+	properties (SetAccess=public)
+		%cfsurfacelogvel
+		name               = '';
+		definitionstring   = ''; %string that identifies this output definition uniquely, from 'Outputdefinition[1-100]'
+		vxobs					 = NaN; %observed field that we compare the model against
+		vxobs_string		 = ''; %string for observed field.
+		vyobs			       = NaN; %observed field that we compare the model against
+		vyobs_string		 = ''; %string for observed field.
+		weights            = NaN; %weight coefficients for every vertex
+		weights_string     = ''; %string to identify this particular set of weights
+		datatime				 = 0; %time in years from start that the data is from 
+		cumulated          = NaN; %do we cumulate cfsurfacelogvel through time?
+	end
+	
+	methods
+		function self = extrude(self,md) % {{{
+			if ~isnan(self.weights)
+				self.weights=project3d(md,'vector',self.weights,'type','node');
+			end
+			if ~isnan(self.vxobs)
+				self.vxobs=project3d(md,'vector',self.vxobs,'type','node');
+			end
+		end % }}}
+		function self = cfsurfacelogvel(varargin) % {{{
+			if nargin==0,
+				self=setdefaultparameters(self);
+			else
+				%use provided options to change fields
+				options=pairoptions(varargin{:});
+
+				%get name
+				self.name=getfieldvalue(options,'name','');
+				self.definitionstring=getfieldvalue(options,'definitionstring');
+				self.vxobs=getfieldvalue(options,'vxobs',NaN);
+				self.vyobs=getfieldvalue(options,'vyobs',NaN);
+				self.vxobs_string=getfieldvalue(options,'vxobs_string');			
+				self.vyobs_string=getfieldvalue(options,'vyobs_string');
+				self.weights=getfieldvalue(options,'weights',NaN);
+				self.weights_string=getfieldvalue(options,'weights_string','');
+				self.datatime = getfieldvalue(options, 'datatime');
+
+			end
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
+			self.datatime = 0;
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
+
+			if ~ischar(self.name),
+				error('cfsurfacelogvel error message: ''name'' field should be a string!');
+			end
+			OutputdefinitionStringArray={};
+			for i=1:100
+				OutputdefinitionStringArray{i}=strcat('Outputdefinition',num2str(i));
+			end
+			md = checkfield(md,'fieldname','self.definitionstring','field',self.definitionstring,'values',OutputdefinitionStringArray);
+
+			md = checkfield(md,'fieldname','self.vxobs','field',self.vxobs,'timeseries',1,'NaN',1,'Inf',1);
+			md = checkfield(md,'fieldname','self.weights','field',self.weights,'timeseries',1,'NaN',1,'Inf',1);
+			md = checkfield(md,'fieldname','self.datatime','field',self.datatime,'<=',md.timestepping.final_time);
+
+		end % }}}
+		function md = disp(self) % {{{
+		
+			disp(sprintf('   TimeMisfit:\n'));
+
+			fielddisplay(self,'name','identifier for this cfsurfacelogvel response');
+			fielddisplay(self,'definitionstring','string that identifies this output definition uniquely, from ''Outputdefinition[1-10]''');
+			fielddisplay(self,'vxobs','observed field that we compare the model against');
+			fielddisplay(self,'vxobs_string','observation string');
+			fielddisplay(self,'weights','weights (at vertices) to apply to the cfsurfacelogvel');
+			fielddisplay(self,'weights_string','string for weights for identification purposes');
+			fielddisplay(self,'datatime','time to compare data to model for misfit');
+
+		end % }}}
+		function md = marshall(self,prefix,md,fid) % {{{
+
+		WriteData(fid,prefix,'data',self.name,'name','md.cfsurfacelogvel.name','format','String');
+		WriteData(fid,prefix,'data',self.definitionstring,'name','md.cfsurfacelogvel.definitionstring','format','String');
+		WriteData(fid,prefix,'data',self.vxobs,'name','md.cfsurfacelogvel.vxobs','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
+		WriteData(fid,prefix,'data',self.vxobs_string,'name','md.cfsurfacelogvel.vxobs_string','format','String');
+		WriteData(fid,prefix,'data',self.vyobs,'name','md.cfsurfacelogvel.vyobs','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
+		WriteData(fid,prefix,'data',self.vyobs_string,'name','md.cfsurfacelogvel.vyobs_string','format','String');
+		WriteData(fid,prefix,'data',self.weights,'name','md.cfsurfacelogvel.weights','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
+		WriteData(fid,prefix,'data',self.weights_string,'name','md.cfsurfacelogvel.weights_string','format','String');
+		WriteData(fid,prefix,'data',round(self.datatime*md.constants.yts),'name','md.cfsurfacelogvel.datatime','format','Integer');
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/cfsurfacesquare.m
===================================================================
--- /issm/trunk/src/m/classes/cfsurfacesquare.m	(revision 22758)
+++ /issm/trunk/src/m/classes/cfsurfacesquare.m	(revision 22758)
@@ -0,0 +1,103 @@
+%MISFIT class definition
+%
+%   Usage:
+%      cfsurfacesquare=cfsurfacesquare();
+%      cfsurfacesquare=cfsurfacesquare('name','SurfaceAltimetry',...
+%                    'definitionstring','Outputdefinition1',... 
+%							'model_string','Surface',...
+%                    'observation_string','SurfaceObservations',...
+%                    'observation',md.geometry.surface,...
+%                    'weights',ones(md.mesh.numberofvertices,1),...
+%                    'weights_string','WeightsSurfaceObservations',...
+%							'datatime',time);
+%
+%
+
+classdef cfsurfacesquare
+	properties (SetAccess=public)
+		%cfsurfacesquare
+		name               = '';
+		definitionstring   = ''; %string that identifies this output definition uniquely, from 'Outputdefinition[1-100]'
+		model_string       = ''; %string for field that is modeled
+		observation        = NaN; %observed field that we compare the model against
+		observation_string = ''; %string for observed field.
+		weights            = NaN; %weight coefficients for every vertex
+		weights_string     = ''; %string to identify this particular set of weights
+		datatime				 = 0; %time in years from start that the data is from 
+		cumulated          = NaN; %do we cumulate cfsurfacesquare through time?
+	end
+	
+	methods
+		function self = extrude(self,md) % {{{
+			if ~isnan(self.weights)
+				self.weights=project3d(md,'vector',self.weights,'type','node');
+			end
+			if ~isnan(self.observation)
+				self.observation=project3d(md,'vector',self.observation,'type','node');
+			end
+		end % }}}
+		function self = cfsurfacesquare(varargin) % {{{
+			if nargin==0,
+				self=setdefaultparameters(self);
+			else
+				%use provided options to change fields
+				options=pairoptions(varargin{:});
+
+				%get name
+				self.name=getfieldvalue(options,'name','');
+				self.definitionstring=getfieldvalue(options,'definitionstring');
+				self.model_string=getfieldvalue(options,'model_string');
+				self.observation=getfieldvalue(options,'observation',NaN);
+				self.observation_string=getfieldvalue(options,'observation_string');
+				self.weights=getfieldvalue(options,'weights',NaN);
+				self.weights_string=getfieldvalue(options,'weights_string','');
+				self.datatime = getfieldvalue(options, 'datatime');
+
+			end
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
+			self.datatime = 0;
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
+
+			if ~ischar(self.name),
+				error('cfsurfacesquare error message: ''name'' field should be a string!');
+			end
+			OutputdefinitionStringArray={};
+			for i=1:100
+				OutputdefinitionStringArray{i}=strcat('Outputdefinition',num2str(i));
+			end
+			md = checkfield(md,'fieldname','self.definitionstring','field',self.definitionstring,'values',OutputdefinitionStringArray);
+
+			md = checkfield(md,'fieldname','self.observation','field',self.observation,'timeseries',1,'NaN',1,'Inf',1);
+			md = checkfield(md,'fieldname','self.weights','field',self.weights,'timeseries',1,'NaN',1,'Inf',1);
+			md = checkfield(md,'fieldname','self.datatime','field',self.datatime,'<=',md.timestepping.final_time);
+
+		end % }}}
+		function md = disp(self) % {{{
+		
+			disp(sprintf('   TimeMisfit:\n'));
+
+			fielddisplay(self,'name','identifier for this cfsurfacesquare response');
+			fielddisplay(self,'definitionstring','string that identifies this output definition uniquely, from ''Outputdefinition[1-10]''');
+			fielddisplay(self,'model_string','string for field that is modeled');
+			fielddisplay(self,'observation','observed field that we compare the model against');
+			fielddisplay(self,'observation_string','observation string');
+			fielddisplay(self,'weights','weights (at vertices) to apply to the cfsurfacesquare');
+			fielddisplay(self,'weights_string','string for weights for identification purposes');
+			fielddisplay(self,'datatime','time to compare data to model for misfit');
+
+		end % }}}
+		function md = marshall(self,prefix,md,fid) % {{{
+
+		WriteData(fid,prefix,'data',self.name,'name','md.cfsurfacesquare.name','format','String');
+		WriteData(fid,prefix,'data',self.definitionstring,'name','md.cfsurfacesquare.definitionstring','format','String');
+		WriteData(fid,prefix,'data',self.model_string,'name','md.cfsurfacesquare.model_string','format','String');
+		WriteData(fid,prefix,'data',self.observation,'name','md.cfsurfacesquare.observation','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
+		WriteData(fid,prefix,'data',self.observation_string,'name','md.cfsurfacesquare.observation_string','format','String');
+		WriteData(fid,prefix,'data',self.weights,'name','md.cfsurfacesquare.weights','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
+		WriteData(fid,prefix,'data',self.weights_string,'name','md.cfsurfacesquare.weights_string','format','String');
+		WriteData(fid,prefix,'data',round(self.datatime*md.constants.yts),'name','md.cfsurfacesquare.datatime','format','Integer');
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/clusters/aci.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/aci.m	(revision 22758)
+++ /issm/trunk/src/m/classes/clusters/aci.m	(revision 22758)
@@ -0,0 +1,117 @@
+%ACI class definition
+%
+%   Usage:
+%      cluster=aci();
+%      cluster=aci('np',3);
+%      cluster=aci('np',3,'login','username');
+
+classdef aci
+	properties (SetAccess=public)  
+		% {{{
+		name='';
+		login='';
+		nodes=0;
+		ppn=0;
+		time=0;
+		port=0;
+		queue='';
+		codepath='';
+		executionpath='';
+		modules={};
+	end
+	%}}}
+	methods
+		function cluster=aci(varargin) % {{{
+
+			%initialize cluster using default settings if provided
+			if (exist('aci_settings')==2), aci_settings; end
+
+			%use provided options to change fields
+			cluster=AssignObjectFields(pairoptions(varargin{:}),cluster);
+		end
+		%}}}
+		function disp(cluster) % {{{
+			%  display the object
+			disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
+			disp(sprintf('    name: %s',cluster.name));
+			disp(sprintf('    login: %s',cluster.login));
+			disp(sprintf('    port: %i',cluster.port));
+			disp(sprintf('    time: %i (in minutes)',cluster.time));
+			disp(sprintf('    nodes: %i (number of nodes)',cluster.nodes));
+			disp(sprintf('    ppn: %i (process per nodes)',cluster.ppn));
+			disp(sprintf('    queue: %s',cluster.queue));
+			disp(sprintf('    codepath: %s',cluster.codepath));
+			disp(sprintf('    executionpath: %s',cluster.executionpath));
+		end
+		%}}}
+		function md = checkconsistency(cluster,md,solution,analyses) % {{{
+
+			available_queues={'brp106_a_g_sc_default','open'};
+			queue_requirements_time=[Inf 48*60];
+			queue_requirements_np=[260 260];
+
+			QueueRequirements(available_queues,queue_requirements_time,queue_requirements_np,cluster.queue,cluster.ppn*cluster.nodes,1)
+
+			%Miscelaneous
+			if cluster.ppn>20, md = checkmessage(md,'cannot request more that 20 cores per node'); end
+			if isempty(cluster.login), md = checkmessage(md,'login empty'); end
+			if isempty(cluster.codepath), md = checkmessage(md,'codepath empty'); end
+			if isempty(cluster.executionpath), md = checkmessage(md,'executionpath empty'); end
+		end
+		%}}}
+		function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof,isdakota,isoceancoupling) % {{{
+
+			if(isvalgrind), disp('valgrind not supported by cluster, ignoring...'); end
+			if(isgprof),    disp('gprof not supported by cluster, ignoring...'); end
+
+			%write queuing script 
+			fid=fopen([modelname '.queue'],'w');
+			fprintf(fid,'#PBS -A %s\n', cluster.queue); %open or brp106....
+			fprintf(fid,'#PBS -l nodes=%i:ppn=%i:stmem\n',cluster.nodes,cluster.ppn);
+			fprintf(fid,'#PBS -l walltime=%i\n',cluster.time*60); % walltime is in seconds
+			fprintf(fid,'#PBS -o %s.outlog\n',(modelname));
+			fprintf(fid,'#PBS -e %s.errlog\n',(modelname));
+			fprintf(fid,'source ~/.bashrc\n');
+			fprintf(fid,'source $ISSM_DIR/etc/environment.sh\n');
+			for i=1:numel(cluster.modules)
+				fprintf(fid,'module load %s\n', cluster.modules{i});
+			end
+			fprintf(fid,'mpirun -np %i %s/issm.exe %s %s %s\n',cluster.nodes*cluster.ppn,cluster.codepath,solution,[cluster.executionpath '/' dirname],modelname);
+			if ~io_gather, %concatenate the output files:
+				fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
+			end
+			fclose(fid);
+		end %}}}
+		function UploadQueueJob(cluster,modelname,dirname,filelist)% {{{
+
+			%compress the files into one zip.
+			compressstring=['tar -zcf ' dirname '.tar.gz '];
+			for i=1:numel(filelist),
+				compressstring = [compressstring ' ' filelist{i}];
+			end
+			system(compressstring);
+
+			disp('uploading input file and queueing script');
+			issmscpout(cluster.name,cluster.executionpath,cluster.login,cluster.port,{[dirname '.tar.gz']});
+
+		end %}}}
+		function LaunchQueueJob(cluster,modelname,dirname,filelist,restart,batch)% {{{
+
+			disp('launching solution sequence on remote cluster');
+			if ~isempty(restart)
+				launchcommand=['cd ' cluster.executionpath ' && cd ' dirname ' && hostname && qsub ' modelname '.queue '];
+			else
+				launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
+					' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && hostname && qsub ' modelname '.queue '];
+			end
+			issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
+		end %}}}
+		function Download(cluster,dirname,filelist)% {{{
+
+			%copy files from cluster to current directory
+			directory=[cluster.executionpath '/' dirname '/'];
+			issmscpin(cluster.name,cluster.login,cluster.port,directory,filelist);
+
+		end %}}}
+	end
+end
Index: /issm/trunk/src/m/classes/clusters/camhpc.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/camhpc.m	(revision 22757)
+++ /issm/trunk/src/m/classes/clusters/camhpc.m	(revision 22758)
@@ -58,5 +58,5 @@
 		 function md = checkconsistency(cluster,md,solution,analyses) % {{{
 
-			 available_queues={'ARNOLD-SL3'};
+			 available_queues={'ARNOLD-SL3-CPU'}; % Updated for csd3 NSA 28/3/18
 			 queue_requirements_time=[Inf Inf];
 			 queue_requirements_np=[80 80];
@@ -77,4 +77,5 @@
 
 			 %write queuing script 
+             disp(modelname)
 			 fid=fopen([modelname '.queue'],'w');
 			 fprintf(fid,'#!/bin/bash\n');
@@ -84,5 +85,5 @@
 			 fprintf(fid,'#SBATCH --mail-type=ALL\n');
 			 fprintf(fid,'#SBATCH -N %i -n %i\n',cluster.numnodes,cluster.cpuspernode);
-			 fprintf(fid,'#SBATCH --time=%i\n',cluster.time*60); %walltime is in seconds.
+			 fprintf(fid,'#SBATCH --time=%i\n',cluster.time*60) %walltime is in seconds.
 			 fprintf(fid,'#SBATCH --mem-per-cpu=%igb\n',cluster.memory);
 			 fprintf(fid,'#SBATCH -o %s.outlog \n',modelname);
@@ -130,9 +131,11 @@
 
 			 disp('launching solution sequence on remote cluster');
+             %
+             % qsub replaced by sbatch for csd3 system NSA 28/3/18
 			 if ~isempty(restart)
 				 launchcommand=['cd ' cluster.executionpath ' && cd ' dirname ' && hostname && qsub ' modelname '.queue '];
 			 else
 				 launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
-					 ' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && hostname && qsub ' modelname '.queue '];
+					 ' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && hostname && sbatch ' modelname '.queue '];
 			 end
 			 issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
Index: /issm/trunk/src/m/classes/clusters/discover.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/discover.m	(revision 22757)
+++ /issm/trunk/src/m/classes/clusters/discover.m	(revision 22758)
@@ -64,7 +64,7 @@
 		 function md = checkconsistency(cluster,md,solution,analyses) % {{{
 
-			 available_queues={'long','general','debug'};
-			 queue_requirements_time=[24*60*60 12*60*60 60];
-			 queue_requirements_np=[4116 532 532];
+			 available_queues={'long','allnccs','debug'};
+			 queue_requirements_time=[24*60*60 12*60*60 1*60*60];
+			 queue_requirements_np=[560 6000 532];
 
 			 QueueRequirements(available_queues,queue_requirements_time,queue_requirements_np,cluster.queue,cluster.np,cluster.time)
@@ -90,5 +90,5 @@
 		 end
 		 %}}}
-		 function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof,isdakota,ioceancoupling) % {{{
+		 function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof,isdakota,isoceancoupling) % {{{
 
 			 if(isgprof),    disp('gprof not supported by cluster, ignoring...'); end
@@ -116,5 +116,5 @@
 			 fprintf(fid,'#SBATCH -N %i \n',cluster.numnodes);
 			 fprintf(fid,'#SBATCH -t %02i:%02i:00 \n',floor(cluster.time/3600),floor(mod(cluster.time,3600)/60));
-			 fprintf(fid,'#SBATCH -A s1010 \n\n');
+			 fprintf(fid,'#SBATCH -A s1690 \n\n');
 			 for i=1:numel(cluster.modules),
 				 fprintf(fid,['module load ' cluster.modules{i} '\n']);
@@ -125,6 +125,9 @@
 			 end
 			 fprintf(fid,'. /usr/share/modules/init/bash\n\n');
-			 fprintf(fid,'module load comp/intel-15.0.0.090\n');
-			 fprintf(fid,'module load mpi/impi-4.0.3.008\n');
+			 fprintf(fid,'module load comp/intel-16.0.2.181\n');
+			 fprintf(fid,'module load mpi/impi-5.1.3.181\n');
+			 fprintf(fid,'module load other/cmake-3.8.2\n');
+			 fprintf(fid,'export MPI_GROUP_MAX=64\n\n');
+			 fprintf(fid,'export MPI_UNBUFFERED_STDIO=true\n\n');
 			 fprintf(fid,'export PATH="$PATH:."\n\n');
 			 fprintf(fid,'export ISSM_DIR="%s/../"\n',cluster.codepath); %FIXME
Index: /issm/trunk/src/m/classes/clusters/fram.py
===================================================================
--- /issm/trunk/src/m/classes/clusters/fram.py	(revision 22758)
+++ /issm/trunk/src/m/classes/clusters/fram.py	(revision 22758)
@@ -0,0 +1,166 @@
+import subprocess
+import numpy as np
+from fielddisplay import fielddisplay
+from pairoptions import pairoptions
+from issmssh import issmssh
+from issmscpin import issmscpin
+from issmscpout import issmscpout
+from QueueRequirements import QueueRequirements
+import datetime
+try:
+	from fram_settings import fram_settings
+except ImportError:
+	print 'You need fram_settings.py to proceed, check presence and sys.path'
+	
+class fram(object):
+	"""
+	Fram cluster class definition
+	This is a SLURM queue
+	The priorities are based on a point system, reservation when reaching 20000 and earning 1 point per min.
+	  -Devel queue starts at 19990
+	  -Normal starts at 19940
+	  -Normal unpri atarts at 19400
+
+	Jobs can be:
+	  -normal (4 to 30 nodes, more if asked, 48h max walltime, 60Gb per nodes)
+	  -bigmem for big memory nodes (8 512Gb nodes and 2 6Tb nodes, shared nodes, 14days max walltime
+
+	   Usage:
+	      cluster=stallo();
+	"""
+
+	def __init__(self,*args):
+	# {{{
+		self.name           = 'fram'
+		self.login          = ''
+		self.numnodes       = 2
+		self.cpuspernode    = 20
+		self.mem            = 1.6
+		self.queue          = 'normal'
+		self.time           = 2*60
+		self.codepath       = ''
+		self.executionpath  = ''
+		self.interactive    = 0
+		self.port           = []
+		self.accountname    = ''
+		self.profiling      = 0
+		#use provided options to change fields
+		options=pairoptions(*args)
+
+		#initialize cluster using user settings if provided
+		self=stallo_settings(self)
+		#OK get other fields
+		self=options.AssignObjectFields(self)
+		self.np=self.numnodes*self.cpuspernode		
+	# }}}
+	
+	def __repr__(self):
+	# {{{
+		#  display the object
+		s = "class vilje object:"
+		s = "%s\n%s"%(s,fielddisplay(self,'name','name of the cluster'))
+		s = "%s\n%s"%(s,fielddisplay(self,'login','login'))
+		s = "%s\n%s"%(s,fielddisplay(self,'numnodes','number of nodes'))
+		s = "%s\n%s"%(s,fielddisplay(self,'cpuspernode','number of nodes per CPUs'))
+		s = "%s\n%s"%(s,fielddisplay(self,'mem','memory per CPU'))
+		s = "%s\n%s"%(s,fielddisplay(self,'queue','name of the queue (normal (D), short,singlenode,multinode,devel)'))
+		s = "%s\n%s"%(s,fielddisplay(self,'time','walltime requested in minutes'))
+		s = "%s\n%s"%(s,fielddisplay(self,'codepath','code path on the cluster'))
+		s = "%s\n%s"%(s,fielddisplay(self,'executionpath','execution path on the cluster'))
+		s = "%s\n%s"%(s,fielddisplay(self,'interactive',''))
+		s = "%s\n%s"%(s,fielddisplay(self,'accountname','your cluster account'))
+		s = "%s\n%s"%(s,fielddisplay(self,'profiling','enable profiling if 1 default is 0'))
+		return s
+	# }}}
+	def checkconsistency(self,md,solution,analyses):
+	# {{{
+		#Queue dictionarry  gives queue name as key and max walltime and cpus as var
+		queuedict = {'normal':[2*24*60,2048],
+								 'devel':[4*60,2048]}
+		QueueRequirements(queuedict,self.queue,self.np,self.time)
+
+		#Miscelaneous
+		if not self.login:
+			md = md.checkmessage('login empty')
+		if not self.codepath:
+			md = md.checkmessage('codepath empty')
+		if not self.executionpath:
+			md = md.checkmessage('executionpath empty')
+		if self.interactive==1:
+			md = md.checkmessage('interactive mode not implemented')
+		return self
+		# }}}
+	def BuildQueueScript(self,dirname,modelname,solution,io_gather,isvalgrind,isgprof,isdakota,isoceancoupling):
+		# {{{
+
+		executable='issm.exe'
+		if isdakota:
+			version=IssmConfig('_DAKOTA_VERSION_')[0:2]
+			version=float(version)
+			if version>=6:
+				executable='issm_dakota.exe'
+		if isoceancoupling:
+			executable='issm_ocean.exe'
+		#write queuing script 
+		shortname=modelname[0:min(12,len(modelname))]
+		fid=open(modelname+'.queue','w')
+									
+		fid.write('#!/bin/bash -l\n')
+		fid.write('#SBATCH --job-name=%s \n' % shortname)
+		fid.write('#SBATCH --partition %s \n' % self.queue)
+		fid.write('#SBATCH --nodes=%i' % self.numnodes)
+		fid.write('#SBATCH --ntasks-per-nodes==%i \n' % self.cpuspernode)									
+		fid.write('#SBATCH --time=%s\n' % self.time) #walltime is minutes
+		fid.write('#SBATCH --mem-per-cpu=%iGB\n' % self.mem)# mem is in GB
+		if (np.mod(self.np,16)+np.mod(self.np,20))==0:
+			fid.write('#SBATCH --ntask=%i\n' % self.np)
+		fid.write('#SBATCH --account=%s\n' % self.accountname) 
+		fid.write('#SBATCH --output %s/%s/%s.outlog \n' % (self.executionpath,dirname,modelname))
+		fid.write('#SBATCH --error %s/%s/%s.errlog \n\n' % (self.executionpath,dirname,modelname))
+
+		fid.write('export ISSM_DIR="%s/../"\n' % self.codepath)
+		fid.write('module restore system\n')
+		fid.write('module load load Automake/1.15.1-GCCcore-6.3.0\n')
+		fid.write('module load libtool/2.4.6-GCCcore-6.3.0\n')
+		fid.write('module load CMake/3.9.1\n')
+		fid.write('module load PETSc/3.8.0-intel-2017a-Python-2.7.13\n')
+		fid.write('module load ParMETIS/4.0.3-intel-2017a\n')
+		fid.write('cd %s/%s/\n\n' % (self.executionpath,dirname))
+		if self.profiling==1:
+			fid.write('module load perf-report\n')
+			fid.write('perf-report mpirun -np %i %s/%s %s %s/%s %s\n' % (self.np,self.codepath,executable,str(solution),self.executionpath,dirname,modelname))
+		else:
+			fid.write('mpirun -np %i %s/%s %s %s/%s %s\n' % (self.np,self.codepath,executable,str(solution),self.executionpath,dirname,modelname))
+		fid.close()
+
+		# }}}
+	def UploadQueueJob(self,modelname,dirname,filelist):
+		# {{{
+		#compress the files into one zip.
+		compressstring='tar -zcf %s.tar.gz ' % dirname
+		for file in filelist:
+			compressstring += ' %s' % file
+		subprocess.call(compressstring,shell=True)
+
+		print 'uploading input file and queueing script'
+		issmscpout(self.name,self.executionpath,self.login,self.port,[dirname+'.tar.gz'])
+
+		# }}}
+	def LaunchQueueJob(self,modelname,dirname,filelist,restart,batch):
+		# {{{
+
+		print 'launching solution sequence on remote cluster'
+		if restart:
+			launchcommand='cd %s && cd %s && sbatch %s.queue' % (self.executionpath,dirname,modelname)
+		else:
+			launchcommand='cd %s && rm -rf ./%s && mkdir %s && cd %s && mv ../%s.tar.gz ./ && tar -zxf %s.tar.gz  && sbatch %s.queue' % (self.executionpath,dirname,dirname,dirname,dirname,dirname,modelname)
+		issmssh(self.name,self.login,self.port,launchcommand)
+
+		# }}}
+	def Download(self,dirname,filelist):
+		# {{{
+
+		#copy files from cluster to current directory
+		directory='%s/%s/' % (self.executionpath,dirname)
+		issmscpin(self.name,self.login,self.port,directory,filelist)
+		# }}}
Index: /issm/trunk/src/m/classes/clusters/generic.js
===================================================================
--- /issm/trunk/src/m/classes/clusters/generic.js	(revision 22757)
+++ /issm/trunk/src/m/classes/clusters/generic.js	(revision 22758)
@@ -53,4 +53,5 @@
 		} //}}}
 		var request = new XMLHttpRequest();
+		request.open("POST", this.url, true);
 		$(callbackid).html(sprintf("%-16s", "CONNECTING...")).prop("disabled", true);
 		request.position = 0; //Keep track of current parsing position in repsonseText
@@ -157,5 +158,4 @@
 		var data = new Blob([nplength,npbuffer,codeversionlength,codeversionbuffer,runtimenamelength,runtimenamebuffer,namelength,namebuffer,toolkitslength,toolkitsbuffer,solutionlength,solutionbuffer,binlength,binbuffer]);
 		
-		request.open("POST", this.url, true);
 		request.responseType = 'application/octet-stream';
 		request.send(data);
@@ -172,3 +172,3 @@
 		return buf;
 	} //}}}
-}
+} 
Index: /issm/trunk/src/m/classes/clusters/generic.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/generic.m	(revision 22757)
+++ /issm/trunk/src/m/classes/clusters/generic.m	(revision 22758)
@@ -11,4 +11,5 @@
 		login         = '';
 		np            = 1;
+		npocean       = 1;
 		port          = 0;
 		interactive   = 1;
@@ -52,4 +53,5 @@
 			disp(sprintf('    login: %s',cluster.login));
 			disp(sprintf('    np: %i',cluster.np));
+			disp(sprintf('    npocean: %i',cluster.npocean));
 			disp(sprintf('    port: %i',cluster.port));
 			disp(sprintf('    codepath: %s',cluster.codepath));
@@ -112,17 +114,17 @@
 					if ismac, 
 						if IssmConfig('_HAVE_MPI_'),
-							fprintf(fid,'mpiexec -np %i %s --leak-check=full --error-limit=no --dsymutil=yes --suppressions=%s %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',...
-							cluster.np,cluster.valgrind,cluster.valgrindsup,cluster.codepath,solution,[cluster.executionpath '/' dirname], modelname,modelname,modelname);
+							fprintf(fid,'mpiexec -np %i %s --leak-check=full --error-limit=no --dsymutil=yes --suppressions=%s %s/%s %s %s %s 2> %s.errlog >%s.outlog ',...
+							cluster.np,cluster.valgrind,cluster.valgrindsup,cluster.codepath,executable,solution,[cluster.executionpath '/' dirname], modelname,modelname,modelname);
 						else
-							fprintf(fid,'%s --leak-check=full --dsymutil=yes --error-limit=no --suppressions=%s %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',...
-							cluster.valgrind,cluster.valgrindsup,cluster.codepath,solution,[cluster.executionpath '/' dirname], modelname,modelname,modelname);
+							fprintf(fid,'%s --leak-check=full --dsymutil=yes --error-limit=no --suppressions=%s %s/%s %s %s %s 2> %s.errlog >%s.outlog ',...
+							cluster.valgrind,cluster.valgrindsup,cluster.codepath,executable,solution,[cluster.executionpath '/' dirname], modelname,modelname,modelname);
 						end
 					else
 						if IssmConfig('_HAVE_MPI_'),
-							fprintf(fid,'mpiexec -np %i %s --leak-check=full --error-limit=no --suppressions=%s %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',...
-							cluster.np,cluster.valgrind,cluster.valgrindsup,cluster.codepath,solution,[cluster.executionpath '/' dirname],modelname,modelname,modelname);
+							fprintf(fid,'mpiexec -np %i %s --leak-check=full --error-limit=no --suppressions=%s %s/%s %s %s %s 2> %s.errlog >%s.outlog ',...
+							cluster.np,cluster.valgrind,cluster.valgrindsup,cluster.codepath,executable,solution,[cluster.executionpath '/' dirname],modelname,modelname,modelname);
 						else
-							fprintf(fid,'%s --leak-check=full --error-limit=no --suppressions=%s %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',...
-							cluster.valgrind,cluster.valgrindsup,cluster.codepath,solution,[cluster.executionpath '/' dirname],modelname,modelname,modelname);
+							fprintf(fid,'%s --leak-check=full --error-limit=no --suppressions=%s %s/%s %s %s %s 2> %s.errlog >%s.outlog ',...
+							cluster.valgrind,cluster.valgrindsup,cluster.codepath,executable,solution,[cluster.executionpath '/' dirname],modelname,modelname,modelname);
 						end
 					end
@@ -144,7 +146,7 @@
 
 				if cluster.np>1,
-					fprintf(fid,'"C:\\Program Files\\MPICH2\\bin\\mpiexec.exe" -n %i "%s/issm.exe" %s ./ %s ',cluster.np,cluster.codepath,solution,modelname);
-				else
-					fprintf(fid,'"%s/issm.exe" %s ./ %s ',cluster.codepath,solution,modelname);
+					fprintf(fid,'"C:\\Program Files\\MPICH2\\bin\\mpiexec.exe" -n %i "%s/%s" %s ./ %s ',cluster.np,cluster.codepath,executable,solution,modelname);
+				else
+					fprintf(fid,'"%s/%s" %s ./ %s ',cluster.codepath,executable,solution,modelname);
 				end
 				fclose(fid);
@@ -209,4 +211,22 @@
 		end
 		%}}}
+		function BuildQueueScriptIceOcean(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof,isdakota) % {{{
+
+			%write queuing script 
+			%what is the executable being called? 
+			executable='issm_ocean.exe';
+
+			fid=fopen([modelname '.queue'],'w');
+			fprintf(fid,'#!%s\n',cluster.shell);
+			fprintf(fid,'mpiexec -np %i %s/%s %s %s %s : -np %i ./mitgcmuv\n',cluster.np,cluster.codepath,executable,solution,cluster.executionpath,modelname,cluster.npocean);
+			fclose(fid);
+
+			%in interactive mode, create a run file, and errlog and outlog file
+			if cluster.interactive,
+				fid=fopen([modelname '.errlog'],'w'); fclose(fid);
+				fid=fopen([modelname '.outlog'],'w'); fclose(fid);
+			end
+		end
+		%}}}
 		function BuildKrigingQueueScript(cluster,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
 
@@ -262,4 +282,7 @@
 				compressstring=['tar -zcf ' dirname '.tar.gz '];
 				for i=1:numel(filelist),
+					if ~exist(filelist{i},'file')
+						error(['File ' filelist{i} ' not found']);
+					end
 					compressstring = [compressstring ' ' filelist{i}];
 				end
@@ -292,4 +315,33 @@
 					launchcommand=['source ' cluster.etcpath '/environment.' shellext ' && cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
 						' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && source  ' modelname '.queue '];
+					else
+					launchcommand=['source ' cluster.etcpath '/environment.' shellext ' && cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
+						' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz '];
+					end
+				end
+				issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
+			else
+				system([modelname '.bat']);
+			end
+
+		end %}}}
+		function LaunchQueueJobIceOcean(cluster,modelname,dirname,filelist,restart,batch)% {{{
+
+			if ~ispc,
+
+				%figure out what shell extension we will use:
+				if isempty(strfind(cluster.shell,'csh')),
+					shellext='sh';
+				else
+					shellext='csh';
+				end
+
+				if cluster.verbose, disp('launching solution sequence on remote cluster'); end
+
+				if ~isempty(restart)
+					launchcommand=['source ' cluster.etcpath '/environment.' shellext ' && cd ' cluster.executionpath ' && cd ' dirname ' && source ' modelname '.queue '];
+				else
+					if ~batch,
+					launchcommand=['source ' cluster.etcpath '/environment.' shellext ' && cd ' cluster.executionpath ' && tar -zxf ' dirname '.tar.gz  && source  ' modelname '.queue '];
 					else
 					launchcommand=['source ' cluster.etcpath '/environment.' shellext ' && cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
Index: /issm/trunk/src/m/classes/clusters/localpfe.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/localpfe.m	(revision 22758)
+++ /issm/trunk/src/m/classes/clusters/localpfe.m	(revision 22758)
@@ -0,0 +1,273 @@
+%localpfe cluster class definition
+%
+%   Usage:
+%      cluster=localpfe('name','astrid','np',3);
+%      cluster=localpfe('name',oshostname(),'np',3,'login','username');
+
+classdef localpfe
+	properties (SetAccess=public) 
+		% {{{
+		name          = '';
+		login         = '';
+		np            = 1;
+		npocean       = 0;
+		port          = 0;
+		interactive   = 1;
+		codepath      = [IssmConfig('ISSM_PREFIX') '/bin'];
+		etcpath       = [issmdir() '/etc'];
+		executionpath = [issmdir() '/execution'];
+		valgrind      = [issmdir() '/externalpackages/valgrind/install/bin/valgrind'];
+		valgrindlib   = [issmdir() '/externalpackages/valgrind/install/lib/libmpidebug.so'];
+		valgrindsup   = [issmdir() '/externalpackages/valgrind/issm.supp'];
+		verbose       = 1;
+		shell         = '/bin/sh';
+		%}}}
+	end
+	methods
+		function cluster=localpfe(varargin) % {{{
+
+			%Change the defaults if ispc
+			if ispc,
+				cluster.codepath      = [issmdir() '\bin'];
+				cluster.etcpath       = [issmdir() '\etc'];
+				cluster.executionpath = [issmdir() '\execution'];
+			end
+
+			%use provided options to change fields
+			options=pairoptions(varargin{:});
+
+			%get name
+			cluster.name=getfieldvalue(options,'name',oshostname());
+
+			%initialize cluster using user settings if provided
+			if (exist([cluster.name '_settings'])==2), eval([cluster.name '_settings']); end
+
+			%OK get other fields
+			cluster=AssignObjectFields(pairoptions(varargin{:}),cluster);
+		end
+		%}}}
+		function disp(cluster) % {{{
+			%  display the object
+			disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
+			disp(sprintf('    name: %s',cluster.name));
+			disp(sprintf('    login: %s',cluster.login));
+			disp(sprintf('    np: %i',cluster.np));
+			disp(sprintf('    port: %i',cluster.port));
+			disp(sprintf('    codepath: %s',cluster.codepath));
+			disp(sprintf('    executionpath: %s',cluster.executionpath));
+			disp(sprintf('    etcpath: %s',cluster.etcpath));
+			disp(sprintf('    valgrind: %s',cluster.valgrind));
+			disp(sprintf('    valgrindlib: %s',cluster.valgrindlib));
+			disp(sprintf('    valgrindsup: %s',cluster.valgrindsup));
+			disp(sprintf('    verbose: %s',cluster.verbose));
+			disp(sprintf('    shell: %s',cluster.shell));
+		end
+		%}}}
+		function md = checkconsistency(cluster,md,solution,analyses) % {{{
+			if cluster.np<1
+				md = checkmessage(md,['number of processors should be at least 1']);
+			end
+			if isnan(cluster.np),
+				md = checkmessage(md,'number of processors should not be NaN!');
+			end
+		end
+		%}}}
+		function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof,isdakota,isoceancoupling) % {{{
+
+			%write queuing script 
+			%what is the executable being called? 
+			executable='issm.exe';
+			if isdakota,
+				version=IssmConfig('_DAKOTA_VERSION_'); version=str2num(version(1:3));
+				if (version>=6),
+					executable='issm_dakota.exe';
+				end
+			end
+
+			fid=fopen([modelname '.queue'],'w');
+			fprintf(fid,'#!%s\n',cluster.shell);
+			fprintf(fid,'mpiexec -np %i %s/%s %s %s %s \n',cluster.np,cluster.codepath,executable,solution,cluster.executionpath,modelname);
+			fclose(fid);
+
+
+			%in interactive mode, create a run file, and errlog and outlog file
+			if cluster.interactive,
+				fid=fopen([modelname '.errlog'],'w'); fclose(fid);
+				fid=fopen([modelname '.outlog'],'w'); fclose(fid);
+			end
+		end
+		%}}}
+		function BuildQueueScriptMultipleModels(cluster,dirname,modelname,solution,dirnames,modelnames,nps) % {{{
+		
+			%some checks: 
+			if isempty(modelname), error('BuildQueueScriptMultipleModels error message: need a non empty model name!');end
+
+			%what is the executable being called? 
+			executable='issm_slr.exe';
+
+			if ispc(), error('BuildQueueScriptMultipleModels not support yet on windows machines');end;
+			
+			%write queuing script 
+			fid=fopen([modelname '.queue'],'w');
+			
+			fprintf(fid,'#!%s\n',cluster.shell);
+
+			%number of cpus: 
+			mpistring=sprintf('mpiexec -np %i ',cluster.np);
+
+			%executable: 
+			mpistring=[mpistring sprintf('%s/%s ',cluster.codepath,executable)];
+			
+			%solution name: 
+			mpistring=[mpistring sprintf('%s ',solution)];
+
+			%execution directory and model name: 
+			mpistring=[mpistring sprintf('%s/%s %s',cluster.executionpath,dirname,modelname)];
+
+			%inform main executable of how many icecaps, glaciers and earth models are being run: 
+			mpistring=[mpistring sprintf(' %i ',length(dirnames))];
+			
+			%icecaps, glaciers and earth location, names and number of processors associated:
+			for i=1:length(dirnames),
+			mpistring=[mpistring sprintf(' %s/%s %s %i ',cluster.executionpath,dirnames{i},modelnames{i},nps{i})];
+			end
+
+			%log files: 
+			if ~cluster.interactive,
+				mpistring=[mpistring sprintf('2> %s.errlog> %s.outlog',modelname,modelname)];
+			end
+
+			%write this long string to disk: 
+			fprintf(fid,mpistring);
+			fclose(fid);
+
+			%in interactive mode, create a run file, and errlog and outlog file
+			if cluster.interactive,
+				fid=fopen([modelname '.errlog'],'w'); fclose(fid);
+				fid=fopen([modelname '.outlog'],'w'); fclose(fid);
+			end
+		end
+		%}}}
+		function BuildQueueScriptIceOcean(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof,isdakota) % {{{
+
+			%write queuing script 
+			%what is the executable being called? 
+			executable='issm_ocean.exe';
+
+			fid=fopen([modelname '.queue'],'w');
+			fprintf(fid,'#!%s\n',cluster.shell);
+			fprintf(fid,'mpiexec -np %i %s/%s %s %s %s : -np %i ./mitgcmuv\n',cluster.np,cluster.codepath,executable,solution,cluster.executionpath,modelname,cluster.npocean);
+			fclose(fid);
+
+			%in interactive mode, create a run file, and errlog and outlog file
+			if cluster.interactive,
+				fid=fopen([modelname '.errlog'],'w'); fclose(fid);
+				fid=fopen([modelname '.outlog'],'w'); fclose(fid);
+			end
+		end
+		%}}}
+		function BuildKrigingQueueScript(cluster,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+
+			%write queuing script 
+			if ~ispc(),
+
+				fid=fopen([modelname '.queue'],'w');
+				fprintf(fid,'#!/bin/sh\n');
+				if ~isvalgrind,
+					if cluster.interactive
+						fprintf(fid,'mpiexec -np %i %s/kriging.exe %s %s ',cluster.np,cluster.codepath,[cluster.executionpath '/' modelname],modelname);
+					else
+						fprintf(fid,'mpiexec -np %i %s/kriging.exe %s %s 2> %s.errlog >%s.outlog ',cluster.np,cluster.codepath,[cluster.executionpath '/' modelname],modelname,modelname,modelname);
+					end
+				elseif isgprof,
+					fprintf(fid,'\n gprof %s/kriging.exe gmon.out > %s.performance',cluster.codepath,modelname);
+				else
+					%Add --gen-suppressions=all to get suppression lines
+					fprintf(fid,'LD_PRELOAD=%s \\\n',cluster.valgrindlib);
+					fprintf(fid,'mpiexec -np %i %s --leak-check=full --suppressions=%s %s/kriging.exe %s %s 2> %s.errlog >%s.outlog ',...
+						cluster.np,cluster.valgrind,cluster.valgrindsup,cluster.codepath,[cluster.executionpath '/' modelname],modelname,modelname,modelname);
+				end
+				if ~io_gather, %concatenate the output files:
+					fprintf(fid,'\ncat %s.outbin.* > %s.outbin',modelname,modelname);
+				end
+				fclose(fid);
+
+			else % Windows
+
+				fid=fopen([modelname '.bat'],'w');
+				fprintf(fid,'@echo off\n');
+				if cluster.interactive
+					fprintf(fid,'"%s/issm.exe" %s "%s" %s ',cluster.codepath,solution,[cluster.executionpath '/' modelname],modelname);
+				else
+					fprintf(fid,'"%s/issm.exe" %s "%s" %s 2> %s.errlog >%s.outlog',...
+						cluster.codepath,solution,[cluster.executionpath '/' modelname],modelname,modelname,modelname);
+				end
+				fclose(fid);
+			end
+
+			%in interactive mode, create a run file, and errlog and outlog file
+			if cluster.interactive,
+				fid=fopen([modelname '.errlog'],'w'); fclose(fid);
+				fid=fopen([modelname '.outlog'],'w'); fclose(fid);
+			end
+		end
+		%}}}
+		function UploadQueueJob(cluster,modelname,dirname,filelist)% {{{
+			if ~ispc,
+
+				%compress the files into one zip.
+				compressstring=['tar -zcf ' dirname '.tar.gz '];
+				for i=1:numel(filelist),
+					compressstring = [compressstring ' ' filelist{i}];
+				end
+				if cluster.interactive,
+					compressstring = [compressstring ' ' modelname '.errlog ' modelname '.outlog '];
+				end
+				system(compressstring);
+
+				if cluster.verbose, disp('uploading input file and queueing script'); end
+				issmscpout(cluster.name,cluster.executionpath,cluster.login,cluster.port,{[dirname '.tar.gz']});
+			end
+		end %}}}
+		function LaunchQueueJob(cluster,modelname,dirname,filelist,restart,batch)% {{{
+
+			%figure out what shell extension we will use:
+			if isempty(strfind(cluster.shell,'csh')),
+				shellext='sh';
+			else
+				shellext='csh';
+			end
+
+			if cluster.verbose, disp('launching solution sequence on remote cluster'); end
+
+			launchcommand=['cd ' cluster.executionpath ' && rm -rf *.lock && rm -rf ADOLC* && tar -zxf ' dirname '.tar.gz  && rm -rf *.tar.gz'];
+			issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
+
+		end %}}}
+		function LaunchQueueJobIceOcean(cluster,modelname,dirname,filelist,restart,batch)% {{{
+
+			%figure out what shell extension we will use:
+			if isempty(strfind(cluster.shell,'csh')),
+				shellext='sh';
+			else
+				shellext='csh';
+			end
+
+			if cluster.verbose, disp('launching solution sequence on remote cluster'); end
+
+			launchcommand=['cd ' cluster.executionpath ' && rm -rf *.lock && tar -zxf ' dirname '.tar.gz  && rm -rf *.tar.gz'];
+			issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
+
+		end %}}}
+		function Download(cluster,dirname,filelist)% {{{
+
+			if ispc(),
+				%do nothing
+				return;
+			end
+
+			%copy files from cluster to current directory
+			issmscpin(cluster.name,cluster.login,cluster.port,cluster.executionpath,filelist);
+		end %}}}
+	end
+end
Index: /issm/trunk/src/m/classes/clusters/pfe.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/pfe.m	(revision 22757)
+++ /issm/trunk/src/m/classes/clusters/pfe.m	(revision 22758)
@@ -353,9 +353,7 @@
 			 fprintf(fid,'#PBS -e %s.errlog \n\n',modelname);
 			 fprintf(fid,'. /usr/share/modules/init/bash\n\n');
-			 fprintf(fid,'module load comp-intel/2015.0.090\n');
-			 fprintf(fid,'module load test/mpt.2.11r8\n');
-			 fprintf(fid,'module load netcdf/4.0\n');
-			 fprintf(fid,'module load mpi-mvapich2/1.4.1/gcc\n');
-			 fprintf(fid,'module load gcc/4.4.4\n');
+			 fprintf(fid,'module load comp-intel/2016.2.181\n');
+			 fprintf(fid,'module load netcdf/4.4.1.1_mpt\n');
+			 fprintf(fid,'module load mpi-sgi/mpt.2.15r20\n');
 			 fprintf(fid,'export PATH="$PATH:."\n');
 			 fprintf(fid,'export MPI_GROUP_MAX=64\n\n');
@@ -370,5 +368,5 @@
 			 if cluster.interactive,
 				 fid=fopen([modelname '.run'],'w');
-				 fprintf(fid,'module load mpi-mvapich2/1.4.1/gcc\n');
+				 fprintf(fid,'module load mpi-sgi/mpt.2.15r20\n');
 				 fprintf(fid,['mpiexec -np %i ./mitgcmuv \n'],np);
 				 fprintf(fid,['touch ' modelname '.lock %s\n']);
Index: /issm/trunk/src/m/classes/clusters/stallo.py
===================================================================
--- /issm/trunk/src/m/classes/clusters/stallo.py	(revision 22758)
+++ /issm/trunk/src/m/classes/clusters/stallo.py	(revision 22758)
@@ -0,0 +1,169 @@
+import subprocess
+import numpy as np
+from fielddisplay import fielddisplay
+from pairoptions import pairoptions
+from issmssh import issmssh
+from issmscpin import issmscpin
+from issmscpout import issmscpout
+from QueueRequirements import QueueRequirements
+import datetime
+try:
+	from stallo_settings import stallo_settings
+except ImportError:
+	print 'You need stallo_settings.py to proceed, check presence and sys.path'
+	
+class stallo(object):
+	"""
+	Stallo cluster class definition
+	This is a SLURM queue
+	The priorities are given to: 
+	   - Large jobs
+	   - Short jobs
+	   - small number of job per user
+
+	There are some 20cpu nodes and 16cpu nodes, with 32GB (a few with 128GB) mem per node, you can ask for part of a node if you need more memory.(1 node, 2 CPUS and 10GB per cpu for example)
+	
+
+	   Usage:
+	      cluster=stallo();
+	"""
+
+	def __init__(self,*args):
+	# {{{
+		self.name           = 'stallo'
+		self.login          = ''
+		self.numnodes       = 2
+		self.cpuspernode    = 20
+		self.mem            = 1.6
+		self.queue          = 'normal'
+		self.time           = 2*60
+		self.codepath       = ''
+		self.executionpath  = ''
+		self.interactive    = 0
+		self.port           = []
+		self.accountname    = ''
+		self.profiling      = 0
+		#use provided options to change fields
+		options=pairoptions(*args)
+
+		#initialize cluster using user settings if provided
+		self=stallo_settings(self)
+		#OK get other fields
+		self=options.AssignObjectFields(self)
+		self.np=self.numnodes*self.cpuspernode		
+	# }}}
+	
+	def __repr__(self):
+	# {{{
+		#  display the object
+		s = "class vilje object:"
+		s = "%s\n%s"%(s,fielddisplay(self,'name','name of the cluster'))
+		s = "%s\n%s"%(s,fielddisplay(self,'login','login'))
+		s = "%s\n%s"%(s,fielddisplay(self,'numnodes','number of nodes'))
+		s = "%s\n%s"%(s,fielddisplay(self,'cpuspernode','number of nodes per CPUs'))
+		s = "%s\n%s"%(s,fielddisplay(self,'mem','memory per CPU'))
+		s = "%s\n%s"%(s,fielddisplay(self,'queue','name of the queue (normal (D), short,singlenode,multinode,devel)'))
+		s = "%s\n%s"%(s,fielddisplay(self,'time','walltime requested in minutes'))
+		s = "%s\n%s"%(s,fielddisplay(self,'codepath','code path on the cluster'))
+		s = "%s\n%s"%(s,fielddisplay(self,'executionpath','execution path on the cluster'))
+		s = "%s\n%s"%(s,fielddisplay(self,'interactive',''))
+		s = "%s\n%s"%(s,fielddisplay(self,'accountname','your cluster account'))
+		s = "%s\n%s"%(s,fielddisplay(self,'profiling','enable profiling if 1 default is 0'))
+		return s
+	# }}}
+	def checkconsistency(self,md,solution,analyses):
+	# {{{
+		#Queue dictionarry  gives queue name as key and max walltime and cpus as var
+		queuedict = {'short':[60, 2048],
+								 'normal':[2*24*60,2048],
+								 'singlenode':[28*24*60,20],
+								 'multinode':[28*24*60,2048],
+								 'devel':[4*60,2048]}
+		QueueRequirements(queuedict,self.queue,self.np,self.time)
+
+		#Miscelaneous
+		if not self.login:
+			md = md.checkmessage('login empty')
+		if not self.codepath:
+			md = md.checkmessage('codepath empty')
+		if not self.executionpath:
+			md = md.checkmessage('executionpath empty')
+		if self.interactive==1:
+			md = md.checkmessage('interactive mode not implemented')
+		return self
+		# }}}
+	def BuildQueueScript(self,dirname,modelname,solution,io_gather,isvalgrind,isgprof,isdakota,isoceancoupling):
+		# {{{
+
+		executable='issm.exe'
+		if isdakota:
+			version=IssmConfig('_DAKOTA_VERSION_')[0:2]
+			version=float(version)
+			if version>=6:
+				executable='issm_dakota.exe'
+		if isoceancoupling:
+			executable='issm_ocean.exe'
+		#write queuing script 
+		shortname=modelname[0:min(12,len(modelname))]
+		fid=open(modelname+'.queue','w')
+									
+		fid.write('#!/bin/bash -l\n')
+		fid.write('#SBATCH --job-name=%s \n' % shortname)
+		fid.write('#SBATCH --partition %s \n' % self.queue)
+		fid.write('#SBATCH --nodes=%i' % self.numnodes)
+		fid.write('#SBATCH --ntasks-per-nodes==%i \n' % self.cpuspernode)									
+		fid.write('#SBATCH --time=%s\n' % self.time) #walltime is minutes
+		fid.write('#SBATCH --mem-per-cpu=%iGB\n' % self.mem)# mem is in GB
+		if (np.mod(self.np,16)+np.mod(self.np,20))==0:
+			fid.write('#SBATCH --ntask=%i\n' % self.np)
+		fid.write('#SBATCH --account=%s\n' % self.accountname) 
+		fid.write('#SBATCH --output %s/%s/%s.outlog \n' % (self.executionpath,dirname,modelname))
+		fid.write('#SBATCH --error %s/%s/%s.errlog \n\n' % (self.executionpath,dirname,modelname))
+
+		fid.write('export ISSM_DIR="%s/../"\n' % self.codepath)
+		fid.write('module purge\n')
+		fid.write('module load CMake/3.8.0-GCCcore-6.3.0\n')
+		fid.write('module load Automake/1.15.1-GCCcore-6.3.0\n')
+		fid.write('module load libtool/2.4.6\n')
+		fid.write('module load OpenSSL/1.1.0e-intel-2017a\n')
+		fid.write('module load PETSc/3.7.5-intel-2017a-downloaded-deps\n')
+
+		fid.write('cd %s/%s/\n\n' % (self.executionpath,dirname))
+		if self.profiling==1:
+			fid.write('module load perf-report\n')
+			fid.write('perf-report mpirun -np %i %s/%s %s %s/%s %s\n' % (self.np,self.codepath,executable,str(solution),self.executionpath,dirname,modelname))
+		else:
+			fid.write('mpirun -np %i %s/%s %s %s/%s %s\n' % (self.np,self.codepath,executable,str(solution),self.executionpath,dirname,modelname))
+		fid.close()
+
+		# }}}
+	def UploadQueueJob(self,modelname,dirname,filelist):
+		# {{{
+		#compress the files into one zip.
+		compressstring='tar -zcf %s.tar.gz ' % dirname
+		for file in filelist:
+			compressstring += ' %s' % file
+		subprocess.call(compressstring,shell=True)
+
+		print 'uploading input file and queueing script'
+		issmscpout(self.name,self.executionpath,self.login,self.port,[dirname+'.tar.gz'])
+
+		# }}}
+	def LaunchQueueJob(self,modelname,dirname,filelist,restart,batch):
+		# {{{
+
+		print 'launching solution sequence on remote cluster'
+		if restart:
+			launchcommand='cd %s && cd %s && sbatch %s.queue' % (self.executionpath,dirname,modelname)
+		else:
+			launchcommand='cd %s && rm -rf ./%s && mkdir %s && cd %s && mv ../%s.tar.gz ./ && tar -zxf %s.tar.gz  && sbatch %s.queue' % (self.executionpath,dirname,dirname,dirname,dirname,dirname,modelname)
+		issmssh(self.name,self.login,self.port,launchcommand)
+
+		# }}}
+	def Download(self,dirname,filelist):
+		# {{{
+
+		#copy files from cluster to current directory
+		directory='%s/%s/' % (self.executionpath,dirname)
+		issmscpin(self.name,self.login,self.port,directory,filelist)
+		# }}}
Index: /issm/trunk/src/m/classes/clusters/vilje.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/vilje.m	(revision 22757)
+++ /issm/trunk/src/m/classes/clusters/vilje.m	(revision 22758)
@@ -1,3 +1,3 @@
-%PFE class definition
+%vilje class definition
 %
 %   Usage:
@@ -7,183 +7,203 @@
 
 classdef vilje
-    properties (SetAccess=public)  
-		 % {{{
-     name           = 'vilje';
-		 login          = '';
-		 numnodes       = 2;
-		 cpuspernode    = 32;
-     procspernodes  = 16;
-     mem            = 28;
-		 queue          = 'workq';
-		 time           = 2*60;
-		 codepath       = '';
-		 executionpath  = '';
-		 interactive    = 0;
-     port           = [];
-     accountname    = '';
-
-	 end
-	 properties (SetAccess=private) 
-		 np=numnodes*procspernodes;
-		 % }}}
-	 end
-	 methods
-		 function cluster=vilje(varargin) % {{{
-
-			 %initialize cluster using default settings if provided
-			 if (exist('vilje_settings')==2), vilje_settings; end
-
-			 %use provided options to change fields
-			 cluster=AssignObjectFields(pairoptions(varargin{:}),cluster);
-		 end
-		 %}}}
-		 function disp(cluster) % {{{
-			 %  display the object
-			 disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
-			 disp(sprintf('    name: %s',cluster.name));
-			 disp(sprintf('    login: %s',cluster.login));
-       disp(sprintf('    accountname: %s',cluster.accountname));
-			 disp(sprintf('    numnodes: %i',cluster.numnodes));
-			 disp(sprintf('    cpuspernode: %i',cluster.cpuspernode));
-			 disp(sprintf('    np: %i', cluster.cpuspernode*cluster.numnodes));
-			 disp(sprintf('    procspernodes: %i',cluster.procspernodes));
-			 disp(sprintf('    queue: %s',cluster.queue));
-			 disp(sprintf('    codepath: %s',cluster.codepath));
-			 disp(sprintf('    executionpath: %s',cluster.executionpath));
-			 disp(sprintf('    interactive: %i',cluster.interactive));
-			 disp(sprintf('    time: %i',cluster.time));
-			 disp(sprintf('    memory: %i',cluster.mem));
-		 end
-		 %}}}
-		 function md = checkconsistency(cluster,md,solution,analyses) % {{{
-
-			 available_queues={'workq'};
-			 queue_requirements_time=[5*24*60];
-			 queue_requirements_np=[30];
-
-			 QueueRequirements(available_queues,queue_requirements_time,queue_requirements_np,cluster.queue,cluster.np,1)
-
-			 %Miscelaneous
-			 if isempty(cluster.login), md = checkmessage(md,'login empty'); end
-       if isempty(cluster.accountname), md = checkmessage(md,'accountname empty'); end
-			 if isempty(cluster.codepath), md = checkmessage(md,'codepath empty'); end
-			 if isempty(cluster.executionpath), md = checkmessage(md,'executionpath empty'); end
-
-		 end
-		 %}}}
-		 function BuildKrigingQueueScript(cluster,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
-
-			 if(isvalgrind), disp('valgrind not supported by cluster, ignoring...'); end
-			 if(isgprof),    disp('gprof not supported by cluster, ignoring...'); end
-
-			 %compute number of processors
-			 cluster.np=cluster.numnodes*cluster.cpuspernode;
-
-			 %write queuing script 
-			 fid=fopen([modelname '.queue'],'w');
-			 fprintf(fid,'#PBS -S /bin/bash\n');
-			 fprintf(fid,'#PBS -N %s\n',modelname);
-       fprintf(fid,'#PBS -l select=%i:ncpus=%i:mpiprocs=%i\n',cluster.numnodes,cluster.cpuspernode,16);
-       fprintf(fid,'#PBS -l walltime=%s\n',cluster.time); %walltime is in seconds.
-       fprintf(fid,'#PBS -A %s\n',cluster.accountname);
-			 fprintf(fid,'#PBS -o %s.outlog \n',modelname);
-			 fprintf(fid,'#PBS -e %s.errlog \n\n',modelname);
-			 fprintf(fid,'export ISSM_DIR="%s/../"\n',cluster.codepath); %FIXME
-			 fprintf(fid,'source $ISSM_DIR/etc/environment.sh\n');       %FIXME
-			 fprintf(fid,'cd %s/%s\n\n',cluster.executionpath,modelname);
-			 fprintf(fid,'mpiexec_mpt -n %i %s/kriging.exe %s %s\n',cluster.np,cluster.codepath,[cluster.executionpath '/' modelname],modelname);
-			 if ~io_gather, %concatenate the output files:
-				 fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
-			 end
-			 fclose(fid);
-		 end
-		 %}}}
-		 function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof,isdakota,isoceancoupling) % {{{
-
-			 if(isvalgrind), disp('valgrind not supported by cluster, ignoring...'); end
-			 if(isgprof),    disp('gprof not supported by cluster, ignoring...'); end
-
-			 executable='issm.exe';
-			 if isdakota,
-				 version=IssmConfig('_DAKOTA_VERSION_'); version=str2num(version(1:3));
-				 if (version>=6),
-					 executable='issm_dakota.exe';
-				 end
-			 end
-			 if isoceancoupling,
-				 executable='issm_ocean.exe';
-			 end
-
-			 %compute number of processors
-			 cluster.np=cluster.numnodes*cluster.cpuspernode;                     
-       shortname = substring(modelname,1,min(12,length(modelname)));
-
-			 %write queuing script 
-			 fid=fopen([modelname '.queue'],'w');
-			 fprintf(fid,'#PBS -S /bin/bash\n');
-			 fprintf(fid,'#PBS -N %s\n',shortname);
-			 fprintf(fid,'#PBS -q %s \n',cluster.queue);
-       fprintf(fid,'#PBS -l select=%i:ncpus=%i:mpiprocs=%i\n',cluster.numnodes,cluster.cpuspernode,cluster.procspernodes);
-			 fprintf(fid,'#PBS -l walltime=%s\n',duration(0,cluster.time,0)); %walltime is in minutes.
-       fprintf(fid,'#PBS -A %s\n',cluster.accountname);
-			 fprintf(fid,'#PBS -o %s.outlog \n',[cluster.executionpath '/' dirname '/' modelname]);
-			 fprintf(fid,'#PBS -e %s.errlog \n\n',[cluster.executionpath '/' dirname '/' modelname]);
-			 fprintf(fid,'export ISSM_DIR="%s/../"\n',cluster.codepath); %FIXME
-			 fprintf(fid,'source $ISSM_DIR/etc/environment.sh\n');       %FIXME
-			 fprintf(fid,'cd %s/%s\n\n',cluster.executionpath,dirname);
-       fprintf(fid,'mpiexec -np %i %s/%s %s %s %s\n',cluster.np,cluster.codepath,executable,solution,[cluster.executionpath '/' dirname],modelname);
-
-			 if ~io_gather, %concatenate the output files:
-				 fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
-			 end
-			 fclose(fid);
-
-			 %in interactive mode, create a run file, and errlog and outlog file
-			 if cluster.interactive,
-				 fid=fopen([modelname '.run'],'w');
-				 fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s\n',cluster.np,cluster.codepath,solution,[cluster.executionpath '/' dirname],modelname);
-				 if ~io_gather, %concatenate the output files:
-					 fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
-				 end
-				 fclose(fid);
-				 fid=fopen([modelname '.errlog'],'w');
-				 fclose(fid);
-				 fid=fopen([modelname '.outlog'],'w');
-				 fclose(fid);
-			 end
-		 end %}}}
-
-
-		 function UploadQueueJob(cluster,modelname,dirname,filelist)% {{{
-
-			 %compress the files into one zip.
-			 compressstring=['tar -zcf ' dirname '.tar.gz '];
-			 for i=1:numel(filelist),
-				 compressstring = [compressstring ' ' filelist{i}];
-			 end
-			 system(compressstring);
-			 disp('uploading input file and queueing script');
-			 directory=cluster.executionpath;
-			 issmbbftpout(cluster.name,directory,cluster.login,cluster.port,cluster.numstreams,{[dirname '.tar.gz']});
-
-		 end
-		 %}}}
-
-
-		 function LaunchQueueJob(cluster,modelname,dirname,filelist)% {{{
-
-			 disp('launching solution sequence on remote cluster');
-			  launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
-											 ' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && hostname && qsub ' modelname '.queue '];
-			 issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
-		 end %}}}
-
-		 function Download(cluster,dirname,filelist)% {{{
-
-			 %copy files from cluster to current directory
-			 directory=[cluster.executionpath '/' dirname '/'];
-			 issmscpin(cluster.name,cluster.login,cluster.port,directory,filelist);
-
-		 end %}}}
+	properties (SetAccess=public)  
+		% {{{
+		name           = 'vilje';
+		login          = '';
+		numnodes       = 2;
+		cpuspernode    = 32;
+		procspernodes  = 16;
+		mem            = 28;
+		numstreams		= 8; %Henning added
+		queue          = 'workq';
+		time           = 2*60;
+		codepath       = '';
+		executionpath  = '';
+		interactive    = 0;
+		port           = [];
+		accountname    = '';
+		% }}}
+	end
+	methods
+		function cluster=vilje(varargin) % {{{
+
+			%initialize cluster using default settings if provided
+			if (exist('vilje_settings')==2), vilje_settings; end
+
+			%use provided options to change fields
+			cluster=AssignObjectFields(pairoptions(varargin{:}),cluster);
+		end
+		%}}}
+		function disp(cluster) % {{{
+			%  display the object
+			disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
+			disp(sprintf('    name: %s',cluster.name));
+			disp(sprintf('    login: %s',cluster.login));
+			disp(sprintf('    accountname: %s',cluster.accountname));
+			disp(sprintf('    numnodes: %i',cluster.numnodes));
+			disp(sprintf('    cpuspernode: %i',cluster.cpuspernode));
+			disp(sprintf('    np: %i', cluster.cpuspernode*cluster.numnodes));
+			disp(sprintf('    procspernodes: %i',cluster.procspernodes));
+			disp(sprintf('    queue: %s',cluster.queue));
+			disp(sprintf('    codepath: %s',cluster.codepath));
+			disp(sprintf('    executionpath: %s',cluster.executionpath));
+			disp(sprintf('    interactive: %i',cluster.interactive));
+			disp(sprintf('    time: %i',cluster.time));
+			disp(sprintf('    memory: %i',cluster.mem));
+		end
+		%}}}
+		function md = checkconsistency(cluster,md,solution,analyses) % {{{
+
+			available_queues={'workq'};
+			queue_requirements_time=[5*24*60];
+			queue_requirements_np=[30];
+
+			QueueRequirements(available_queues,queue_requirements_time,queue_requirements_np,cluster.queue,cluster.np,1)
+
+			%Miscelaneous
+			if isempty(cluster.login), md = checkmessage(md,'login empty'); end
+			if isempty(cluster.accountname), md = checkmessage(md,'accountname empty'); end
+			if isempty(cluster.codepath), md = checkmessage(md,'codepath empty'); end
+			if isempty(cluster.executionpath), md = checkmessage(md,'executionpath empty'); end
+
+		end
+		%}}}
+		function numprocs=np(self) % {{{
+			%compute number of processors
+			numprocs=self.numnodes*self.procspernodes;
+		end
+		%}}}
+		function BuildKrigingQueueScript(cluster,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+
+			if(isvalgrind), disp('valgrind not supported by cluster, ignoring...'); end
+			if(isgprof),    disp('gprof not supported by cluster, ignoring...'); end
+
+			%compute number of processors
+% 			cluster.np=cluster.numnodes*cluster.cpuspernode;
+			np(cluster);%=cluster.numnodes*cluster.cpuspernode;
+
+			%write queuing script 
+			fid=fopen([modelname '.queue'],'w');
+			fprintf(fid,'#PBS -S /bin/bash\n');
+			fprintf(fid,'#PBS -N %s\n',modelname);
+			fprintf(fid,'#PBS -l select=%i:ncpus=%i:mpiprocs=%i\n',cluster.numnodes,cluster.cpuspernode,16);
+			
+			%calculate walltime in hh:mm:ss format
+			walltime=datestr(cluster.time/(60*24),'HH:MM:SS');
+			fprintf(fid,'#PBS -l walltime=%s\n',walltime); %walltime should be in hh:mm:ss
+			fprintf(fid,'#PBS -A %s\n',cluster.accountname);
+			fprintf(fid,'#PBS -o %s.outlog \n',modelname);
+			fprintf(fid,'#PBS -e %s.errlog \n\n',modelname);
+			fprintf(fid,'export ISSM_DIR="%s/../"\n',cluster.codepath); %FIXME
+			fprintf(fid,'source $ISSM_DIR/etc/environment.sh\n');       %FIXME
+			fprintf(fid,'module load intelcomp/17.0.0\n') 
+			fprintf(fid,'module load mpt/2.14\n')
+			fprintf(fid,'module load petsc/3.7.4d\n')
+			fprintf(fid,'module load parmetis/4.0.3\n') 
+			fprintf(fid,'module load mumps/5.0.2\n')
+			fprintf(fid,'cd %s/%s\n\n',cluster.executionpath,modelname);
+			fprintf(fid,'mpiexec_mpt -n %i %s/kriging.exe %s %s\n',cluster.np,cluster.codepath,[cluster.executionpath '/' modelname],modelname);
+			if ~io_gather, %concatenate the output files:
+				fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
+			end
+			fclose(fid);
+		end
+		%}}}
+		function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof,isdakota,isoceancoupling) % {{{
+
+			if(isvalgrind), disp('valgrind not supported by cluster, ignoring...'); end
+			if(isgprof),    disp('gprof not supported by cluster, ignoring...'); end
+
+			executable='issm.exe';
+			if isdakota,
+				version=IssmConfig('_DAKOTA_VERSION_'); version=str2num(version(1:3));
+				if (version>=6),
+					executable='issm_dakota.exe';
+				end
+			end
+			if isoceancoupling,
+				executable='issm_ocean.exe';
+			end
+
+			%compute number of processors
+% 			cluster.np=cluster.numnodes*cluster.cpuspernode;
+			np(cluster);%=cluster.numnodes*cluster.cpuspernode;                     
+% 			shortname = substring(modelname,1,min(12,length(modelname)));
+
+			%write queuing script 
+			fid=fopen([modelname '.queue'],'w');
+			fprintf(fid,'#PBS -S /bin/bash\n');
+% 			fprintf(fid,'#PBS -N %s\n',shortname);
+			fprintf(fid,'#PBS -N %s\n',modelname);
+			fprintf(fid,'#PBS -q %s \n',cluster.queue);
+			fprintf(fid,'#PBS -l select=%i:ncpus=%i:mpiprocs=%i\n',cluster.numnodes,cluster.cpuspernode,cluster.procspernodes);
+
+			%calculate walltime in hh:mm:ss format
+			walltime=datestr(cluster.time/(60*24),'HH:MM:SS');
+% 			fprintf(fid,'#PBS -l walltime=%s\n',duration(0,cluster.time,0)); %walltime is in minutes.
+% 			fprintf(fid,'#PBS -l walltime=%s\n',10); %walltime is in minutes.
+			fprintf(fid,'#PBS -l walltime=%s\n',walltime); %walltime should be in hh:mm:ss
+% 			fprintf(fid,'#PBS -l walltime=%i\n',walltime); %walltime is in hh:mm:ss
+			fprintf(fid,'#PBS -A %s\n',cluster.accountname);
+			fprintf(fid,'#PBS -o %s.outlog \n',[cluster.executionpath '/' dirname '/' modelname]);
+			fprintf(fid,'#PBS -e %s.errlog \n\n',[cluster.executionpath '/' dirname '/' modelname]);
+			fprintf(fid,'export ISSM_DIR="%s/../"\n',cluster.codepath); %FIXME
+			fprintf(fid,'source $ISSM_DIR/etc/environment.sh\n');       %FIXME
+			fprintf(fid,'module load intelcomp/17.0.0\n') 
+			fprintf(fid,'module load mpt/2.14\n')
+			fprintf(fid,'module load petsc/3.7.4d\n')
+			fprintf(fid,'module load parmetis/4.0.3\n') 
+			fprintf(fid,'module load mumps/5.0.2\n')
+			fprintf(fid,'cd %s/%s\n\n',cluster.executionpath,dirname);
+			fprintf(fid,'mpiexec_mpt -np %i %s/%s %s %s %s\n',cluster.np,cluster.codepath,executable,solution,[cluster.executionpath '/' dirname],modelname);
+
+			if ~io_gather, %concatenate the output files:
+				fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
+			end
+			fclose(fid);
+
+			%in interactive mode, create a run file, and errlog and outlog file
+			if cluster.interactive,
+				fid=fopen([modelname '.run'],'w');
+				fprintf(fid,'mpiexec_mpt -np %i %s/issm.exe %s %s %s\n',cluster.np,cluster.codepath,solution,[cluster.executionpath '/' dirname],modelname);
+				if ~io_gather, %concatenate the output files:
+					fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
+				end
+				fclose(fid);
+				fid=fopen([modelname '.errlog'],'w');
+				fclose(fid);
+				fid=fopen([modelname '.outlog'],'w');
+				fclose(fid);
+			end
+		end %}}}
+		function UploadQueueJob(cluster,modelname,dirname,filelist)% {{{
+
+			%compress the files into one zip.
+			compressstring=['tar -zcf ' dirname '.tar.gz '];
+			for i=1:numel(filelist),
+				compressstring = [compressstring ' ' filelist{i}];
+			end
+			system(compressstring);
+			disp('uploading input file and queueing script');
+			directory=cluster.executionpath;
+% 			issmbbftpout(cluster.name,directory,cluster.login,cluster.port,cluster.numstreams,{[dirname '.tar.gz']});
+			issmscpout(cluster.name,directory,cluster.login,cluster.port,{[dirname '.tar.gz']});
+
+		end
+		%}}}
+		function LaunchQueueJob(cluster,modelname,dirname,filelist,restart,batch)% {{{
+
+			disp('launching solution sequence on remote cluster');
+			launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
+				' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && hostname && qsub ' modelname '.queue '];
+			issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
+		end %}}}
+		function Download(cluster,dirname,filelist)% {{{
+
+			%copy files from cluster to current directory
+			directory=[cluster.executionpath '/' dirname '/'];
+			issmscpin(cluster.name,cluster.login,cluster.port,directory,filelist);
+
+		end %}}}
 	end
 end
Index: /issm/trunk/src/m/classes/clusters/vilje.py
===================================================================
--- /issm/trunk/src/m/classes/clusters/vilje.py	(revision 22757)
+++ /issm/trunk/src/m/classes/clusters/vilje.py	(revision 22758)
@@ -100,8 +100,8 @@
 		fid.write('#PBS -q %s \n' % self.queue)
 		fid.write('#PBS -l select=%i:ncpus=%i:mpiprocs=%s\n' % (self.numnodes,self.cpuspernode,self.procspernodes))
-                timeobj=datetime.timedelta(minutes=self.time)
-                m,s=divmod(timeobj.total_seconds(), 60)
-                h,m=divmod(m, 60)
-                timestring="%02d:%02d:%02d" % (h, m, s)
+		timeobj=datetime.timedelta(minutes=self.time)
+		m,s=divmod(timeobj.total_seconds(), 60)
+		h,m=divmod(m, 60)
+		timestring="%02d:%02d:%02d" % (h, m, s)
 		fid.write('#PBS -l walltime=%s\n' % timestring) #walltime is hh:mm:ss
 		#fid.write('#PBS -l mem=%igb\n' % self.mem)
Index: /issm/trunk/src/m/classes/constants.py
===================================================================
--- /issm/trunk/src/m/classes/constants.py	(revision 22757)
+++ /issm/trunk/src/m/classes/constants.py	(revision 22758)
@@ -12,7 +12,8 @@
 
 	def __init__(self): # {{{
-		self.g                    = 0
-		self.yts                  = 0
-		self.referencetemperature = 0
+		self.g                    = 0.
+		self.omega                = 0.
+		self.yts                  = 0.
+		self.referencetemperature = 0.
 		
 		#set defaults
@@ -24,4 +25,5 @@
 
 		string="%s\n%s"%(string,fielddisplay(self,"g","gravitational acceleration [m/s^2]"))
+		string="%s\n%s"%(string,fielddisplay(self,"omega","angular velocity of Earth [rad/s]"))
 		string="%s\n%s"%(string,fielddisplay(self,"yts","number of seconds in a year [s/yr]"))
 		string="%s\n%s"%(string,fielddisplay(self,"referencetemperature","reference temperature used in the enthalpy model [K]"))
@@ -33,4 +35,7 @@
 		#acceleration due to gravity (m/s^2)
 		self.g=9.81
+
+		#Earth's rotation speed 
+		self.omega = 7.292*1e-5;
 
 		#converstion from year to seconds
@@ -44,7 +49,8 @@
 	def checkconsistency(self,md,solution,analyses):    # {{{
 
-		md = checkfield(md,'fieldname','constants.g','>',0,'size',[1])
-		md = checkfield(md,'fieldname','constants.yts','>',0,'size',[1])
-		md = checkfield(md,'fieldname','constants.referencetemperature','size',[1])
+		md = checkfield(md,'fieldname','constants.g','>=',0,'size',[1,1])
+		md = checkfield(md,'fieldname','constants.omega','>=',0,'size',[1,1])
+		md = checkfield(md,'fieldname','constants.yts','>',0,'size',[1,1])
+		md = checkfield(md,'fieldname','constants.referencetemperature','size',[1,1])
 
 		return md
Index: /issm/trunk/src/m/classes/esa.js
===================================================================
--- /issm/trunk/src/m/classes/esa.js	(revision 22757)
+++ /issm/trunk/src/m/classes/esa.js	(revision 22758)
@@ -10,5 +10,8 @@
 		//numerical discretization accuracy
 		this.degacc=.01;
-		
+	
+		//computational flags:
+		this.hemisphere=0;
+
 		//output default:
 		this.requested_outputs=['default'];
@@ -26,4 +29,5 @@
 			md = checkfield(md,'fieldname','esa.love_h','NaN',1,'Inf',1);
 			md = checkfield(md,'fieldname','esa.love_l','NaN',1,'Inf',1);
+			md = checkfield(md,'fieldname','esa.hemisphere','NaN',1,'Inf',1);
 			md = checkfield(md,'fieldname','esa.degacc','size',[1, 1],'>=',1e-10);
 			md = checkfield(md,'fieldname','esa.requested_outputs','stringrow',1);
@@ -48,4 +52,5 @@
 		fielddisplay(this,'love_h','load Love number for radial displacement');
 		fielddisplay(this,'love_l','load Love number for horizontal displacements'); 
+		fielddisplay(this,'hemisphere','North-south, East-west components of 2-D horiz displacement vector: -1 south, 1 north'); 
 		fielddisplay(this,'degacc',"accuracy (default .01 deg) for numerical discretization of the Green's functions");
 		fielddisplay(this,'transitions','indices into parts of the mesh that will be icecaps');
@@ -57,4 +62,5 @@
 			WriteData(fid,prefix,'object',this,'fieldname','love_h','format','DoubleMat','mattype',1);
 			WriteData(fid,prefix,'object',this,'fieldname','love_l','format','DoubleMat','mattype',1);
+			WriteData(fid,prefix,'object',this,'fieldname','hemisphere','format','Integer');
 			WriteData(fid,prefix,'object',this,'fieldname','degacc','format','Double');
 			WriteData(fid,prefix,'object',this,'fieldname','transitions','format','MatArray');
@@ -75,4 +81,5 @@
 			this.love_h=NullFix(this.love_h,NaN);
 			this.love_l=NullFix(this.love_l,NaN);
+			this.hemisphere=NullFix(this.hemisphere,NaN);
 			this.degacc=NullFix(this.degacc,NaN);
 		}//}}}
@@ -82,4 +89,5 @@
 	this.love_h         = 0; //provided by PREM model
 	this.love_l         = 0; //idam
+	this.hemisphere     = 0;
 	this.degacc         = 0;
 	this.requested_outputs = [];
Index: /issm/trunk/src/m/classes/esa.m
===================================================================
--- /issm/trunk/src/m/classes/esa.m	(revision 22757)
+++ /issm/trunk/src/m/classes/esa.m	(revision 22758)
@@ -10,4 +10,5 @@
 		love_l         = 0; %ideam
 		degacc         = 0;
+		hemisphere		= 0;
 		requested_outputs      = {};
 		transitions    = {};
@@ -26,5 +27,8 @@
 		%numerical discretization accuracy
 		self.degacc=.01;
-		
+	
+		%computational flags:
+		self.hemisphere=0;
+
 		%output default:
 		self.requested_outputs={'default'};
@@ -40,4 +44,5 @@
 			md = checkfield(md,'fieldname','esa.love_h','NaN',1,'Inf',1);
 			md = checkfield(md,'fieldname','esa.love_l','NaN',1,'Inf',1);
+			md = checkfield(md,'fieldname','esa.hemisphere','NaN',1,'Inf',1);
 			md = checkfield(md,'fieldname','esa.degacc','size',[1 1],'>=',1e-10);
 			md = checkfield(md,'fieldname','esa.requested_outputs','stringrow',1);
@@ -66,4 +71,5 @@
 			fielddisplay(self,'love_h','load Love number for radial displacement');
 			fielddisplay(self,'love_l','load Love number for horizontal displacements');
+			fielddisplay(self,'hemisphere','North-south, East-west components of 2-D horiz displacement vector: -1 south, 1 north'); 
 			fielddisplay(self,'degacc','accuracy (default .01 deg) for numerical discretization of the Green''s functions');
 			fielddisplay(self,'transitions','indices into parts of the mesh that will be icecaps');
@@ -75,4 +81,5 @@
 			WriteData(fid,prefix,'object',self,'fieldname','love_h','format','DoubleMat','mattype',1);
 			WriteData(fid,prefix,'object',self,'fieldname','love_l','format','DoubleMat','mattype',1);
+			WriteData(fid,prefix,'object',self,'fieldname','hemisphere','format','Integer'); 
 			WriteData(fid,prefix,'object',self,'fieldname','degacc','format','Double');
 			WriteData(fid,prefix,'object',self,'fieldname','transitions','format','MatArray');
@@ -93,4 +100,5 @@
 			writejs1Darray(fid,[modelname '.esa.love_h'],self.love_h);
 			writejs1Darray(fid,[modelname '.esa.love_l'],self.love_l);
+			writejsdouble(fid,[modelname '.esa.hemisphere'],self.hemisphere); 
 			writejsdouble(fid,[modelname '.esa.degacc'],self.degacc);
 			writejscellstring(fid,[modelname '.esa.requested_outputs'],self.requested_outputs);
Index: /issm/trunk/src/m/classes/esa.py
===================================================================
--- /issm/trunk/src/m/classes/esa.py	(revision 22757)
+++ /issm/trunk/src/m/classes/esa.py	(revision 22758)
@@ -15,7 +15,8 @@
 	
 	def __init__(self): # {{{
-		self.deltathickness    = np.nan
+		self.deltathickness    = float('NaN')
 		self.love_h            = 0 #provided by PREM model()
 		self.love_l            = 0 #ideam
+		self.hemisphere        = 0
 		self.degacc            = 0
 		self.requested_outputs = []
@@ -30,4 +31,5 @@
 			string="%s\n%s"%(string,fielddisplay(self,'love_h','load Love number for radial displacement'))
 			string="%s\n%s"%(string,fielddisplay(self,'love_l','load Love number for horizontal displaements'))
+                        string="%s\n%s"%(string,fielddisplay(self,'hemisphere','North-south, East-west components of 2-D horiz displacement vector: -1 south, 1 north'))
 			string="%s\n%s"%(string,fielddisplay(self,'degacc','accuracy (default .01 deg) for numerical discretization of the Green''s functions'))
 			string="%s\n%s"%(string,fielddisplay(self,'transitions','indices into parts of the mesh that will be icecaps'))
@@ -40,5 +42,8 @@
 		#numerical discretization accuracy
 		self.degacc=.01
-		
+	
+                #computational flags:
+                self.hemisphere=0;
+
 		#output default:
 		self.requested_outputs=['default']
@@ -60,4 +65,5 @@
 		md = checkfield(md,'fieldname','esa.love_h','NaN',1,'Inf',1)
 		md = checkfield(md,'fieldname','esa.love_l','NaN',1,'Inf',1)
+		md = checkfield(md,'fieldname','esa.hemisphere','NaN',1,'Inf',1)
 		md = checkfield(md,'fieldname','esa.degacc','size',[1,1],'>=',1e-10)
 		md = checkfield(md,'fieldname','esa.requested_outputs','stringrow',1)
@@ -75,4 +81,5 @@
 		WriteData(fid,prefix,'object',self,'fieldname','love_h','format','DoubleMat','mattype',1)
 		WriteData(fid,prefix,'object',self,'fieldname','love_l','format','DoubleMat','mattype',1)
+		WriteData(fid,prefix,'object',self,'fieldname','hemisphere','format','Integer')
 		WriteData(fid,prefix,'object',self,'fieldname','degacc','format','Double')
 		WriteData(fid,prefix,'object',self,'fieldname','transitions','format','MatArray')
Index: /issm/trunk/src/m/classes/flowequation.m
===================================================================
--- /issm/trunk/src/m/classes/flowequation.m	(revision 22757)
+++ /issm/trunk/src/m/classes/flowequation.m	(revision 22758)
@@ -99,5 +99,5 @@
 			md = checkfield(md,'fieldname','flowequation.isFS','numel',[1],'values',[0 1]);
 			md = checkfield(md,'fieldname','flowequation.fe_SSA','values',{'P1','P1bubble','P1bubblecondensed','P2','P2bubble'});
-			md = checkfield(md,'fieldname','flowequation.fe_HO' ,'values',{'P1','P1bubble','P1bubblecondensed','P1xP2','P2xP1','P2','P2bubble','P1xP3','P2xP4'});
+			md = checkfield(md,'fieldname','flowequation.fe_HO' ,'values',{'P1','P1bubble','P1bubblecondensed','P1xP2','P2xP1','P2','P2bubble','P1xP3','P1xP4','P2xP4'});
 			md = checkfield(md,'fieldname','flowequation.fe_FS' ,'values',{'P1P1','P1P1GLS','MINIcondensed','MINI','TaylorHood','LATaylorHood','XTaylorHood','OneLayerP4z','CrouzeixRaviart','LACrouzeixRaviart'});
 			md = checkfield(md,'fieldname','flowequation.augmented_lagrangian_r','numel',[1],'>=',0.);
Index: /issm/trunk/src/m/classes/flowequation.py
===================================================================
--- /issm/trunk/src/m/classes/flowequation.py	(revision 22757)
+++ /issm/trunk/src/m/classes/flowequation.py	(revision 22758)
@@ -92,5 +92,5 @@
 		md = checkfield(md,'fieldname','flowequation.fe_SSA','values',['P1','P1bubble','P1bubblecondensed','P2','P2bubble'])
 		md = checkfield(md,'fieldname','flowequation.fe_HO' ,'values',['P1','P1bubble','P1bubblecondensed','P1xP2','P2xP1','P2','P2bubble','P1xP3','P2xP4'])
-		md = checkfield(md,'fieldname','flowequation.fe_FS' ,'values',['P1P1','P1P1GLS','MINIcondensed','MINI','TaylorHood','XTaylorHood','OneLayerP4z','CrouzeixRaviart'])
+		md = checkfield(md,'fieldname','flowequation.fe_FS' ,'values',['P1P1','P1P1GLS','MINIcondensed','MINI','TaylorHood','LATaylorHood','XTaylorHood','OneLayerP4z','CrouzeixRaviart','LACrouzeixRaviart'])
 		md = checkfield(md,'fieldname','flowequation.borderSSA','size',[md.mesh.numberofvertices],'values',[0,1])
 		md = checkfield(md,'fieldname','flowequation.borderHO','size',[md.mesh.numberofvertices],'values',[0,1])
@@ -104,4 +104,7 @@
 			md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',[1,2])
 			md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements],'values',[1,2])
+		elif m.strcmp(md.mesh.domaintype(),'2Dvertical'):
+			md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',[2,4,5])
+			md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements],'values',[2,4,5])
 		elif m.strcmp(md.mesh.domaintype(),'3D'):
 			md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',np.arange(0,8+1))
Index: /issm/trunk/src/m/classes/fourierlove.js
===================================================================
--- /issm/trunk/src/m/classes/fourierlove.js	(revision 22758)
+++ /issm/trunk/src/m/classes/fourierlove.js	(revision 22758)
@@ -0,0 +1,84 @@
+//FOURIERLOVE class definition
+//
+//   Usage:
+//      md.love=fourierlove();
+
+function fourierlove (){
+	//methods
+	this.extrude = function(md) { // {{{
+		return this;
+	} // }}}
+	this.setdefaultparameters = function() { // {{{
+		//we setup an elastic love number computation by default.
+		this.nfreq=1; 
+		this.frequencies=[0]; //Hz
+		this.sh_nmax=256; // .35 degree, 40 km at the equator.
+		this.sh_nmin=1; 
+		this.g0=10; // m/s^2; 
+		this.r0=6378*1e3; //m;
+		this.mu0=10**11; // Pa
+		this.allow_layer_deletion=1; 
+		this.love_kernels=0; 
+		this.forcing_type = 11; 
+	} // }}}
+	this.disp = function() { // {{{
+		fielddisplay(this,'nfreq','number of frequencies sampled (default 1, elastic) [Hz]');
+		fielddisplay(this,'frequencies','frequencies sampled (convention defaults to 0 for the elastic case) [Hz]');
+		fielddisplay(this,'sh_nmax','maximum spherical harmonic degree (default 256, .35 deg, or 40 km at equator)');
+		fielddisplay(this,'sh_nmin','minimum spherical harmonic degree (default 1)');
+		fielddisplay(this,'g0','adimensioning constant for gravity (default 10) [m/s^2]');
+		fielddisplay(this,'r0','adimensioning constant for radius (default 6378*10^3) [m]');
+		fielddisplay(this,'mu0','adimensioning constant for stress (default 10^11) [Pa]');
+		fielddisplay(this,'allow_layer_deletion','allow for migration of the integration boundary with increasing spherical harmonics degree (default 1)');
+		fielddisplay(this,'love_kernels','compute love numbers at depth? (default 0)');
+		fielddisplay(this,'forcing_type',['integer indicating the nature and depth of the forcing for the Love number calculation (default 11) :','1:  Inner core boundary -- Volumic Potential','2:  Inner core boundary -- Pressure','3:  Inner core boundary -- Loading','4:  Inner core boundary -- Tangential traction','5:  Core mantle boundary -- Volumic Potential','6:  Core mantle boundary -- Pressure','7:  Core mantle boundary -- Loading','8:  Core mantle boundary -- Tangential traction','9:  Surface -- Volumic Potential','10: Surface -- Pressure','11: Surface -- Loading','12: Surface -- Tangential traction ']); 
+
+	} // }}}
+	this.checkconsistency = function(md,solution,analyses) { // {{{
+
+		md = checkfield(md,'fieldname','love.nfreq','NaN',1,'Inf',1,'numel',1,'>',0);
+		md = checkfield(md,'fieldname','love.frequencies','NaN',1,'Inf',1,'numel',md.love.nfreq);
+		md = checkfield(md,'fieldname','love.sh_nmax','NaN',1,'Inf',1,'numel',1,'>',0);
+		md = checkfield(md,'fieldname','love.sh_nmin','NaN',1,'Inf',1,'numel',1,'>',0);
+		md = checkfield(md,'fieldname','love.g0','NaN',1,'Inf',1,'numel',1,'>',0);
+		md = checkfield(md,'fieldname','love.r0','NaN',1,'Inf',1,'numel',1,'>',0);
+		md = checkfield(md,'fieldname','love.mu0','NaN',1,'Inf',1,'numel',1,'>',0);
+		md = checkfield(md,'fieldname','love.allow_layer_deletion','values',[0, 1]);
+		md = checkfield(md,'fieldname','love.love_kernels','values',[0, 1]);
+		md = checkfield(md,'fieldname','love.forcing_type','NaN',1,'Inf',1,'numel',1,'>',0, '<=', 12);
+		if (md.love.sh_nmin<=1 && md.love.forcing_type==9) {
+			throw 'Degree 1 not supported for Volumetric Potential forcing. Use sh_min>=2 for this kind of calculation.';
+		}
+	} // }}}
+	this.marshall = function(md,prefix,fid) { // {{{
+	
+		WriteData(fid,prefix,'object',this,'fieldname','nfreq','format','Integer');
+		WriteData(fid,prefix,'object',this,'fieldname','frequencies','format','DoubleMat','mattype',3);
+		WriteData(fid,prefix,'object',this,'fieldname','sh_nmax','format','Integer');
+		WriteData(fid,prefix,'object',this,'fieldname','sh_nmin','format','Integer');
+		WriteData(fid,prefix,'object',this,'fieldname','g0','format','Double');
+		WriteData(fid,prefix,'object',this,'fieldname','r0','format','Double');
+		WriteData(fid,prefix,'object',this,'fieldname','mu0','format','Double');
+		WriteData(fid,prefix,'object',this,'fieldname','allow_layer_deletion','format','Boolean');
+		WriteData(fid,prefix,'object',this,'fieldname','love_kernels','format','Boolean');
+		WriteData(fid,prefix,'object',this,'fieldname','forcing_type','format','Integer');
+
+	} // }}}
+	//properties 
+	// {{{
+		
+	this.nfreq                =  NaN;
+	this.frequencies          =  NaN;
+	this.sh_nmax              =  NaN;
+	this.sh_nmin              =  NaN;
+	this.g0                   =  NaN; 
+	this.r0                   =  NaN; 
+	this.mu0                  =  NaN;
+	this.allow_layer_deletion =  NaN;
+	this.love_kernels =  NaN;
+	this.forcing_type         =  NaN;
+	
+	//set defaults
+	this.setdefaultparameters();
+	// }}}
+}
Index: /issm/trunk/src/m/classes/fourierlove.m
===================================================================
--- /issm/trunk/src/m/classes/fourierlove.m	(revision 22758)
+++ /issm/trunk/src/m/classes/fourierlove.m	(revision 22758)
@@ -0,0 +1,96 @@
+%FOURIERLOVE class definition
+%
+%   Usage:
+%      md.love=fourierlove();
+
+classdef fourierlove
+	properties (SetAccess=public) 
+		nfreq                = 0;
+		frequencies          = 0;
+		sh_nmax              = 0;
+		sh_nmin              = 0;
+		g0                   = 0;
+		r0                   = 0;
+		mu0                  = 0;
+		allow_layer_deletion = 0;
+		love_kernels         = 0;
+		forcing_type         = 0;
+	end
+	methods (Static)
+		function self = loadobj(self) % {{{
+			% This function is directly called by matlab when a model object is
+			% loaded. Update old properties here
+		end% }}}
+	end
+	methods
+		function self = extrude(self,md) % {{{
+		end % }}}
+		function self = fourierlove(varargin) % {{{
+			switch nargin
+				case 0
+					self=setdefaultparameters(self);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
+			%we setup an elastic love number computation by default.
+			self.nfreq=1; 
+			self.frequencies=[0]; %Hz
+			self.sh_nmax=256; % .35 degree, 40 km at the equator.
+			self.sh_nmin=1; 
+			self.g0=10; % m/s^2; 
+			self.r0=6378*1e3; %m;
+			self.mu0=10^11; % Pa
+			self.allow_layer_deletion=1; 
+			self.love_kernels=0; 
+			self.forcing_type = 11; 
+		end % }}}
+		function disp(self) % {{{
+			fielddisplay(self,'nfreq','number of frequencies sampled (default 1, elastic) [Hz]');
+			fielddisplay(self,'frequencies','frequencies sampled (convention defaults to 0 for the elastic case) [Hz]');
+			fielddisplay(self,'sh_nmax','maximum spherical harmonic degree (default 256, .35 deg, or 40 km at equator)');
+			fielddisplay(self,'sh_nmin','minimum spherical harmonic degree (default 1)');
+			fielddisplay(self,'g0','adimensioning constant for gravity (default 10) [m/s^2]');
+			fielddisplay(self,'r0','adimensioning constant for radius (default 6378*10^3) [m]');
+			fielddisplay(self,'mu0','adimensioning constant for stress (default 10^11) [Pa]');
+			fielddisplay(self,'allow_layer_deletion','allow for migration of the integration boundary with increasing spherical harmonics degree (default 1)');
+			fielddisplay(self,'love_kernels','compute love numbers at depth? (default 0)');
+			fielddisplay(self,'forcing_type',{'integer indicating the nature and depth of the forcing for the Love number calculation (default 11) :','1:  Inner core boundary -- Volumic Potential','2:  Inner core boundary -- Pressure','3:  Inner core boundary -- Loading','4:  Inner core boundary -- Tangential traction','5:  Core mantle boundary -- Volumic Potential','6:  Core mantle boundary -- Pressure','7:  Core mantle boundary -- Loading','8:  Core mantle boundary -- Tangential traction','9:  Surface -- Volumic Potential','10: Surface -- Pressure','11: Surface -- Loading','12: Surface -- Tangential traction '}); 
+
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
+
+			md = checkfield(md,'fieldname','love.nfreq','NaN',1,'Inf',1,'numel',1,'>',0);
+			md = checkfield(md,'fieldname','love.frequencies','NaN',1,'Inf',1,'numel',md.love.nfreq);
+			md = checkfield(md,'fieldname','love.sh_nmax','NaN',1,'Inf',1,'numel',1,'>',0);
+			md = checkfield(md,'fieldname','love.sh_nmin','NaN',1,'Inf',1,'numel',1,'>',0);
+			md = checkfield(md,'fieldname','love.g0','NaN',1,'Inf',1,'numel',1,'>',0);
+			md = checkfield(md,'fieldname','love.r0','NaN',1,'Inf',1,'numel',1,'>',0);
+			md = checkfield(md,'fieldname','love.mu0','NaN',1,'Inf',1,'numel',1,'>',0);
+			md = checkfield(md,'fieldname','love.allow_layer_deletion','values',[0 1]);
+			md = checkfield(md,'fieldname','love.love_kernels','values',[0 1]);
+			md = checkfield(md,'fieldname','love.forcing_type','NaN',1,'Inf',1,'numel',1,'>',0, '<=', 12);
+			if md.love.sh_nmin<=1 & md.love.forcing_type==9
+				error('Degree 1 not supported for Volumetric Potential forcing. Use sh_min>=2 for this kind of calculation.')
+			end
+		end % }}}
+		function marshall(self,prefix,md,fid) % {{{
+		
+			WriteData(fid,prefix,'object',self,'fieldname','nfreq','format','Integer');
+			WriteData(fid,prefix,'object',self,'fieldname','frequencies','format','DoubleMat','mattype',3);
+			WriteData(fid,prefix,'object',self,'fieldname','sh_nmax','format','Integer');
+			WriteData(fid,prefix,'object',self,'fieldname','sh_nmin','format','Integer');
+			WriteData(fid,prefix,'object',self,'fieldname','g0','format','Double');
+			WriteData(fid,prefix,'object',self,'fieldname','r0','format','Double');
+			WriteData(fid,prefix,'object',self,'fieldname','mu0','format','Double');
+			WriteData(fid,prefix,'object',self,'fieldname','allow_layer_deletion','format','Boolean');
+			WriteData(fid,prefix,'object',self,'fieldname','love_kernels','format','Boolean');
+			WriteData(fid,prefix,'object',self,'fieldname','forcing_type','format','Integer');
+
+		end % }}}
+		function savemodeljs(self,fid,modelname) % {{{
+			error('not implemented yet!');
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/fourierlove.py
===================================================================
--- /issm/trunk/src/m/classes/fourierlove.py	(revision 22758)
+++ /issm/trunk/src/m/classes/fourierlove.py	(revision 22758)
@@ -0,0 +1,109 @@
+from fielddisplay import fielddisplay
+from checkfield import checkfield
+from WriteData import WriteData
+
+class fourierlove(object):
+	"""
+	Fourier Love Number class definition
+
+	   Usage:
+	      fourierlove=fourierlove();
+	"""
+
+	def __init__(self): # {{{
+                self.nfreq                =  float('NaN');
+		self.frequencies          =  float('NaN');
+		self.sh_nmax              =  float('NaN');
+		self.sh_nmin              =  float('NaN');
+		self.g0                   =  float('NaN'); 
+		self.r0                   =  float('NaN'); 
+		self.mu0                  =  float('NaN');
+                self.allow_layer_deletion = float('NaN');
+                self.love_kernels = float('NaN');
+		self.forcing_type         =  float('NaN');
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		
+		string='   Fourier Love class:' 
+		
+                string="%s\n%s"%(string,fielddisplay(self,'nfreq','number of frequencies sampled (default 1, elastic) [Hz]'))
+                string="%s\n%s"%(string,fielddisplay(self,'frequencies','frequencies sampled (convention defaults to 0 for the elastic case) [Hz]'))
+                string="%s\n%s"%(string,fielddisplay(self,'sh_nmax','maximum spherical harmonic degree (default 256, .35 deg, or 40 km at equator)'))
+                string="%s\n%s"%(string,fielddisplay(self,'sh_nmin','minimum spherical harmonic degree (default 1)'))
+                string="%s\n%s"%(string,fielddisplay(self,'g0','adimensioning constant for gravity (default 10) [m/s^2]'))
+                string="%s\n%s"%(string,fielddisplay(self,'r0','adimensioning constant for radius (default 6378*10^3) [m]'))
+                string="%s\n%s"%(string,fielddisplay(self,'mu0','adimensioning constant for stress (default 10^11) [Pa]'))
+                string="%s\n%s"%(string,fielddisplay(self,'allow_layer_deletion','allow for migration of the integration boundary with increasing spherical harmonics degree (default 1)'))
+                string="%s\n%s"%(string,fielddisplay(self,'love_kernels','compute love numbers at depth? (default 0)'))
+                string="%s\n%s"%(string,fielddisplay(self,'forcing_type','integer indicating the nature and depth of the forcing for the Love number calculation (default 11) :'))
+                string="%s\n%s"%(string,'                                                     1:  Inner core boundary -- Volumic Potential')
+                string="%s\n%s"%(string,'                                                     2:  Inner core boundary -- Pressure')
+                string="%s\n%s"%(string,'                                                     3:  Inner core boundary -- Loading')
+                string="%s\n%s"%(string,'                                                     4:  Inner core boundary -- Tangential traction')
+                string="%s\n%s"%(string,'                                                     5:  Core mantle boundary -- Volumic Potential')
+                string="%s\n%s"%(string,'                                                     6:  Core mantle boundary -- Pressure')
+                string="%s\n%s"%(string,'                                                     7:  Core mantle boundary -- Loading')
+                string="%s\n%s"%(string,'                                                     8:  Core mantle boundary -- Tangential traction')
+                string="%s\n%s"%(string,'                                                     9:  Surface -- Volumic Potential')
+                string="%s\n%s"%(string,'                                                     10: Surface -- Pressure')
+                string="%s\n%s"%(string,'                                                     11: Surface -- Loading')
+                string="%s\n%s"%(string,'                                                     12: Surface -- Tangential traction ')
+
+                return string;
+
+
+		#}}}
+	def extrude(self,md): # {{{
+		return self
+	#}}}
+	def setdefaultparameters(self): # {{{
+
+            #we setup an elastic love number computation by default.
+            self.nfreq=1
+            self.frequencies=[0]; #Hz
+            self.sh_nmax=256 # .35 degree, 40 km at the equator.
+            self.sh_nmin=1
+            self.g0=10 # m/s^2
+            self.r0=6378*1e3 #m
+            self.mu0=1e11 # Pa
+            self.allow_layer_deletion=1
+            self.love_kernels=0 
+            self.forcing_type = 11
+
+            return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+            md = checkfield(md,'fieldname','love.nfreq','NaN',1,'Inf',1,'numel',[1],'>',0);
+            md = checkfield(md,'fieldname','love.frequencies','NaN',1,'Inf',1,'numel',[md.love.nfreq]);
+            md = checkfield(md,'fieldname','love.sh_nmax','NaN',1,'Inf',1,'numel',[1],'>',0);
+            md = checkfield(md,'fieldname','love.sh_nmin','NaN',1,'Inf',1,'numel',[1],'>',0);
+            md = checkfield(md,'fieldname','love.g0','NaN',1,'Inf',1,'numel',[1],'>',0);
+            md = checkfield(md,'fieldname','love.r0','NaN',1,'Inf',1,'numel',[1],'>',0);
+            md = checkfield(md,'fieldname','love.mu0','NaN',1,'Inf',1,'numel',[1],'>',0);
+            md = checkfield(md,'fieldname','love.allow_layer_deletion','values',[0,1]);
+            md = checkfield(md,'fieldname','love.love_kernels','values',[0,1]);
+            md = checkfield(md,'fieldname','love.forcing_type','NaN',1,'Inf',1,'numel',[1],'>',0, '<=', 12);
+            if md.love.sh_nmin<=1 and md.love.forcing_type==9:
+                raise RuntimeError("Degree 1 not supported for Volumetric Potential forcing. Use sh_min>=2 for this kind of calculation.")
+
+            return md
+	# }}}
+	def marshall(self,prefix,md,fid):    # {{{
+            
+            WriteData(fid,prefix,'object',self,'fieldname','nfreq','format','Integer');
+            WriteData(fid,prefix,'object',self,'fieldname','frequencies','format','DoubleMat','mattype',3);
+            WriteData(fid,prefix,'object',self,'fieldname','sh_nmax','format','Integer');
+            WriteData(fid,prefix,'object',self,'fieldname','sh_nmin','format','Integer');
+            WriteData(fid,prefix,'object',self,'fieldname','g0','format','Double');
+            WriteData(fid,prefix,'object',self,'fieldname','r0','format','Double');
+            WriteData(fid,prefix,'object',self,'fieldname','mu0','format','Double');
+            WriteData(fid,prefix,'object',self,'fieldname','allow_layer_deletion','format','Boolean');
+            WriteData(fid,prefix,'object',self,'fieldname','love_kernels','format','Boolean');
+            WriteData(fid,prefix,'object',self,'fieldname','forcing_type','format','Integer');
+
+	# }}}
Index: /issm/trunk/src/m/classes/friction.js
===================================================================
--- /issm/trunk/src/m/classes/friction.js	(revision 22757)
+++ /issm/trunk/src/m/classes/friction.js	(revision 22758)
@@ -14,11 +14,23 @@
 		fielddisplay(this,'p','p exponent');
 		fielddisplay(this,'q','q exponent');
+		fielddisplay(this,'coupling','Coupling flag: 0 for default, 1 for forcing(provide md.friction.effective_pressure)  and 2 for coupled(not implemented yet)');
 	} // }}}
-    this.extrude = function(md) {//{{{
-        this.coefficient = project3d(md, 'vector', this.coefficient, 'type', 'node', 'layer', 1);
-        this.p = project3d(md, 'vector', this.p, 'type', 'element');
-        this.q = project3d(md, 'vector', this.q, 'type', 'element');
-        return this;
-    }//}}}
+	this.extrude = function(md) {//{{{
+		this.coefficient = project3d(md, 'vector', this.coefficient, 'type', 'node', 'layer', 1);
+		this.p = project3d(md, 'vector', this.p, 'type', 'element');
+		this.q = project3d(md, 'vector', this.q, 'type', 'element');
+		switch (this.coupling) {
+			case 0:
+			case 1:
+				this.effective_pressure=project3d(md, 'vector', this.effective_pressure, 'type', 'node', 'layer', 1);
+				break;
+			case 2:
+				console.error('not implemented yet');
+				break;
+			default:	
+				console.error('not supported yet');
+		}
+		return this;
+	}//}}}
 	this.classname= function (){// {{{
 		return "friction";
@@ -33,4 +45,16 @@
 			md = checkfield(md,'fieldname','friction.q','NaN',1,'Inf',1,'size',[md.mesh.numberofelements ,1]);
 			md = checkfield(md,'fieldname','friction.p','NaN',1,'Inf',1,'size',[md.mesh.numberofelements ,1]);
+			md = checkfield(md,'fieldname','friction.coupling','numel',[1],'values',[0, 1, 2]);
+			switch (this.coupling) {
+				case 0:
+				case 1:
+					md = checkfield(md,'fieldname','friction.effective_pressure','NaN',1,'Inf',1,'timeseries',1);
+					break;
+				case 2:
+					console.error('not implemented yet');
+					break;
+				default:	
+					console.error('not supported yet');
+			}
 
 		} // }}}
@@ -43,4 +67,16 @@
 			WriteData(fid,prefix,'object',this,'fieldname','p','format','DoubleMat','mattype',2);
 			WriteData(fid,prefix,'object',this,'fieldname','q','format','DoubleMat','mattype',2);
+			WriteData(fid,prefix,'class','friction','object',this,'fieldname','coupling','format','Integer');
+			switch (this.coupling) {
+				case 0:
+				case 1:
+					WriteData(fid,prefix,'class','friction','object',this,'fieldname','effective_pressure','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
+					break;
+				case 2:
+					console.error('not implemented yet');
+					break;
+				default:
+					console.error('not supported yet');		
+			}
 			
 
@@ -53,4 +89,6 @@
 	this.p           = NaN;
 	this.q           = NaN;
+	this.coupling    = 0;
+	this.effective_pressure = NaN;
 	this.setdefaultparameters();
 	//}}}
Index: /issm/trunk/src/m/classes/friction.m
===================================================================
--- /issm/trunk/src/m/classes/friction.m	(revision 22757)
+++ /issm/trunk/src/m/classes/friction.m	(revision 22758)
@@ -9,4 +9,6 @@
 		p           = NaN;
 		q           = NaN;
+		coupling    = 0;
+		effective_pressure = NaN;
 	end
 	methods
@@ -15,4 +17,13 @@
 			self.p=project3d(md,'vector',self.p,'type','element');
 			self.q=project3d(md,'vector',self.q,'type','element');
+			switch self.coupling
+				case 0
+				case 1
+					self.effective_pressure=project3d(md,'vector',self.effective_pressure,'type','node','layer',1);
+				case 2
+					error('not implemented yet');
+				otherwise
+					error('not supported yet');		
+			end
 		end % }}}
 		function self = friction(varargin) % {{{
@@ -20,4 +31,6 @@
 				case 0
 					self=setdefaultparameters(self);
+				case 1
+					self=structtoobj(friction(),varargin{1});
 				otherwise
 					error('constructor not supported');
@@ -36,4 +49,14 @@
 			md = checkfield(md,'fieldname','friction.q','NaN',1,'Inf',1,'size',[md.mesh.numberofelements 1]);
 			md = checkfield(md,'fieldname','friction.p','NaN',1,'Inf',1,'size',[md.mesh.numberofelements 1]);
+			md = checkfield(md,'fieldname','friction.coupling','numel',[1],'values',[0 1 2]);
+			switch self.coupling
+				case 0
+				case 1
+					md = checkfield(md,'fieldname','friction.effective_pressure','NaN',1,'Inf',1,'timeseries',1);
+				case 2
+					error('not implemented yet');
+				otherwise
+					error('not supported yet');		
+			end
 		end % }}}
 		function disp(self) % {{{
@@ -42,4 +65,6 @@
 			fielddisplay(self,'p','p exponent');
 			fielddisplay(self,'q','q exponent');
+			fielddisplay(self,'effective_pressure','Effective Pressure for the forcing if not coupled [Pa]');
+			fielddisplay(self,'coupling','Coupling flag: 0 for default, 1 for forcing(provide md.friction.effective_pressure)  and 2 for coupled(not implemented yet)');
 		end % }}}
 		function marshall(self,prefix,md,fid) % {{{
@@ -50,6 +75,14 @@
 			WriteData(fid,prefix,'object',self,'fieldname','p','format','DoubleMat','mattype',2);
 			WriteData(fid,prefix,'object',self,'fieldname','q','format','DoubleMat','mattype',2);
-			
-
+			WriteData(fid,prefix,'class','friction','object',self,'fieldname','coupling','format','Integer');
+			switch self.coupling
+				case 0
+				case 1
+					WriteData(fid,prefix,'class','friction','object',self,'fieldname','effective_pressure','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
+				case 2
+					error('not implemented yet');
+				otherwise
+					error('not supported yet');		
+			end
 		end % }}}
 		function savemodeljs(self,fid,modelname) % {{{
@@ -58,4 +91,6 @@
 			writejs1Darray(fid,[modelname '.friction.p'],self.p);
 			writejs1Darray(fid,[modelname '.friction.q'],self.q);
+			writejs1Darray(fid,[modelname '.friction.coupling'],self.coupling);
+			writejs1Darray(fid,[modelname '.friction.effective_pressure'],self.effective_pressure);
 
 		end % }}}
Index: /issm/trunk/src/m/classes/friction.py
===================================================================
--- /issm/trunk/src/m/classes/friction.py	(revision 22757)
+++ /issm/trunk/src/m/classes/friction.py	(revision 22758)
@@ -1,2 +1,3 @@
+import numpy as np
 from fielddisplay import fielddisplay
 from project3d import project3d
@@ -16,5 +17,6 @@
 		self.p           = float('NaN')
 		self.q           = float('NaN')
-
+                self.coupling  	 = 0
+                self.effective_pressure	= float('NaN')
 		#set defaults
 		self.setdefaultparameters()
@@ -22,9 +24,11 @@
 		#}}}
 	def __repr__(self): # {{{
-		string="Basal shear stress parameters: Sigma_b = coefficient^2 * Neff ^r * |u_b|^(s-1) * u_b,\n(effective stress Neff=rho_ice*g*thickness+rho_water*g*bed, r=q/p and s=1/p)"
+		string="Basal shear stress parameters: Sigma_b = coefficient^2 * Neff ^r * |u_b|^(s-1) * u_b,\n(effective stress Neff=rho_ice*g*thickness+rho_water*g*base, r=q/p and s=1/p)"
 
 		string="%s\n%s"%(string,fielddisplay(self,"coefficient","friction coefficient [SI]"))
 		string="%s\n%s"%(string,fielddisplay(self,"p","p exponent"))
 		string="%s\n%s"%(string,fielddisplay(self,"q","q exponent"))
+		string="%s\n%s"%(string,fielddisplay(self,'coupling','Coupling flag: 0 for default, 1 for forcing(provide md.friction.effective_pressure)  and 2 for coupled(not implemented yet)'))
+		string="%s\n%s"%(string,fielddisplay(self,'effective_pressure','Effective Pressure for the forcing if not coupled [Pa]'))
 		return string
 		#}}}
@@ -33,4 +37,11 @@
 		self.p=project3d(md,'vector',self.p,'type','element')
 		self.q=project3d(md,'vector',self.q,'type','element')
+		#if self.coupling==0: #doesnt work with empty loop, so just skip it?
+		if self.coupling==1:
+			self.effective_pressure=project3d(md,'vector',self.effective_pressure,'type','node','layer',1)
+		elif self.coupling==2:
+			raise ValueError('coupling not supported yet')
+		elif self.coupling > 2:
+			raise ValueError('md.friction.coupling larger than 2, not supported yet')	
 		return self
 	#}}}
@@ -47,5 +58,11 @@
 		md = checkfield(md,'fieldname','friction.q','NaN',1,'Inf',1,'size',[md.mesh.numberofelements])
 		md = checkfield(md,'fieldname','friction.p','NaN',1,'Inf',1,'size',[md.mesh.numberofelements])
-
+		md = checkfield(md,'fieldname','friction.coupling','numel',[1],'values',[0,1,2])
+		if self.coupling==1:
+			md = checkfield(md,'fieldname','friction.effective_pressure','NaN',1,'Inf',1,'timeseries',1)
+		elif self.coupling==2:
+			raise ValueError('coupling not supported yet')
+		elif self.coupling > 2:
+			raise ValueError('md.friction.coupling larger than 2, not supported yet')
 		return md
 	# }}}
@@ -55,3 +72,10 @@
 		WriteData(fid,prefix,'object',self,'fieldname','p','format','DoubleMat','mattype',2)
 		WriteData(fid,prefix,'object',self,'fieldname','q','format','DoubleMat','mattype',2)
+		WriteData(fid,prefix,'class','friction','object',self,'fieldname','coupling','format','Integer')
+		if self.coupling==1:
+			WriteData(fid,prefix,'class','friction','object',self,'fieldname','effective_pressure','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
+		elif self.coupling==2:
+			raise ValueError('coupling not supported yet')
+		elif self.coupling > 2:
+			raise ValueError('md.friction.coupling larger than 2, not supported yet')			
 	# }}}
Index: /issm/trunk/src/m/classes/frictioncoulomb.m
===================================================================
--- /issm/trunk/src/m/classes/frictioncoulomb.m	(revision 22757)
+++ /issm/trunk/src/m/classes/frictioncoulomb.m	(revision 22758)
@@ -10,4 +10,6 @@
 		q                  = NaN;
 		coefficientcoulomb = NaN;
+		coupling	= 0;
+		effective_pressure = NaN;
 	end
 	methods
@@ -17,4 +19,13 @@
 			self.p=project3d(md,'vector',self.p,'type','element');
 			self.q=project3d(md,'vector',self.q,'type','element');
+			switch self.coupling
+				case 0
+				case 1
+					self.effective_pressure=project3d(md,'vector',self.effective_pressure,'type','node','layer',1);
+				case 2
+					error('not implemented yet');
+				otherwise
+					error('not supported yet');		
+			end
 		end % }}}
 		function self = frictioncoulomb(varargin) % {{{
@@ -37,4 +48,14 @@
 			md = checkfield(md,'fieldname','friction.q','NaN',1,'Inf',1,'size',[md.mesh.numberofelements 1]);
 			md = checkfield(md,'fieldname','friction.p','NaN',1,'Inf',1,'size',[md.mesh.numberofelements 1]);
+			md = checkfield(md,'fieldname','friction.coupling','numel',[1],'values',[0 1 2]);
+			switch self.coupling
+				case 0
+				case 1
+					md = checkfield(md,'fieldname','friction.effective_pressure','NaN',1,'Inf',1,'timeseries',1);
+				case 2
+					error('not implemented yet');
+				otherwise
+					error('not supported yet');		
+			end
 		end % }}}
 		function disp(self) % {{{
@@ -44,4 +65,6 @@
 			fielddisplay(self,'p','p exponent');
 			fielddisplay(self,'q','q exponent');
+			fielddisplay(self,'effective_pressure','Effective Pressure for the forcing if not coupled [Pa]');
+			fielddisplay(self,'coupling','Coupling flag: 0 for default, 1 for forcing(provide md.friction.effective_pressure)  and 2 for coupled(not implemented yet)');
 		end % }}}
 		function marshall(self,prefix,md,fid) % {{{
@@ -52,4 +75,14 @@
 			WriteData(fid,prefix,'object',self,'fieldname','p','format','DoubleMat','mattype',2);
 			WriteData(fid,prefix,'object',self,'fieldname','q','format','DoubleMat','mattype',2);
+			WriteData(fid,prefix,'class','friction','object',self,'fieldname','coupling','format','Integer');
+			switch self.coupling
+				case 0
+				case 1
+					WriteData(fid,prefix,'class','friction','object',self,'fieldname','effective_pressure','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
+				case 2
+					error('not implemented yet');
+				otherwise
+					error('not supported yet');		
+			end
 
 		end % }}}
Index: /issm/trunk/src/m/classes/frictioncoulomb.py
===================================================================
--- /issm/trunk/src/m/classes/frictioncoulomb.py	(revision 22757)
+++ /issm/trunk/src/m/classes/frictioncoulomb.py	(revision 22758)
@@ -17,5 +17,6 @@
         self.p = float('NaN')
 	self.q = float('NaN')
-
+	self.coupling  	 = 0
+	self.effective_pressure	= float('NaN')
 	#set defaults
 	self.setdefaultparameters()
@@ -29,4 +30,6 @@
 	string="%s\n%s"%(string,fielddisplay(self,"p","p exponent"))
 	string="%s\n%s"%(string,fielddisplay(self,"q","q exponent"))
+	string="%s\n%s"%(string,fielddisplay(self,'coupling','Coupling flag: 0 for default, 1 for forcing(provide md.friction.effective_pressure)  and 2 for coupled(not implemented yet)'))
+	string="%s\n%s"%(string,fielddisplay(self,'effective_pressure','Effective Pressure for the forcing if not coupled [Pa]'))
 	return string
     #}}}
@@ -36,4 +39,10 @@
 	self.p=project3d(md,'vector',self.p,'type','element')
 	self.q=project3d(md,'vector',self.q,'type','element')
+	if self.coupling==1:
+		self.effective_pressure=project3d(md,'vector',self.effective_pressure,'type','node','layer',1)
+	elif self.coupling==2:
+		raise ValueError('coupling not supported yet')
+	elif self.coupling > 2:
+		raise ValueError('md.friction.coupling larger than 2, not supported yet')	
 	return self
     #}}}
@@ -51,6 +60,12 @@
 	md = checkfield(md,'fieldname','friction.q','NaN',1,'Inf',1,'size',[md.mesh.numberofelements])
 	md = checkfield(md,'fieldname','friction.p','NaN',1,'Inf',1,'size',[md.mesh.numberofelements])
+	if self.coupling==1:
+		md = checkfield(md,'fieldname','friction.effective_pressure','NaN',1,'Inf',1,'timeseries',1)
+	elif self.coupling==2:
+		raise ValueError('coupling not supported yet')
+	elif self.coupling > 2:
+		raise ValueError('md.friction.coupling larger than 2, not supported yet')
+	return md
 
-	return md
     # }}}
     def marshall(self,prefix,md,fid):    # {{{
@@ -60,3 +75,10 @@
 	WriteData(fid,prefix,'object',self,'fieldname','p','format','DoubleMat','mattype',2)
 	WriteData(fid,prefix,'object',self,'fieldname','q','format','DoubleMat','mattype',2)
+	WriteData(fid,prefix,'class','friction','object',self,'fieldname','coupling','format','Integer')
+	if self.coupling==1:
+		WriteData(fid,prefix,'class','friction','object',self,'fieldname','effective_pressure','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
+	elif self.coupling==2:
+		raise ValueError('coupling not supported yet')
+	elif self.coupling > 2:
+		raise ValueError('md.friction.coupling larger than 2, not supported yet')	
     # }}}
Index: /issm/trunk/src/m/classes/frictionhydro.m
===================================================================
--- /issm/trunk/src/m/classes/frictionhydro.m	(revision 22757)
+++ /issm/trunk/src/m/classes/frictionhydro.m	(revision 22758)
@@ -6,5 +6,5 @@
 classdef frictionhydro
 	properties (SetAccess=public) 
-		Coupling           = 0;
+		coupling           = 0;
 		q                  = NaN;
 		C                  = NaN;
@@ -28,10 +28,17 @@
 			%Early return
 			if ~ismember('StressbalanceAnalysis',analyses) & ~ismember('ThermalAnalysis',analyses), return; end
-			md = checkfield(md,'fieldname','friction.Coupling','numel',[1],'values',[0 1]);
+			md = checkfield(md,'fieldname','friction.coupling','numel',[1],'values',[0 1 2]);
 			md = checkfield(md,'fieldname','friction.q','NaN',1,'Inf',1,'size',[md.mesh.numberofelements 1]);
 			md = checkfield(md,'fieldname','friction.C','NaN',1,'Inf',1,'size',[md.mesh.numberofelements 1]);
 			md = checkfield(md,'fieldname','friction.As','NaN',1,'Inf',1,'size',[md.mesh.numberofelements 1]);
-			if self.Coupling==0,
-				md = checkfield(md,'fieldname','friction.effective_pressure','NaN',1,'Inf',1,'timeseries',1);
+			switch self.coupling
+				case 0
+				case 1
+					md = checkfield(md,'fieldname','friction.effective_pressure','NaN',1,'Inf',1,'timeseries',1);
+				case 2
+					error('not implemented yet');
+				otherwise
+					error('not supported yet');		
+			end
 	    end
 		end % }}}
@@ -40,11 +47,17 @@
 			self.C=project3d(md,'vector',self.C,'type','element');
 			self.As=project3d(md,'vector',self.As,'type','element');
-			if self.Coupling==0,
-				self.effective_pressure=project3d(md,'vector',self.effective_pressure,'type','node','layer',1);
+			switch self.coupling
+				case 0
+				case 1
+					self.effective_pressure=project3d(md,'vector',self.effective_pressure,'type','node','layer',1);
+				case 2
+					error('not implemented yet');
+				otherwise
+					error('not supported yet');		
 			end
 	  end % }}}
 		function disp(self) % {{{
 			disp(sprintf('Effective Pressure based friction law described in Gagliardini 2007'));
-			fielddisplay(self,'Coupling','Coupling flag, 1 for coupling and 0 for forcing');
+			fielddisplay(self,'coupling','Coupling flag: 0 for default, 1 for forcing(provide md.friction.effective_pressure)  and 2 for coupled(not implemented yet)');
 			fielddisplay(self,'q','friction law exponent q>=1');
 			fielddisplay(self,'C','friction law max value [SI]');
@@ -54,10 +67,16 @@
 		function marshall(self,prefix,md,fid) % {{{
 			WriteData(fid,prefix,'name','md.friction.law','data',3,'format','Integer');
-			WriteData(fid,prefix,'class','friction','object',self,'fieldname','Coupling','format','Integer');
+			WriteData(fid,prefix,'class','friction','object',self,'fieldname','coupling','format','Integer');
 			WriteData(fid,prefix,'class','friction','object',self,'fieldname','q','format','DoubleMat','mattype',2);
 			WriteData(fid,prefix,'class','friction','object',self,'fieldname','C','format','DoubleMat','mattype',2);
 			WriteData(fid,prefix,'class','friction','object',self,'fieldname','As','format','DoubleMat','mattype',2);
-			if self.Coupling==0,
-				WriteData(fid,prefix,'class','friction','object',self,'fieldname','effective_pressure','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
+			switch self.coupling
+				case 0
+				case 1
+					WriteData(fid,prefix,'class','friction','object',self,'fieldname','effective_pressure','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
+				case 2
+					error('not implemented yet');
+				otherwise
+					error('not supported yet');		
 			end
 	  end % }}}
Index: /issm/trunk/src/m/classes/frictionhydro.py
===================================================================
--- /issm/trunk/src/m/classes/frictionhydro.py	(revision 22758)
+++ /issm/trunk/src/m/classes/frictionhydro.py	(revision 22758)
@@ -0,0 +1,93 @@
+import numpy as np
+from project3d import project3d
+from fielddisplay import fielddisplay
+from checkfield import checkfield
+from WriteData import WriteData
+
+
+class frictionhydro(object):
+	"""
+	FRICTIONWEERTMAN class definition
+
+	Usage:
+		friction=frictionhydro();
+	"""
+	def __init__(self): # {{{
+		self.coupling  		  		= 0
+		self.q    				= float('NaN')
+		self.C    				= float('NaN')
+		self.As    				= float('NaN')
+		self.effective_pressure			= float('NaN')
+		#set defaults
+		self.setdefaultparameters()
+	#}}}
+
+		#what is this:
+		#function self = frictionhydro(varargin) % {{{
+		#	switch nargin
+		#		case 0
+		#			self=setdefaultparameters(self);
+		#		otherwise
+		#			error('constructor not supported');
+		#	end
+		#end % }}}
+		
+	def checkconsistency(self,md,solution,analyses): #{{{ 
+
+		#Early return
+		if 'StressbalanceAnalysis' in analyses and 'ThermalAnalysis' in analyses:
+			return md
+		
+		md = checkfield(md,'fieldname','friction.coupling','numel',[1],'values',[0,1,2])
+		md = checkfield(md,'fieldname','friction.q','NaN',1,'Inf',1,'size',[md.mesh.numberofelements,1])
+		md = checkfield(md,'fieldname','friction.C','NaN',1,'Inf',1,'size',[md.mesh.numberofelements,1])
+		md = checkfield(md,'fieldname','friction.As','NaN',1,'Inf',1,'size',[md.mesh.numberofelements,1])
+		if self.coupling==1:
+			md = checkfield(md,'fieldname','friction.effective_pressure','NaN',1,'Inf',1,'timeseries',1)
+		elif self.coupling==2:
+			raise ValueError('coupling not supported yet')
+		elif self.coupling > 2:
+			raise ValueError('md.friction.coupling larger than 2, not supported yet')
+	# }}}
+
+	def extrude(self,md): # {{{
+		self.q=project3d(md,'vector',self.q,'type','element')
+		self.C=project3d(md,'vector',self.C,'type','element')
+		self.As=project3d(md,'vector',self.As,'type','element')
+		if self.coupling==1:
+			self.effective_pressure=project3d(md,'vector',self.effective_pressure,'type','node','layer',1)
+		elif self.coupling==2:
+			raise ValueError('coupling not supported yet')
+		elif self.coupling > 2:
+			raise ValueError('md.friction.coupling larger than 2, not supported yet')		
+		return self	
+	 # }}} 
+
+
+	def __repr__(self): # {{{
+		string='Effective Pressure based friction law described in Gagliardini 2007'
+		string="%s\n%s"%(string,fielddisplay(self,'coupling','Coupling flag: 0 for default, 1 for forcing(provide md.friction.effective_pressure)  and 2 for coupled(not implemented yet)'))
+		string="%s\n%s"%(string,fielddisplay(self,'q','friction law exponent q>=1'))
+		string="%s\n%s"%(string,fielddisplay(self,'C','friction law max value [SI]'))
+		string="%s\n%s"%(string,fielddisplay(self,'As','Sliding Parameter without cavitation [m Pa^-n s^-1]'))
+		string="%s\n%s"%(string,fielddisplay(self,'effective_pressure','Effective Pressure for the forcing if not coupled [Pa]'))
+
+		return string
+	#}}}
+
+
+	def marshall(self,prefix,md,fid): #{{{
+		WriteData(fid,prefix,'name','md.friction.law','data',3,'format','Integer')
+		WriteData(fid,prefix,'class','friction','object',self,'fieldname','coupling','format','Integer')
+		WriteData(fid,prefix,'class','friction','object',self,'fieldname','q','format','DoubleMat','mattype',2)
+		WriteData(fid,prefix,'class','friction','object',self,'fieldname','C','format','DoubleMat','mattype',2)
+		WriteData(fid,prefix,'class','friction','object',self,'fieldname','As','format','DoubleMat','mattype',2)
+		if self.coupling==1:
+			WriteData(fid,prefix,'class','friction','object',self,'fieldname','effective_pressure','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
+		elif self.coupling==2:
+			raise ValueError('coupling not supported yet')
+		elif self.coupling > 2:
+			raise ValueError('md.friction.coupling larger than 2, not supported yet')
+	#}}}
+
+
Index: /issm/trunk/src/m/classes/frictionsommers.py
===================================================================
--- /issm/trunk/src/m/classes/frictionsommers.py	(revision 22758)
+++ /issm/trunk/src/m/classes/frictionsommers.py	(revision 22758)
@@ -0,0 +1,47 @@
+from fielddisplay import fielddisplay
+from project3d import project3d
+from checkfield import checkfield
+from WriteData import WriteData
+
+class frictionsommers(object):
+    """
+    FRICTIONSOMMERS class definition
+
+    Usage:
+        friction=frictionsommers()
+    """
+
+    def __init__(self,md): # {{{
+        self.coefficient = md.friction.coefficient
+	#set defaults
+	self.setdefaultparameters()
+
+    #}}}
+    def __repr__(self): # {{{
+	string="Basal shear stress parameters: Sigma_b = coefficient^2 * Neff * u_b\n(effective stress Neff=rho_ice*g*thickness+rho_water*g*(head-b))"
+
+	string="%s\n%s"%(string,fielddisplay(self,"coefficient","friction coefficient [SI]"))
+	return string
+    #}}}
+    def extrude(self,md): # {{{
+	self.coefficient=project3d(md,'vector',self.coefficient,'type','node','layer',1)	
+	return self
+    #}}}
+    def setdefaultparameters(self): # {{{
+	return self
+    #}}}
+    def checkconsistency(self,md,solution,analyses):    # {{{
+
+	#Early return
+	if 'StressbalanceAnalysis' not in analyses and 'ThermalAnalysis' not in analyses:
+	    return md
+
+	md = checkfield(md,'fieldname','friction.coefficient','timeseries',1,'NaN',1,'Inf',1)
+	return md
+
+    # }}}
+    def marshall(self,prefix,md,fid):    # {{{
+	yts=md.constants.yts
+	WriteData(fid,prefix,'name','md.friction.law','data',8,'format','Integer')
+	WriteData(fid,prefix,'object',self,'fieldname','coefficient','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)	
+    # }}}
Index: /issm/trunk/src/m/classes/frictionwaterlayer.py
===================================================================
--- /issm/trunk/src/m/classes/frictionwaterlayer.py	(revision 22758)
+++ /issm/trunk/src/m/classes/frictionwaterlayer.py	(revision 22758)
@@ -0,0 +1,67 @@
+import numpy as np
+from project3d import project3d
+from fielddisplay import fielddisplay
+from checkfield import checkfield
+from WriteData import WriteData
+
+
+class frictionwaterlayer(object):
+	"""
+	frictionwaterlayer class definition
+
+	Usage:
+		friction=frictionwaterlayer(md);
+	"""
+	def __init__(self,md): # {{{
+		self.coefficient  		  	= md.friction.coefficient
+		self.f    				= float('NaN')
+		self.p    				= md.friction.p
+		self.q    				= md.friction.q
+		self.water_layer    			= float('NaN')
+	#}}}
+		
+	def checkconsistency(self,md,solution,analyses): #{{{ 
+		#Early return
+		if ('StressbalanceAnalysis' not in analyses) and ('ThermalAnalysis' not in analyses):
+			return
+
+		md = checkfield(md,'fieldname','friction.coefficient','timeseries',1,'NaN',1,'Inf',1)
+		md = checkfield(md,'fieldname','friction.f','size',[1,1],'NaN',1,'Inf',1)
+		md = checkfield(md,'fieldname','friction.q','NaN',1,'Inf',1,'size',[md.mesh.numberofelements])
+		md = checkfield(md,'fieldname','friction.p','NaN',1,'Inf',1,'size',[md.mesh.numberofelements])
+		md = checkfield(md,'fieldname','thermal.spctemperature','Inf',1,'timeseries',1,'>=',0.)
+	# }}}
+
+	def extrude(self,md): # {{{
+		self.coefficient=project3d(md,'vector',self.coefficient,'type','node','layer',1)
+		self.p=project3d(md,'vector',self.p,'type','element')
+		self.q=project3d(md,'vector',self.q,'type','element')
+		self.water_layer=project3d(md,'vector',self.water_layer,'type','node','layer',1)
+		return self	
+	 # }}} 
+
+
+	def __repr__(self): # {{{
+		string='Basal shear stress parameters: tau_b = coefficient^2 * Neff ^r * |u_b|^(s-1) * u_b * 1/f(T)\n(effective stress Neff=rho_ice*g*thickness+rho_water*g*(bed+water_layer), r=q/p and s=1/p)'
+		string="%s\n%s"%(string,fielddisplay(self,'coefficient','frictiontemp coefficient [SI]'))
+		string="%s\n%s"%(string,fielddisplay(self,'f','f variable for effective pressure'))
+		string="%s\n%s"%(string,fielddisplay(self,'p','p exponent'))
+		string="%s\n%s"%(string,fielddisplay(self,'q','q exponent'))
+		string="%s\n%s"%(string,fielddisplay(self,'water_layer','water thickness at the base of the ice (m)'))
+
+		return string
+	#}}}
+
+
+	def marshall(self,prefix,md,fid): #{{{
+		yts=md.constants.yts
+		
+		WriteData(fid,prefix,'name','md.friction.law','data',5,'format','Integer')
+		WriteData(fid,prefix,'class','friction','object',self,'fieldname','coefficient','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
+		WriteData(fid,prefix,'class','friction','object',self,'fieldname','f','format','Double')
+		WriteData(fid,prefix,'class','friction','object',self,'fieldname','p','format','DoubleMat','mattype',2)
+		WriteData(fid,prefix,'class','friction','object',self,'fieldname','q','format','DoubleMat','mattype',2)
+		WriteData(fid,prefix,'class','friction','object',self,'fieldname','water_layer','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
+	#}}}
+
+
Index: /issm/trunk/src/m/classes/geometry.m
===================================================================
--- /issm/trunk/src/m/classes/geometry.m	(revision 22757)
+++ /issm/trunk/src/m/classes/geometry.m	(revision 22758)
@@ -55,4 +55,6 @@
 			if (strcmp(solution,'TransientSolution') & md.transient.isgia) | strcmp(solution,'GiaSolution'),
 				md = checkfield(md,'fieldname','geometry.thickness','timeseries',1,'NaN',1,'Inf',1,'>=',0);
+			elseif strcmpi(solution,'LoveSolution')
+				return; 
 			else
 				md = checkfield(md,'fieldname','geometry.surface'  ,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices 1]);
Index: /issm/trunk/src/m/classes/geometry.py
===================================================================
--- /issm/trunk/src/m/classes/geometry.py	(revision 22757)
+++ /issm/trunk/src/m/classes/geometry.py	(revision 22758)
@@ -47,4 +47,6 @@
 		if (solution=='TransientSolution' and md.transient.isgia) or (solution=='GiaSolution'):
 			md = checkfield(md,'fieldname','geometry.thickness','NaN',1,'Inf',1,'>=',0,'timeseries',1)
+		elif solution=='LoveSolution':
+			return
 		else:
 			md = checkfield(md,'fieldname','geometry.surface'  ,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
Index: /issm/trunk/src/m/classes/hydrologydc.m
===================================================================
--- /issm/trunk/src/m/classes/hydrologydc.m	(revision 22757)
+++ /issm/trunk/src/m/classes/hydrologydc.m	(revision 22758)
@@ -12,9 +12,12 @@
 		rel_tol                  = 0;
 		max_iter                 = 0;
+    steps_per_step           = 0;
 		sedimentlimit_flag       = 0;
 		sedimentlimit            = 0;
 		transfer_flag            = 0;
+		unconfined_flag          = 0;
 		leakage_factor           = 0;
 		basal_moulin_input       = NaN;
+    requested_outputs        = {};
 
 		spcsediment_head         = NaN;
@@ -58,4 +61,17 @@
 		end 
 		% }}}
+    function list = defaultoutputs(self,md) % {{{
+        list = {'SedimentHead','SedimentHeadResidual','EffectivePressure'};
+        if self.isefficientlayer,
+            list=[list,{'EplHead','HydrologydcMaskEplactiveNode','HydrologydcMaskEplactiveElt','EplHeadSlopeX','EplHeadSlopeY','HydrologydcEplThickness'}];
+        end
+        if self.steps_per_step>1,
+            list = [list,'EffectivePressureTimeAverage','SedimentHeadTimeAverage'];
+            if self.isefficientlayer,
+                list = [list,'EplHeadTimeAverage','HydrologydcEplThicknessTimeAverage'];
+            end
+        end
+    end % }}}    
+
 		function self = initialize(self,md) % {{{
 			if isnan(self.basal_moulin_input),
@@ -76,8 +92,12 @@
 			self.rel_tol                  = 1.0e-06;
 			self.max_iter                 = 100;
+			self.steps_per_step           = 1;
 			self.sedimentlimit_flag       = 0;
 			self.sedimentlimit            = 0;
 			self.transfer_flag            = 0;
+			self.unconfined_flag          = 0;
 			self.leakage_factor           = 10.0;
+      self.requested_outputs        = {'default'};
+
 
 			self.sediment_compressibility = 1.0e-08;
@@ -111,6 +131,9 @@
 			md = checkfield(md,'fieldname','hydrology.rel_tol','>',0,'numel',1);
 			md = checkfield(md,'fieldname','hydrology.max_iter','>',0,'numel',1);
+			md = checkfield(md,'fieldname','hydrology.steps_per_step','>',0,'numel',1);
 			md = checkfield(md,'fieldname','hydrology.sedimentlimit_flag','numel',[1],'values',[0 1 2 3]);
 			md = checkfield(md,'fieldname','hydrology.transfer_flag','numel',[1],'values',[0 1]);
+			md = checkfield(md,'fieldname','hydrology.unconfined_flag','numel',[1],'values',[0 1]);
+      md = checkfield(md,'fieldname','hydrology.requested_outputs','stringrow',1);
 			if self.sedimentlimit_flag==1,
 				md = checkfield(md,'fieldname','hydrology.sedimentlimit','>',0,'numel',1);
@@ -156,4 +179,5 @@
 			fielddisplay(self,'rel_tol','tolerance of the nonlinear iteration for the transfer between layers [dimensionless]');
 			fielddisplay(self,'max_iter','maximum number of nonlinear iteration');
+			fielddisplay(self,'steps_per_step','number of hydrology steps per timestep');
 			fielddisplay(self,'sedimentlimit_flag','what kind of upper limit is applied for the inefficient layer');
 			disp(sprintf('%55s  0: no limit',' '));
@@ -170,4 +194,8 @@
 				fielddisplay(self,'leakage_factor','user defined leakage factor [m]');
 			end
+			fielddisplay(self,'unconfined_flag',['Do you want unconfined scheme to be used (transitory)']);
+			disp(sprintf('%55s  0: confined only',' '));
+			disp(sprintf('%55s  1: confined unconfined'));
+      fielddisplay(self,'requested_outputs','additional outputs requested');
 			fielddisplay(self,'basal_moulin_input','water flux at a given point [m3 s-1]');
 			disp(sprintf('   - for the sediment layer'));
@@ -205,6 +233,8 @@
 			WriteData(fid,prefix,'object',self,'fieldname','rel_tol','format','Double');
 			WriteData(fid,prefix,'object',self,'fieldname','max_iter','format','Integer');
+			WriteData(fid,prefix,'object',self,'fieldname','steps_per_step','format','Integer');
 			WriteData(fid,prefix,'object',self,'fieldname','sedimentlimit_flag','format','Integer');
 			WriteData(fid,prefix,'object',self,'fieldname','transfer_flag','format','Integer');
+			WriteData(fid,prefix,'object',self,'fieldname','unconfined_flag','format','Integer');
 			if self.sedimentlimit_flag==1,
 				WriteData(fid,prefix,'object',self,'fieldname','sedimentlimit','format','Double');
@@ -233,4 +263,11 @@
 				WriteData(fid,prefix,'object',self,'fieldname','eplflip_lock','format','Integer');
 			end
+      outputs = self.requested_outputs;
+      pos  = find(ismember(outputs,'default'));
+      if ~isempty(pos),
+        outputs(pos) = [];  %remove 'default' from outputs
+        outputs      = [outputs defaultoutputs(self,md)]; %add defaults
+      end
+      WriteData(fid,prefix,'data',outputs,'name','md.hydrology.requested_outputs','format','StringArray');
 		end 
 
Index: /issm/trunk/src/m/classes/hydrologydc.py
===================================================================
--- /issm/trunk/src/m/classes/hydrologydc.py	(revision 22757)
+++ /issm/trunk/src/m/classes/hydrologydc.py	(revision 22758)
@@ -20,9 +20,12 @@
 		self.rel_tol                  = 0
 		self.max_iter                 = 0
+		self.steps_per_step           = 0
 		self.sedimentlimit_flag       = 0
 		self.sedimentlimit            = 0
 		self.transfer_flag            = 0
+		self.unconfined_flag          = 0
 		self.leakage_factor           = 0
 		self.basal_moulin_input       = float('NaN')
+		self.requested_outputs        = []
 
 		self.spcsediment_head         = float('NaN')
@@ -31,5 +34,4 @@
 		self.sediment_porosity        = 0
 		self.sediment_thickness       = 0
-
 
 		self.spcepl_head              = float('NaN')
@@ -56,5 +58,7 @@
 		string="%s\n%s"%(string,fielddisplay(self,'rel_tol','tolerance of the nonlinear iteration for the transfer between layers [dimensionless]'))
 		string="%s\n%s"%(string,fielddisplay(self,'max_iter','maximum number of nonlinear iteration'))
+		string="%s\n%s"%(string,fielddisplay(self,'steps_per_step','number of hydrology steps per time step')) 
 		string="%s\n%s"%(string,fielddisplay(self,'basal_moulin_input','water flux at a given point [m3 s-1]'))
+		string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','additional outputs requested'))
 		string="%s\n%s"%(string,fielddisplay(self,'sedimentlimit_flag','what kind of upper limit is applied for the inefficient layer'))
 		string="%s\n\t\t%s"%(string,'0: no limit')
@@ -73,4 +77,8 @@
 			string="%s\n%s"%(string,fielddisplay(self,'leakage_factor','user defined leakage factor [m]'))
 
+		string="%s\n%s"%(string,fielddisplay(self,'unconfined_flag','using an unconfined scheme or not (transitory)'))
+		string="%s\n\t\t%s"%(string,'0: Confined only')
+		string="%s\n\t\t%s"%(string,'1: Confined-Unconfined')
+			 
 		string="%s\n%s"%(string,'   - for the sediment layer')
 		string="%s\n%s"%(string,fielddisplay(self,'spcsediment_head','sediment water head constraints (NaN means no constraint) [m above MSL]'))
@@ -86,5 +94,5 @@
 			string="%s\n%s"%(string,fielddisplay(self,'epl_compressibility','epl compressibility [Pa^-1]'))
 			string="%s\n%s"%(string,fielddisplay(self,'epl_porosity','epl [dimensionless]'))
-			string="%s\n%s"%(string,fielddisplay(self,'epl_max_thickness','epl initial thickness [m]'))
+			string="%s\n%s"%(string,fielddisplay(self,'epl_max_thickness','epl maximal thickness [m]'))
 			string="%s\n%s"%(string,fielddisplay(self,'epl_initial_thickness','epl initial thickness [m]'))			
 			string="%s\n%s"%(string,fielddisplay(self,'epl_colapse_thickness','epl colapsing thickness [m]'))
@@ -104,5 +112,4 @@
 	#}}}
 	def setdefaultparameters(self): #{{{ 
-
 		#Parameters from de Fleurian 2014
 		self.water_compressibility    = 5.04e-10
@@ -112,8 +119,11 @@
 		self.rel_tol                  = 1.0e-06
 		self.max_iter                 = 100
+		self.steps_per_step           = 1
 		self.sedimentlimit_flag       = 0
 		self.sedimentlimit            = 0
 		self.transfer_flag            = 0
+		self.unconfined_flag          = 0
 		self.leakage_factor           = 10.0
+		self.requested_outputs        = ['default']
 
 		self.sediment_compressibility = 1.0e-08
@@ -133,4 +143,16 @@
 		return self
 	# }}}
+
+	def defaultoutputs(self,md): # {{{
+		list = ['SedimentHead','SedimentHeadResidual','EffectivePressure']
+		if self.isefficientlayer==1:
+			list.extend(['EplHead','HydrologydcMaskEplactiveNode','HydrologydcMaskEplactiveElt','EplHeadSlopeX','EplHeadSlopeY','HydrologydcEplThickness'])
+		if self.steps_per_step>1:
+			list.extend(['EffectivePressureTimeAverage','SedimentHeadTimeAverage'])
+			if self.isefficientlayer==1:
+				list.extend(['EplHeadTimeAverage','HydrologydcEplThicknessTimeAverage'])
+		return list
+	#}}}
+
 	def initialize(self,md): # {{{
 		if np.all(np.isnan(self.basal_moulin_input)):
@@ -152,6 +174,9 @@
 		md = checkfield(md,'fieldname','hydrology.rel_tol','>',0.,'numel',[1])
 		md = checkfield(md,'fieldname','hydrology.max_iter','>',0.,'numel',[1])
+		md = checkfield(md,'fieldname','hydrology.steps_per_step','>',0.,'numel',[1])
 		md = checkfield(md,'fieldname','hydrology.sedimentlimit_flag','numel',[1],'values',[0,1,2,3])
 		md = checkfield(md,'fieldname','hydrology.transfer_flag','numel',[1],'values',[0,1])
+		md = checkfield(md,'fieldname','hydrology.unconfined_flag','numel',[1],'values',[0,1])
+		md = checkfield(md,'fieldname','hydrology.requested_outputs','stringrow',1)
 
 		if self.sedimentlimit_flag==1:
@@ -189,6 +214,8 @@
 		WriteData(fid,prefix,'object',self,'fieldname','rel_tol','format','Double')
 		WriteData(fid,prefix,'object',self,'fieldname','max_iter','format','Integer')
+		WriteData(fid,prefix,'object',self,'fieldname','steps_per_step','format','Integer')
 		WriteData(fid,prefix,'object',self,'fieldname','sedimentlimit_flag','format','Integer')
 		WriteData(fid,prefix,'object',self,'fieldname','transfer_flag','format','Integer')
+		WriteData(fid,prefix,'object',self,'fieldname','unconfined_flag','format','Integer')
 		if self.sedimentlimit_flag==1:
 			WriteData(fid,prefix,'object',self,'fieldname','sedimentlimit','format','Double')
@@ -215,3 +242,11 @@
 			WriteData(fid,prefix,'object',self,'fieldname','epl_conductivity','format','Double')
 			WriteData(fid,prefix,'object',self,'fieldname','eplflip_lock','format','Integer')
-	# }}}
+
+		#process requested outputs
+		outputs = self.requested_outputs
+		indices = [i for i, x in enumerate(outputs) if x == 'default']
+		if len(indices) > 0:
+			outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:]
+			outputs    =outputscopy
+		WriteData(fid,prefix,'data',outputs,'name','md.hydrology.requested_outputs','format','StringArray')
+	# }}}
Index: /issm/trunk/src/m/classes/hydrologyshreve.js
===================================================================
--- /issm/trunk/src/m/classes/hydrologyshreve.js	(revision 22757)
+++ /issm/trunk/src/m/classes/hydrologyshreve.js	(revision 22758)
@@ -11,4 +11,7 @@
 		this.stabilization=1;
 
+		//default output
+		this.requested_outputs=['default'];
+
 	}// }}}
 		this.disp= function(){// {{{
@@ -17,4 +20,5 @@
 		fielddisplay(this,'spcwatercolumn','water thickness constraints (NaN means no constraint) [m]');
 		fielddisplay(this,'stabilization','artificial diffusivity (default is 1). can be more than 1 to increase diffusivity.');
+		fielddisplay(this,'requested_outputs','additional outputs requested');
 
 	}// }}}
@@ -37,4 +41,5 @@
 			checkfield(md,'fieldname','hydrology.spcwatercolumn','Inf',1,'timeseries',1);
 			checkfield(md,'fieldname','hydrology.stabilization','>=',0);
+			checkfield(md,'fieldname','hydrology.requested_outputs','stringrow',1);
 
 		} // }}}
@@ -43,4 +48,16 @@
 			WriteData(fid,prefix,'object',this,'fieldname','spcwatercolumn','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
 			WriteData(fid,prefix,'object',this,'fieldname','stabilization','format','Double');
+			var outputs = this.requested_outputs;
+			for (var i=0;i<outputs.length;i++){
+				if (outputs[i] == 'default') {
+					outputs.splice(i,1);
+					var newoutputs=this.defaultoutputs(md);
+					for (var j=0;j<newoutputs.length;j++) outputs.push(newoutputs[j]);
+				}
+			}
+			WriteData(fid,prefix,'data',outputs,'name','md.hydrology.requested_outputs','format','StringArray');
+		}//}}}
+		this.defaultoutputs = function(md) { //{{{
+				return ['Watercolumn','HydrologyWaterVx','HydrologyWaterVy'];
 		}//}}}
 		this.fix=function() { //{{{
@@ -51,4 +68,5 @@
 	this.spcwatercolumn = NaN;
 	this.stabilization  = 0;
+	this.requested_outputs = [];
 	this.setdefaultparameters();
 	//}}}
Index: /issm/trunk/src/m/classes/hydrologyshreve.m
===================================================================
--- /issm/trunk/src/m/classes/hydrologyshreve.m	(revision 22757)
+++ /issm/trunk/src/m/classes/hydrologyshreve.m	(revision 22758)
@@ -6,6 +6,7 @@
 classdef hydrologyshreve
 	properties (SetAccess=public) 
-		spcwatercolumn = NaN;
-		stabilization  = 0;
+		spcwatercolumn     = NaN;
+		stabilization      = 0;
+    requested_outputs  = {};
 	end
 	methods
@@ -22,8 +23,13 @@
 			end
 		end % }}}
+    function list = defaultoutputs(self,md) % {{{
+        list = {'Watercolumn','HydrologyWaterVx','HydrologyWaterVy'};
+    end % }}}    
+
 		function self = setdefaultparameters(self) % {{{
 
 			%Type of stabilization to use 0:nothing 1:artificial_diffusivity
-			self.stabilization=1;
+			self.stabilization     = 1;
+      self.requested_outputs = {'default'};
 		end % }}}
 		function md = checkconsistency(self,md,solution,analyses) % {{{
@@ -41,4 +47,5 @@
 			fielddisplay(self,'spcwatercolumn','water thickness constraints (NaN means no constraint) [m]');
 			fielddisplay(self,'stabilization','artificial diffusivity (default is 1). can be more than 1 to increase diffusivity.');
+      fielddisplay(self,'requested_outputs','additional outputs requested');
 
 		end % }}}
@@ -47,4 +54,11 @@
 			WriteData(fid,prefix,'object',self,'fieldname','spcwatercolumn','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
 			WriteData(fid,prefix,'object',self,'fieldname','stabilization','format','Double');
+      outputs = self.requested_outputs;
+      pos  = find(ismember(outputs,'default'));
+      if ~isempty(pos),
+        outputs(pos) = [];  %remove 'default' from outputs
+        outputs      = [outputs defaultoutputs(self,md)]; %add defaults
+      end
+      WriteData(fid,prefix,'data',outputs,'name','md.hydrology.requested_outputs','format','StringArray');
 		end % }}}
 		function savemodeljs(self,fid,modelname) % {{{
Index: /issm/trunk/src/m/classes/hydrologyshreve.py
===================================================================
--- /issm/trunk/src/m/classes/hydrologyshreve.py	(revision 22757)
+++ /issm/trunk/src/m/classes/hydrologyshreve.py	(revision 22758)
@@ -14,5 +14,5 @@
 		self.spcwatercolumn = float('NaN')
 		self.stabilization  = 0
-
+		self.requested_outputs = []
 		#set defaults
 		self.setdefaultparameters()
@@ -24,4 +24,5 @@
 		string="%s\n%s"%(string,fielddisplay(self,'spcwatercolumn','water thickness constraints (NaN means no constraint) [m]'))
 		string="%s\n%s"%(string,fielddisplay(self,'stabilization','artificial diffusivity (default is 1). can be more than 1 to increase diffusivity.'))
+		string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','additional outputs requested'))
 		return string
 		#}}}
@@ -33,7 +34,12 @@
 		#Type of stabilization to use 0:nothing 1:artificial_diffusivity
 		self.stabilization=1
-
+		self.requested_outputs= ['default']
 		return self
 	#}}}
+	def defaultoutputs(self,md): # {{{
+		list = ['Watercolumn','HydrologyWaterVx','HydrologyWaterVy']
+		return list
+	#}}}
+
 	def checkconsistency(self,md,solution,analyses):    # {{{
 		
@@ -44,5 +50,5 @@
 		md = checkfield(md,'fieldname','hydrology.spcwatercolumn','Inf',1,'timeseries',1)
 		md = checkfield(md,'fieldname','hydrology.stabilization','>=',0)
-
+		md = checkfield(md,'fieldname','hydrology.requested_outputs','stringrow',1)
 		return md
 	# }}}
@@ -51,3 +57,11 @@
 		WriteData(fid,prefix,'object',self,'fieldname','spcwatercolumn','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
 		WriteData(fid,prefix,'object',self,'fieldname','stabilization','format','Double')
+		#process requested outputs
+		outputs = self.requested_outputs
+		indices = [i for i, x in enumerate(outputs) if x == 'default']
+		if len(indices) > 0:
+			outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:]
+			outputs    =outputscopy
+		WriteData(fid,prefix,'data',outputs,'name','md.hydrology.requested_outputs','format','StringArray')
+
 	# }}}
Index: /issm/trunk/src/m/classes/hydrologysommers.m
===================================================================
--- /issm/trunk/src/m/classes/hydrologysommers.m	(revision 22757)
+++ /issm/trunk/src/m/classes/hydrologysommers.m	(revision 22758)
@@ -17,4 +17,5 @@
 		relaxation      = 0;
 		storage         = 0;
+    requested_outputs = {};
 	end
 	methods
@@ -31,8 +32,13 @@
 			end
 		end % }}}
+    function list = defaultoutputs(self,md) % {{{
+        list = {'HydrologyHead','HydrologyGapHeight','EffectivePressure','HydrologyBasalFlux','DegreeOfChannelization'};
+    end % }}}    
+
 		function self = setdefaultparameters(self) % {{{
 	      % Set under-relaxation parameter to be 1 (no under-relaxation of nonlinear iteration)	
 			self.relaxation=1;
 			self.storage=0;
+      self.requested_outputs={'default'};
 		end % }}}
 		function md = checkconsistency(self,md,solution,analyses) % {{{
@@ -54,4 +60,5 @@
          md = checkfield(md,'fieldname','hydrology.relaxation','>=',0);	
 			md = checkfield(md,'fieldname','hydrology.storage','>=',0);
+      md = checkfield(md,'fieldname','hydrology.requested_outputs','stringrow',1);
 		end % }}}
 		function disp(self) % {{{
@@ -68,4 +75,5 @@
 			fielddisplay(self,'relaxation','under-relaxation coefficient for nonlinear iteration');
 			fielddisplay(self,'storage','englacial storage coefficient (void ratio)');
+      fielddisplay(self,'requested_outputs','additional outputs requested');
 		end % }}}
 		function marshall(self,prefix,md,fid) % {{{
@@ -83,6 +91,13 @@
 			WriteData(fid,prefix,'object',self,'class','hydrology','fieldname','neumannflux','format','DoubleMat','mattype',2,'timeserieslength',md.mesh.numberofelements+1,'yts',md.constants.yts);
 			WriteData(fid,prefix,'object',self,'class','hydrology','fieldname','spchead','format','DoubleMat','mattype',1);
-         WriteData(fid,prefix,'object',self,'class','hydrology','fieldname','relaxation','format','Double');
+      WriteData(fid,prefix,'object',self,'class','hydrology','fieldname','relaxation','format','Double');
 			WriteData(fid,prefix,'object',self,'class','hydrology','fieldname','storage','format','Double');
+      outputs = self.requested_outputs;
+      pos  = find(ismember(outputs,'default'));
+      if ~isempty(pos),
+        outputs(pos) = [];  %remove 'default' from outputs
+        outputs      = [outputs defaultoutputs(self,md)]; %add defaults
+      end
+      WriteData(fid,prefix,'data',outputs,'name','md.hydrology.requested_outputs','format','StringArray');
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/hydrologysommers.py
===================================================================
--- /issm/trunk/src/m/classes/hydrologysommers.py	(revision 22758)
+++ /issm/trunk/src/m/classes/hydrologysommers.py	(revision 22758)
@@ -0,0 +1,106 @@
+from fielddisplay import fielddisplay
+from checkfield import checkfield
+from WriteData import WriteData
+
+class hydrologysommers(object):
+	"""
+	HYDROLOGYSOMMERS class definition
+
+	   Usage:
+	      hydrologysommers=hydrologysommers()
+	"""
+
+	def __init__(self): # {{{
+		self.head            = float('NaN')
+		self.gap_height      = float('NaN')
+		self.bump_spacing    = float('NaN')
+		self.bump_height     = float('NaN')
+		self.englacial_input = float('NaN')
+		self.moulin_input    = float('NaN')
+		self.reynolds        = float('NaN')
+		self.spchead         = float('NaN')
+		self.neumannflux     = float('NaN')
+		self.relaxation      = 0
+		self.storage         = 0
+		self.requested_outputs = []
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		
+		string='   hydrologysommers solution parameters:'
+		string="%s\n%s"%(string,fielddisplay(self,'head','subglacial hydrology water head (m)'))
+		string="%s\n%s"%(string,fielddisplay(self,'gap_height','height of gap separating ice to bed (m)'))
+		string="%s\n%s"%(string,fielddisplay(self,'bump_spacing','characteristic bedrock bump spacing (m)'))
+		string="%s\n%s"%(string,fielddisplay(self,'bump_height','characteristic bedrock bump height (m)'))
+		string="%s\n%s"%(string,fielddisplay(self,'englacial_input','liquid water input from englacial to subglacial system (m/yr)'))
+		string="%s\n%s"%(string,fielddisplay(self,'moulin_input','liquid water input from moulins (at the vertices) to subglacial system (m^3/s)'))
+		string="%s\n%s"%(string,fielddisplay(self,'reynolds','Reynolds'' number'))
+		string="%s\n%s"%(string,fielddisplay(self,'neumannflux','water flux applied along the model boundary (m^2/s)'))
+		string="%s\n%s"%(string,fielddisplay(self,'spchead','water head constraints (NaN means no constraint) (m)'))
+		string="%s\n%s"%(string,fielddisplay(self,'relaxation','under-relaxation coefficient for nonlinear iteration'))
+		string="%s\n%s"%(string,fielddisplay(self,'storage','englacial storage coefficient (void ratio)'))
+		string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','additional outputs requested'))
+		return string
+		#}}}
+	def extrude(self,md): # {{{
+		return self
+	#}}}
+	def setdefaultparameters(self): # {{{
+		# Set under-relaxation parameter to be 1 (no under-relaxation of nonlinear iteration)	
+		self.relaxation=1
+		self.storage=0
+		self.requested_outputs=['default']
+		return self
+	#}}}
+	def defaultoutputs(self,md): # {{{
+		list = ['HydrologyHead','HydrologyGapHeight','EffectivePressure','HydrologyBasalFlux','DegreeOfChannelization']
+		return list
+	#}}}
+
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		
+		#Early return
+		if 'HydrologySommersAnalysis' not in analyses:
+			return md
+
+		md = checkfield(md,'fieldname','hydrology.head','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1)
+		md = checkfield(md,'fieldname','hydrology.gap_height','>=',0,'size',[md.mesh.numberofelements],'NaN',1,'Inf',1)
+		md = checkfield(md,'fieldname','hydrology.bump_spacing','>',0,'size',[md.mesh.numberofelements],'NaN',1,'Inf',1)
+		md = checkfield(md,'fieldname','hydrology.bump_height','>=',0,'size',[md.mesh.numberofelements],'NaN',1,'Inf',1)
+		md = checkfield(md,'fieldname','hydrology.englacial_input','>=',0,'NaN',1,'Inf',1,'timeseries',1)
+		md = checkfield(md,'fieldname','hydrology.moulin_input','>=',0,'NaN',1,'Inf',1,'timeseries',1)
+		md = checkfield(md,'fieldname','hydrology.reynolds','>',0,'size',[md.mesh.numberofelements],'NaN',1,'Inf',1)
+		md = checkfield(md,'fieldname','hydrology.neumannflux','timeseries',1,'NaN',1,'Inf',1)
+		md = checkfield(md,'fieldname','hydrology.spchead','size',[md.mesh.numberofvertices])
+         	md = checkfield(md,'fieldname','hydrology.relaxation','>=',0)	
+		md = checkfield(md,'fieldname','hydrology.storage','>=',0)
+		md = checkfield(md,'fieldname','hydrology.requested_outputs','stringrow',1)
+
+		return md
+	# }}}
+	def marshall(self,prefix,md,fid):    # {{{
+		yts=md.constants.yts
+
+		WriteData(fid,prefix,'name','md.hydrology.model','data',3,'format','Integer')
+		WriteData(fid,prefix,'object',self,'class','hydrology','fieldname','head','format','DoubleMat','mattype',1)
+		WriteData(fid,prefix,'object',self,'class','hydrology','fieldname','gap_height','format','DoubleMat','mattype',2)
+		WriteData(fid,prefix,'object',self,'class','hydrology','fieldname','bump_spacing','format','DoubleMat','mattype',2)
+		WriteData(fid,prefix,'object',self,'class','hydrology','fieldname','bump_height','format','DoubleMat','mattype',2)
+		WriteData(fid,prefix,'object',self,'class','hydrology','fieldname','englacial_input','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
+		WriteData(fid,prefix,'object',self,'class','hydrology','fieldname','moulin_input','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
+		WriteData(fid,prefix,'object',self,'class','hydrology','fieldname','reynolds','format','DoubleMat','mattype',2)
+		WriteData(fid,prefix,'object',self,'class','hydrology','fieldname','neumannflux','format','DoubleMat','mattype',2,'timeserieslength',md.mesh.numberofelements+1,'yts',md.constants.yts)
+		WriteData(fid,prefix,'object',self,'class','hydrology','fieldname','spchead','format','DoubleMat','mattype',1)
+		WriteData(fid,prefix,'object',self,'class','hydrology','fieldname','relaxation','format','Double')
+		WriteData(fid,prefix,'object',self,'class','hydrology','fieldname','storage','format','Double')
+		#process requested outputs
+		outputs = self.requested_outputs
+		indices = [i for i, x in enumerate(outputs) if x == 'default']
+		if len(indices) > 0:
+			outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:]
+			outputs    =outputscopy
+		WriteData(fid,prefix,'data',outputs,'name','md.hydrology.requested_outputs','format','StringArray')
+	# }}}
Index: /issm/trunk/src/m/classes/independent.m
===================================================================
--- /issm/trunk/src/m/classes/independent.m	(revision 22757)
+++ /issm/trunk/src/m/classes/independent.m	(revision 22758)
@@ -6,9 +6,15 @@
 classdef independent
 	properties (SetAccess=public) 
-		name                 = '';
-		type                 = '';
-		fos_forward_index    = NaN;
-		fov_forward_indices  = [];
-		nods                 = 0;
+		name			               = '';
+		md_name							= '';
+		type					         = '';
+		fos_forward_index			   = NaN;
+		fov_forward_indices			= [];
+		nods								= 0;
+		min_parameters					= NaN;
+		max_parameters					= NaN;
+		control_scaling_factor     = NaN;
+		control_size					= 0;
+
 	end
 	methods
@@ -20,4 +26,5 @@
 			%OK get other fields
 			self=AssignObjectFields(pairoptions(varargin{:}),self);
+
 
 		end
@@ -45,7 +52,11 @@
 				end
 				md = checkfield(md,'fieldname',['autodiff.independents{' num2str(i) '}.fov_forward_indices'],'>=',1,'<=',self.nods,'size',[NaN 1]);
+				%md = checkfield(md,'fieldname',['autodiff.independents{' num2str(i) '}.min_parameters'],'size',[md.mesh.numberofvertices 1]);
+				%md = checkfield(md,'fieldname',['autodiff.independents{' num2str(i) '}.max_parameters'],'size',[md.mesh.numberofvertices 1]);
+				%md = checkfield(md,'fieldname',['autodiff.independents{' num2str(i) '}.control_scaling_factors'],'size',[1 1],'>',0,'NaN',1,'Inf',1);
+
 			end
+		end % }}}
 
-		end % }}}
 		function disp(self) % {{{
 			disp(sprintf('   independent variable:'));
@@ -54,4 +65,8 @@
 			fielddisplay(self,'type','type of variable (''vertex'' or ''scalar'')');
 			fielddisplay(self,'nods','size of dependent variables');
+			fielddisplay(self,'control_size','number of timesteps');
+			fielddisplay(self,'min_parameters','absolute minimum acceptable value of the inversed parameter on each vertex');
+			fielddisplay(self,'max_parameters','absolute maximum acceptable value of the inversed parameter on each vertex');
+			fielddisplay(self,'control_scaling_factor','order of magnitude of each control (useful for multi-parameter optimization)');
 			if ~isnan(self.fos_forward_index),
 				fielddisplay(self,'fos_forward_index','index for fos_foward driver of ADOLC');
Index: /issm/trunk/src/m/classes/inversion.js
===================================================================
--- /issm/trunk/src/m/classes/inversion.js	(revision 22757)
+++ /issm/trunk/src/m/classes/inversion.js	(revision 22758)
@@ -81,11 +81,11 @@
         this.thickness_obs=project3d(md,'vector',this.thickness_obs,'type','node');
 
-        if (numel(this.cost_functions_coefficients)>1) {
+        if (this.cost_functions_coefficients.length>1) {
             this.cost_functions_coefficients=project3d(md,'vector',this.cost_functions_coefficients,'type','node');
         }			
-        if (numel(this.min_parameters)>1) {
+        if (this.min_parameters.length>1) {
             this.min_parameters=project3d(md,'vector',this.min_parameters,'type','node');
         }
-        if (numel(this.max_parameters)>1) {
+        if (this.max_parameters.length>1) {
             this.max_parameters=project3d(md,'vector',this.max_parameters,'type','node');
         }
Index: /issm/trunk/src/m/classes/inversion.m
===================================================================
--- /issm/trunk/src/m/classes/inversion.m	(revision 22757)
+++ /issm/trunk/src/m/classes/inversion.m	(revision 22758)
@@ -155,4 +155,5 @@
 			WriteData(fid,prefix,'object',self,'fieldname','iscontrol','format','Boolean');
 			WriteData(fid,prefix,'object',self,'fieldname','incomplete_adjoint','format','Boolean');
+			WriteData(fid,prefix,'object',self,'fieldname','vel_obs','format','DoubleMat','mattype',1,'scale',1./yts);
 			if ~self.iscontrol, return; end
 			WriteData(fid,prefix,'object',self,'fieldname','nsteps','format','Integer');
Index: /issm/trunk/src/m/classes/inversionvalidation.m
===================================================================
--- /issm/trunk/src/m/classes/inversionvalidation.m	(revision 22757)
+++ /issm/trunk/src/m/classes/inversionvalidation.m	(revision 22758)
@@ -125,4 +125,5 @@
 			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts);
 			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','vel_obs','format','DoubleMat','mattype',1,'scale',1./yts);
 			if(numel(self.thickness_obs)==md.mesh.numberofelements),
 				mattype=2; 
Index: /issm/trunk/src/m/classes/issmsettings.js
===================================================================
--- /issm/trunk/src/m/classes/issmsettings.js	(revision 22758)
+++ /issm/trunk/src/m/classes/issmsettings.js	(revision 22758)
@@ -0,0 +1,94 @@
+//ISSMSETTINGS class definition
+//
+//   Usage:
+//      issmsettings=new issmsettings();
+
+function issmsettings (){
+	//methods
+	this.setdefaultparameters = function(){// {{{
+		//are we short in memory ? (0 faster but requires more memory)
+		this.lowmem=0;
+
+		//i/o:
+		this.io_gather=1;
+
+		//results frequency by default every step
+		this.output_frequency=1;
+
+		//checkpoints frequency, by default never: 
+		this.recording_frequency=0;
+
+		//this option can be activated to load automatically the results
+		//onto the model after a parallel run by waiting for the lock file
+		//N minutes that is generated once the solution has converged
+		//0 to deactivate
+		this.waitonlock=Infinity;
+
+		//upload options: 
+		upload_port         = 0;
+		
+		//throw an error if solver residue exceeds this value
+		this.solver_residue_threshold=1e-6;
+
+	}// }}}
+	this.disp= function(){// {{{
+		console.log(sprintf('   issmsettings class echo:'));
+		
+		fielddisplay(this,'results_on_nodes','results are output for all the nodes of each element');
+		fielddisplay(this,'io_gather','I/O gathering strategy for result outputs (default 1)');
+		fielddisplay(this,'lowmem','is the memory limited ? (0 or 1)');
+		fielddisplay(this,'output_frequency','frequency at which results are saved in all solutions with multiple time_steps');
+		fielddisplay(this,'recording_frequency','frequency at which the runs are being recorded, allowing for a restart');
+		fielddisplay(this,'waitonlock','maximum number of minutes to wait for batch results (NaN to deactivate)');
+		fielddisplay(this,'upload_server','server hostname where model should be uploaded');
+		fielddisplay(this,'upload_path','path on server where model should be uploaded');
+		fielddisplay(this,'upload_login','server login');
+		fielddisplay(this,'upload_port','port login (default is 0)');
+		fielddisplay(this,'upload_filename','unique id generated when uploading the file to server');
+		fielddisplay(this,'solver_residue_threshold','throw an error if solver residue exceeds this value');
+
+
+	}// }}}
+	this.classname= function(){// {{{
+		return "issmsettings";
+
+	}// }}}
+		this.checkconsistency = function(md,solution,analyses) { // {{{
+
+			checkfield(md,'fieldname','settings.results_on_nodes','numel',[1],'values',[0, 1]);
+			checkfield(md,'fieldname','settings.io_gather','numel',[1],'values',[0, 1]);
+			checkfield(md,'fieldname','settings.lowmem','numel',[1],'values',[0, 1]);
+			checkfield(md,'fieldname','settings.output_frequency','numel',[1],'>=',1);
+			checkfield(md,'fieldname','settings.recording_frequency','numel',[1],'>=',0);
+			checkfield(md,'fieldname','settings.waitonlock','numel',[1]);
+			checkfield(md,'fieldname','settings.solver_residue_threshold','numel',[1],'>',0);
+		} // }}}
+		this.marshall=function(md,prefix,fid) { //{{{
+			WriteData(fid,prefix,'object',this,'class','settings','fieldname','results_on_nodes','format','Boolean');
+			WriteData(fid,prefix,'object',this,'class','settings','fieldname','io_gather','format','Boolean');
+			WriteData(fid,prefix,'object',this,'class','settings','fieldname','lowmem','format','Boolean');
+			WriteData(fid,prefix,'object',this,'class','settings','fieldname','output_frequency','format','Integer');
+			WriteData(fid,prefix,'object',this,'class','settings','fieldname','recording_frequency','format','Integer');
+			WriteData(fid,prefix,'object',this,'class','settings','fieldname','solver_residue_threshold','format','Double');
+			if (this.waitonlock>0) WriteData(fid,prefix,'name','md.settings.waitonlock','data',true,'format','Boolean');
+			else WriteData(fid,prefix,'name','md.settings.waitonlock','data',false,'format','Boolean');
+		}//}}}
+		this.fix=function() { //{{{
+		}//}}}
+	//properties 
+	// {{{
+	this.results_on_nodes    = 0;
+	this.io_gather           = 0;
+	this.lowmem              = 0;
+	this.output_frequency    = 0;
+	this.recording_frequency   = 0;
+	this.waitonlock          = 0;
+	this.upload_server       = '';
+	this.upload_path         = '';
+	this.upload_login        = '';
+	this.upload_port         = 0;
+	this.upload_filename     = '';
+	this.solver_residue_threshold = 0;
+	this.setdefaultparameters();
+	//}}}
+}
Index: /issm/trunk/src/m/classes/issmsettings.m
===================================================================
--- /issm/trunk/src/m/classes/issmsettings.m	(revision 22758)
+++ /issm/trunk/src/m/classes/issmsettings.m	(revision 22758)
@@ -0,0 +1,110 @@
+%ISSMSETTINGS class definition
+%
+%   Usage:
+%      issmsettings=issmsettings();
+
+classdef issmsettings
+	properties (SetAccess=public) 
+		results_on_nodes    = 0;
+		io_gather           = 0;
+		lowmem              = 0;
+		output_frequency    = 0;
+		recording_frequency   = 0;
+		waitonlock          = 0;
+		upload_server       = '';
+		upload_path         = '';
+		upload_login        = '';
+		upload_port         = 0;
+		upload_filename     = '';
+		solver_residue_threshold = 0;
+	end
+	methods
+		function self = issmsettings(varargin) % {{{
+			switch nargin
+				case 0
+					self=setdefaultparameters(self);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
+
+			%are we short in memory ? (0 faster but requires more memory)
+			self.lowmem=0;
+
+			%i/o:
+			self.io_gather=1;
+
+			%results frequency by default every step
+			self.output_frequency=1;
+
+			%checkpoints frequency, by default never: 
+			self.recording_frequency=0;
+
+			%this option can be activated to load automatically the results
+			%onto the model after a parallel run by waiting for the lock file
+			%N minutes that is generated once the solution has converged
+			%0 to deactivate
+			self.waitonlock=Inf;
+
+			%upload options: 
+			self.upload_port         = 0;
+
+			%throw an error if solver residue exceeds this value
+			self.solver_residue_threshold = 1e-6;
+
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
+
+			md = checkfield(md,'fieldname','settings.results_on_nodes','numel',[1],'values',[0 1]);
+			md = checkfield(md,'fieldname','settings.io_gather','numel',[1],'values',[0 1]);
+			md = checkfield(md,'fieldname','settings.lowmem','numel',[1],'values',[0 1]);
+			md = checkfield(md,'fieldname','settings.output_frequency','numel',[1],'>=',1);
+			md = checkfield(md,'fieldname','settings.recording_frequency','numel',[1],'>=',0);
+			md = checkfield(md,'fieldname','settings.waitonlock','numel',[1]);
+			md = checkfield(md,'fieldname','settings.solver_residue_threshold','numel',[1],'>',0);
+
+		end % }}}
+		function disp(self) % {{{
+			disp(sprintf('   general issmsettings parameters:'));
+
+			fielddisplay(self,'results_on_nodes','results are output for all the nodes of each element');
+			fielddisplay(self,'io_gather','I/O gathering strategy for result outputs (default 1)');
+			fielddisplay(self,'lowmem','is the memory limited ? (0 or 1)');
+			fielddisplay(self,'output_frequency','frequency at which results are saved in all solutions with multiple time_steps');
+			fielddisplay(self,'recording_frequency','frequency at which the runs are being recorded, allowing for a restart');
+			fielddisplay(self,'waitonlock','maximum number of minutes to wait for batch results (NaN to deactivate)');
+			fielddisplay(self,'upload_server','server hostname where model should be uploaded');
+			fielddisplay(self,'upload_path','path on server where model should be uploaded');
+			fielddisplay(self,'upload_login','server login');
+			fielddisplay(self,'upload_port','port login (default is 0)');
+			fielddisplay(self,'upload_filename','unique id generated when uploading the file to server');
+			fielddisplay(self,'solver_residue_threshold','throw an error if solver residue exceeds this value (NaN to deactivate)');
+
+		end % }}}
+		function marshall(self,prefix,md,fid) % {{{
+			WriteData(fid,prefix,'object',self,'class','settings','fieldname','results_on_nodes','format','Boolean');
+			WriteData(fid,prefix,'object',self,'class','settings','fieldname','io_gather','format','Boolean');
+			WriteData(fid,prefix,'object',self,'class','settings','fieldname','lowmem','format','Boolean');
+			WriteData(fid,prefix,'object',self,'class','settings','fieldname','output_frequency','format','Integer');
+			WriteData(fid,prefix,'object',self,'class','settings','fieldname','recording_frequency','format','Integer');
+			WriteData(fid,prefix,'object',self,'class','settings','fieldname','waitonlock','data',self.waitonlock>0,'format','Boolean');
+			WriteData(fid,prefix,'object',self,'class','settings','fieldname','solver_residue_threshold','format','Double');
+		end % }}}
+		function savemodeljs(self,fid,modelname) % {{{
+		
+			writejsdouble(fid,[modelname '.settings.results_on_nodes'],self.results_on_nodes);
+			writejsdouble(fid,[modelname '.settings.io_gather'],self.io_gather);
+			writejsdouble(fid,[modelname '.settings.lowmem'],self.lowmem);
+			writejsdouble(fid,[modelname '.settings.output_frequency'],self.output_frequency);
+			writejsdouble(fid,[modelname '.settings.recording_frequency'],self.recording_frequency);
+			writejsdouble(fid,[modelname '.settings.waitonlock'],self.waitonlock);
+			writejsstring(fid,[modelname '.settings.upload_server'],self.upload_server);
+			writejsstring(fid,[modelname '.settings.upload_path'],self.upload_path);
+			writejsstring(fid,[modelname '.settings.upload_login'],self.upload_login);
+			writejsdouble(fid,[modelname '.settings.upload_port'],self.upload_port);
+			writejsstring(fid,[modelname '.settings.upload_filename'],self.upload_filename);
+			writejsstring(fid,[modelname '.settings.solver_residue_threshold'],self.solver_residue_threshold);
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/issmsettings.py
===================================================================
--- /issm/trunk/src/m/classes/issmsettings.py	(revision 22758)
+++ /issm/trunk/src/m/classes/issmsettings.py	(revision 22758)
@@ -0,0 +1,87 @@
+from fielddisplay import fielddisplay
+from checkfield import checkfield
+from WriteData import WriteData
+
+class issmsettings(object):
+	"""
+	ISSMSETTINGS class definition
+
+	   Usage:
+	      issmsettings=issmsettings();
+	"""
+
+	def __init__(self): # {{{
+		self.results_on_nodes    = 0
+		self.io_gather           = 0
+		self.lowmem              = 0
+		self.output_frequency    = 0
+		self.recording_frequency = 0
+		self.waitonlock          = 0
+		self.solver_residue_threshold = 0
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		string="   general issmsettings parameters:"
+
+		string="%s\n%s"%(string,fielddisplay(self,"results_on_nodes","results are output for all the nodes of each element"))
+		string="%s\n%s"%(string,fielddisplay(self,"io_gather","I/O gathering strategy for result outputs (default 1)"))
+		string="%s\n%s"%(string,fielddisplay(self,"lowmem","is the memory limited ? (0 or 1)"))
+		string="%s\n%s"%(string,fielddisplay(self,"output_frequency","frequency at which results are saved in all solutions with multiple time_steps"))
+		string="%s\n%s"%(string,fielddisplay(self,"recording_frequency","frequency at which the runs are being recorded, allowing for a restart"))
+		string="%s\n%s"%(string,fielddisplay(self,"waitonlock","maximum number of minutes to wait for batch results, or return 0"))
+		string="%s\n%s"%(string,fielddisplay(self,"solver_residue_threshold","throw an error if solver residue exceeds this value (NaN to deactivate)"))
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		
+		#are we short in memory ? (0 faster but requires more memory)
+		self.lowmem=0
+
+		#i/o:
+		self.io_gather=1
+
+		#results frequency by default every step
+		self.output_frequency=1
+
+		#checkpoints frequency, by default never: 
+		self.recording_frequency=0
+
+
+		#this option can be activated to load automatically the results
+		#onto the model after a parallel run by waiting for the lock file
+		#N minutes that is generated once the solution has converged
+		#0 to deactivate
+		self.waitonlock=2**31-1
+
+      #throw an error if solver residue exceeds this value
+		self.solver_residue_threshold=1e-6;
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		md = checkfield(md,'fieldname','settings.results_on_nodes','numel',[1],'values',[0,1])
+		md = checkfield(md,'fieldname','settings.io_gather','numel',[1],'values',[0,1])
+		md = checkfield(md,'fieldname','settings.lowmem','numel',[1],'values',[0,1])
+		md = checkfield(md,'fieldname','settings.output_frequency','numel',[1],'>=',1)
+		md = checkfield(md,'fieldname','settings.recording_frequency','numel',[1],'>=',0)
+		md = checkfield(md,'fieldname','settings.waitonlock','numel',[1])
+		md = checkfield(md,'fieldname','settings.solver_residue_threshold','numel',[1],'>',0)
+
+		return md
+	# }}}
+	def marshall(self,prefix,md,fid):    # {{{
+		WriteData(fid,prefix,'object',self,'class','settings','fieldname','results_on_nodes','format','Boolean')
+		WriteData(fid,prefix,'object',self,'class','settings','fieldname','io_gather','format','Boolean')
+		WriteData(fid,prefix,'object',self,'class','settings','fieldname','lowmem','format','Boolean')
+		WriteData(fid,prefix,'object',self,'class','settings','fieldname','output_frequency','format','Integer')
+		WriteData(fid,prefix,'object',self,'class','settings','fieldname','recording_frequency','format','Integer')
+		
+		if self.waitonlock>0:
+			WriteData(fid,prefix,'name','md.settings.waitonlock','data',True,'format','Boolean')
+		else:
+			WriteData(fid,prefix,'name','md.settings.waitonlock','data',False,'format','Boolean')
+		WriteData(fid,prefix,'object',self,'fieldname','solver_residue_threshold','format','Double')
+	# }}}
Index: /issm/trunk/src/m/classes/levelset.m
===================================================================
--- /issm/trunk/src/m/classes/levelset.m	(revision 22757)
+++ /issm/trunk/src/m/classes/levelset.m	(revision 22758)
@@ -36,6 +36,6 @@
 		function self = setdefaultparameters(self) % {{{
 
-			%stabilization = 2 by default
-			self.stabilization    = 2;
+			%stabilization = 1 by default
+			self.stabilization    = 1;
 			self.reinit_frequency = 5;
 			self.calving_max      = 3000.;
Index: /issm/trunk/src/m/classes/levelset.py
===================================================================
--- /issm/trunk/src/m/classes/levelset.py	(revision 22757)
+++ /issm/trunk/src/m/classes/levelset.py	(revision 22758)
@@ -38,6 +38,6 @@
 	def setdefaultparameters(self): # {{{
 
-		#stabilization = 2 by default
-		self.stabilization = 2
+		#stabilization = 1 by default
+		self.stabilization = 1
 		self.reinit_frequency = 5
 		self.calving_max      = 3000
Index: /issm/trunk/src/m/classes/linearbasalforcings.m
===================================================================
--- /issm/trunk/src/m/classes/linearbasalforcings.m	(revision 22757)
+++ /issm/trunk/src/m/classes/linearbasalforcings.m	(revision 22758)
@@ -47,19 +47,19 @@
 			if ismember('MasstransportAnalysis',analyses) & ~(strcmp(solution,'TransientSolution') & md.transient.ismasstransport==0),
 				md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'Inf',1,'timeseries',1);
-				md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0,'numel',1);
-				md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<','basalforcings.upperwater_elevation','numel',1);
-				md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<',0,'numel',1);
+				md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0,'singletimeseries',1);
+				md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<','basalforcings.upperwater_elevation','singletimeseries',1);
+				md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<=',0,'singletimeseries',1);
 			end
 			if ismember('BalancethicknessAnalysis',analyses),
 				md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices 1]);
-				md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0,'numel',1);
-				md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<','basalforcings.upperwater_elevation','numel',1);
-				md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<=',0,'numel',1);
+				md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0,'singletimeseries',1);
+				md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<','basalforcings.upperwater_elevation','singletimeseries',1);
+				md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<=',0,'singletimeseries',1);
 			end
 			if ismember('ThermalAnalysis',analyses) & ~(strcmp(solution,'TransientSolution') & md.transient.isthermal==0),
 				md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'Inf',1,'timeseries',1);
-				md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0,'numel',1);
-				md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<','basalforcings.upperwater_elevation','numel',1);
-				md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<',0,'numel',1);
+				md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0,'singletimeseries',1);
+				md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<','basalforcings.upperwater_elevation','singletimeseries',1);
+				md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<=',0,'singletimeseries',1);
 				md = checkfield(md,'fieldname','basalforcings.geothermalflux','NaN',1,'Inf',1,'timeseries',1,'>=',0);
 			end
@@ -79,15 +79,10 @@
 			yts=md.constants.yts;
 
-			floatingice_melting_rate=zeros(md.mesh.numberofvertices,1);
-			floatingice_melting_rate(find(md.geometry.base<=md.basalforcings.deepwater_elevation))=md.basalforcings.deepwater_melting_rate;
-			pos=find(md.geometry.base>md.basalforcings.deepwater_elevation & md.geometry.base<md.basalforcings.upperwater_elevation);
-			floatingice_melting_rate(pos)=md.basalforcings.deepwater_melting_rate*(md.geometry.base(pos)-md.basalforcings.upperwater_elevation)/(md.basalforcings.deepwater_elevation-md.basalforcings.upperwater_elevation);
 			WriteData(fid,prefix,'name','md.basalforcings.model','data',2,'format','Integer');
-			WriteData(fid,prefix,'data',floatingice_melting_rate,'format','DoubleMat','name','md.basalforcings.floatingice_melting_rate','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
 			WriteData(fid,prefix,'object',self,'fieldname','groundedice_melting_rate','format','DoubleMat','name','md.basalforcings.groundedice_melting_rate','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
 			WriteData(fid,prefix,'object',self,'fieldname','geothermalflux','name','md.basalforcings.geothermalflux','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
-			WriteData(fid,prefix,'object',self,'fieldname','deepwater_melting_rate','format','Double','name','md.basalforcings.deepwater_melting_rate','scale',1./yts)
-			WriteData(fid,prefix,'object',self,'fieldname','deepwater_elevation','format','Double','name','md.basalforcings.deepwater_elevation')
-			WriteData(fid,prefix,'object',self,'fieldname','upperwater_elevation','format','Double','name','md.basalforcings.upperwater_elevation')
+			WriteData(fid,prefix,'object',self,'fieldname','deepwater_melting_rate','format','DoubleMat','mattype',3,'timeserieslength',2,'name','md.basalforcings.deepwater_melting_rate','scale',1./yts,'yts',md.constants.yts)
+			WriteData(fid,prefix,'object',self,'fieldname','deepwater_elevation','format','DoubleMat','mattype',3,'name','md.basalforcings.deepwater_elevation','yts',md.constants.yts)
+			WriteData(fid,prefix,'object',self,'fieldname','upperwater_elevation','format','DoubleMat','mattype',3,'name','md.basalforcings.upperwater_elevation','yts',md.constants.yts)
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/linearbasalforcings.py
===================================================================
--- /issm/trunk/src/m/classes/linearbasalforcings.py	(revision 22757)
+++ /issm/trunk/src/m/classes/linearbasalforcings.py	(revision 22758)
@@ -69,19 +69,19 @@
 		if 'MasstransportAnalysis' in analyses and not (solution=='TransientSolution' and not md.transient.ismasstransport):
 			md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'Inf',1,'timeseries',1)
-			md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0);
-			md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<',md.basalforcings.upperwater_elevation);
-			md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<',0);
+			md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0,'singletimeseries',1)
+			md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<','basalforcings.upperwater_elevation','singletimeseries',1)
+			md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<=',0,'singletimeseries',1)
 
 		if 'BalancethicknessAnalysis' in analyses:
 			md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
-			md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0);
-			md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<',md.basalforcings.upperwater_elevation);
-			md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<',0);
+			md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0,'singletimeseries',1)
+			md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<','basalforcings.upperwater_elevation','singletimeseries',1)
+			md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<=',0,'singletimeseries',1)
 
 		if 'ThermalAnalysis' in analyses and not (solution=='TransientSolution' and not md.transient.isthermal):
 			md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'Inf',1,'timeseries',1)
-			md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0);
-			md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<',md.basalforcings.upperwater_elevation);
-			md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<=',0);
+			md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0,'singletimeseries',1)
+			md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<','basalforcings.upperwater_elevation','singletimeseries',1)
+			md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<=',0,'singletimeseries',1)
 			md = checkfield(md,'fieldname','basalforcings.geothermalflux','NaN',1,'Inf',1,'timeseries',1,'>=',0)
 
@@ -92,16 +92,9 @@
 		yts=md.constants.yts
 
-		floatingice_melting_rate = np.zeros((md.mesh.numberofvertices))
-		pos=np.nonzero(md.geometry.base<=md.basalforcings.deepwater_elevation)
-		floatingice_melting_rate[pos]=md.basalforcings.deepwater_melting_rate
-		pos=np.nonzero(np.logical_and(md.geometry.base>md.basalforcings.deepwater_elevation,md.geometry.base<md.basalforcings.upperwater_elevation))
-		floatingice_melting_rate[pos]=md.basalforcings.deepwater_melting_rate*(md.geometry.base[pos]-md.basalforcings.upperwater_elevation)/(md.basalforcings.deepwater_elevation-md.basalforcings.upperwater_elevation)
-
-		WriteData(fid,prefix,'name','md.basalforcings.model','data',2,'format','Integer');
+		WriteData(fid,prefix,'name','md.basalforcings.model','data',2,'format','Integer')
 		WriteData(fid,prefix,'object',self,'fieldname','groundedice_melting_rate','name','md.basalforcings.groundedice_melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
-		WriteData(fid,prefix,'data',floatingice_melting_rate,'name','md.basalforcings.floatingice_melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
 		WriteData(fid,prefix,'object',self,'fieldname','geothermalflux','name','md.basalforcings.geothermalflux','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
-		WriteData(fid,prefix,'object',self,'fieldname','deepwater_melting_rate','name','md.basalforcings.deepwater_melting_rate','format','Double','scale',1./yts)
-		WriteData(fid,prefix,'object',self,'fieldname','deepwater_elevation','name','md.basalforcings.deepwater_elevation','format','Double')
-		WriteData(fid,prefix,'object',self,'fieldname','upperwater_elevation','name','md.basalforcings.upperwater_elevation','format','Double')
+		WriteData(fid,prefix,'object',self,'fieldname','deepwater_melting_rate','format','DoubleMat','mattype',3,'timeserieslength',2,'name','md.basalforcings.deepwater_melting_rate','scale',1./yts,'yts',md.constants.yts)
+		WriteData(fid,prefix,'object',self,'fieldname','deepwater_elevation','format','DoubleMat','mattype',3,'name','md.basalforcings.deepwater_elevation','yts',md.constants.yts)
+		WriteData(fid,prefix,'object',self,'fieldname','upperwater_elevation','format','DoubleMat','mattype',3,'name','md.basalforcings.upperwater_elevation','yts',md.constants.yts)
 	# }}}
Index: /issm/trunk/src/m/classes/m1qn3inversion.m
===================================================================
--- /issm/trunk/src/m/classes/m1qn3inversion.m	(revision 22757)
+++ /issm/trunk/src/m/classes/m1qn3inversion.m	(revision 22758)
@@ -155,4 +155,5 @@
 			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts);
 			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','vel_obs','format','DoubleMat','mattype',1,'scale',1./yts);
 			if(numel(self.thickness_obs)==md.mesh.numberofelements),
 				mattype=2;
Index: /issm/trunk/src/m/classes/mask.m
===================================================================
--- /issm/trunk/src/m/classes/mask.m	(revision 22757)
+++ /issm/trunk/src/m/classes/mask.m	(revision 22758)
@@ -38,4 +38,5 @@
 		end % }}}
 		function md = checkconsistency(self,md,solution,analyses) % {{{
+			if strcmpi(solution,'LoveSolution'), return; end;
 
 			md = checkfield(md,'fieldname','mask.groundedice_levelset','forcing',1,'NaN',1);
@@ -44,7 +45,4 @@
 			if sum(isice)==0,
 				warning('no ice present in the domain');
-			end
-			if max(md.mask.ice_levelset)<0,
-				disp('WARNING: no ice front provided');
 			end
 		end % }}}
Index: /issm/trunk/src/m/classes/mask.py
===================================================================
--- /issm/trunk/src/m/classes/mask.py	(revision 22757)
+++ /issm/trunk/src/m/classes/mask.py	(revision 22758)
@@ -38,4 +38,6 @@
 	#}}}
 	def checkconsistency(self,md,solution,analyses):    # {{{
+		if(solution=='LoveSolution'):
+			return
 
 		md = checkfield(md,'fieldname','mask.ice_levelset'        ,'size',[md.mesh.numberofvertices])
Index: /issm/trunk/src/m/classes/maskpsl.m
===================================================================
--- /issm/trunk/src/m/classes/maskpsl.m	(revision 22757)
+++ /issm/trunk/src/m/classes/maskpsl.m	(revision 22758)
@@ -42,4 +42,6 @@
 		end % }}}
 		function md = checkconsistency(self,md,solution,analyses) % {{{
+			
+			if strcmpi(solution,'LoveSolution'), return; end;
 
 			md = checkfield(md,'fieldname','mask.groundedice_levelset','size',[md.mesh.numberofvertices 1]);
Index: /issm/trunk/src/m/classes/masscon.m
===================================================================
--- /issm/trunk/src/m/classes/masscon.m	(revision 22757)
+++ /issm/trunk/src/m/classes/masscon.m	(revision 22758)
@@ -3,10 +3,10 @@
 %   Usage:
 %      masscon=masscon();
-%      masscon=masscon('name','MassCon58',... %name of a North-East Greenland JPL MassCon
+%      masscon=masscon('name','MassCon58','definitionstring','Outputdefinition1',... %name of a North-East Greenland JPL MassCon
 %                    'levelset',level);
 % 
 %   where level is a levelset vectorial field.
 %
-%   See also: MISFIT
+%   See also: MISFIT, MASSCONAXPBY, REGIONALOUTPUT
 
 classdef masscon
@@ -14,9 +14,14 @@
 		%masscon
 		name              = '';
-		definitionstring   = ''; %string that identifies this output definition uniquely, from 'Outputdefinition[1-10]'
+		definitionstring  = ''; %string that identifies this output definition uniquely, from 'Outputdefinition[1-10]'
 		levelset          = NaN; %levelset vectorial field which identifies the boundaries of the masscon
 	end
 	
 	methods
+		function self = extrude(self,md) % {{{
+			if ~isnan(self.levelset)
+				self.levelset=project3d(md,'vector',self.levelset,'type','node');
+			end
+		end % }}}
 		function self = masscon(varargin) % {{{
 			if nargin==0,
@@ -40,5 +45,5 @@
 				error('masscon error message: ''name'' field should be a string!');
 			end
-			
+
 			OutputdefinitionStringArray={};
 			for i=1:100
@@ -46,11 +51,11 @@
 			end
 
-			md = checkfield(md,'fieldname','self.definitionstring','field',self.definitionstring,'values','Outputdefinition');
+			md = checkfield(md,'fieldname','self.definitionstring','field',self.definitionstring,'values',OutputdefinitionStringArray);
 			md = checkfield(md,'fieldname','self.levelset','field',self.levelset,'timeseries',1,'NaN',1,'Inf',1);
 
 		end % }}}
 		function md = disp(self) % {{{
-		
-			disp(sprintf('   Misfit:\n'));
+
+			disp(sprintf('   Masscon:\n'));
 
 			fielddisplay(self,'name','identifier for this masscon response');
@@ -61,7 +66,7 @@
 		function md = marshall(self,prefix,md,fid) % {{{
 
-		WriteData(fid,prefix,'object',self,'fieldname','name','format','String');
-		WriteData(fid,prefix,'object',self,'fieldname','definitionstring','format','String');
-		WriteData(fid,prefix,'object',self,'fieldname','levelset','format','DoubleMat','mattype',1);
+			WriteData(fid,prefix,'data',self.name,'name','md.masscon.name','format','String');
+			WriteData(fid,prefix,'data',self.definitionstring,'name','md.masscon.definitionstring','format','String');
+			WriteData(fid,prefix,'data',self.levelset,'name','md.masscon.levelset','format','DoubleMat','mattype',1);
 
 		end % }}}
Index: /issm/trunk/src/m/classes/massconaxpby.m
===================================================================
--- /issm/trunk/src/m/classes/massconaxpby.m	(revision 22757)
+++ /issm/trunk/src/m/classes/massconaxpby.m	(revision 22758)
@@ -3,5 +3,5 @@
 %   Usage:
 %      massconaxpby=massconaxpby();
-%      massconsumaxpby=massconaxpby('name','MassCon58+35','namex','MassCon58','alpha',.5,'namey','MassCon35','beta',.5); 
+%      massconaxpby=massconaxpby('name','MassCon58+35','namex','MassCon58','alpha',.5,'namey','MassCon35','beta',.5,'definitionstring','Outputdefinition1'); 
 % 
 %   where name is the name of the massconaxpby object, namex is the name of the first masscon, namey the name of the second masscon and alpha,beta the 
@@ -9,18 +9,20 @@
 %         of two masscons.
 %
-%   See also: MASSCON
+%   See also: MASSCON, REGIONALOUTPUT
 
 classdef massconaxpby
 	properties (SetAccess=public)
 		%masscon axpby
-		name              = '';
+		name               = '';
 		definitionstring   = ''; %String that identifies this output definition uniquely, from 'Outputdefinition[1-10]'
 		namex              = '';
 		namey              = '';
 		alpha              = NaN;
-		beta              = NaN;
+		beta               = NaN;
 	end
 	
 	methods
+		function self = extrude(self,md) % {{{
+		end % }}}
 		function self = massconaxpby(varargin) % {{{
 			if nargin==0,
@@ -65,5 +67,5 @@
 		function md = disp(self) % {{{
 		
-			disp(sprintf('   Misfit:\n'));
+			disp(sprintf('   Massconaxpby:\n'));
 
 			fielddisplay(self,'name','name');
@@ -77,10 +79,10 @@
 		function md = marshall(self,prefix,md,fid) % {{{
 
-		WriteData(fid,prefix,'object',self,'fieldname','name','format','String');
-		WriteData(fid,prefix,'object',self,'fieldname','definitionstring','format','Integer');
-		WriteData(fid,prefix,'object',self,'fieldname','namex','format','String');
-		WriteData(fid,prefix,'object',self,'fieldname','namey','format','String');
-		WriteData(fid,prefix,'object',self,'fieldname','alpha','format','Double');
-		WriteData(fid,prefix,'object',self,'fieldname','beta','format','Double');
+			WriteData(fid,prefix,'data',self.name,'name','md.massconaxpby.name','format','String');
+			WriteData(fid,prefix,'data',self.definitionstring,'name','md.massconaxpby.definitionstring','format','String');
+			WriteData(fid,prefix,'data',self.namex,'name','md.massconaxpby.namex','format','String');
+			WriteData(fid,prefix,'data',self.namey,'name','md.massconaxpby.namey','format','String');
+			WriteData(fid,prefix,'data',self.alpha,'name','md.massconaxpby.alpha','format','Double');
+			WriteData(fid,prefix,'data',self.beta,'name','md.massconaxpby.beta','format','Double');
 
 		end % }}}
Index: /issm/trunk/src/m/classes/massfluxatgate.m
===================================================================
--- /issm/trunk/src/m/classes/massfluxatgate.m	(revision 22757)
+++ /issm/trunk/src/m/classes/massfluxatgate.m	(revision 22758)
@@ -16,4 +16,6 @@
 	end
 	methods
+		function self = extrude(self,md) % {{{
+		end % }}}
 		function self = massfluxatgate(varargin) % {{{
 			if nargin==0,
@@ -56,5 +58,5 @@
 			fielddisplay(self,'name','identifier for this massfluxatgate response');
 			fielddisplay(self,'profilename','name of file (shapefile or argus file) defining a profile (or gate)');
-			fielddisplay(self,'definitionstring','string that identifies this output definition uniquely, from ''Outputdefinition[1-10]''');
+			fielddisplay(self,'definitionstring','string that identifies this output definition uniquely, from ''Outputdefinition[1-100]''');
 			
 		end % }}}
Index: /issm/trunk/src/m/classes/massfluxatgate.py
===================================================================
--- /issm/trunk/src/m/classes/massfluxatgate.py	(revision 22757)
+++ /issm/trunk/src/m/classes/massfluxatgate.py	(revision 22758)
@@ -35,8 +35,11 @@
 		string="   Massfluxatgate:"
 		string="%s\n%s"%(string,fielddisplay(self,'name','identifier for this massfluxatgate response'))
-		string="%s\n%s"%(string,fielddisplay(self,'definitionstring','string that identifies this output definition uniquely, from Outputdefinition[1-10]'))
+		string="%s\n%s"%(string,fielddisplay(self,'definitionstring','string that identifies this output definition uniquely, from Outputdefinition[1-100]'))
 		string="%s\n%s"%(string,fielddisplay(self,'profilename','name of file (shapefile or argus file) defining a profile (or gate)'))
 		return string
 		#}}}
+	def extrude(self,md): # {{{
+		return self
+	   #}}}
 	def setdefaultparameters(self): # {{{
 		return self
@@ -49,6 +52,11 @@
 		if  not isinstance(self.profilename, basestring):
 			raise RuntimeError("massfluxatgate error message: 'profilename' field should be a string!") 
-
-			md = checkfield(md,'field',self.definitionstring,'values',['Outputdefinition1','Outputdefinition2','Outputdefinition3','Outputdefinition4','Outputdefinition5','Outputdefinition6','Outputdefinition7','Outputdefinition8','Outputdefinition9','Outputdefinition10'])
+		
+		OutputdefinitionStringArray=[]
+		for i in range(1,100):
+			x='Outputdefinition'+str(i)
+			OutputdefinitionStringArray.append(x)
+			
+		md = checkfield(md,'field',self.definitionstring,'values',OutputdefinitionStringArray)
 		
 		#check the profilename points to a file!: 
Index: /issm/trunk/src/m/classes/matenhancedice.py
===================================================================
--- /issm/trunk/src/m/classes/matenhancedice.py	(revision 22758)
+++ /issm/trunk/src/m/classes/matenhancedice.py	(revision 22758)
@@ -0,0 +1,171 @@
+from fielddisplay import fielddisplay
+from project3d import project3d
+from checkfield import checkfield
+from WriteData import WriteData
+
+class matenhancedice(object):
+	"""
+	MATICE class definition
+
+	   Usage:
+	      matenhancedice=matenhancedice();
+	"""
+
+	def __init__(self): # {{{
+		self.rho_ice                   = 0.
+		self.rho_water                 = 0.
+		self.rho_freshwater            = 0.
+		self.mu_water                  = 0.
+		self.heatcapacity              = 0.
+		self.latentheat                = 0.
+		self.thermalconductivity       = 0.
+		self.temperateiceconductivity  = 0.
+		self.meltingpoint              = 0.
+		self.beta                      = 0.
+		self.mixed_layer_capacity      = 0.
+		self.thermal_exchange_velocity = 0.
+		self.rheology_E		       = float('NaN')
+		self.rheology_B                = float('NaN')
+		self.rheology_n                = float('NaN')
+		self.rheology_law              = ''
+
+		#giaivins: 
+		self.lithosphere_shear_modulus  = 0.
+		self.lithosphere_density        = 0.
+		self.mantle_shear_modulus       = 0.
+		self.mantle_density             = 0.
+		
+		#SLR
+		self.earth_density= 0  # average density of the Earth, (kg/m^3)
+
+		self.setdefaultparameters()
+		#}}}
+	def __repr__(self): # {{{
+		string="   Materials:"
+
+		string="%s\n%s"%(string,fielddisplay(self,"rho_ice","ice density [kg/m^3]"))
+		string="%s\n%s"%(string,fielddisplay(self,"rho_water","water density [kg/m^3]"))
+		string="%s\n%s"%(string,fielddisplay(self,"rho_freshwater","fresh water density [kg/m^3]"))
+		string="%s\n%s"%(string,fielddisplay(self,"mu_water","water viscosity [N s/m^2]"))
+		string="%s\n%s"%(string,fielddisplay(self,"heatcapacity","heat capacity [J/kg/K]"))
+		string="%s\n%s"%(string,fielddisplay(self,"thermalconductivity","ice thermal conductivity [W/m/K]"))
+		string="%s\n%s"%(string,fielddisplay(self,"temperateiceconductivity","temperate ice thermal conductivity [W/m/K]"))
+		string="%s\n%s"%(string,fielddisplay(self,"meltingpoint","melting point of ice at 1atm in K"))
+		string="%s\n%s"%(string,fielddisplay(self,"latentheat","latent heat of fusion [J/m^3]"))
+		string="%s\n%s"%(string,fielddisplay(self,"beta","rate of change of melting point with pressure [K/Pa]"))
+		string="%s\n%s"%(string,fielddisplay(self,"mixed_layer_capacity","mixed layer capacity [W/kg/K]"))
+		string="%s\n%s"%(string,fielddisplay(self,"thermal_exchange_velocity","thermal exchange velocity [m/s]"))
+		string="%s\n%s"%(string,fielddisplay(self,"rheology_E","enhancement factor"))
+		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', 'BuddJacka', 'Cuffey', 'CuffeyTemperate', 'Paterson', 'Arrhenius' or 'LliboutryDuval'"))
+		string="%s\n%s"%(string,fielddisplay(self,"lithosphere_shear_modulus","Lithosphere shear modulus [Pa]"))
+		string="%s\n%s"%(string,fielddisplay(self,"lithosphere_density","Lithosphere density [g/cm^-3]"))
+		string="%s\n%s"%(string,fielddisplay(self,"mantle_shear_modulus","Mantle shear modulus [Pa]"))
+		string="%s\n%s"%(string,fielddisplay(self,"mantle_density","Mantle density [g/cm^-3]"))
+		string="%s\n%s"%(string,fielddisplay(self,"earth_density","Mantle density [kg/m^-3]"))
+
+		return string
+		#}}}
+	def extrude(self,md): # {{{
+		self.rheology_E=project3d(md,'vector',self.rheology_E,'type','node')
+		self.rheology_B=project3d(md,'vector',self.rheology_B,'type','node')
+		self.rheology_n=project3d(md,'vector',self.rheology_n,'type','element')
+		return self
+	#}}}
+	def setdefaultparameters(self): # {{{
+		#ice density (kg/m^3)
+		self.rho_ice=917.
+
+		#ocean water density (kg/m^3)
+		self.rho_water=1023.
+
+		#fresh water density (kg/m^3)
+		self.rho_freshwater=1000.
+
+		#water viscosity (N.s/m^2)
+		self.mu_water=0.001787  
+
+		#ice heat capacity cp (J/kg/K)
+		self.heatcapacity=2093.
+
+		#ice latent heat of fusion L (J/kg)
+		self.latentheat=3.34*10**5
+
+		#ice thermal conductivity (W/m/K)
+		self.thermalconductivity=2.4
+
+		#temperate ice thermal conductivity (W/m/K)
+		self.temperateiceconductivity=0.24
+
+		#the melting point of ice at 1 atmosphere of pressure in K
+		self.meltingpoint=273.15
+
+		#rate of change of melting point with pressure (K/Pa)
+		self.beta=9.8*10**-8
+
+		#mixed layer (ice-water interface) heat capacity (J/kg/K)
+		self.mixed_layer_capacity=3974.
+
+		#thermal exchange velocity (ice-water interface) (m/s)
+		self.thermal_exchange_velocity=1.00*10**-4
+
+		#Rheology law: what is the temperature dependence of B with T
+		#available: none, paterson and arrhenius
+		self.rheology_law='Paterson'
+
+		# GIA:
+		self.lithosphere_shear_modulus  = 6.7*10**10  # (Pa)
+		self.lithosphere_density        = 3.32        # (g/cm^-3)
+		self.mantle_shear_modulus       = 1.45*10**11 # (Pa)
+		self.mantle_density             = 3.34        # (g/cm^-3)
+		
+		#SLR
+		self.earth_density= 5512  #average density of the Earth, (kg/m^3)
+
+		return self
+		#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		md = checkfield(md,'fieldname','materials.rho_ice','>',0)
+		md = checkfield(md,'fieldname','materials.rho_water','>',0)
+		md = checkfield(md,'fieldname','materials.rho_freshwater','>',0)
+		md = checkfield(md,'fieldname','materials.mu_water','>',0)
+		md = checkfield(md,'fieldname','materials.rheology_E','>',0,'timeseries',1,'NaN',1,'Inf',1)
+		md = checkfield(md,'fieldname','materials.rheology_B','>',0,'timeseries',1,'NaN',1,'Inf',1)
+		md = checkfield(md,'fieldname','materials.rheology_n','>',0,'size',[md.mesh.numberofelements])
+		md = checkfield(md,'fieldname','materials.rheology_law','values',['None','BuddJacka','Cuffey','CuffeyTemperate','Paterson','Arrhenius','LliboutryDuval'])
+
+		if 'GiaAnalysis' in analyses:
+			md = checkfield(md,'fieldname','materials.lithosphere_shear_modulus','>',0,'numel',1)
+			md = checkfield(md,'fieldname','materials.lithosphere_density','>',0,'numel',1)
+			md = checkfield(md,'fieldname','materials.mantle_shear_modulus','>',0,'numel',1)
+			md = checkfield(md,'fieldname','materials.mantle_density','>',0,'numel',1)
+		if 'SealevelriseAnalysis' in analyses:
+			md = checkfield(md,'fieldname','materials.earth_density','>',0,'numel',1)
+		return md
+	# }}}
+	def marshall(self,prefix,md,fid):    # {{{
+		WriteData(fid,prefix,'name','md.materials.type','data',4,'format','Integer')
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','rho_ice','format','Double')
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','rho_water','format','Double')
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','rho_freshwater','format','Double')
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','mu_water','format','Double')
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','heatcapacity','format','Double')
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','latentheat','format','Double')
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','thermalconductivity','format','Double')
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','temperateiceconductivity','format','Double')
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','meltingpoint','format','Double')
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','beta','format','Double')
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','mixed_layer_capacity','format','Double')
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','thermal_exchange_velocity','format','Double')
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','rheology_E','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','rheology_B','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','rheology_n','format','DoubleMat','mattype',2)
+		WriteData(fid,prefix,'data',self.rheology_law,'name','md.materials.rheology_law','format','String')
+
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','lithosphere_shear_modulus','format','Double')
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','lithosphere_density','format','Double','scale',10^3)
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','mantle_shear_modulus','format','Double')
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','mantle_density','format','Double','scale',10^3)
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','earth_density','format','Double')
+	# }}}
Index: /issm/trunk/src/m/classes/materials.m
===================================================================
--- /issm/trunk/src/m/classes/materials.m	(revision 22757)
+++ /issm/trunk/src/m/classes/materials.m	(revision 22758)
@@ -113,16 +113,16 @@
 					self.numlayers=2;
 
-					%surface, then the lab (lithosphere/asthenosphere boundary) then the center of the earth 
+					%center of the earth (approximation, must not be 0), then the lab (lithosphere/asthenosphere boundary) then the surface
 					%(with 1d3 to avoid numerical singularities) 
-					self.radius=[6378*1e3;6278*1e3;1e3]; 
-
-					self.viscosity=[1e40;1e21]; %lithosphere and mantle viscosity (respectively) [Pa.s]
-					self.lame_mu=[6.7*10^10;1.45*1e11];  % (Pa) %lithosphere and mantle shear modulus (respectively) [Pa]
-					self.lame_lambda=[6.7*10^10;1.45*1e11];  % (Pa) %lithosphere and mantle lamba parameter (respectively) [Pa]
+					self.radius=[1e3;6278*1e3;6378*1e3];
+
+					self.viscosity=[1e21;1e40]; %mantle and lithosphere viscosity (respectively) [Pa.s]
+					self.lame_mu=[1.45*1e11;6.7*10^10];  % (Pa) %lithosphere and mantle shear modulus (respectively) [Pa]
+					self.lame_lambda=self.lame_mu;  % (Pa) %mantle and lithosphere lamba parameter (respectively) [Pa]
 					self.burgers_viscosity=[NaN;NaN];
 					self.burgers_mu=[NaN;NaN];
-					self.isburgers=[false;false];
-					self.density=[3.32*1e3;3.34*1e3];  % (Pa) %lithosphere and mantle density [kg/m^3]
-					self.issolid=[true;true]; % is layer solid or liquid.
+					self.isburgers=[0;0];
+					self.density=[5.51*1e3;5.50*1e3];  % (Pa) %mantle and lithosphere density [kg/m^3]
+					self.issolid=[1;1]; % is layer solid or liquid.
 
 				otherwise
@@ -188,37 +188,30 @@
 					md = checkfield(md,'fieldname','materials.numlayers','NaN',1,'Inf',1,'>',0,'numel',1);
 					md = checkfield(md,'fieldname','materials.radius','NaN',1,'Inf',1,'size',[md.materials.numlayers+1 1],'>',0);
-					md = checkfield(md,'fieldname','materials.lame_mu','NaN',1,'Inf',1,'size',[md.materials.numlayers 1],'>',0);
-					md = checkfield(md,'fieldname','materials.lame_lambda','NaN',1,'Inf',1,'size',[md.materials.numlayers 1],'>',0);
-					md = checkfield(md,'fieldname','materials.issolid','NaN',1,'Inf',1,'size',[md.materials.numlayers 1],'>',0,'<',2);
+					md = checkfield(md,'fieldname','materials.lame_mu','NaN',1,'Inf',1,'size',[md.materials.numlayers 1],'>=',0);
+					md = checkfield(md,'fieldname','materials.lame_lambda','NaN',1,'Inf',1,'size',[md.materials.numlayers 1],'>=',0);
+					md = checkfield(md,'fieldname','materials.issolid','NaN',1,'Inf',1,'size',[md.materials.numlayers 1],'>=',0,'<',2);
 					md = checkfield(md,'fieldname','materials.density','NaN',1,'Inf',1,'size',[md.materials.numlayers 1],'>',0);
-					md = checkfield(md,'fieldname','materials.viscosity','NaN',1,'Inf',1,'size',[md.materials.numlayers 1],'>',0);
-					md = checkfield(md,'fieldname','materials.isburgers','NaN',1,'Inf',1,'size',[md.materials.numlayers 1],'>',0,'<',2);
-					md = checkfield(md,'fieldname','materials.burgers_viscosity','NaN',1,'Inf',1,'size',[md.materials.numlayers 1],'>',0);
-					md = checkfield(md,'fieldname','materials.burgers_mu','NaN',1,'Inf',1,'size',[md.materials.numlayers 1],'>',0);
-
-				otherwise
-					error('materials constructor error message: nature of the material not supported yet! (''ice'' or ''litho'')');
-				end
-			end
-
-		end % }}}
-		function intnat = naturetointeger(strnat) % {{{
-			intnat=zeros(length(strnat),1);
-			for i=1:length(strnat),
-				switch strnat{i},
-				case 'damageice'
-					intnat(i)=1; 
-				case 'estar'
-					intnat(i)=2; 
-				case 'ice'
-					intnat(i)=3; 
-				case 'enhancedice'
-					intnat(i)=4; 
-				case 'litho'
-					intnat(i)=5;
-				otherwise
-					error('materials constructor error message: nature of the material not supported yet! (''ice'' or ''litho'')');
-				end
-			end
+					md = checkfield(md,'fieldname','materials.viscosity','NaN',1,'Inf',1,'size',[md.materials.numlayers 1],'>=',0);
+					md = checkfield(md,'fieldname','materials.isburgers','NaN',1,'Inf',1,'size',[md.materials.numlayers 1],'>=',0,'<=',1);
+					md = checkfield(md,'fieldname','materials.burgers_viscosity','Inf',1,'size',[md.materials.numlayers 1],'>=',0);
+					md = checkfield(md,'fieldname','materials.burgers_mu','Inf',1,'size',[md.materials.numlayers 1],'>=',0);
+
+					for i=1:md.materials.numlayers,
+						if md.materials.isburgers(i) & (isnan(md.materials.burgers_viscosity(i) | isnan(md.materials.burgers_mu(i)))), 
+							error('materials checkconsistency error message: Litho burgers_viscosity or burgers_mu has NaN values, inconsistent with isburgers choice');
+						end
+					end
+					if md.materials.issolid(1)==0 | md.materials.lame_mu(1)==0 
+							error('First layer must be solid (issolid(1) > 0 AND lame_mu(1) > 0). Add a weak inner core if necessary.');
+					end
+					ind=find(md.materials.issolid==0);
+					if sum(ismember(diff(ind),1)>=1) %if there are at least two consecutive indices that contain issolid = 0
+							error(['Fluid layers detected at layers #', num2str(ind'), ', but having 2 or more adjacent fluid layers is not supported yet. Consider merging them.'])
+					end
+				otherwise
+					error('materials constructor error message: nature of the material not supported yet! (''ice'' or ''litho'')');
+				end
+			end
+
 		end % }}}
 		function marshall(self,prefix,md,fid) % {{{
@@ -226,5 +219,5 @@
 			%1: MatdamageiceEnum 2: MatestarEnum 3: MaticeEnum 4: MatenhancediceEnum 5: MaterialsEnum 
 			WriteData(fid,prefix,'name','md.materials.type','data',6,'format','Integer');
-			WriteData(fid,prefix,'name','md.materials.nature','data',naturetointeger(self.nature),'format','IntMat','mattype',1);
+			WriteData(fid,prefix,'name','md.materials.nature','data',naturetointeger(self.nature),'format','IntMat','mattype',3);
 
 			for i=1:length(self.nature),
@@ -248,14 +241,14 @@
 					WriteData(fid,prefix,'data',self.rheology_law,'name','md.materials.rheology_law','format','String');
 				case 'litho'
-					WriteData(fid,prefix,'object',self,'class','materials','fieldname','numlayers','format','Double');
-					WriteData(fid,prefix,'object',self,'class','materials','fieldname','radius','format','DoubleMat','mattype',1);
-					WriteData(fid,prefix,'object',self,'class','materials','fieldname','lame_mu','format','DoubleMat','mattype',1);
-					WriteData(fid,prefix,'object',self,'class','materials','fieldname','lame_lambda ','format','DoubleMat','mattype',1);
-					WriteData(fid,prefix,'object',self,'class','materials','fieldname','issolid','format','BooleanMat','mattype',1);
-					WriteData(fid,prefix,'object',self,'class','materials','fieldname','density','format','DoubleMat','mattype',1); 
-					WriteData(fid,prefix,'object',self,'class','materials','fieldname','viscosity','format','DoubleMat','mattype',1); 
-					WriteData(fid,prefix,'object',self,'class','materials','fieldname','isburgers','format','BooleanMat','mattype',1); 
-					WriteData(fid,prefix,'object',self,'class','materials','fieldname','burgers_viscosity','format','DoubleMat','mattype',1); 
-					WriteData(fid,prefix,'object',self,'class','materials','fieldname','burgers_mu','format','DoubleMat','mattype',1); 
+					WriteData(fid,prefix,'object',self,'class','materials','fieldname','numlayers','format','Integer');
+					WriteData(fid,prefix,'object',self,'class','materials','fieldname','radius','format','DoubleMat','mattype',3);
+					WriteData(fid,prefix,'object',self,'class','materials','fieldname','lame_mu','format','DoubleMat','mattype',3);
+					WriteData(fid,prefix,'object',self,'class','materials','fieldname','lame_lambda','format','DoubleMat','mattype',3);
+					WriteData(fid,prefix,'object',self,'class','materials','fieldname','issolid','format','DoubleMat','mattype',3);
+					WriteData(fid,prefix,'object',self,'class','materials','fieldname','density','format','DoubleMat','mattype',3); 
+					WriteData(fid,prefix,'object',self,'class','materials','fieldname','viscosity','format','DoubleMat','mattype',3); 
+					WriteData(fid,prefix,'object',self,'class','materials','fieldname','isburgers','format','DoubleMat','mattype',3); 
+					WriteData(fid,prefix,'object',self,'class','materials','fieldname','burgers_viscosity','format','DoubleMat','mattype',3); 
+					WriteData(fid,prefix,'object',self,'class','materials','fieldname','burgers_mu','format','DoubleMat','mattype',3); 
 				otherwise
 					error('materials constructor error message: nature of the material not supported yet! (''ice'' or ''litho'')');
@@ -316,4 +309,21 @@
 	end
 end
-
-
+		function intnat = naturetointeger(strnat) % {{{
+			intnat=zeros(length(strnat),1);
+			for i=1:length(strnat),
+				switch strnat{i},
+				case 'damageice'
+					intnat(i)=1; 
+				case 'estar'
+					intnat(i)=2; 
+				case 'ice'
+					intnat(i)=3; 
+				case 'enhancedice'
+					intnat(i)=4; 
+				case 'litho'
+					intnat(i)=5;
+				otherwise
+					error('materials constructor error message: nature of the material not supported yet! (''ice'' or ''litho'')');
+				end
+			end
+		end % }}}
Index: /issm/trunk/src/m/classes/materials.py
===================================================================
--- /issm/trunk/src/m/classes/materials.py	(revision 22758)
+++ /issm/trunk/src/m/classes/materials.py	(revision 22758)
@@ -0,0 +1,280 @@
+import numpy as np
+from fielddisplay import fielddisplay
+from project3d import project3d
+from checkfield import checkfield
+from WriteData import WriteData
+		
+def naturetointeger(strnat): #{{{
+    
+    intnat=np.zeros(len(strnat))
+    for i in range(len(intnat)):
+        if strnat[i]=='damageice':
+            intnat[i]=1
+        elif strnat[i]=='estar':
+            intnat[i]=2 
+        elif strnat[i]=='ice':
+            intnat[i]=3 
+        elif strnat[i]=='enhancedice':
+            intnat[i]=4 
+        elif strnat[i]=='litho':
+            intnat[i]=5
+        else: 
+            raise RuntimeError("materials constructor error message: nature of the material not supported yet! (''ice'' or ''litho'')");
+    
+    return intnat
+# }}}
+class materials(object):
+	"""
+	MATERIALS class definition
+
+	   Usage:
+	      materials=materials();
+	"""
+
+	def __init__(self,*args): # {{{
+		
+                self.nature                    = []
+
+                if not len(args):
+                    self.nature=['ice']
+                else:
+                    self.nature=args
+
+                for i in range(len(self.nature)):
+                    if not(self.nature[i] == 'litho' or self.nature[i]=='ice'):
+                        raise RuntimeError("materials constructor error message: nature of the material not supported yet! ('ice' or 'litho')")
+                    
+                #start filling in the dynamic fields: 
+                for i in range(len(self.nature)):
+                    nat=self.nature[i]; 
+                    if nat=='ice':
+                        setattr(self,'rho_ice',0)
+                        setattr(self,'rho_ice',0);
+                        setattr(self,'rho_water',0);
+                        setattr(self,'rho_freshwater',0);
+                        setattr(self,'mu_water',0);
+                        setattr(self,'heatcapacity',0);
+                        setattr(self,'latentheat',0);
+                        setattr(self,'thermalconductivity',0);
+                        setattr(self,'temperateiceconductivity',0);
+                        setattr(self,'meltingpoint',0);
+                        setattr(self,'beta',0);
+                        setattr(self,'mixed_layer_capacity',0);
+                        setattr(self,'thermal_exchange_velocity',0);
+                        setattr(self,'rheology_B',0);
+                        setattr(self,'rheology_n',0);
+                        setattr(self,'rheology_law',0);
+                    elif nat=='litho':
+                        setattr(self,'numlayers',0);
+                        setattr(self,'radius',0);
+                        setattr(self,'viscosity',0);
+                        setattr(self,'lame_lambda',0);
+                        setattr(self,'lame_mu',0);
+                        setattr(self,'burgers_viscosity',0);
+                        setattr(self,'burgers_mu',0);
+                        setattr(self,'isburgers',0);
+                        setattr(self,'density',0);
+                        setattr(self,'issolid',0);
+                    else:
+                        raise RuntimeError("materials constructor error message: nature of the material not supported yet! ('ice' or 'litho')");
+                #set default parameters:
+		self.setdefaultparameters()
+		#}}}
+	def __repr__(self): # {{{
+		string="   Materials:"
+                for i in range(len(self.nature)):
+                    nat=self.nature[i]; 
+                    if nat=='ice':
+                        string="%s\n%s"%(string,'Ice:');
+                        string="%s\n%s"%(string,fielddisplay(self,"rho_ice","ice density [kg/m^3]"))
+                        string="%s\n%s"%(string,fielddisplay(self,"rho_water","water density [kg/m^3]"))
+                        string="%s\n%s"%(string,fielddisplay(self,"rho_freshwater","fresh water density [kg/m^3]"))
+                        string="%s\n%s"%(string,fielddisplay(self,"mu_water","water viscosity [N s/m^2]"))
+                        string="%s\n%s"%(string,fielddisplay(self,"heatcapacity","heat capacity [J/kg/K]"))
+                        string="%s\n%s"%(string,fielddisplay(self,"thermalconductivity","ice thermal conductivity [W/m/K]"))
+                        string="%s\n%s"%(string,fielddisplay(self,"temperateiceconductivity","temperate ice thermal conductivity [W/m/K]"))
+                        string="%s\n%s"%(string,fielddisplay(self,"meltingpoint","melting point of ice at 1atm in K"))
+                        string="%s\n%s"%(string,fielddisplay(self,"latentheat","latent heat of fusion [J/m^3]"))
+                        string="%s\n%s"%(string,fielddisplay(self,"beta","rate of change of melting point with pressure [K/Pa]"))
+                        string="%s\n%s"%(string,fielddisplay(self,"mixed_layer_capacity","mixed layer capacity [W/kg/K]"))
+                        string="%s\n%s"%(string,fielddisplay(self,"thermal_exchange_velocity","thermal exchange velocity [m/s]"))
+                        string="%s\n%s"%(string,fielddisplay(self,"rheology_B","flow law parameter [Pa/s^(1/n)]"))
+                        string="%s\n%s"%(string,fielddisplay(self,"rheology_n","Glen's flow law exponent"))
+                        string="%s\n%s"%(string,fielddisplay(self,"rheology_law","law for the temperature dependance of the rheology: 'None', 'BuddJacka', 'Cuffey', 'CuffeyTemperate', 'Paterson', 'Arrhenius' or 'LliboutryDuval'"))
+                    elif nat=='litho':
+                        string="%s\n%s"%(string,'Litho:');
+                        string="%s\n%s"%(string,fielddisplay(self,'numlayers','number of layers (default 2)'))
+                        string="%s\n%s"%(string,fielddisplay(self,'radius','array describing the radius for each interface (numlayers+1) [m]'))
+                        string="%s\n%s"%(string,fielddisplay(self,'viscosity','array describing each layer''s viscosity (numlayers) [Pa.s]'))
+                        string="%s\n%s"%(string,fielddisplay(self,'lame_lambda','array describing the lame lambda parameter (numlayers) [Pa]'))
+                        string="%s\n%s"%(string,fielddisplay(self,'lame_mu','array describing the shear modulus for each layers (numlayers) [Pa]'))
+                        string="%s\n%s"%(string,fielddisplay(self,'burgers_viscosity','array describing each layer''s transient viscosity, only for Burgers rheologies  (numlayers) [Pa.s]'))
+                        string="%s\n%s"%(string,fielddisplay(self,'burgers_mu','array describing each layer''s transient shear modulus, only for Burgers rheologies  (numlayers) [Pa]'))
+                        string="%s\n%s"%(string,fielddisplay(self,'isburgers','array describing whether we adopt a MaxWell (0) or Burgers (1) rheology (default 0)'))
+                        string="%s\n%s"%(string,fielddisplay(self,'density','array describing each layer''s density (numlayers) [kg/m^3]'))
+                        string="%s\n%s"%(string,fielddisplay(self,'issolid','array describing whether the layer is solid or liquid (default 1) (numlayers)'))
+
+                    else:
+                        raise RuntimeError("materials constructor error message: nature of the material not supported yet! ('ice' or 'litho')");
+
+		return string
+		#}}}
+	def extrude(self,md): # {{{
+            for i in range(len(self.nature)):
+                nat=self.nature[i]; 
+                if nat=='ice':
+                    self.rheology_B=project3d(md,'vector',self.rheology_B,'type','node')
+                    self.rheology_n=project3d(md,'vector',self.rheology_n,'type','element')
+            return self
+	#}}}
+	def setdefaultparameters(self): # {{{
+            for i in range(len(self.nature)):
+                nat=self.nature[i]; 
+                if nat=='ice':
+                    #ice density (kg/m^3)
+                    self.rho_ice=917.
+
+                    #ocean water density (kg/m^3)
+                    self.rho_water=1023.
+
+                    #fresh water density (kg/m^3)
+                    self.rho_freshwater=1000.
+
+                    #water viscosity (N.s/m^2)
+                    self.mu_water=0.001787  
+
+                    #ice heat capacity cp (J/kg/K)
+                    self.heatcapacity=2093.
+
+                    #ice latent heat of fusion L (J/kg)
+                    self.latentheat=3.34*10^5
+
+                    #ice thermal conductivity (W/m/K)
+                    self.thermalconductivity=2.4
+                    
+                    #wet ice thermal conductivity (W/m/K)
+                    self.temperateiceconductivity=.24
+
+                    #the melting point of ice at 1 atmosphere of pressure in K
+                    self.meltingpoint=273.15
+
+                    #rate of change of melting point with pressure (K/Pa)
+                    self.beta=9.8*10^-8
+
+                    #mixed layer (ice-water interface) heat capacity (J/kg/K)
+                    self.mixed_layer_capacity=3974.
+
+                    #thermal exchange velocity (ice-water interface) (m/s)
+                    self.thermal_exchange_velocity=1.00*10^-4
+
+                    #Rheology law: what is the temperature dependence of B with T
+                    #available: none, paterson and arrhenius
+                    self.rheology_law='Paterson'
+
+                elif nat=='litho':
+                    #we default to a configuration that enables running GIA solutions using giacaron and/or giaivins. 
+                    self.numlayers=2
+
+                    #center of the earth (approximation, must not be 0), then the lab (lithosphere/asthenosphere boundary) then the surface
+                    #(with 1d3 to avoid numerical singularities) 
+                    self.radius=[1e3,6278*1e3,6378*1e3]
+
+                    self.viscosity=[1e21,1e40] #mantle and lithosphere viscosity (respectively) [Pa.s]
+                    self.lame_mu=[1.45*1e11,6.7*1e10]  # (Pa) #lithosphere and mantle shear modulus (respectively) [Pa]
+                    self.lame_lambda=self.lame_mu  # (Pa) #mantle and lithosphere lamba parameter (respectively) [Pa]
+                    self.burgers_viscosity=[np.nan,np.nan]
+                    self.burgers_mu=[np.nan,np.nan]
+                    self.isburgers=[0,0]
+                    self.density=[5.51*1e3,5.50*1e3]  # (Pa) #mantle and lithosphere density [kg/m^3]
+                    self.issolid=[1,1] # is layer solid or liquid.
+
+                else:
+                    raise RuntimeError("materials setdefaultparameters error message: nature of the material not supported yet! ('ice' or 'litho')");
+
+		return self
+		#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+            for i in range(len(self.nature)):
+                nat=self.nature[i]; 
+                if nat=='ice':
+                    md = checkfield(md,'fieldname','materials.rho_ice','>',0)
+                    md = checkfield(md,'fieldname','materials.rho_water','>',0)
+                    md = checkfield(md,'fieldname','materials.rho_freshwater','>',0)
+                    md = checkfield(md,'fieldname','materials.mu_water','>',0)
+                    md = checkfield(md,'fieldname','materials.rheology_B','>',0,'timeseries',1,'NaN',1,'Inf',1)
+                    md = checkfield(md,'fieldname','materials.rheology_n','>',0,'size',[md.mesh.numberofelements])
+                    md = checkfield(md,'fieldname','materials.rheology_law','values',['None','BuddJacka','Cuffey','CuffeyTemperate','Paterson','Arrhenius','LliboutryDuval'])
+                elif nat=='litho':
+                    if 'LoveAnalysis' not in analyses: 
+                        return md
+
+                    md = checkfield(md,'fieldname','materials.numlayers','NaN',1,'Inf',1,'>',0,'numel',[1])
+                    md = checkfield(md,'fieldname','materials.radius','NaN',1,'Inf',1,'size',[md.materials.numlayers+1,1],'>',0)
+                    md = checkfield(md,'fieldname','materials.lame_mu','NaN',1,'Inf',1,'size',[md.materials.numlayers,1],'>=',0)
+                    md = checkfield(md,'fieldname','materials.lame_lambda','NaN',1,'Inf',1,'size',[md.materials.numlayers,1],'>=',0)
+                    md = checkfield(md,'fieldname','materials.issolid','NaN',1,'Inf',1,'size',[md.materials.numlayers,1],'>=',0,'<',2)
+                    md = checkfield(md,'fieldname','materials.density','NaN',1,'Inf',1,'size',[md.materials.numlayers,1],'>',0)
+                    md = checkfield(md,'fieldname','materials.viscosity','NaN',1,'Inf',1,'size',[md.materials.numlayers,1],'>=',0)
+                    md = checkfield(md,'fieldname','materials.isburgers','NaN',1,'Inf',1,'size',[md.materials.numlayers,1],'>=',0,'<=',1)
+                    md = checkfield(md,'fieldname','materials.burgers_viscosity','Inf',1,'size',[md.materials.numlayers,1],'>=',0)
+                    md = checkfield(md,'fieldname','materials.burgers_mu','Inf',1,'size',[md.materials.numlayers,1],'>=',0)
+
+                    for i in range(md.materials.numlayers):
+                        if md.materials.isburgers[i] and (np.isnan(md.materials.burgers_viscosity[i] or np.isnan(md.materials.burgers_mu[i]))):
+                            raise RuntimeError("materials checkconsistency error message: Litho burgers_viscosity or burgers_mu has NaN values, inconsistent with isburgers choice")
+                        
+                    if md.materials.issolid[0]==0 or md.materials.lame_mu[0]==0:
+                        raise RuntimeError('First layer must be solid (issolid(1) > 0 AND lame_mu(1) > 0). Add a weak inner core if necessary.')
+                    
+                    for i in range(md.materials.numlayers-1):
+                        if (not md.materials.issolid[i]) and (not md.materials.issolid[i+1]): #if there are at least two consecutive indices that contain issolid = 0
+                            raise RuntimeError("%s%i%s"%('2 or more adjacent fluid layers detected starting at layer ',i,'. This is not supported yet. Consider merging them.'))
+
+                else:
+                    raise RuntimeError("materials checkconsistency error message: nature of the material not supported yet! ('ice' or 'litho')");
+
+		return md
+	# }}}
+	def marshall(self,prefix,md,fid):    # {{{
+
+            #1: MatdamageiceEnum 2: MatestarEnum 3: MaticeEnum 4: MatenhancediceEnum 5: MaterialsEnum 
+            WriteData(fid,prefix,'name','md.materials.type','data',6,'format','Integer')
+            WriteData(fid,prefix,'name','md.materials.nature','data',naturetointeger(self.nature),'format','IntMat','mattype',3)
+
+            for i in range(len(self.nature)):
+                nat=self.nature[i]; 
+                if nat=='ice':
+
+                    WriteData(fid,prefix,'name','md.materials.type','data',3,'format','Integer')
+                    WriteData(fid,prefix,'object',self,'class','materials','fieldname','rho_ice','format','Double')
+                    WriteData(fid,prefix,'object',self,'class','materials','fieldname','rho_water','format','Double')
+                    WriteData(fid,prefix,'object',self,'class','materials','fieldname','rho_freshwater','format','Double')
+                    WriteData(fid,prefix,'object',self,'class','materials','fieldname','mu_water','format','Double')
+                    WriteData(fid,prefix,'object',self,'class','materials','fieldname','heatcapacity','format','Double')
+                    WriteData(fid,prefix,'object',self,'class','materials','fieldname','latentheat','format','Double')
+                    WriteData(fid,prefix,'object',self,'class','materials','fieldname','thermalconductivity','format','Double')
+                    WriteData(fid,prefix,'object',self,'class','materials','fieldname','temperateiceconductivity','format','Double')
+                    WriteData(fid,prefix,'object',self,'class','materials','fieldname','meltingpoint','format','Double')
+                    WriteData(fid,prefix,'object',self,'class','materials','fieldname','beta','format','Double')
+                    WriteData(fid,prefix,'object',self,'class','materials','fieldname','mixed_layer_capacity','format','Double')
+                    WriteData(fid,prefix,'object',self,'class','materials','fieldname','thermal_exchange_velocity','format','Double')
+                    WriteData(fid,prefix,'object',self,'class','materials','fieldname','rheology_B','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
+                    WriteData(fid,prefix,'object',self,'class','materials','fieldname','rheology_n','format','DoubleMat','mattype',2)
+                    WriteData(fid,prefix,'data',self.rheology_law,'name','md.materials.rheology_law','format','String')
+
+                elif nat=='litho':
+                    WriteData(fid,prefix,'object',self,'class','materials','fieldname','numlayers','format','Integer') 
+                    WriteData(fid,prefix,'object',self,'class','materials','fieldname','radius','format','DoubleMat','mattype',3)
+                    WriteData(fid,prefix,'object',self,'class','materials','fieldname','lame_mu','format','DoubleMat','mattype',3)
+                    WriteData(fid,prefix,'object',self,'class','materials','fieldname','lame_lambda','format','DoubleMat','mattype',3)
+                    WriteData(fid,prefix,'object',self,'class','materials','fieldname','issolid','format','DoubleMat','mattype',3)
+                    WriteData(fid,prefix,'object',self,'class','materials','fieldname','density','format','DoubleMat','mattype',3) 
+                    WriteData(fid,prefix,'object',self,'class','materials','fieldname','viscosity','format','DoubleMat','mattype',3) 
+                    WriteData(fid,prefix,'object',self,'class','materials','fieldname','isburgers','format','DoubleMat','mattype',3) 
+                    WriteData(fid,prefix,'object',self,'class','materials','fieldname','burgers_viscosity','format','DoubleMat','mattype',3) 
+                    WriteData(fid,prefix,'object',self,'class','materials','fieldname','burgers_mu','format','DoubleMat','mattype',3)
+
+                else:
+                    raise RuntimeError("materials constructor error message: nature of the material not supported yet! (''ice'' or ''litho'')")
+
+	# }}}
Index: /issm/trunk/src/m/classes/matestar.py
===================================================================
--- /issm/trunk/src/m/classes/matestar.py	(revision 22758)
+++ /issm/trunk/src/m/classes/matestar.py	(revision 22758)
@@ -0,0 +1,175 @@
+import numpy as np
+from fielddisplay import fielddisplay
+from project3d import project3d
+from checkfield import checkfield
+from WriteData import WriteData
+
+class matestar(object):
+	"""
+	matestar class definition
+
+	   Usage:
+	      matestar=matestar()
+	"""
+
+	def __init__(self): # {{{
+		
+		rho_ice                    = 0.
+		rho_water                  = 0.
+		rho_freshwater             = 0.
+		mu_water                   = 0.
+		heatcapacity               = 0.
+		latentheat                 = 0.
+		thermalconductivity        = 0.
+		temperateiceconductivity   = 0.
+		meltingpoint               = 0.
+		beta                       = 0.
+		mixed_layer_capacity       = 0.
+		thermal_exchange_velocity  = 0.
+		rheology_B    = float('NaN')
+		rheology_Ec   = float('NaN')
+		rheology_Es   = float('NaN')
+		rheology_law = ''
+
+		#giaivins: 
+		lithosphere_shear_modulus  = 0.
+		lithosphere_density        = 0.
+		mantle_shear_modulus       = 0.
+		mantle_density             = 0.
+
+		#slr
+		earth_density              = 0
+
+                #set default parameters:
+		self.setdefaultparameters()
+	#}}}
+	def __repr__(self): # {{{
+		string="   Materials:"
+
+		string="%s\n%s"%(string,fielddisplay(self,'rho_ice','ice density [kg/m^3]'))
+		string="%s\n%s"%(string,fielddisplay(self,'rho_water','ocean water density [kg/m^3]'))
+		string="%s\n%s"%(string,fielddisplay(self,'rho_freshwater','fresh water density [kg/m^3]'))
+		string="%s\n%s"%(string,fielddisplay(self,'mu_water','water viscosity [N s/m^2]'))
+		string="%s\n%s"%(string,fielddisplay(self,'heatcapacity','heat capacity [J/kg/K]'))
+		string="%s\n%s"%(string,fielddisplay(self,'thermalconductivity',['ice thermal conductivity [W/m/K]']))
+		string="%s\n%s"%(string,fielddisplay(self,'temperateiceconductivity','temperate ice thermal conductivity [W/m/K]'))
+		string="%s\n%s"%(string,fielddisplay(self,'meltingpoint','melting point of ice at 1atm in K'))
+		string="%s\n%s"%(string,fielddisplay(self,'latentheat','latent heat of fusion [J/kg]'))
+		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/3)]'))
+		string="%s\n%s"%(string,fielddisplay(self,'rheology_Ec','compressive enhancement factor'))
+		string="%s\n%s"%(string,fielddisplay(self,'rheology_Es','shear enhancement factor'))
+		string="%s\n%s"%(string,fielddisplay(self,'rheology_law',['law for the temperature dependance of the rheology: ''None'', ''BuddJacka'', ''Cuffey'', ''CuffeyTemperate'', ''Paterson'', ''Arrhenius'' or ''LliboutryDuval''']))
+		string="%s\n%s"%(string,fielddisplay(self,'lithosphere_shear_modulus','Lithosphere shear modulus [Pa]'))
+		string="%s\n%s"%(string,fielddisplay(self,'lithosphere_density','Lithosphere density [g/cm^-3]'))
+		string="%s\n%s"%(string,fielddisplay(self,'mantle_shear_modulus','Mantle shear modulus [Pa]'))
+		string="%s\n%s"%(string,fielddisplay(self,'mantle_density','Mantle density [g/cm^-3]'))
+		string="%s\n%s"%(string,fielddisplay(self,'earth_density','Mantle density [kg/m^-3]'))
+
+		return string
+	#}}}
+	def extrude(self,md): # {{{
+		self.rheology_B=project3d(md,'vector',self.rheology_B,'type','node')
+		self.rheology_Ec=project3d(md,'vector',self.rheology_Ec,'type','node')
+		self.rheology_Es=project3d(md,'vector',self.rheology_Es,'type','node')
+       		return self
+	#}}}
+	def setdefaultparameters(self): # {{{
+		#ice density (kg/m^3)
+		self.rho_ice=917.
+
+		#ocean water density (kg/m^3)
+		self.rho_water=1023.
+
+		#fresh water density (kg/m^3)
+		self.rho_freshwater=1000.
+
+		#water viscosity (N.s/m^2)
+		self.mu_water=0.001787 
+
+		#ice heat capacity cp (J/kg/K)
+		self.heatcapacity=2093.
+
+		#ice latent heat of fusion L (J/kg)
+		self.latentheat=3.34*10**5
+
+		#ice thermal conductivity (W/m/K)
+		self.thermalconductivity=2.4
+			
+		#wet ice thermal conductivity (W/m/K)
+		self.temperateiceconductivity=.24
+
+		#the melting point of ice at 1 atmosphere of pressure in K
+		self.meltingpoint=273.15
+
+		#rate of change of melting point with pressure (K/Pa)
+		self.beta=9.8*10**-8
+
+		#mixed layer (ice-water interface) heat capacity (J/kg/K)
+		self.mixed_layer_capacity=3974.
+
+		#thermal exchange velocity (ice-water interface) (m/s)
+		self.thermal_exchange_velocity=1.00*10**-4
+
+		#Rheology law: what is the temperature dependence of B with T
+		#available: none, paterson and arrhenius
+		self.rheology_law='Paterson'
+
+		# GIA:
+		self.lithosphere_shear_modulus  = 6.7*10**10  # (Pa)
+		self.lithosphere_density        = 3.32      # (g/cm^-3)
+		self.mantle_shear_modulus       = 1.45*10**11 # (Pa)
+		self.mantle_density             = 3.34      # (g/cm^-3)
+
+		#SLR
+		self.earth_density= 5512  # average density of the Earth, (kg/m^3)
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		md = checkfield(md,'fieldname','materials.rho_ice','>',0)
+		md = checkfield(md,'fieldname','materials.rho_water','>',0)
+		md = checkfield(md,'fieldname','materials.rho_freshwater','>',0)
+		md = checkfield(md,'fieldname','materials.mu_water','>',0)
+		md = checkfield(md,'fieldname','materials.rheology_B','>',0,'size',[md.mesh.numberofvertices],'NaN',1,'Inf',1)
+		md = checkfield(md,'fieldname','materials.rheology_Ec','>',0,'size',[md.mesh.numberofvertices],'NaN',1,'Inf',1)
+		md = checkfield(md,'fieldname','materials.rheology_Es','>',0,'size',[md.mesh.numberofvertices],'NaN',1,'Inf',1)
+		md = checkfield(md,'fieldname','materials.rheology_law','values',['None','BuddJacka', 'Cuffey','CuffeyTemperate','Paterson','Arrhenius','LliboutryDuval'])
+
+		if 'GiaAnalysis' in analyses:
+			md = checkfield(md,'fieldname','materials.lithosphere_shear_modulus','>',0,'numel',1)
+			md = checkfield(md,'fieldname','materials.lithosphere_density','>',0,'numel',1)
+			md = checkfield(md,'fieldname','materials.mantle_shear_modulus','>',0,'numel',1)
+			md = checkfield(md,'fieldname','materials.mantle_density','>',0,'numel',1)
+		if 'SealevelriseAnalysis' in analyses:
+			md = checkfield(md,'fieldname','materials.earth_density','>',0,'numel',1)
+
+		return md
+	# }}}
+	def marshall(self,prefix,md,fid):    # {{{
+		WriteData(fid,prefix,'name','md.materials.type','data',2,'format','Integer')
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','rho_ice','format','Double')
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','rho_water','format','Double')
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','rho_freshwater','format','Double')
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','mu_water','format','Double')
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','heatcapacity','format','Double')
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','latentheat','format','Double')
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','thermalconductivity','format','Double')
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','temperateiceconductivity','format','Double')
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','meltingpoint','format','Double')
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','beta','format','Double')
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','mixed_layer_capacity','format','Double')
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','thermal_exchange_velocity','format','Double')
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','rheology_B','format','DoubleMat','mattype',1)
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','rheology_Ec','format','DoubleMat','mattype',1)
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','rheology_Es','format','DoubleMat','mattype',1)
+		WriteData(fid,prefix,'data',self.rheology_law,'name','md.materials.rheology_law','format','String')
+
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','lithosphere_shear_modulus','format','Double')
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','lithosphere_density','format','Double','scale',10^3)
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','mantle_shear_modulus','format','Double')
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','mantle_density','format','Double','scale',10**3)
+		WriteData(fid,prefix,'object',self,'class','materials','fieldname','earth_density','format','Double')
+	# }}}
Index: /issm/trunk/src/m/classes/matice.js
===================================================================
--- /issm/trunk/src/m/classes/matice.js	(revision 22757)
+++ /issm/trunk/src/m/classes/matice.js	(revision 22758)
@@ -6,137 +6,137 @@
 function matice(){
 	//methods
-		this.setdefaultparameters = function(){ // {{{
+	this.setdefaultparameters = function(){ // {{{
 
-			//ice density (kg/m^3)
-			this.rho_ice=917.;
+		//ice density (kg/m^3)
+		this.rho_ice=917.;
 
-			//ocean water density (kg/m^3)
-			this.rho_water=1023.;
+		//ocean water density (kg/m^3)
+		this.rho_water=1023.;
 
-			//fresh water density (kg/m^3)
-			this.rho_freshwater=1000.;
+		//fresh water density (kg/m^3)
+		this.rho_freshwater=1000.;
 
-			//water viscosity (N.s/m^2)
-			this.mu_water=0.001787;  
+		//water viscosity (N.s/m^2)
+		this.mu_water=0.001787;  
 
-			//ice heat capacity cp (J/kg/K)
-			this.heatcapacity=2093.;
+		//ice heat capacity cp (J/kg/K)
+		this.heatcapacity=2093.;
 
-			//ice latent heat of fusion L (J/kg)
-			this.latentheat=3.34*Math.pow(10,5);
+		//ice latent heat of fusion L (J/kg)
+		this.latentheat=3.34*Math.pow(10,5);
 
-			//ice thermal conductivity (W/m/K)
-			this.thermalconductivity=2.4;
-			
-			//wet ice thermal conductivity (W/m/K)
-			this.temperateiceconductivity=.24;
+		//ice thermal conductivity (W/m/K)
+		this.thermalconductivity=2.4;
 
-			//the melting point of ice at 1 atmosphere of pressure in K
-			this.meltingpoint=273.15;
+		//wet ice thermal conductivity (W/m/K)
+		this.temperateiceconductivity=.24;
 
-			//rate of change of melting point with pressure (K/Pa)
-			this.beta=9.8*Math.pow(10,-8);
+		//the melting point of ice at 1 atmosphere of pressure in K
+		this.meltingpoint=273.15;
 
-			//mixed layer (ice-water interface) heat capacity (J/kg/K)
-			this.mixed_layer_capacity=3974.;
+		//rate of change of melting point with pressure (K/Pa)
+		this.beta=9.8*Math.pow(10,-8);
 
-			//thermal exchange velocity (ice-water interface) (m/s)
-			this.thermal_exchange_velocity=1.00*Math.pow(10,-4);
+		//mixed layer (ice-water interface) heat capacity (J/kg/K)
+		this.mixed_layer_capacity=3974.;
 
-			//Rheology law: what is the temperature dependence of B with T
-			//available: none, paterson and arrhenius
-			this.rheology_law='Paterson';
+		//thermal exchange velocity (ice-water interface) (m/s)
+		this.thermal_exchange_velocity=1.00*Math.pow(10,-4);
 
-			// GIA:
-			this.lithosphere_shear_modulus  = 6.7*Math.pow(10,10);  // (Pa)
-			this.lithosphere_density        = 3.32;       // (g/cm^-3)
-			this.mantle_shear_modulus       = 1.45*Math.pow(10,11); // (Pa)
-			this.mantle_density             = 3.34;       // (g/cm^-3)
-			
-			//SLR
-			this.earth_density= 5512;  // average density of the Earth, (kg/m^3)
+		//Rheology law: what is the temperature dependence of B with T
+		//available: none, paterson and arrhenius
+		this.rheology_law='Paterson';
+
+		// GIA:
+		this.lithosphere_shear_modulus  = 6.7*Math.pow(10,10);  // (Pa)
+		this.lithosphere_density        = 3.32;       // (g/cm^-3)
+		this.mantle_shear_modulus       = 1.45*Math.pow(10,11); // (Pa)
+		this.mantle_density             = 3.34;       // (g/cm^-3)
+
+		//SLR
+		this.earth_density= 5512;  // average density of the Earth, (kg/m^3)
 
 
-		} //}}}
-		this.disp = function() {// {{{
-			console.log(sprintf('   Materials:'));
+	} //}}}
+	this.disp = function() {// {{{
+		console.log(sprintf('   Materials:'));
 
-			fielddisplay(this,'rho_ice','ice density [kg/m^3]');
-			fielddisplay(this,'rho_water','ocean water density [kg/m^3]');
-			fielddisplay(this,'rho_freshwater','fresh water density [kg/m^3]');
-			fielddisplay(this,'mu_water','water viscosity [N s/m^2]');
-			fielddisplay(this,'heatcapacity','heat capacity [J/kg/K]');
-			fielddisplay(this,'thermalconductivity','ice thermal conductivity [W/m/K]');
-			fielddisplay(this,'temperateiceconductivity','temperate ice thermal conductivity [W/m/K]');
-			fielddisplay(this,'meltingpoint','melting point of ice at 1atm in K');
-			fielddisplay(this,'latentheat','latent heat of fusion [J/kg]');
-			fielddisplay(this,'beta','rate of change of melting point with pressure [K/Pa]');
-			fielddisplay(this,'mixed_layer_capacity','mixed layer capacity [W/kg/K]');
-			fielddisplay(this,'thermal_exchange_velocity','thermal exchange velocity [m/s]');
-			fielddisplay(this,'rheology_B','flow law parameter [Pa/s^(1/n)]');
-			fielddisplay(this,'rheology_n',"Glen's flow law exponent");
-			fielddisplay(this,'rheology_law',"law for the temperature dependance of the rheology: 'None', 'BuddJacka', 'Cuffey', 'CuffeyTemperate', 'Paterson', 'Arrhenius' or 'LliboutryDuval'");
-			fielddisplay(this,'lithosphere_shear_modulus','Lithosphere shear modulus [Pa]');
-			fielddisplay(this,'lithosphere_density','Lithosphere density [g/cm^-3]');
-			fielddisplay(this,'mantle_shear_modulus','Mantle shear modulus [Pa]');
-			fielddisplay(this,'mantle_density','Mantle density [g/cm^-3]');
-			fielddisplay(this,'earth_density','Mantle density [kg/m^-3]');
+		fielddisplay(this,'rho_ice','ice density [kg/m^3]');
+		fielddisplay(this,'rho_water','ocean water density [kg/m^3]');
+		fielddisplay(this,'rho_freshwater','fresh water density [kg/m^3]');
+		fielddisplay(this,'mu_water','water viscosity [N s/m^2]');
+		fielddisplay(this,'heatcapacity','heat capacity [J/kg/K]');
+		fielddisplay(this,'thermalconductivity','ice thermal conductivity [W/m/K]');
+		fielddisplay(this,'temperateiceconductivity','temperate ice thermal conductivity [W/m/K]');
+		fielddisplay(this,'meltingpoint','melting point of ice at 1atm in K');
+		fielddisplay(this,'latentheat','latent heat of fusion [J/kg]');
+		fielddisplay(this,'beta','rate of change of melting point with pressure [K/Pa]');
+		fielddisplay(this,'mixed_layer_capacity','mixed layer capacity [W/kg/K]');
+		fielddisplay(this,'thermal_exchange_velocity','thermal exchange velocity [m/s]');
+		fielddisplay(this,'rheology_B','flow law parameter [Pa/s^(1/n)]');
+		fielddisplay(this,'rheology_n',"Glen's flow law exponent");
+		fielddisplay(this,'rheology_law',"law for the temperature dependance of the rheology: 'None', 'BuddJacka', 'Cuffey', 'CuffeyTemperate', 'Paterson', 'Arrhenius' or 'LliboutryDuval'");
+		fielddisplay(this,'lithosphere_shear_modulus','Lithosphere shear modulus [Pa]');
+		fielddisplay(this,'lithosphere_density','Lithosphere density [g/cm^-3]');
+		fielddisplay(this,'mantle_shear_modulus','Mantle shear modulus [Pa]');
+		fielddisplay(this,'mantle_density','Mantle density [g/cm^-3]');
+		fielddisplay(this,'earth_density','Mantle density [kg/m^-3]');
 
-		} // }}}
-        this.extrude = function(md) {//{{{
-            this.rheology_B=project3d(md,'vector',this.rheology_B,'type','node');
-            this.rheology_n=project3d(md,'vector',this.rheology_n,'type','element');
-            return this;
-        }//}}}
-		this.classname = function() {// {{{
-			return "matice";
-		} // }}}
-		this.checkconsistency = function(md,solution,analyses) { // {{{
-			checkfield(md,'fieldname','materials.rho_ice','>',0);
-			checkfield(md,'fieldname','materials.rho_water','>',0);
-			checkfield(md,'fieldname','materials.rho_freshwater','>',0);
-			checkfield(md,'fieldname','materials.mu_water','>',0);
-			checkfield(md,'fieldname','materials.rheology_B','>',0,'timeseries',1,'NaN',1,'Inf',1);
-			checkfield(md,'fieldname','materials.rheology_n','>',0,'size',[md.mesh.numberofelements,1]);
-			checkfield(md,'fieldname','materials.rheology_law','values',['None','BuddJacka','Cuffey','CuffeyTemperate','Paterson','Arrhenius','LliboutryDuval']);
+	} // }}}
+	this.extrude = function(md) {//{{{
+		this.rheology_B=project3d(md,'vector',this.rheology_B,'type','node');
+		this.rheology_n=project3d(md,'vector',this.rheology_n,'type','element');
+		return this;
+	}//}}}
+	this.classname = function() {// {{{
+		return "matice";
+	} // }}}
+	this.checkconsistency = function(md,solution,analyses) { // {{{
+		checkfield(md,'fieldname','materials.rho_ice','>',0);
+		checkfield(md,'fieldname','materials.rho_water','>',0);
+		checkfield(md,'fieldname','materials.rho_freshwater','>',0);
+		checkfield(md,'fieldname','materials.mu_water','>',0);
+		checkfield(md,'fieldname','materials.rheology_B','>',0,'timeseries',1,'NaN',1,'Inf',1);
+		checkfield(md,'fieldname','materials.rheology_n','>',0,'size',[md.mesh.numberofelements,1]);
+		checkfield(md,'fieldname','materials.rheology_law','values',['None','BuddJacka','Cuffey','CuffeyTemperate','Paterson','Arrhenius','LliboutryDuval']);
 
-			if(ArrayAnyEqual(ArrayIsMember('GiaAnalysis',analyses),1)){
-				checkfield(md,'fieldname','materials.lithosphere_shear_modulus','>',0,'numel',1);
-				checkfield(md,'fieldname','materials.lithosphere_density','>',0,'numel',1);
-				checkfield(md,'fieldname','materials.mantle_shear_modulus','>',0,'numel',1);
-				checkfield(md,'fieldname','materials.mantle_density','>',0,'numel',1);
-			}
-			if (ArrayAnyEqual(ArrayIsMember('SealevelriseAnalysis',analyses),1)){
-				checkfield(md,'fieldname','materials.earth_density','>',0,'numel',1);
-			}
+		if(ArrayAnyEqual(ArrayIsMember('GiaAnalysis',analyses),1)){
+			checkfield(md,'fieldname','materials.lithosphere_shear_modulus','>',0,'numel',1);
+			checkfield(md,'fieldname','materials.lithosphere_density','>',0,'numel',1);
+			checkfield(md,'fieldname','materials.mantle_shear_modulus','>',0,'numel',1);
+			checkfield(md,'fieldname','materials.mantle_density','>',0,'numel',1);
+		}
+		if (ArrayAnyEqual(ArrayIsMember('SealevelriseAnalysis',analyses),1)){
+			checkfield(md,'fieldname','materials.earth_density','>',0,'numel',1);
+		}
 
 
-		} // }}}
-		this.marshall=function(md,prefix,fid) { //{{{
-			WriteData(fid,prefix,'name','md.materials.type','data',3,'format','Integer');
-			WriteData(fid,prefix,'object',this,'class','materials','fieldname','rho_ice','format','Double');
-			WriteData(fid,prefix,'object',this,'class','materials','fieldname','rho_water','format','Double');
-			WriteData(fid,prefix,'object',this,'class','materials','fieldname','rho_freshwater','format','Double');
-			WriteData(fid,prefix,'object',this,'class','materials','fieldname','mu_water','format','Double');
-			WriteData(fid,prefix,'object',this,'class','materials','fieldname','heatcapacity','format','Double');
-			WriteData(fid,prefix,'object',this,'class','materials','fieldname','latentheat','format','Double');
-			WriteData(fid,prefix,'object',this,'class','materials','fieldname','thermalconductivity','format','Double');
-			WriteData(fid,prefix,'object',this,'class','materials','fieldname','temperateiceconductivity','format','Double');
-			WriteData(fid,prefix,'object',this,'class','materials','fieldname','meltingpoint','format','Double');
-			WriteData(fid,prefix,'object',this,'class','materials','fieldname','beta','format','Double');
-			WriteData(fid,prefix,'object',this,'class','materials','fieldname','mixed_layer_capacity','format','Double');
-			WriteData(fid,prefix,'object',this,'class','materials','fieldname','thermal_exchange_velocity','format','Double');
-			WriteData(fid,prefix,'object',this,'class','materials','fieldname','rheology_B','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
-			WriteData(fid,prefix,'object',this,'class','materials','fieldname','rheology_n','format','DoubleMat','mattype',2);
-			WriteData(fid,prefix,'data',this.rheology_law,'name','md.materials.rheology_law','format','String');
-			WriteData(fid,prefix,'object',this,'class','materials','fieldname','lithosphere_shear_modulus','format','Double');
-			WriteData(fid,prefix,'object',this,'class','materials','fieldname','lithosphere_density','format','Double','scale',Math.pow(10,3));
-			WriteData(fid,prefix,'object',this,'class','materials','fieldname','mantle_shear_modulus','format','Double');
-			WriteData(fid,prefix,'object',this,'class','materials','fieldname','mantle_density','format','Double','scale',Math.pow(10,3));
-			WriteData(fid,prefix,'object',this,'class','materials','fieldname','earth_density','format','Double');
+	} // }}}
+	this.marshall=function(md,prefix,fid) { //{{{
+		WriteData(fid,prefix,'name','md.materials.type','data',3,'format','Integer');
+		WriteData(fid,prefix,'object',this,'class','materials','fieldname','rho_ice','format','Double');
+		WriteData(fid,prefix,'object',this,'class','materials','fieldname','rho_water','format','Double');
+		WriteData(fid,prefix,'object',this,'class','materials','fieldname','rho_freshwater','format','Double');
+		WriteData(fid,prefix,'object',this,'class','materials','fieldname','mu_water','format','Double');
+		WriteData(fid,prefix,'object',this,'class','materials','fieldname','heatcapacity','format','Double');
+		WriteData(fid,prefix,'object',this,'class','materials','fieldname','latentheat','format','Double');
+		WriteData(fid,prefix,'object',this,'class','materials','fieldname','thermalconductivity','format','Double');
+		WriteData(fid,prefix,'object',this,'class','materials','fieldname','temperateiceconductivity','format','Double');
+		WriteData(fid,prefix,'object',this,'class','materials','fieldname','meltingpoint','format','Double');
+		WriteData(fid,prefix,'object',this,'class','materials','fieldname','beta','format','Double');
+		WriteData(fid,prefix,'object',this,'class','materials','fieldname','mixed_layer_capacity','format','Double');
+		WriteData(fid,prefix,'object',this,'class','materials','fieldname','thermal_exchange_velocity','format','Double');
+		WriteData(fid,prefix,'object',this,'class','materials','fieldname','rheology_B','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
+		WriteData(fid,prefix,'object',this,'class','materials','fieldname','rheology_n','format','DoubleMat','mattype',2);
+		WriteData(fid,prefix,'data',this.rheology_law,'name','md.materials.rheology_law','format','String');
+		WriteData(fid,prefix,'object',this,'class','materials','fieldname','lithosphere_shear_modulus','format','Double');
+		WriteData(fid,prefix,'object',this,'class','materials','fieldname','lithosphere_density','format','Double','scale',Math.pow(10,3));
+		WriteData(fid,prefix,'object',this,'class','materials','fieldname','mantle_shear_modulus','format','Double');
+		WriteData(fid,prefix,'object',this,'class','materials','fieldname','mantle_density','format','Double','scale',Math.pow(10,3));
+		WriteData(fid,prefix,'object',this,'class','materials','fieldname','earth_density','format','Double');
 
-		}//}}}
-		this.fix=function() { //{{{
-		}//}}}
+	}//}}}
+	this.fix=function() { //{{{
+	}//}}}
 	//properties 
 	// {{{
Index: /issm/trunk/src/m/classes/mesh2d.js
===================================================================
--- /issm/trunk/src/m/classes/mesh2d.js	(revision 22757)
+++ /issm/trunk/src/m/classes/mesh2d.js	(revision 22758)
@@ -44,4 +44,5 @@
 			fielddisplay(this,"long","vertices longitude [degrees]");
 			fielddisplay(this,"epsg","EPSG code (ex: 3413 for UPS Greenland, 3031 for UPS Antarctica)");
+			fielddisplay(self,"scale_factor","Projection correction for volume, area, etc. computation)");
 		} //}}}
 		this.classname = function () { //{{{
@@ -70,4 +71,5 @@
 			checkfield(md,'fieldname','mesh.average_vertex_connectivity','>=',9,'message',"'mesh.average_vertex_connectivity' should be at least 9 in 2d");
 			checkfield(md,'fieldname','mesh.segments','NaN',1,'Inf',1,'>',0,'size',[NaN, 3]);
+			if(this.scale_factor.length>1) checkfield(md,'fieldname','mesh.scale_factor','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices, 1]);
 
 			switch(solution){
@@ -92,4 +94,5 @@
 			WriteData(fid,prefix,'object',this,'class','mesh','fieldname','vertexonboundary','format','DoubleMat','mattype',1);
 			WriteData(fid,prefix,'object',this,'class','mesh','fieldname','segments','format','DoubleMat','mattype',3);
+			WriteData(fid,prefix,'object',this,'class','mesh','fieldname','scale_factor','format','DoubleMat','mattype',1);
 		}//}}}
 		this.fix=function() { //{{{
@@ -104,4 +107,5 @@
 			this.lat=NullFix(this.lat,NaN);
 			this.long=NullFix(this.long,NaN);
+			this.scale_factor=NullFix(this.scale_factor,NaN);
 		}//}}}
 
@@ -118,4 +122,5 @@
 		this.long                        = NaN;
 		this.epsg                        = 0;
+		this.scale_factor                = NaN;
 
 		this.vertexonboundary            = NaN;
Index: /issm/trunk/src/m/classes/mesh2d.m
===================================================================
--- /issm/trunk/src/m/classes/mesh2d.m	(revision 22757)
+++ /issm/trunk/src/m/classes/mesh2d.m	(revision 22758)
@@ -16,4 +16,5 @@
 		long                        = NaN;
 		epsg                        = 0;
+		scale_factor                = NaN;
 
 		vertexonboundary            = NaN;
@@ -80,4 +81,6 @@
 		end % }}}
 		function md = checkconsistency(self,md,solution,analyses) % {{{
+			
+			if strcmpi(solution,'LoveSolution'), return; end
 
 			md = checkfield(md,'fieldname','mesh.x','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices 1]);
@@ -92,4 +95,7 @@
 			md = checkfield(md,'fieldname','mesh.average_vertex_connectivity','>=',9,'message','''mesh.average_vertex_connectivity'' should be at least 9 in 2d');
 			md = checkfield(md,'fieldname','mesh.segments','NaN',1,'Inf',1,'>',0,'size',[NaN 3]);
+			if numel(md.mesh.scale_factor)>1,
+				md = checkfield(md,'fieldname','mesh.scale_factor','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices 1]);
+			end
 
 			if strcmp(solution,'ThermalSolution')
@@ -125,4 +131,5 @@
 			fielddisplay(self,'long','vertices longitude [degrees]');
 			fielddisplay(self,'epsg','EPSG code (ex: 3413 for UPS Greenland, 3031 for UPS Antarctica)');
+			fielddisplay(self,'scale_factor','Projection correction for volume, area, etc. computation)');
 		end % }}}
 		function marshall(self,prefix,md,fid) % {{{
@@ -139,4 +146,9 @@
 			WriteData(fid,prefix,'object',self,'class','mesh','fieldname','vertexonboundary','format','DoubleMat','mattype',1);
 			WriteData(fid,prefix,'object',self,'class','mesh','fieldname','segments','format','DoubleMat','mattype',3);
+			WriteData(fid,prefix,'object',self,'class','mesh','fieldname','scale_factor','format','DoubleMat','mattype',1);
+			if md.transient.isoceancoupling, %Need to add lat/long coordinates to couple with ocean as they rely on lat/long coordinate system
+				WriteData(fid,prefix,'object',self,'class','mesh','fieldname','lat','format','DoubleMat','mattype',1);
+				WriteData(fid,prefix,'object',self,'class','mesh','fieldname','long','format','DoubleMat','mattype',1);
+			end
 		end % }}}
 		function t = domaintype(self) % {{{
@@ -160,4 +172,5 @@
 			writejs1Darray(fid,[modelname '.mesh.long'],self.long);
 			writejsdouble(fid,[modelname '.mesh.epsg'],self.epsg);
+			writejsdouble(fid,[modelname '.mesh.scale_factor'],self.scale_factor);
 			writejs1Darray(fid,[modelname '.mesh.vertexonboundary'],self.vertexonboundary);
 			writejs2Darray(fid,[modelname '.mesh.edges'],self.edges);
Index: /issm/trunk/src/m/classes/mesh2d.py
===================================================================
--- /issm/trunk/src/m/classes/mesh2d.py	(revision 22757)
+++ /issm/trunk/src/m/classes/mesh2d.py	(revision 22758)
@@ -24,4 +24,5 @@
 		self.long                        = float('NaN');
 		self.epsg                        = 0;
+		self.scale_factor                = float('NaN');
 
 		self.vertexonboundary            = float('NaN');
@@ -68,4 +69,5 @@
 		string="%s\n%s"%(string,fielddisplay(self,"long","vertices longitude [degrees]"))
 		string="%s\n%s"%(string,fielddisplay(self,"epsg","EPSG code (ex: 3413 for UPS Greenland, 3031 for UPS Antarctica)"))
+		string="%s\n%s"%(string,fielddisplay(self,"scale_factor","Projection correction for volume, area, etc. computation"))
 		return string
 		#}}}
@@ -82,4 +84,6 @@
 	#}}}
 	def checkconsistency(self,md,solution,analyses):    # {{{
+		if(solution=='LoveSolution'):
+			return
 
 		md = checkfield(md,'fieldname','mesh.x','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
@@ -93,4 +97,7 @@
 		md = checkfield(md,'fieldname','mesh.average_vertex_connectivity','>=',9,'message',"'mesh.average_vertex_connectivity' should be at least 9 in 2d")
 		md = checkfield(md,'fieldname','mesh.segments','NaN',1,'Inf',1,'>',0,'size',[np.nan,3]);
+		if(np.size(self.scale_factor)>1):
+                        md = checkfield(md,'fieldname','mesh.scale_factor','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
+                
 		if solution=='ThermalSolution':
 			md.checkmessage("thermal not supported for 2d mesh")
@@ -118,4 +125,9 @@
 		WriteData(fid,prefix,'object',self,'class','mesh','fieldname','numberofvertices','format','Integer')
 		WriteData(fid,prefix,'object',self,'class','mesh','fieldname','average_vertex_connectivity','format','Integer')
-		WriteData(fid,prefix,'object',self,'class','mesh','fieldname','segments','format','DoubleMat','mattype',3);
+		WriteData(fid,prefix,'object',self,'class','mesh','fieldname','vertexonboundary','format','DoubleMat','mattype',1)
+		WriteData(fid,prefix,'object',self,'class','mesh','fieldname','segments','format','DoubleMat','mattype',3)
+		WriteData(fid,prefix,'object',self,'class','mesh','fieldname','scale_factor','format','DoubleMat','mattype',1)
+		if md.transient.isoceancoupling:
+			WriteData(fid,prefix,'object',self,'class','mesh','fieldname','lat','format','DoubleMat','mattype',1)
+			WriteData(fid,prefix,'object',self,'class','mesh','fieldname','long','format','DoubleMat','mattype',1)
 	# }}}
Index: /issm/trunk/src/m/classes/mesh2dvertical.m
===================================================================
--- /issm/trunk/src/m/classes/mesh2dvertical.m	(revision 22757)
+++ /issm/trunk/src/m/classes/mesh2dvertical.m	(revision 22758)
@@ -16,4 +16,5 @@
 		long                        = NaN;
 		epsg                        = NaN;
+		scale_factor                = NaN;
 
 		vertexonboundary            = NaN;
@@ -79,4 +80,6 @@
 		end % }}}
 		function md = checkconsistency(self,md,solution,analyses) % {{{
+			
+			if strcmpi(solution,'LoveSolution'), return; end
 
 			md = checkfield(md,'fieldname','mesh.x','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices 1]);
@@ -92,4 +95,7 @@
 			md = checkfield(md,'fieldname','mesh.vertexonsurface','size',[md.mesh.numberofvertices 1],'values',[0 1]);
 			md = checkfield(md,'fieldname','mesh.average_vertex_connectivity','>=',9,'message','''mesh.average_vertex_connectivity'' should be at least 9 in 2d');
+			if numel(md.mesh.scale_factor)>1,
+				md = checkfield(md,'fieldname','mesh.scale_factor','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices 1]);
+			end
 
 			if strcmp(solution,'ThermalSolution')
@@ -123,4 +129,5 @@
 			fielddisplay(self,'long','vertices longitude [degrees]');
 			fielddisplay(self,'epsg','EPSG code (ex: 3413 for UPS Greenland, 3031 for UPS Antarctica)');
+			fielddisplay(self,'scale_factor','Projection correction for volume, area, etc. computation)');
 		end % }}}
 		function marshall(self,prefix,md,fid) % {{{
@@ -137,4 +144,5 @@
 			WriteData(fid,prefix,'object',self,'class','mesh','fieldname','vertexonsurface','format','BooleanMat','mattype',1);
 			WriteData(fid,prefix,'object',self,'class','mesh','fieldname','average_vertex_connectivity','format','Integer');
+			WriteData(fid,prefix,'object',self,'class','mesh','fieldname','scale_factor','format','DoubleMat','mattype',1);
 		end % }}}
 		function t = domaintype(self) % {{{
Index: /issm/trunk/src/m/classes/mesh2dvertical.py
===================================================================
--- /issm/trunk/src/m/classes/mesh2dvertical.py	(revision 22758)
+++ /issm/trunk/src/m/classes/mesh2dvertical.py	(revision 22758)
@@ -0,0 +1,135 @@
+import numpy as np
+from fielddisplay import fielddisplay
+from checkfield import checkfield
+import MatlabFuncs as m
+from WriteData import WriteData
+
+class mesh2dvertical(object):
+	"""
+	MESH2DVERTICAL class definition
+
+	   Usage:
+	      mesh2dvertical=mesh2dvertical();
+	"""
+
+	def __init__(self): # {{{
+		self.x                           = float('NaN')
+		self.y                           = float('NaN')
+		self.elements                    = float('NaN')
+		self.numberofelements            = 0
+		self.numberofvertices            = 0
+		self.numberofedges               = 0
+		
+		self.lat                         = float('NaN')
+		self.long                        = float('NaN')
+		self.epsg                        = float('NaN')
+		self.scale_factor                = float('NaN');
+
+		self.vertexonboundary            = float('NaN')
+		self.vertexonbase            	 = float('NaN')
+		self.vertexonsurface             = float('NaN')
+
+		self.edges                       = float('NaN')
+		self.segments                    = float('NaN')
+		self.segmentmarkers              = float('NaN')
+		self.vertexconnectivity          = float('NaN')
+		self.elementconnectivity         = float('NaN')
+		self.average_vertex_connectivity = 0
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		string="   2D tria Mesh (vertical):" 
+
+		string="%s\n%s"%(string,"\n      Elements and vertices:")
+		string="%s\n%s"%(string,fielddisplay(self,"numberofelements","number of elements"))
+		string="%s\n%s"%(string,fielddisplay(self,"numberofvertices","number of vertices"))
+		string="%s\n%s"%(string,fielddisplay(self,"elements","vertex indices of the mesh elements"))
+		string="%s\n%s"%(string,fielddisplay(self,"x","vertices x coordinate [m]"))
+		string="%s\n%s"%(string,fielddisplay(self,"y","vertices y coordinate [m]"))
+		string="%s\n%s"%(string,fielddisplay(self,"edges","edges of the 2d mesh (vertex1 vertex2 element1 element2)"))
+		string="%s\n%s"%(string,fielddisplay(self,"numberofedges","number of edges of the 2d mesh"))
+
+		string="%s%s"%(string,"\n\n      Properties:")
+		string="%s\n%s"%(string,fielddisplay(self,"vertexonboundary","vertices on the boundary of the domain flag list"))
+		string="%s\n%s"%(string,fielddisplay(self,'vertexonbase','vertices on the bed of the domain flag list'))
+		string="%s\n%s"%(string,fielddisplay(self,'vertexonsurface','vertices on the surface of the domain flag list'))
+		string="%s\n%s"%(string,fielddisplay(self,"segments","edges on domain boundary (vertex1 vertex2 element)"))
+		string="%s\n%s"%(string,fielddisplay(self,"segmentmarkers","number associated to each segment"))
+		string="%s\n%s"%(string,fielddisplay(self,"vertexconnectivity","list of vertices connected to vertex_i"))
+		string="%s\n%s"%(string,fielddisplay(self,"elementconnectivity","list of vertices connected to element_i"))
+		string="%s\n%s"%(string,fielddisplay(self,"average_vertex_connectivity","average number of vertices connected to one vertex"))
+
+		string="%s%s"%(string,"\n\n      Projection:")
+		string="%s\n%s"%(string,fielddisplay(self,"lat","vertices latitude [degrees]"))
+		string="%s\n%s"%(string,fielddisplay(self,"long","vertices longitude [degrees]"))
+		string="%s\n%s"%(string,fielddisplay(self,"epsg","EPSG code (ex: 3413 for UPS Greenland, 3031 for UPS Antarctica)"))
+		string="%s\n%s"%(string,fielddisplay(self,"scale_factor","Projection correction for volume, area, etc. computation"))
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		
+		#the connectivity is the averaged number of nodes linked to a
+		#given node through an edge. This connectivity is used to initially
+		#allocate memory to the stiffness matrix. A value of 16 seems to
+		#give a good memory/time ration. This value can be checked in
+		#trunk/test/Miscellaneous/runme.m
+		self.average_vertex_connectivity=25.
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		if(solution=='LoveSolution'):
+			return
+
+		md = checkfield(md,'fieldname','mesh.x','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
+		md = checkfield(md,'fieldname','mesh.y','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
+		md = checkfield(md,'fieldname','mesh.elements','NaN',1,'Inf',1,'>',0,'values',np.arange(1,md.mesh.numberofvertices+1))
+		md = checkfield(md,'fieldname','mesh.elements','size',[md.mesh.numberofelements,3])
+		if np.any(np.logical_not(m.ismember(np.arange(1,md.mesh.numberofvertices+1),md.mesh.elements))):
+			md.checkmessage("orphan nodes have been found. Check the mesh outline")
+		md = checkfield(md,'fieldname','mesh.numberofelements','>',0)
+		md = checkfield(md,'fieldname','mesh.numberofvertices','>',0)
+		md = checkfield(md,'fieldname','mesh.vertexonbase','size',[md.mesh.numberofvertices],'values',[0,1])
+		md = checkfield(md,'fieldname','mesh.vertexonsurface','size',[md.mesh.numberofvertices],'values',[0,1])
+		md = checkfield(md,'fieldname','mesh.average_vertex_connectivity','>=',9,'message',"'mesh.average_vertex_connectivity' should be at least 9 in 2d")
+		if(np.size(self.scale_factor)>1):
+                        md = checkfield(md,'fieldname','mesh.scale_factor','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
+
+		if solution=='ThermalSolution':
+			md.checkmessage("thermal not supported for 2d mesh")
+
+		return md
+	# }}}
+	def domaintype(self): # {{{
+		return "2Dvertical"
+	#}}}
+	def dimension(self): # {{{
+		return 2
+	#}}}
+	def elementtype(self): # {{{
+		return "Tria"
+	#}}}
+	def vertexflags(self,value): # {{{
+		flags = np.zeros((self.numberofvertices,))
+		pos   = self.segments[np.where(self.segmentmarkers==value),0:2]-1
+		flags[pos] = 1
+		return flags
+	#}}}
+	def marshall(self,prefix,md,fid):    # {{{
+		WriteData(fid,prefix,'name','md.mesh.domain_type','data',"Domain"+self.domaintype(),'format','String');
+		WriteData(fid,prefix,'name','md.mesh.domain_dimension','data',self.dimension(),'format','Integer');
+		WriteData(fid,prefix,'name','md.mesh.elementtype','data',self.elementtype(),'format','String');
+		WriteData(fid,prefix,'object',self,'class','mesh','fieldname','x','format','DoubleMat','mattype',1)
+		WriteData(fid,prefix,'object',self,'class','mesh','fieldname','y','format','DoubleMat','mattype',1)
+		WriteData(fid,prefix,'name','md.mesh.z','data',np.zeros(self.numberofvertices),'format','DoubleMat','mattype',1);
+		WriteData(fid,prefix,'object',self,'class','mesh','fieldname','elements','format','DoubleMat','mattype',2)
+		WriteData(fid,prefix,'object',self,'class','mesh','fieldname','numberofelements','format','Integer')
+		WriteData(fid,prefix,'object',self,'class','mesh','fieldname','numberofvertices','format','Integer')
+		WriteData(fid,prefix,'object',self,'class','mesh','fieldname','vertexonbase','format','BooleanMat','mattype',1)
+		WriteData(fid,prefix,'object',self,'class','mesh','fieldname','vertexonsurface','format','BooleanMat','mattype',1)
+		WriteData(fid,prefix,'object',self,'class','mesh','fieldname','average_vertex_connectivity','format','Integer')
+		WriteData(fid,prefix,'object',self,'class','mesh','fieldname','scale_factor','format','DoubleMat','mattype',1)
+	# }}}
Index: /issm/trunk/src/m/classes/mesh3dprisms.js
===================================================================
--- /issm/trunk/src/m/classes/mesh3dprisms.js	(revision 22757)
+++ /issm/trunk/src/m/classes/mesh3dprisms.js	(revision 22758)
@@ -34,4 +34,5 @@
 			checkfield(md,'fieldname','mesh.z','<=',md.geometry.surface+Math.pow(10, -10),'message','\'mesh.z\' higher than surface elevation');
 			checkfield(md,'fieldname','mesh.average_vertex_connectivity','>=',24,'message','\'mesh.average_vertex_connectivity\' should be at least 24 in 3d');
+			if(this.scale_factor.length>1) checkfield(md,'fieldname','mesh.scale_factor','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices, 1]);
 		} // }}}
 		this.disp = function()  { // {{{
@@ -75,4 +76,5 @@
 			fielddisplay(this,'long','vertices longitude [degrees]');
 			fielddisplay(this,'epsg','EPSG code (ex: 3413 for UPS Greenland, 3031 for UPS Antarctica)');
+			fielddisplay(self,"scale_factor","Projection correction for volume, area, etc. computation)");
 		} // }}}
 		this.marshall = function(md,prefix,fid) { // {{{
@@ -95,4 +97,5 @@
 			WriteData(fid,prefix,'object',this,'class','mesh','fieldname','numberofvertices2d','format','Integer');
 			WriteData(fid,prefix,'object',this,'class','mesh','fieldname','numberofelements2d','format','Integer');
+			WriteData(fid,prefix,'object',this,'class','mesh','fieldname','scale_factor','format','DoubleMat','mattype',1);
 		} // }}}
         this.fix=function() { //{{{
@@ -109,4 +112,5 @@
             this.lat=NaNFix(this.lat,NaN);
             this.long=NaNFix(this.long,NaN);
+				this.scale_factor=NullFix(this.scale_factor,NaN);
         }//}}}
 		this.domaintype = function() { // {{{)
@@ -135,4 +139,5 @@
         this.long                        = NaN;
         this.epsg                        = 0;
+		  this.scale_factor                = NaN;
 
         this.vertexonbase                = NaN;
Index: /issm/trunk/src/m/classes/mesh3dprisms.m
===================================================================
--- /issm/trunk/src/m/classes/mesh3dprisms.m	(revision 22757)
+++ /issm/trunk/src/m/classes/mesh3dprisms.m	(revision 22758)
@@ -17,4 +17,5 @@
 		long                        = NaN;
 		epsg                        = 0;
+		scale_factor                = NaN;
 
 		vertexonbase                = NaN;
@@ -90,4 +91,6 @@
 		end % }}}
 		function md = checkconsistency(self,md,solution,analyses) % {{{
+			
+			if strcmpi(solution,'LoveSolution'), return; end
 
 			md = checkfield(md,'fieldname','mesh.x','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices 1]);
@@ -117,4 +120,7 @@
 			if any(max(abs(project2d(md,md.mesh.z,md.mesh.numberoflayers)-project2d(md,md.mesh.z,1) - project2d(md,md.geometry.thickness,1)))>1e-10),
 				md = checkmessage(md,'md.mesh.z is not consistent with md.geometry.thickness, you changed the geometry after extrusion !!');
+			end
+			if numel(md.mesh.scale_factor)>1,
+				md = checkfield(md,'fieldname','mesh.scale_factor','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices 1]);
 			end
 		end % }}}
@@ -159,4 +165,5 @@
 			fielddisplay(self,'long','vertices longitude [degrees]');
 			fielddisplay(self,'epsg','EPSG code (ex: 3413 for UPS Greenland, 3031 for UPS Antarctica)');
+			fielddisplay(self,'scale_factor','Projection correction for volume, area, etc. computation)');
 		end % }}}
 		function marshall(self,prefix,md,fid) % {{{
@@ -179,4 +186,9 @@
 			WriteData(fid,prefix,'object',self,'class','mesh','fieldname','numberofvertices2d','format','Integer');
 			WriteData(fid,prefix,'object',self,'class','mesh','fieldname','numberofelements2d','format','Integer');
+			WriteData(fid,prefix,'object',self,'class','mesh','fieldname','scale_factor','format','DoubleMat','mattype',1);
+			if md.transient.isoceancoupling,
+				WriteData(fid,prefix,'object',self,'class','mesh','fieldname','lat','format','DoubleMat','mattype',1);
+				WriteData(fid,prefix,'object',self,'class','mesh','fieldname','long','format','DoubleMat','mattype',1);
+			end
 		end % }}}
 		function type = domaintype(self) % {{{
Index: /issm/trunk/src/m/classes/mesh3dprisms.py
===================================================================
--- /issm/trunk/src/m/classes/mesh3dprisms.py	(revision 22757)
+++ /issm/trunk/src/m/classes/mesh3dprisms.py	(revision 22758)
@@ -25,4 +25,5 @@
 		self.long                        = float('NaN');
 		self.epsg                        = 0;
+		self.scale_factor                = float('NaN');
 
 		self.vertexonbase                = float('NaN');
@@ -90,4 +91,5 @@
 		string="%s\n%s"%(string,fielddisplay(self,"long","vertices longitude [degrees]"))
 		string="%s\n%s"%(string,fielddisplay(self,"epsg","EPSG code (ex: 3413 for UPS Greenland, 3031 for UPS Antarctica)"))
+		string="%s\n%s"%(string,fielddisplay(self,"scale_factor","Projection correction for volume, area, etc. computation"))
 		return string
 		#}}}
@@ -118,4 +120,6 @@
 		md = checkfield(md,'fieldname','mesh.vertexonsurface','size',[md.mesh.numberofvertices],'values',[0,1])
 		md = checkfield(md,'fieldname','mesh.average_vertex_connectivity','>=',24,'message',"'mesh.average_vertex_connectivity' should be at least 24 in 3d")
+		if(np.size(self.scale_factor)>1):
+                        md = checkfield(md,'fieldname','mesh.scale_factor','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
 
 		return md
@@ -149,3 +153,7 @@
 		WriteData(fid,prefix,'object',self,'class','mesh','fieldname','numberofvertices2d','format','Integer')
 		WriteData(fid,prefix,'object',self,'class','mesh','fieldname','numberofelements2d','format','Integer')
+		WriteData(fid,prefix,'object',self,'class','mesh','fieldname','scale_factor','format','DoubleMat','mattype',1)
+		if md.transient.isoceancoupling:
+			WriteData(fid,prefix,'object',self,'class','mesh','fieldname','lat','format','DoubleMat','mattype',1)
+			WriteData(fid,prefix,'object',self,'class','mesh','fieldname','long','format','DoubleMat','mattype',1)
 	# }}}
Index: /issm/trunk/src/m/classes/mesh3dsurface.m
===================================================================
--- /issm/trunk/src/m/classes/mesh3dsurface.m	(revision 22757)
+++ /issm/trunk/src/m/classes/mesh3dsurface.m	(revision 22758)
@@ -80,4 +80,6 @@
 		end % }}}
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			if strcmpi(solution,'LoveSolution'), return; end
 
 			md = checkfield(md,'fieldname','mesh.x','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices 1]);
Index: /issm/trunk/src/m/classes/mesh3dtetras.m
===================================================================
--- /issm/trunk/src/m/classes/mesh3dtetras.m	(revision 22757)
+++ /issm/trunk/src/m/classes/mesh3dtetras.m	(revision 22758)
@@ -17,4 +17,5 @@
 		long                        = NaN;
 		epsg                        = 0;
+		scale_factor                = NaN;
 
 		vertexonbase                = NaN;
@@ -90,4 +91,6 @@
 		end % }}}
 		function md = checkconsistency(self,md,solution,analyses) % {{{
+			
+			if strcmpi(solution,'LoveSolution'), return; end
 
 			md = checkfield(md,'fieldname','mesh.x','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices 1]);
@@ -107,4 +110,8 @@
 			md = checkfield(md,'fieldname','mesh.z','<=',md.geometry.surface+10^-10,'message','''mesh.z'' higher than surface elevation');
 			md = checkfield(md,'fieldname','mesh.average_vertex_connectivity','>=',24,'message','''mesh.average_vertex_connectivity'' should be at least 24 in 3d');
+			if numel(md.mesh.scale_factor)>1,
+				md = checkfield(md,'fieldname','mesh.scale_factor','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices 1]);
+			end
+
 		end % }}}
 		function disp(self) % {{{
@@ -148,4 +155,5 @@
 			fielddisplay(self,'long','vertices longitude [degrees]');
 			fielddisplay(self,'epsg','EPSG code (ex: 3413 for UPS Greenland, 3031 for UPS Antarctica)');
+			fielddisplay(self,'scale_factor','Projection correction for volume, area, etc. computation)');
 		end % }}}
 		function marshall(self,prefix,md,fid) % {{{
@@ -164,4 +172,5 @@
 			WriteData(fid,prefix,'object',self,'class','mesh','fieldname','lowerelements','format','DoubleMat','mattype',2);
 			WriteData(fid,prefix,'object',self,'class','mesh','fieldname','upperelements','format','DoubleMat','mattype',2);
+			WriteData(fid,prefix,'object',self,'class','mesh','fieldname','scale_factor','format','DoubleMat','mattype',1);
 			WriteData(fid,prefix,'object',self,'class','mesh','fieldname','average_vertex_connectivity','format','Integer');
 			WriteData(fid,prefix,'object',self,'class','mesh','fieldname','elements2d','format','DoubleMat','mattype',3);
Index: /issm/trunk/src/m/classes/misfit.m
===================================================================
--- /issm/trunk/src/m/classes/misfit.m	(revision 22757)
+++ /issm/trunk/src/m/classes/misfit.m	(revision 22758)
@@ -18,17 +18,25 @@
 	properties (SetAccess=public)
 		%misfit
-		name						= '';
-		definitionstring		= ''; %string that identifies this output definition uniquely, from 'Outputdefinition[1-10]'
-		model_string			= ''; %string for field that is modeled
-		observation				= NaN; %observed field that we compare the model against
-		observation_string	= ''; %string for observed field.
-		timeinterpolation		= '';
-		local						= 1;
-		weights					= NaN; %weight coefficients for every vertex
-		weights_string			= ''; %string to identify this particular set of weights
-		cumulated				= NaN; %do we cumulate misfit through time?
+		name               = '';
+		definitionstring   = ''; %string that identifies this output definition uniquely, from 'Outputdefinition[1-100]'
+		model_string       = ''; %string for field that is modeled
+		observation        = NaN; %observed field that we compare the model against
+		observation_string = ''; %string for observed field.
+		timeinterpolation  = '';
+		local              = 1;
+		weights            = NaN; %weight coefficients for every vertex
+		weights_string     = ''; %string to identify this particular set of weights
+		cumulated          = NaN; %do we cumulate misfit through time?
 	end
 	
 	methods
+		function self = extrude(self,md) % {{{
+			if ~isnan(self.weights)
+				self.weights=project3d(md,'vector',self.weights,'type','node');
+			end
+			if ~isnan(self.observation)
+				self.observation=project3d(md,'vector',self.observation,'type','node');
+			end
+		end % }}}
 		function self = misfit(varargin) % {{{
 			if nargin==0,
Index: /issm/trunk/src/m/classes/misfit.py
===================================================================
--- /issm/trunk/src/m/classes/misfit.py	(revision 22758)
+++ /issm/trunk/src/m/classes/misfit.py	(revision 22758)
@@ -0,0 +1,109 @@
+import numpy as np
+from project3d import project3d
+from pairoptions import *
+from collections import OrderedDict
+from fielddisplay import fielddisplay
+from checkfield import checkfield
+from WriteData import WriteData
+
+
+class misfit(object):
+	"""
+	MISFIT class definition
+
+	Usage:
+		misfit=misfit()
+		misfit=misfit(name='SurfaceAltimetry',
+                	definitionstring='Outputdefinition1',
+			model_string='Surface',
+	                observation_string='SurfaceObservations',
+ 	            	observation=md.geometry.surface,
+                    	timeinterpolation='nearestneighbor',
+                    	local=1,
+                    	weights=np.ones((md.mesh.numberofvertices,1)),
+                    	weights_string='WeightsSurfaceObservations')
+	"""
+
+	def __init__(self, name = None, definitionstring = None, model_string = None, observation = None, observation_string = None, timeinterpolation = None, local = None, weights = None, weights_string = None, cumulated = None):
+		# {{{
+		self.name = name if name is not None else ''
+
+		#string that identifies this output definition uniquely, from 'Outputdefinition[1-100]'
+		self.definitionstring = definitionstring if definitionstring is not None else ''
+
+		#string for field that is modeled
+		self.model_string = model_string if model_string is not None else ''
+
+		#observed field that we compare the model against
+		self.observation = observation if observation is not None else float('NaN')
+
+		#string for observed field.
+		self.observation_string = observation_string if observation_string is not None else ''
+
+		self.timeinterpolation = timeinterpolation if timeinterpolation is not None else 'nearestneighbor'
+
+		self.local = local if local is not None else 1
+
+		#weight coefficients for every vertex
+		self.weights = weights if weights is not None else float('NaN')
+
+		#string to identify this particular set of weights
+		self.weights_string = weights_string if weights_string is not None else ''
+
+		#do we cumulate misfit through time?
+		self.cumulated = cumulated if cumulated is not None else float('NaN')		
+		#}}}
+
+	def __repr__(self): # {{{
+		string='   Misfit:'
+
+		string="%s\n%s"%(string,fielddisplay(self,'name','identifier for this misfit response'))
+		string="%s\n%s"%(string,fielddisplay(self,'definitionstring','string that identifies this output definition uniquely, from "Outputdefinition[1-10]"'))
+		string="%s\n%s"%(string,fielddisplay(self,'model_string','string for field that is modeled'))
+		string="%s\n%s"%(string,fielddisplay(self,'observation','observed field that we compare the model against'))
+		string="%s\n%s"%(string,fielddisplay(self,'observation_string','observation string'))
+		string="%s\n%s"%(string,fielddisplay(self,'local','is the response local to the elements, or global? (default is 1)'))
+		string="%s\n%s"%(string,fielddisplay(self,'timeinterpolation','interpolation routine used to interpolate misfit between two time steps (default is "nearestneighbor"'))
+		string="%s\n%s"%(string,fielddisplay(self,'weights','weights (at vertices) to apply to the misfit'))
+		string="%s\n%s"%(string,fielddisplay(self,'weights_string','string for weights for identification purposes'))
+		return string
+		#}}}
+
+	def extrude(self,md): # {{{
+		if not np.any(np.isnan(self.weights)):
+			self.weights = project3d(md,'vector',self.weights,'type','node')
+		if not np.any(np.isnan(self.observation)):
+			self.observation = project3d(md,'vector',self.observation,'type','node')
+		return self
+	#}}}
+
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		if type(self.name) != str:
+			raise TypeError('misfit error message: "name" field should be a string!')
+
+		OutputdefinitionStringArray = []
+		for i in range(100):
+			OutputdefinitionStringArray.append('Outputdefinition' + str(i))
+
+		md = checkfield(md,'fieldname','self.definitionstring','field',self.definitionstring,'values',OutputdefinitionStringArray)
+		if type(self.timeinterpolation) != str:
+			raise TypeError('misfit error message: "timeinterpolation" field should be a string!')
+
+		md = checkfield(md,'fieldname','self.observation','field',self.observation,'timeseries',1,'NaN',1,'Inf',1)
+		md = checkfield(md,'fieldname','self.timeinterpolation','field',self.timeinterpolation,'values',['nearestneighbor'])
+		md = checkfield(md,'fieldname','self.weights','field',self.weights,'timeseries',1,'NaN',1,'Inf',1)
+
+		return md
+	# }}}
+
+	def marshall(self,prefix,md,fid):    #  {{{
+		WriteData(fid,prefix,'data',self.name,'name','md.misfit.name','format','String')
+		WriteData(fid,prefix,'data',self.definitionstring,'name','md.misfit.definitionstring','format','String')
+		WriteData(fid,prefix,'data',self.model_string,'name','md.misfit.model_string','format','String')
+		WriteData(fid,prefix,'data',self.observation,'name','md.misfit.observation','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
+		WriteData(fid,prefix,'data',self.observation_string,'name','md.misfit.observation_string','format','String')
+		WriteData(fid,prefix,'data',self.local,'name','md.misfit.local','format','Integer')
+		WriteData(fid,prefix,'data',self.timeinterpolation,'name','md.misfit.timeinterpolation','format','String')
+		WriteData(fid,prefix,'data',self.weights,'name','md.misfit.weights','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
+		WriteData(fid,prefix,'data',self.weights_string,'name','md.misfit.weights_string','format','String')
+	# }}}
Index: /issm/trunk/src/m/classes/mismipbasalforcings.m
===================================================================
--- /issm/trunk/src/m/classes/mismipbasalforcings.m	(revision 22757)
+++ /issm/trunk/src/m/classes/mismipbasalforcings.m	(revision 22758)
@@ -85,9 +85,5 @@
 			end
 
-			floatingice_melting_rate=zeros(md.mesh.numberofvertices,1);
-			floatingice_melting_rate=md.basalforcings.meltrate_factor*tanh((md.geometry.base-md.geometry.bed)./md.basalforcings.threshold_thickness).*max(md.basalforcings.upperdepth_melt-md.geometry.base,0);
-
 			WriteData(fid,prefix,'name','md.basalforcings.model','data',3,'format','Integer');
-			WriteData(fid,prefix,'data',floatingice_melting_rate,'format','DoubleMat','name','md.basalforcings.floatingice_melting_rate','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
 			WriteData(fid,prefix,'object',self,'fieldname','groundedice_melting_rate','format','DoubleMat','name','md.basalforcings.groundedice_melting_rate','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
 			WriteData(fid,prefix,'object',self,'fieldname','geothermalflux','name','md.basalforcings.geothermalflux','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
Index: /issm/trunk/src/m/classes/mismipbasalforcings.py
===================================================================
--- /issm/trunk/src/m/classes/mismipbasalforcings.py	(revision 22757)
+++ /issm/trunk/src/m/classes/mismipbasalforcings.py	(revision 22758)
@@ -40,6 +40,9 @@
     def initialize(self,md): # {{{
         if np.all(np.isnan(self.groundedice_melting_rate)):
-            self.groundedice_melting_rate=np.zeros(md.mesh.numberofvertices)
+            self.groundedice_melting_rate=np.zeros((md.mesh.numberofvertices))
             print ' no basalforcings.groundedice_melting_rate specified: values set as zero'
+	if np.all(np.isnan(self.geothermalflux)):
+			self.geothermalflux=np.zeros((md.mesh.numberofvertices))
+			print "      no basalforcings.geothermalflux specified: values set as zero"
         return self
     #}}}
@@ -83,9 +86,5 @@
             print 'WARNING: value of yts for MISMIP+ runs different from ISSM default!'
 
-        floatingice_melting_rate = np.zeros((md.mesh.numberofvertices))
-        floatingice_melting_rate = md.basalforcings.meltrate_factor*np.tanh((md.geometry.base-md.geometry.bed)/md.basalforcings.threshold_thickness)*np.amax(md.basalforcings.upperdepth_melt-md.geometry.base,0)
-
 	WriteData(fid,prefix,'name','md.basalforcings.model','data',3,'format','Integer')
-	WriteData(fid,prefix,'data',floatingice_melting_rate,'format','DoubleMat','name','md.basalforcings.floatingice_melting_rate','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
 	WriteData(fid,prefix,'object',self,'fieldname','groundedice_melting_rate','format','DoubleMat','name','md.basalforcings.groundedice_melting_rate','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
 	WriteData(fid,prefix,'object',self,'fieldname','geothermalflux','name','md.basalforcings.geothermalflux','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
Index: /issm/trunk/src/m/classes/model.js
===================================================================
--- /issm/trunk/src/m/classes/model.js	(revision 22757)
+++ /issm/trunk/src/m/classes/model.js	(revision 22758)
@@ -34,8 +34,10 @@
 			console.log(sprintf("//19s: //-22s -- //s","thermal"         ,"[1x1 " + typeof(this.thermal) + "]","parameters for thermal solution"));
 			console.log(sprintf("//19s: //-22s -- //s","steadystate"     ,"[1x1 " + typeof(this.steadystate) + "]","parameters for steadystate solution"));
-			console.log(sprintf("//19s: //-22s -- //s","trans"       ,"[1x1 " + typeof(this.trans) + "]","parameters for trans solution"));
+			console.log(sprintf("//19s: //-22s -- //s","trans"           ,"[1x1 " + typeof(this.trans) + "]","parameters for trans solution"));
 			console.log(sprintf("//19s: //-22s -- //s","levelset"        ,"[1x1 " + typeof(this.levelset) + "]","parameters for moving boundaries (level-set method)"));
 			console.log(sprintf("//19s: //-22s -- //s","calving"         ,"[1x1 " + typeof(this.calving) + "]","parameters for calving"));
 			console.log(sprintf("//19s: //-22s -- //s","gia"             ,"[1x1 " + typeof(this.gia) + "]","parameters for gia solution"));
+			console.log(sprintf("//19s: //-22s -- //s","love"            ,"[1x1 " + typeof(this.love) + "]","parameters for love solution"));
+			console.log(sprintf("//19s: //-22s -- //s","esa"             ,"[1x1 " + typeof(this.esa) + "]","parameters for elastic adjustment solution"));
 			console.log(sprintf("//19s: //-22s -- //s","autodiff"        ,"[1x1 " + typeof(this.autodiff) + "]","automatic differentiation parameters"));
 			console.log(sprintf("//19s: //-22s -- //s","inversion"       ,"[1x1 " + typeof(this.inversion) + "]","parameters for inverse methods"));
@@ -54,22 +56,24 @@
 			this.constants        = new constants();
 			this.geometry         = new geometry();
-			this.initialization   = new initialization();
 			this.smb              = new SMBforcing();
 			this.basalforcings    = new basalforcings();
+			this.materials        = new matice();
+			this.damage           = new damage();
 			this.friction         = new friction();
+			this.flowequation     = new flowequation();
+			this.timestepping     = new timestepping();
+			this.initialization   = new initialization();
 			this.rifts            = new rifts();
 			this.slr              = new slr();
-			this.timestepping     = new timestepping();
-			this.groundingline    = new groundingline();
-			this.materials        = new matice();
-			this.damage           = new damage();
-			this.flowequation     = new flowequation();
+
 			this.debug            = new debug();
 			this.verbose          = new verbose();
-			this.settings         = new settings();
+			this.settings         = new issmsettings();
 			this.toolkits         = new toolkits();
 			this.cluster          = new local();
+
 			this.balancethickness = new balancethickness();
 			this.stressbalance    = new stressbalance();
+			this.groundingline    = new groundingline();
 			this.hydrology        = new hydrologyshreve();
 			this.masstransport    = new masstransport();
@@ -77,14 +81,18 @@
 			this.steadystate      = new steadystate();
 			this.trans            = new trans();
-			this.levelset		  = new levelset();
+			this.levelset         = new levelset();
 			this.calving          = new calving();
+			this.love             = new fourierlove();
 			this.gia              = new giaivins();
+
+			this.esa              = new esa();
 			this.autodiff         = new autodiff();
 			this.inversion        = new inversion();
 			this.qmu              = new qmu();
-			this.amr					 = new amr();
-			this.radaroverlay     = new radaroverlay();
+			this.amr              = new amr();
+
 			this.results          = {};
 			this.outputdefinition = new outputdefinition();
+			this.radaroverlay     = new radaroverlay();
 			this.miscellaneous    = new miscellaneous();
 			this.priv             = new priv();
@@ -111,467 +119,607 @@
 
 		} //}}}
-        this.extrude = function(md) { //{{{
-        //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,15,1.3);
-        //      md=extrude(md,15,1.3,1.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
-            var argc = arguments.length;
-
-            if ((argc > 4) | (argc < 2)) {
-                throw "extrude error message";
-            }
-
-            //Extrude the mesh
-            if (argc==2) { //list of coefficients
-                clist=arguments[0];
-
-                if (clist.some(function(x) { return x < 0; }) | clist.some(function(x) { return x > 1; }))
-                    throw 'extrusioncoefficients must be between 0 and 1';
-                clistcopy.push.apply(clistcopy, [0, 1]);
-
-                extrusionlist=clistcopy.reverse().filter(function(e, i, arr) { //only keep unique elements
-                    return arr.indexOf(e, i+1) === -1;
-                }).sort();
-
-                numlayers=extrusionlist.length;
-            } else if (argc==3) { //one polynomial law
-                if (arguments[1]<=0) {
-                    //help extrude;
-                    throw 'extrusionexponent must be >=0';
-                }
-                numlayers=arguments[0];
-
-                extrusionlist = [];
-
-                for (var i = 0; i < numlayers; i++) {
-                    extrusionlist.push(Math.pow(i/(numlayers-1), arguments[1]));
-                };
-
-            } else if (argc==4) { //two polynomial laws
-                numlayers=arguments[0];
-                lowerexp=arguments[1];
-                upperexp=arguments[2];
-
-                if (arguments[1]<=0 | args[2]<=0) {
-                    throw 'lower and upper extrusionexponents must be >=0';
-                }
-
-                lowerextrusionlist = [];
-                for (var i = 0; i <= 1; i += (2/(numlayers-1))) {
-                    lowerextrusionlist.push(Math.pow(i, lowerexp)/2)
-                };
-
-                upperextrusionlist = [];
-                for (var i = 0; i <= 1; i += (2/(numlayers-1))) {
-                    upperextrusionlist.push(Math.pow(i, upperexp)/2)
-                };
-
-                //lowerextrusionlist=[(0:2/(numlayers-1):1).^lowerexp]/2;
-                //upperextrusionlist=[(0:2/(numlayers-1):1).^upperexp]/2;
-
-                var temp = lowerextrusionlist;
-                temp.push.apply(temp, [1]);
-
-                var temp2 = upperextrusionlist.map(function(x) { return -x; });
-                temp.push.apply(temp, temp2);
-
-                clistcopy.push.apply(clistcopy, [0, 1]);
-                //extrusionlist=sort(unique([lowerextrusionlist 1-upperextrusionlist]));
-                extrusionlist=temp.sort();
-            }
-
-            if (numlayers<2) {
-                console.error('number of layers should be at least 2');
-            }
-
-            if (md.mesh.domaintype() === '3D') {
-                console.error('Cannot extrude a 3d mesh (extrude cannot be called more than once)');
-            }
-
-            //Initialize with the 2d mesh
-            var mesh2d = md.mesh;
-            md.mesh=new mesh3dprisms();
-
-            md.mesh.x                           = mesh2d.x;
-            md.mesh.y                           = mesh2d.y;
-            md.mesh.elements                    = mesh2d.elements;
-            md.mesh.numberofelements            = mesh2d.numberofelements;
-            md.mesh.numberofvertices            = mesh2d.numberofvertices;
-
-            md.mesh.lat                         = mesh2d.lat;
-            md.mesh.long                        = mesh2d.long;
-            md.mesh.epsg                        = mesh2d.epsg;
-
-            md.mesh.vertexonboundary            = mesh2d.vertexonboundary;
-            md.mesh.vertexconnectivity          = mesh2d.vertexconnectivity;
-            md.mesh.elementconnectivity         = mesh2d.elementconnectivity;
-            md.mesh.average_vertex_connectivity = mesh2d.average_vertex_connectivity;
-
-            md.mesh.extractedvertices           = mesh2d.extractedvertices;
-            md.mesh.extractedelements           = mesh2d.extractedelements;
-
-            x3d=[]; 
-            y3d=[];
-            z3d=[];  //the lower node is on the bed
-            thickness3d=md.geometry.thickness; //thickness and bed for these nodes
-                bed3d=md.geometry.base;
-
-            //Create the new layers
-            for (var i = 1; i <= numlayers; i++) {
-                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)]; 
-            };
-
-            number_nodes3d=x3d.length; //number of 3d nodes for the non extruded part of the mesh
-
-            //Extrude elements 
-            elements3d=[];
-            for (var i = 0; i < numlayers; i++) {
-                elements3d.push(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
-            };
-
-            number_el3d=elements3d.length; //number of 3d nodes for the non extruded part of the mesh
-
-            function fillArray(value, len) {
-                if (len == 0) return [];
-                var a = [value];
-                while (a.length * 2 <= len) a = a.concat(a);
-                if (a.length < len) a = a.concat(a.slice(0, len - a.length));
-                return a;
-            }
-
-            //Keep a trace of lower and upper nodes
-            //lowervertex=NaN*ones(number_nodes3d,1);
-            //uppervertex=NaN*ones(number_nodes3d,1);
-
-            lowervertex = fillArray(NaN, number_nodes3d);
-            uppervertex = fillArray(NaN, number_nodes3d);
-
-            //lowervertex(md.mesh.numberofvertices+1:end)=1:(numlayers-1)*md.mesh.numberofvertices;
-            //uppervertex(1:(numlayers-1)*md.mesh.numberofvertices)=md.mesh.numberofvertices+1:number_nodes3d;
-
-            for (var i = md.mesh.numberofvertices+1, k = 1; i < lowervertex.length && k <= (numlayers-1)*md.mesh.numberofvertices; i++, k++) {
-                lowervertex[i] = k;
-            };
-
-            for (var i = 1, k = md.mesh.numberofvertices+1; i <= (numlayers-1)*md.mesh.numberofvertices && k <= number_nodes3d; i++, k++) {
-                uppervertex[i] = k;
-            };
-
-            md.mesh.lowervertex=lowervertex;
-            md.mesh.uppervertex=uppervertex;
-
-            //same for lower and upper elements
-            lowerelements = fillArray(NaN, number_el3d);
-            upperelements = fillArray(NaN, number_el3d);
-            //lowerelements(md.mesh.numberofelements+1:end)=1:(numlayers-2)*md.mesh.numberofelements;
-            //upperelements(1:(numlayers-2)*md.mesh.numberofelements)=md.mesh.numberofelements+1:(numlayers-1)*md.mesh.numberofelements;
-
-            for (var i = md.mesh.numberofvertices+1, k = 1; i < lowerelements.length && k <= (numlayers-2)*md.mesh.numberofelements; i++, k++) {
-                lowerelements[i] = k;
-            };
-
-            for (var i = 1, k = md.mesh.numberofelements + 1; i <= (numlayers-2)*md.mesh.numberofelements && k <= (numlayers-1)*md.mesh.numberofelements; i++, k++) {
-                upperelements[i] = k;
-            };
-
-            md.mesh.lowerelements=lowerelements;
-            md.mesh.upperelements=upperelements;
-
-            //Save old mesh 
-            md.mesh.x2d=md.mesh.x;
-            md.mesh.y2d=md.mesh.y;
-            md.mesh.elements2d=md.mesh.elements;
-            md.mesh.numberofelements2d=md.mesh.numberofelements;
-            md.mesh.numberofvertices2d=md.mesh.numberofvertices;
-
-            //Build global 3d mesh 
-            md.mesh.elements=elements3d;
-            md.mesh.x=x3d;
-            md.mesh.y=y3d;
-            md.mesh.z=z3d;
-            md.mesh.numberofelements=number_el3d;
-            md.mesh.numberofvertices=number_nodes3d;
-            md.mesh.numberoflayers=numlayers;
-
-            //Ok, now deal with the other fields from the 2d mesh:
-
-            //bedinfo and surface info
-            md.mesh.vertexonbase=project3d(md,'vector',ones(md.mesh.numberofvertices2d,1),'type','node','layer',1);
-            md.mesh.vertexonsurface=project3d(md,'vector',ones(md.mesh.numberofvertices2d,1),'type','node','layer',md.mesh.numberoflayers);
-            md.mesh.vertexonboundary=project3d(md,'vector',md.mesh.vertexonboundary,'type','node');
-
-            //lat long
-            md.mesh.lat=project3d(md,'vector',md.mesh.lat,'type','node');
-            md.mesh.long=project3d(md,'vector',md.mesh.long,'type','node');
-
-                //md.geometry=md.geometry.extrude(md);
-                //md.friction=md.friction.extrude(md);
-                //md.inversion=md.inversion.extrude(md);
-                //md.smb=md.smb.extrude(md);
-                //md.initialization=md.initialization.extrude(md);
-
-                //md.flowequation=md.flowequation.extrude(md);
-                //md.stressbalance=md.stressbalance.extrude(md);
-                //md.thermal=md.thermal.extrude(md);
-                //md.masstransport=md.masstransport.extrude(md);
-                //md.levelset=md.levelset.extrude(md);
-                //md.calving=md.calving.extrude(md);
-                //md.hydrology = md.hydrology.extrude(md);
-
-                ////connectivity
-                ////if ~isnan(md.mesh.elementconnectivity)
-
-                //if (md.mesh.elementconnectivity.every(function(e, i, arr) { return e !== null && typeof e !== 'undefined'; })) {
-                    //var temparr = [];
-                    //for (var i = 0; i < numlayers; i++) {
-                        //temparr.push(md.mesh.elementconnectivity);
-                    //};
-
-                    ////md.mesh.elementconnectivity=repmat(md.mesh.elementconnectivity,numlayers-1,1);
-
-                    //md.mesh.elementconnectivity = temparr;
-
-                    ////md.mesh.elementconnectivity(find(md.mesh.elementconnectivity==0))=NaN;
-
-                    //for (var i = 0; i < md.mesh.elementconnectivity.length; i++) {
-                        //if (md.mesh.elementconnectivity[i] == 0) {
-                            //md.mesh.elementconnectivity[i] = NaN;
-                        //}
-                    //};
-
-                    //for (var i = 2; i < numlayers; i++) {
-                        //for (var j = (i-1)*md.mesh.nuberofelements2d+1; i <= (i)*md.mesh.numberofelements2d; i++) {
-                            //md.mesh.elementconnectivity[i] += md.mesh.numberofelements2d;
-                        //};
-                        ////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;
-                    //};
-
-                    //md.mesh.elementconnectivity.map(function(x) { return (isNaN(x)) ? 0 : x; });
-                //}
-
-                //md.materials=md.materials.extrude(md);
-                //md.damage=md.damage.extrude(md);
-                //md.mask=md.mask.extrude(md);
-                //md.qmu=md.qmu.extrude(md);
-                //md.basalforcings=md.basalforcings.extrude(md);
-
-                ////increase connectivity if less than 25:
-                //if (md.mesh.average_vertex_connectivity<=25)
-                    //md.mesh.average_vertex_connectivity=100;
-        } //}}}
-        this.collapse = function(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.elementtype() !== 'Penta') {
-                console.error('collapse error message: only 3d mesh can be collapsed')
-            }
-
-            // Start with changing all the fields from the 3d mesh 
-
-            // dealing with the friction law
-            // drag is limited to nodes that are on the bedrock.
-            if (md.friction.classname() === 'friction') {
-                md.friction.coefficient=project2d(md,md.friction.coefficient,1);
-                md.friction.p=project2d(md,md.friction.p,1);
-                md.friction.q=project2d(md,md.friction.q,1);
-            } else if (md.friction.classname() === 'frictionhydro') {
-                md.friction.q=project2d(md,md.friction.q,1);
-                md.friction.C=project2d(md,md.friction.C,1);
-                md.friction.As=project2d(md,md.friction.As,1);
-                md.friction.effective_pressure=project2d(md,md.friction.effective_pressure,1);
-            } else if (md.friction.classname() === 'frictionwaterlayer') {
-                md.friction.coefficient=project2d(md,md.friction.coefficient,1);
-                md.friction.p=project2d(md,md.friction.p,1);
-                md.friction.q=project2d(md,md.friction.q,1);
-                md.friction.water_layer=project2d(md,md.friction.water_layer,1);
-            } else if (md.friction.classname() === 'frictionweertman') {
-                md.friction.C=project2d(md,md.friction.C,1);
-                md.friction.m=project2d(md,md.friction.m,1);
-            } else if (md.friction.classname() === 'frictionweertmantemp') {
-                md.friction.C=project2d(md,md.friction.C,1);
-                md.friction.m=project2d(md,md.friction.m,1);
-            } else {
-                disp('friction type not supported');
-            }
-
-            // observations
-            if (!isNaN(md.inversion.vx_obs))
-                md.inversion.vx_obs=project2d(md,md.inversion.vx_obs,md.mesh.numberoflayers);
-
-            if (!isNaN(md.inversion.vy_obs))
-                md.inversion.vy_obs=project2d(md,md.inversion.vy_obs,md.mesh.numberoflayers);
-
-            if (!isNaN(md.inversion.vel_obs))
-                md.inversion.vel_obs=project2d(md,md.inversion.vel_obs,md.mesh.numberoflayers);
-
-            if (!isNaN(md.inversion.cost_functions_coefficients))
-                md.inversion.cost_functions_coefficients=project2d(md,md.inversion.cost_functions_coefficients,md.mesh.numberoflayers);
-
-            if (numel(md.inversion.min_parameters)>1)
-                md.inversion.min_parameters=project2d(md,md.inversion.min_parameters,md.mesh.numberoflayers);
-
-            if (numel(md.inversion.max_parameters)>1) 
-                md.inversion.max_parameters=project2d(md,md.inversion.max_parameters,md.mesh.numberoflayers);
-
-            if (md.smb.classname() === 'SMBforcing' && !isNaN(md.smb.mass_balance)) {
-                md.smb.mass_balance=project2d(md,md.smb.mass_balance,md.mesh.numberoflayers);
-            } else if (md.smb.classname() === 'SMBhenning' && !isNaN(md.smb.smbref)) {
-                md.smb.smbref=project2d(md,md.smb.smbref,md.mesh.numberoflayers);
-            }
-
-            // results
-            if (!isNaN(md.initialization.vx))
-                md.initialization.vx=DepthAverage(md,md.initialization.vx);
-            if (!isNaN(md.initialization.vy))
-                md.initialization.vy=DepthAverage(md,md.initialization.vy);
-            if (!isNaN(md.initialization.vz))
-                md.initialization.vz=DepthAverage(md,md.initialization.vz);
-            if (!isNaN(md.initialization.vel))
-                md.initialization.vel=DepthAverage(md,md.initialization.vel);
-            if (!isNaN(md.initialization.temperature))
-                md.initialization.temperature=DepthAverage(md,md.initialization.temperature);
-            if (!isNaN(md.initialization.pressure))
-                md.initialization.pressure=project2d(md,md.initialization.pressure,1);
-            if (!isNaN(md.initialization.sediment_head))
-                md.initialization.sediment_head=project2d(md,md.initialization.sediment_head,1);
-            if (!isNaN(md.initialization.epl_head))
-                md.initialization.epl_head=project2d(md,md.initialization.epl_head,1);
-            if (!isNaN(md.initialization.epl_thickness))
-                md.initialization.epl_thickness=project2d(md,md.initialization.epl_thickness,1);
-
-            // giaivins
-            if (!isNaN(md.gia.mantle_viscosity))
-                md.gia.mantle_viscosity=project2d(md,md.gia.mantle_viscosity,1);
-            if (!isNaN(md.gia.lithosphere_thickness))
-                md.gia.lithosphere_thickness=project2d(md,md.gia.lithosphere_thickness,1);
-
-            // elementstype
-            if (!isNaN(md.flowequation.element_equation)) {
-                md.flowequation.element_equation=project2d(md,md.flowequation.element_equation,1);
-                md.flowequation.vertex_equation=project2d(md,md.flowequation.vertex_equation,1);
-                md.flowequation.borderSSA=project2d(md,md.flowequation.borderSSA,1);
-                md.flowequation.borderHO=project2d(md,md.flowequation.borderHO,1);
-                md.flowequation.borderFS=project2d(md,md.flowequation.borderFS,1);
-            }
-
-            // boundary conditions
-            md.stressbalance.spcvx=project2d(md,md.stressbalance.spcvx,md.mesh.numberoflayers);
-            md.stressbalance.spcvy=project2d(md,md.stressbalance.spcvy,md.mesh.numberoflayers);
-            md.stressbalance.spcvz=project2d(md,md.stressbalance.spcvz,md.mesh.numberoflayers);
-            md.stressbalance.referential=project2d(md,md.stressbalance.referential,md.mesh.numberoflayers);
-            md.stressbalance.loadingforce=project2d(md,md.stressbalance.loadingforce,md.mesh.numberoflayers);
-            md.masstransport.spcthickness=project2d(md,md.masstransport.spcthickness,md.mesh.numberoflayers);
-            if (!isNaN(md.damage.spcdamage))
-                md.damage.spcdamage=project2d(md,md.damage.spcdamage,md.mesh.numberoflayers);
-            md.thermal.spctemperature=project2d(md,md.thermal.spctemperature,md.mesh.numberoflayers);
-
-            // Hydrologydc variables
-            if (md.hydrology.classname() === 'hydrologydc') {
-                md.hydrology.spcsediment_head=project2d(md,md.hydrology.spcsediment_head,1);
-                md.hydrology.mask_eplactive_node=project2d(md,md.hydrology.mask_eplactive_node,1);
-                md.hydrology.sediment_transmitivity=project2d(md,md.hydrology.sediment_transmitivity,1);
-                md.hydrology.basal_moulin_input=project2d(md,md.hydrology.basal_moulin_input,1);
-
-                if(md.hydrology.isefficientlayer==1)
-                    md.hydrology.spcepl_head=project2d(md,md.hydrology.spcepl_head,1);
-            }
-            
-            // materials
-            md.materials.rheology_B=DepthAverage(md,md.materials.rheology_B);
-            md.materials.rheology_n=project2d(md,md.materials.rheology_n,1);
-            
-            // damage: 
-            if (md.damage.isdamage)
-                md.damage.D=DepthAverage(md,md.damage.D);
-
-            // special for thermal modeling:
-            if (!isNaN(md.basalforcings.groundedice_melting_rate))
-                md.basalforcings.groundedice_melting_rate=project2d(md,md.basalforcings.groundedice_melting_rate,1); 
-
-            if (!isNaN(md.basalforcings.floatingice_melting_rate))
-                md.basalforcings.floatingice_melting_rate=project2d(md,md.basalforcings.floatingice_melting_rate,1); 
-
-            md.basalforcings.geothermalflux=project2d(md,md.basalforcings.geothermalflux,1); // bedrock only gets geothermal flux
-
-            // update of connectivity matrix
-            md.mesh.average_vertex_connectivity=25;
-
-            // Collapse the mesh
-            var nodes2d=md.mesh.numberofvertices2d;
-            var elements2d=md.mesh.numberofelements2d;
-
-            // parameters
-            md.geometry.surface=project2d(md,md.geometry.surface,1);
-            md.geometry.thickness=project2d(md,md.geometry.thickness,1);
-            md.geometry.base=project2d(md,md.geometry.base,1);
-            if (!isNaN(md.geometry.bed))
-                md.geometry.bed=project2d(md,md.geometry.bed,1);
-
-            if (!isNaN(md.mask.groundedice_levelset))
-                md.mask.groundedice_levelset=project2d(md,md.mask.groundedice_levelset,1);
-
-            if (!isNaN(md.mask.ice_levelset))
-                md.mask.ice_levelset=project2d(md,md.mask.ice_levelset,1);
-
-            // lat long
-            if (numel(md.mesh.lat) === md.mesh.numberofvertices)
-                md.mesh.lat=project2d(md,md.mesh.lat,1);
-            if (numel(md.mesh.long) === md.mesh.numberofvertices)
-                md.mesh.long=project2d(md,md.mesh.long,1);
-
-            // Initialize with the 2d mesh
-            var mesh = new mesh2d();
-            mesh.x=md.mesh.x2d;
-            mesh.y=md.mesh.y2d;
-            mesh.numberofvertices=md.mesh.numberofvertices2d;
-            mesh.numberofelements=md.mesh.numberofelements2d;
-            mesh.elements=md.mesh.elements2d;
-
-            if (!isNaN(md.mesh.vertexonboundary))
-                mesh.vertexonboundary=project2d(md,md.mesh.vertexonboundary,1);
-            if (!isNaN(md.mesh.elementconnectivity))
-                mesh.elementconnectivity=project2d(md,md.mesh.elementconnectivity,1);
-
-            md.mesh=mesh;
-            md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
-            md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
-            md.mesh.segments=contourenvelope(md.mesh);
-
-            return md;
-        } /*}}}*/
+		this.extrude = function(md) { //{{{
+			//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 described 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,15,1.3);
+			//      md=extrude(md,15,1.3,1.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
+			var argc = arguments.length;
+			var extrusionlist;
+			var numlayers;
+			
+			if ((argc > 4) | (argc < 2)) {
+				throw "extrude error message";
+			}
+
+			//Extrude the mesh
+			if (argc==2) { //list of coefficients
+				clist=arguments[0];
+				if (ArrayAnyBelowStrict(clist,0) || ArrayAnyAboveStrict(clist,1)) {
+					throw 'extrusioncoefficients must be between 0 and 1';
+				}
+				extrusionlist=ArraySort(ArrayUnique(clist.push(0,1)));
+				numlayers=extrusionlist.length;
+			} else if (argc==3) { //one polynomial law
+				if (arguments[1]<=0) {
+					throw 'extrusionexponent must be >=0';
+				}
+				numlayers=arguments[1];
+				extrusionlist = [];
+				for (var i = 0; i < numlayers; i++) {
+					extrusionlist.push(Math.pow(i/(numlayers-1), arguments[2]));
+				}
+			} else if (argc==4) { //two polynomial laws
+				numlayers=arguments[1];
+				var lowerexp=arguments[2];
+				var upperexp=arguments[3];
+
+				if (arguments[2]<=0 || arguments[3]<=0) {
+					throw 'lower and upper extrusionexponents must be >=0';
+				}
+
+				var lowerextrusionlist = [];
+				for (var i = 0; i <= 1; i += (2/(numlayers-1))) {
+					lowerextrusionlist.push(Math.pow(i, lowerexp)/2)
+				}
+				var upperextrusionlist = [];
+				for (var i = 0; i <= 1; i += (2/(numlayers-1))) {
+					upperextrusionlist.push(1-Math.pow(i, upperexp)/2)
+				}
+				extrusionlist=ArrayConcat(lowerextrusionlist,upperextrusionlist);
+				extrusionlist=ArraySort(ArrayUnique(extrusionlist.push(1)));
+			}
+
+			if (numlayers<2) {
+				console.error('number of layers should be at least 2');
+			}
+			if (md.mesh.domaintype() === '3D') {
+				console.error('Cannot extrude a 3d mesh (extrude cannot be called more than once)');
+			}
+
+			//Initialize with the 2d mesh
+			var mesh2d = md.mesh;
+			md.mesh=new mesh3dprisms();
+			md.mesh.x                           = mesh2d.x;
+			md.mesh.y                           = mesh2d.y;
+			md.mesh.elements                    = mesh2d.elements;
+			md.mesh.numberofelements            = mesh2d.numberofelements;
+			md.mesh.numberofvertices            = mesh2d.numberofvertices;
+
+			md.mesh.lat                         = mesh2d.lat;
+			md.mesh.long                        = mesh2d.long;
+			md.mesh.epsg                        = mesh2d.epsg;
+			md.mesh.scale_factor                = mesh2d.scale_factor;
+
+			md.mesh.vertexonboundary            = mesh2d.vertexonboundary;
+			md.mesh.vertexconnectivity          = mesh2d.vertexconnectivity;
+			md.mesh.elementconnectivity         = mesh2d.elementconnectivity;
+			md.mesh.average_vertex_connectivity = mesh2d.average_vertex_connectivity;
+
+			md.mesh.extractedvertices           = mesh2d.extractedvertices;
+			md.mesh.extractedelements           = mesh2d.extractedelements;
+
+			var x3d=new Float64Array(); 
+			var y3d=new Float64Array();
+			var z3d=new Float64Array();  //the lower node is on the bed
+			var thickness3d=md.geometry.thickness; //thickness and bed for these nodes
+			var bed3d=md.geometry.base;
+
+			//Create the new layers
+			//Dimensions of x/y/z3d: md.mesh.numberofvertices * numlayers, 1
+			for (var i = 1; i <= numlayers; i++) {
+				x3d=ArrayConcat(x3d, md.mesh.x); 
+				y3d=ArrayConcat(y3d, md.mesh.y); 
+				//nodes are distributed between bed and surface accordingly to the given exponent
+				z3d=ArrayConcat(z3d, FloatFix(thickness3d.map(function(value,index) { return bed3d[index] + value * extrusionlist[i-1]; }), thickness3d.length)); 
+			}
+			var number_nodes3d=x3d.length; //number of 3d nodes for the non extruded part of the mesh
+
+			//Extrude elements 
+			//Create the elements of the 3d mesh for the non extruded part
+			//Dimensions of elements3d: md.mesh.numberofelements * (numlayers - 1), 6
+			var elements3d=[];
+			var elements_prisms=[];
+			for (var i = 1; i < numlayers; i++) {
+				for (var j = 0; j < md.mesh.numberofelements; j++) {
+					elements_prisms = [];
+					for (var k = 0, offset = (i - 1) * md.mesh.numberofvertices; k < 3; k++) {
+						elements_prisms.push(md.mesh.elements[j][k]+offset);
+					}
+					for (var k = 0, offset = i * md.mesh.numberofvertices; k < 3; k++) {
+						elements_prisms.push(md.mesh.elements[j][k]+offset);
+					}
+					elements3d.push(elements_prisms);
+				}				
+			}
+			number_el3d=elements3d.length; //number of 3d nodes for the non extruded part of the mesh
+
+			//Keep a trace of lower and upper nodes
+			var lowervertex = NewArrayFill(number_nodes3d, NaN);
+			var uppervertex = NewArrayFill(number_nodes3d, NaN);
+			//Set first layer to NaN and start count from 1 at next layer (i = md.mesh.numberofvertices+1)
+			for (var i = md.mesh.numberofvertices, k = 1; i < lowervertex.length; i++, k++) {
+				lowervertex[i] = k;
+			};
+			//Set last layer to NaN and start count from md.mesh.numberofvertices+1 at first layer (i = 1)
+			for (var i = 0, k = md.mesh.numberofvertices+1; i < (numlayers-1)*md.mesh.numberofvertices; i++, k++) {
+				uppervertex[i] = k;
+			};
+			md.mesh.lowervertex=lowervertex;
+			md.mesh.uppervertex=uppervertex;
+
+			//same for lower and upper elements
+			var lowerelements = NewArrayFill(number_el3d, NaN);
+			var upperelements = NewArrayFill(number_el3d, NaN);
+			//Set first layer to NaN and start count from 1 at next layer (i = md.mesh.numberofelements+1)
+			for (var i = md.mesh.numberofelements, k = 1; i < lowerelements.length; i++, k++) {
+				lowerelements[i] = k;
+			};
+			//Set last 2 layers to NaN and start count from md.mesh.numberofvertices+1 at first layer (i = 1)
+			for (var i = 0, k = md.mesh.numberofelements + 1; i < (numlayers-2)*md.mesh.numberofelements; i++, k++) {
+				upperelements[i] = k;
+			};
+			md.mesh.lowerelements=lowerelements;
+			md.mesh.upperelements=upperelements;
+
+			//Save old mesh 
+			md.mesh.x2d=md.mesh.x;
+			md.mesh.y2d=md.mesh.y;
+			md.mesh.elements2d=md.mesh.elements;
+			md.mesh.numberofelements2d=md.mesh.numberofelements;
+			md.mesh.numberofvertices2d=md.mesh.numberofvertices;
+
+			//Build global 3d mesh 
+			md.mesh.elements=elements3d;
+			md.mesh.x=x3d;
+			md.mesh.y=y3d;
+			md.mesh.z=z3d;
+			md.mesh.numberofelements=number_el3d;
+			md.mesh.numberofvertices=number_nodes3d;
+			md.mesh.numberoflayers=numlayers;
+
+			//Ok, now deal with the other fields from the 2d mesh:
+
+			//bedinfo and surface info
+			md.mesh.vertexonbase=project3d(md,'vector',NewArrayFill(md.mesh.numberofvertices2d,1),'type','node','layer',1);
+			md.mesh.vertexonsurface=project3d(md,'vector',NewArrayFill(md.mesh.numberofvertices2d,1),'type','node','layer',md.mesh.numberoflayers);
+			md.mesh.vertexonboundary=project3d(md,'vector',md.mesh.vertexonboundary,'type','node');
+
+			//lat long
+			md.mesh.lat=project3d(md,'vector',md.mesh.lat,'type','node');
+			md.mesh.long=project3d(md,'vector',md.mesh.long,'type','node');
+			md.mesh.scale_factor=project3d(md,'vector',md.mesh.scale_factor,'type','node');
+
+			md.geometry=md.geometry.extrude(md);
+			md.friction=md.friction.extrude(md);
+			md.inversion=md.inversion.extrude(md);
+			md.smb=md.smb.extrude(md);
+			md.initialization=md.initialization.extrude(md);
+
+			md.flowequation=md.flowequation.extrude(md);
+			md.stressbalance=md.stressbalance.extrude(md);
+			md.thermal=md.thermal.extrude(md);
+			md.masstransport=md.masstransport.extrude(md);
+			md.levelset=md.levelset.extrude(md);
+			md.calving=md.calving.extrude(md);
+			md.hydrology = md.hydrology.extrude(md);
+
+			//connectivity
+			if (!ArrayAnyNaN(md.mesh.elementconnectivity)) {
+				//md.mesh.elementconnectivity=repmat(md.mesh.elementconnectivity,numlayers-1,1); //Replicate the matrix across numlayers-1 
+				var temparr = [];
+				for (var i = 0; i < numlayers - 1; i++) {
+					temparr = ArrayConcat(temparr, md.mesh.elementconnectivity);
+				}
+				md.mesh.elementconnectivity = temparr;
+		
+				//md.mesh.elementconnectivity(find(md.mesh.elementconnectivity==0))=NaN;
+				var indices = ArrayFind(md.mesh.elementconnectivity, 0);
+				for (var i = 0; i < indices.length; i++) {
+					md.mesh.elementconnectivity[i] = NaN;
+				};
+		
+				for (var i = 2; i < numlayers; i++) {
+					//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;
+					for (var j = (i-1)*md.mesh.numberofelements2d; j <= (i)*md.mesh.numberofelements2d-1; j++) {
+						for (var k = 0; k < 3; k++) {
+							md.mesh.elementconnectivity[j][k] += md.mesh.numberofelements2d;
+						}
+					}
+				}
+				md.mesh.elementconnectivity = md.mesh.elementconnectivity.map(function(value) { return (Number.isNaN(value)) ? 0 : value; });
+			}
+
+			md.materials=md.materials.extrude(md);
+			md.damage=md.damage.extrude(md);
+			md.mask=md.mask.extrude(md);
+			md.qmu=md.qmu.extrude(md);
+			md.basalforcings=md.basalforcings.extrude(md);
+
+			//increase connectivity if less than 25:
+			if (md.mesh.average_vertex_connectivity<=25) {
+				md.mesh.average_vertex_connectivity=100;
+			}
+		} //}}}
+		this.extract = function(md,area) { //{{{
+			//extract - extract a model according to an Argus contour or flag list
+			//
+			//   This routine extracts a submodel from a bigger model with respect to a given contour
+			//   md must be followed by the corresponding exp file or flags list
+			//   It can either be a domain file (argus type, .exp extension), or an array of element flags. 
+			//   If user wants every element outside the domain to be 
+			//   extract2d, add '~' to the name of the domain file (ex: '~HO.exp');
+			//   an empty string '' will be considered as an empty domain
+			//   a string 'all' will be considered as the entire domain
+			//
+			//   Usage:
+			//      md2=extract(md,area);
+			//
+			//   Examples:
+			//      md2=extract(md,'Domain.exp');
+			//
+			//   See also: EXTRUDE, COLLAPSE
+
+			//some checks on list of arguments
+			var argc = arguments.length;
+
+			if (!((argc == 2) | (argc == 1))) {
+				throw "extract error message: bad usage";
+			}
+			
+			//get elements that are inside area
+			flag_elem=FlagElements(this,area);
+
+			if (!ArrayAnyEqual(flag_elem,1))throw "extracted model is empty!"
+
+			/*kick out all elements with 3 dirichlets: actually, not so fast, not good for javscript usually.
+			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
+			var pos_elem = ArrayFind(flag_elem,1);
+			var dup_nodes= new Array(pos_elem.length*3);
+			for(var i=0;i<pos_elem.length;i++){
+				dup_nodes[3*i]=md.mesh.elements[pos_elem[i]][0]-1;
+				dup_nodes[3*i+1]=md.mesh.elements[pos_elem[i]][1]-1;
+				dup_nodes[3*i+2]=md.mesh.elements[pos_elem[i]][2]-1;
+			}
+			pos_node=ArrayUnique(dup_nodes); pos_node=ArraySort(pos_node);
+
+			//keep track of some fields
+			var numberofvertices1=md.mesh.numberofvertices;
+			var numberofelements1=md.mesh.numberofelements;
+			var numberofvertices2=pos_node.length;
+			var numberofelements2=pos_elem.length;
+			var flag_node=NewArrayFill(numberofvertices1,0);
+			for (var i=0;i<pos_node.length;i++)flag_node[pos_node[i]]=1;
+
+			//Create Pelem and Pnode (transform old nodes in new nodes and same thing for the elements)
+			Pelem=NewArrayFill(numberofelements1,0);
+			for (var i=0;i<numberofelements2;i++) Pelem[pos_elem[i]]=i;
+			Pnode=NewArrayFill(numberofvertices1,0);
+			for (var i=0;i<numberofvertices2;i++) Pnode[pos_node[i]]=i;
+			//renumber the elements (some nodes won't exist anymore)
+			var elements_2=NewArrayFill2D(numberofelements2,3,0);
+			for (var i=0;i<numberofelements2;i++){
+				for (var j=0;j<3;j++){
+					elements_2[i][j]=Pnode[md.mesh.elements[i][j]-1]+1;
+				}
+			}
+			
+			/*if isa(md.mesh,'mesh3dprisms'),
+				elements_2(:,4)=Pnode(elements_2(:,4));
+				elements_2(:,5)=Pnode(elements_2(:,5));
+				elements_2(:,6)=Pnode(elements_2(:,6));
+			end
+			*/
+			
+			//OK, now create the new model!
+
+			//take every field from model
+			var md2=md.deepcopy(md);
+			//var md2=new model(); md2.mesh=new mesh3dsurface();
+			
+			//deal with mesh: {{{
+			md2.mesh.numberofvertices=numberofvertices2;
+			md2.mesh.numberofelements=numberofelements2;
+			md2.mesh.elements=elements_2;
+
+			md2.mesh.x=new Array(numberofvertices2); for (var i=0;i<numberofvertices2;i++)md2.mesh.x[i]=md.mesh.x[pos_node[i]];
+			md2.mesh.y=new Array(numberofvertices2); for (var i=0;i<numberofvertices2;i++)md2.mesh.y[i]=md.mesh.y[pos_node[i]];
+			md2.mesh.z=new Array(numberofvertices2); for (var i=0;i<numberofvertices2;i++)md2.mesh.z[i]=md.mesh.z[pos_node[i]];
+			md2.mesh.lat=new Array(numberofvertices2); for (var i=0;i<numberofvertices2;i++)md2.mesh.lat[i]=md.mesh.lat[pos_node[i]];
+			md2.mesh.long=new Array(numberofvertices2); for (var i=0;i<numberofvertices2;i++)md2.mesh.long[i]=md.mesh.long[pos_node[i]];
+			md2.mesh.r=new Array(numberofvertices2); for (var i=0;i<numberofvertices2;i++)md2.mesh.r[i]=md.mesh.r[pos_node[i]];
+			//}}}
+			//deal with geometry: {{{
+			md2.geometry.base=new Array(numberofvertices2); for (var i=0;i<numberofvertices2;i++)md2.geometry.base[i]=md.geometry.base[pos_node[i]];
+			md2.geometry.thickness=new Array(numberofvertices2); for (var i=0;i<numberofvertices2;i++)md2.geometry.thickness[i]=md.geometry.thickness[pos_node[i]];
+			md2.geometry.surface=new Array(numberofvertices2); for (var i=0;i<numberofvertices2;i++)md2.geometry.surface[i]=md.geometry.surface[pos_node[i]];
+			md2.geometry.bed=new Array(numberofvertices2); for (var i=0;i<numberofvertices2;i++)md2.geometry.bed[i]=md.geometry.bed[pos_node[i]];
+			//}}}
+
+			//Keep track of pos_node and pos_elem
+			for (var i=0;i<md2.mesh.numberofvertices;i++)pos_node[i]=pos_node[i]+1;
+			for (var i=0;i<md2.mesh.numberofelements;i++)pos_elem[i]=pos_elem[i]+1;
+			md2.mesh.extractedvertices=pos_node;
+			md2.mesh.extractedelements=pos_elem;
+
+			return md2;
+
+
+
+			//automatically modify fields
+
+			//loop over model fields
+			//model_fields=fields(md);
+
+
+
+
+
+		} //}}}
+		this.collapse = function(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.elementtype() !== 'Penta') {
+				console.error('collapse error message: only 3d mesh can be collapsed')
+			}
+
+			// Start with changing all the fields from the 3d mesh 
+
+			// dealing with the friction law
+			// drag is limited to nodes that are on the bedrock.
+			if (md.friction.classname() === 'friction') {
+				md.friction.coefficient=project2d(md,md.friction.coefficient,1);
+				md.friction.p=project2d(md,md.friction.p,1);
+				md.friction.q=project2d(md,md.friction.q,1);
+			} else if (md.friction.classname() === 'frictionhydro') {
+				md.friction.q=project2d(md,md.friction.q,1);
+				md.friction.C=project2d(md,md.friction.C,1);
+				md.friction.As=project2d(md,md.friction.As,1);
+				md.friction.effective_pressure=project2d(md,md.friction.effective_pressure,1);
+			} else if (md.friction.classname() === 'frictionwaterlayer') {
+				md.friction.coefficient=project2d(md,md.friction.coefficient,1);
+				md.friction.p=project2d(md,md.friction.p,1);
+				md.friction.q=project2d(md,md.friction.q,1);
+				md.friction.water_layer=project2d(md,md.friction.water_layer,1);
+			} else if (md.friction.classname() === 'frictionweertman') {
+				md.friction.C=project2d(md,md.friction.C,1);
+				md.friction.m=project2d(md,md.friction.m,1);
+			} else if (md.friction.classname() === 'frictionweertmantemp') {
+				md.friction.C=project2d(md,md.friction.C,1);
+				md.friction.m=project2d(md,md.friction.m,1);
+			} else {
+				disp('friction type not supported');
+			}
+
+			// observations
+			if (!Number.isNaN(md.inversion.vx_obs))
+				md.inversion.vx_obs=project2d(md,md.inversion.vx_obs,md.mesh.numberoflayers);
+
+			if (!Number.isNaN(md.inversion.vy_obs))
+				md.inversion.vy_obs=project2d(md,md.inversion.vy_obs,md.mesh.numberoflayers);
+
+			if (!Number.isNaN(md.inversion.vel_obs))
+				md.inversion.vel_obs=project2d(md,md.inversion.vel_obs,md.mesh.numberoflayers);
+
+			if (!Number.isNaN(md.inversion.cost_functions_coefficients))
+				md.inversion.cost_functions_coefficients=project2d(md,md.inversion.cost_functions_coefficients,md.mesh.numberoflayers);
+
+			if (numel(md.inversion.min_parameters)>1)
+				md.inversion.min_parameters=project2d(md,md.inversion.min_parameters,md.mesh.numberoflayers);
+
+			if (numel(md.inversion.max_parameters)>1) 
+				md.inversion.max_parameters=project2d(md,md.inversion.max_parameters,md.mesh.numberoflayers);
+
+			if (md.smb.classname() === 'SMBforcing' && !Number.isNaN(md.smb.mass_balance)) {
+				md.smb.mass_balance=project2d(md,md.smb.mass_balance,md.mesh.numberoflayers);
+			} else if (md.smb.classname() === 'SMBhenning' && !Number.isNaN(md.smb.smbref)) {
+				md.smb.smbref=project2d(md,md.smb.smbref,md.mesh.numberoflayers);
+			}
+
+			// results
+			if (!Number.isNaN(md.initialization.vx))
+				md.initialization.vx=DepthAverage(md,md.initialization.vx);
+			if (!Number.isNaN(md.initialization.vy))
+				md.initialization.vy=DepthAverage(md,md.initialization.vy);
+			if (!Number.isNaN(md.initialization.vz))
+				md.initialization.vz=DepthAverage(md,md.initialization.vz);
+			if (!Number.isNaN(md.initialization.vel))
+				md.initialization.vel=DepthAverage(md,md.initialization.vel);
+			if (!Number.isNaN(md.initialization.temperature))
+				md.initialization.temperature=DepthAverage(md,md.initialization.temperature);
+			if (!Number.isNaN(md.initialization.pressure))
+				md.initialization.pressure=project2d(md,md.initialization.pressure,1);
+			if (!Number.isNaN(md.initialization.sediment_head))
+				md.initialization.sediment_head=project2d(md,md.initialization.sediment_head,1);
+			if (!Number.isNaN(md.initialization.epl_head))
+				md.initialization.epl_head=project2d(md,md.initialization.epl_head,1);
+			if (!Number.isNaN(md.initialization.epl_thickness))
+				md.initialization.epl_thickness=project2d(md,md.initialization.epl_thickness,1);
+
+			// giaivins
+			if (!Number.isNaN(md.gia.mantle_viscosity))
+				md.gia.mantle_viscosity=project2d(md,md.gia.mantle_viscosity,1);
+			if (!Number.isNaN(md.gia.lithosphere_thickness))
+				md.gia.lithosphere_thickness=project2d(md,md.gia.lithosphere_thickness,1);
+
+			// elementstype
+			if (!Number.isNaN(md.flowequation.element_equation)) {
+				md.flowequation.element_equation=project2d(md,md.flowequation.element_equation,1);
+				md.flowequation.vertex_equation=project2d(md,md.flowequation.vertex_equation,1);
+				md.flowequation.borderSSA=project2d(md,md.flowequation.borderSSA,1);
+				md.flowequation.borderHO=project2d(md,md.flowequation.borderHO,1);
+				md.flowequation.borderFS=project2d(md,md.flowequation.borderFS,1);
+			}
+
+			// boundary conditions
+			md.stressbalance.spcvx=project2d(md,md.stressbalance.spcvx,md.mesh.numberoflayers);
+			md.stressbalance.spcvy=project2d(md,md.stressbalance.spcvy,md.mesh.numberoflayers);
+			md.stressbalance.spcvz=project2d(md,md.stressbalance.spcvz,md.mesh.numberoflayers);
+			md.stressbalance.referential=project2d(md,md.stressbalance.referential,md.mesh.numberoflayers);
+			md.stressbalance.loadingforce=project2d(md,md.stressbalance.loadingforce,md.mesh.numberoflayers);
+			md.masstransport.spcthickness=project2d(md,md.masstransport.spcthickness,md.mesh.numberoflayers);
+			if (!Number.isNaN(md.damage.spcdamage))
+				md.damage.spcdamage=project2d(md,md.damage.spcdamage,md.mesh.numberoflayers);
+			md.thermal.spctemperature=project2d(md,md.thermal.spctemperature,md.mesh.numberoflayers);
+
+			// Hydrologydc variables
+			if (md.hydrology.classname() === 'hydrologydc') {
+				md.hydrology.spcsediment_head=project2d(md,md.hydrology.spcsediment_head,1);
+				md.hydrology.mask_eplactive_node=project2d(md,md.hydrology.mask_eplactive_node,1);
+				md.hydrology.sediment_transmitivity=project2d(md,md.hydrology.sediment_transmitivity,1);
+				md.hydrology.basal_moulin_input=project2d(md,md.hydrology.basal_moulin_input,1);
+
+				if(md.hydrology.isefficientlayer==1)
+					md.hydrology.spcepl_head=project2d(md,md.hydrology.spcepl_head,1);
+			}
+			
+			// materials
+			md.materials.rheology_B=DepthAverage(md,md.materials.rheology_B);
+			md.materials.rheology_n=project2d(md,md.materials.rheology_n,1);
+			
+			// damage: 
+			if (md.damage.isdamage)
+				md.damage.D=DepthAverage(md,md.damage.D);
+
+			// special for thermal modeling:
+			if (!Number.isNaN(md.basalforcings.groundedice_melting_rate))
+				md.basalforcings.groundedice_melting_rate=project2d(md,md.basalforcings.groundedice_melting_rate,1); 
+
+			if (!Number.isNaN(md.basalforcings.floatingice_melting_rate))
+				md.basalforcings.floatingice_melting_rate=project2d(md,md.basalforcings.floatingice_melting_rate,1); 
+
+			md.basalforcings.geothermalflux=project2d(md,md.basalforcings.geothermalflux,1); // bedrock only gets geothermal flux
+
+			// update of connectivity matrix
+			md.mesh.average_vertex_connectivity=25;
+
+			// Collapse the mesh
+			var nodes2d=md.mesh.numberofvertices2d;
+			var elements2d=md.mesh.numberofelements2d;
+
+			// parameters
+			md.geometry.surface=project2d(md,md.geometry.surface,1);
+			md.geometry.thickness=project2d(md,md.geometry.thickness,1);
+			md.geometry.base=project2d(md,md.geometry.base,1);
+			if (!Number.isNaN(md.geometry.bed))
+				md.geometry.bed=project2d(md,md.geometry.bed,1);
+
+			if (!Number.isNaN(md.mask.groundedice_levelset))
+				md.mask.groundedice_levelset=project2d(md,md.mask.groundedice_levelset,1);
+
+			if (!Number.isNaN(md.mask.ice_levelset))
+				md.mask.ice_levelset=project2d(md,md.mask.ice_levelset,1);
+
+			// lat long
+			if (numel(md.mesh.lat) === md.mesh.numberofvertices)
+				md.mesh.lat=project2d(md,md.mesh.lat,1);
+			if (numel(md.mesh.long) === md.mesh.numberofvertices)
+				md.mesh.long=project2d(md,md.mesh.long,1);
+			if (numel(md.mesh.scale_factor) === md.mesh.numberofvertices)
+				md.mesh.scale_factor=project2d(md,md.mesh.scale_factor,1);
+
+			// Initialize with the 2d mesh
+			var mesh = new mesh2d();
+			mesh.x=md.mesh.x2d;
+			mesh.y=md.mesh.y2d;
+			mesh.numberofvertices=md.mesh.numberofvertices2d;
+			mesh.numberofelements=md.mesh.numberofelements2d;
+			mesh.elements=md.mesh.elements2d;
+
+			if (!Number.isNaN(md.mesh.vertexonboundary))
+				mesh.vertexonboundary=project2d(md,md.mesh.vertexonboundary,1);
+			if (!Number.isNaN(md.mesh.elementconnectivity))
+				mesh.elementconnectivity=project2d(md,md.mesh.elementconnectivity,1);
+
+			md.mesh=mesh;
+			md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+			md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+			md.mesh.segments=contourenvelope(md.mesh);
+
+			return md;
+		} /*}}}*/
+		this.deepCopy = function(md) { //{{{
+			/*
+			 *DEEPCOPY - returns a deep copy of the model.
+			 *
+			 *   This routine creates a new model with new objects 
+			 *   for each corresponding object in the original model,
+			 *   so that changes in one do not affect the other.
+			 *
+			 *   Usage:
+			 *	 md1=deepCopy(md)
+			 *
+			 */
+			function recursiveDeepCopy(obj) {
+				var returnValue;
+
+				switch (typeof obj) {
+					case "object":
+						if (obj === null) {
+							// null => null
+							returnValue = null;
+						} else {
+							switch (toString.call(obj)) {
+								case "[object Array]":
+									// It's an array, create a new array with deep copies of the entries
+									returnValue = obj.map(recursiveDeepCopy);
+									break;
+								default:
+									// Some other kind of object, deep-copy its properties into a new object
+									returnValue = Object.keys(obj).reduce(function(prev, key) {
+										prev[key] = recursiveDeepCopy(obj[key]);
+										return prev;
+									}, {});
+									break;
+							}
+						}
+						break;
+					default:
+						// It's a primitive, copy via assignment
+						returnValue = obj;
+						break;
+				}
+				return returnValue;
+			}
+			
+			return recursiveDeepCopy(md);
+		} /*}}}*/
 	//properties
 	// {{{
@@ -609,10 +757,12 @@
 		this.levelset         = 0;
 		this.calving          = 0;
+		this.love             = 0;
 		this.gia              = 0;
+		this.esa              = 0;
 
 		this.autodiff         = 0;
 		this.inversion        = 0;
 		this.qmu              = 0;
-		this.amr					 = 0;
+		this.amr              = 0;
 
 		this.results          = 0;
Index: /issm/trunk/src/m/classes/model.m
===================================================================
--- /issm/trunk/src/m/classes/model.m	(revision 22757)
+++ /issm/trunk/src/m/classes/model.m	(revision 22758)
@@ -40,4 +40,5 @@
 		levelset			  = 0;
 		calving          = 0;
+		love			     = 0;
 		gia				  = 0;
 		esa              = 0;
@@ -127,4 +128,9 @@
 			%2016 October 11
 			if isa(md.esa,'double'); md.esa=esa(); end
+			%2017 Dec 21st (needs to be here)
+			if isempty(md.settings)
+				disp('Warning: md.settings had to be reset, make sure to adjust md.settings.output_frequency and other fields');
+				md.settings = issmsettings();
+			end
 			%2017 February 10th
 			if md.settings.solver_residue_threshold==0,
@@ -135,4 +141,11 @@
 			%2017 May 4th
 			if isa(md.amr,'double'); md.amr=amr(); end
+			%2017 Aug 29th
+			if isa(md.love,'double'); md.love=fourierlove(); end
+			%2017 Oct 26th
+			if isa(md.calving,'calvingdev')
+				disp('Warning: calvingdev is now calvingvonmises');
+				md.calving=calvingvonmises(md.calving); 
+			end
 
 		end% }}}
@@ -177,8 +190,13 @@
 			%Start with changing all the fields from the 3d mesh 
 
-			%dealing with the friciton law
+			%dealing with the friction law
 			%drag is limited to nodes that are on the bedrock.
 			if isa(md.friction,'friction'),
 				md.friction.coefficient=project2d(md,md.friction.coefficient,1);
+				md.friction.p=project2d(md,md.friction.p,1);
+				md.friction.q=project2d(md,md.friction.q,1);
+			elseif isa(md.friction,'frictioncoulomb'),
+				md.friction.coefficient=project2d(md,md.friction.coefficient,1);
+				md.friction.coefficientcoulomb=project2d(md,md.friction.coefficientcoulomb,1);
 				md.friction.p=project2d(md,md.friction.p,1);
 				md.friction.q=project2d(md,md.friction.q,1);
@@ -201,5 +219,5 @@
 			else
 				disp('friction type not supported');
-	    end
+			end
 
 			%observations
@@ -260,6 +278,6 @@
 				if(md.hydrology.isefficientlayer==1)
 					md.hydrology.spcepl_head=project2d(md,md.hydrology.spcepl_head,1);
-		    end
-	    end
+				end
+			end
 			
 			%materials
@@ -308,4 +326,18 @@
 			if ~isnan(md.mask.ice_levelset),
 				md.mask.ice_levelset=project2d(md,md.mask.ice_levelset,1);
+			end
+
+			%outputdefinitions
+			for i=1:length(md.outputdefinition.definitions)
+				if isobject(md.outputdefinition.definitions{i})
+					%get subfields
+					solutionsubfields=fields(md.outputdefinition.definitions{i});
+					for j=1:length(solutionsubfields),
+						field=md.outputdefinition.definitions{i}.(solutionsubfields{j});
+						if length(field)==md.mesh.numberofvertices | length(field)==md.mesh.numberofelements,
+							md.outputdefinition.definitions{i}.(solutionsubfields{j})=project2d(md,md.outputdefinition.definitions{i}.(solutionsubfields{j}),1);
+						end
+					end
+				end
 			end
 
@@ -320,4 +352,5 @@
 			if numel(md.mesh.long)==md.mesh.numberofvertices,	mesh.long=project2d(md,md.mesh.long,1); end
 			mesh.epsg=md.mesh.epsg;
+			if numel(md.mesh.scale_factor)==md.mesh.numberofvertices,	mesh.scale_factor=project2d(md,md.mesh.scale_factor,1); end
 			if ~isnan(md.mesh.vertexonboundary), mesh.vertexonboundary=project2d(md,md.mesh.vertexonboundary,1); end
 			if ~isnan(md.mesh.elementconnectivity), mesh.elementconnectivity=project2d(md,md.mesh.elementconnectivity,1); end
@@ -607,4 +640,20 @@
 			end
 
+			%OutputDefinitions fields
+			for i=1:length(md1.outputdefinition.definitions),
+				if isobject(md1.outputdefinition.definitions{i})
+					%get subfields
+					solutionsubfields=fields(md1.outputdefinition.definitions{i});
+					for j=1:length(solutionsubfields),
+						field=md1.outputdefinition.definitions{i}.(solutionsubfields{j});
+						if length(field)==numberofvertices1,
+							md2.outputdefinition.definitions{i}.(solutionsubfields{j})=field(pos_node);
+						elseif length(field)==numberofelements1,
+							md2.outputdefinition.definitions{i}.(solutionsubfields{j})=field(pos_elem);
+						end
+					end
+				end
+			end
+
 			%Keep track of pos_node and pos_elem
 			md2.mesh.extractedvertices=pos_node;
@@ -689,4 +738,5 @@
 			md.mesh.long                        = mesh2d.long;
 			md.mesh.epsg                        = mesh2d.epsg;
+			md.mesh.scale_factor                = mesh2d.scale_factor;
 
 			md.mesh.vertexonboundary            = mesh2d.vertexonboundary;
@@ -762,4 +812,5 @@
 			md.mesh.lat=project3d(md,'vector',md.mesh.lat,'type','node');
 			md.mesh.long=project3d(md,'vector',md.mesh.long,'type','node');
+			md.mesh.scale_factor=project3d(md,'vector',md.mesh.scale_factor,'type','node');
 
 			md.geometry=extrude(md.geometry,md);
@@ -793,4 +844,5 @@
 			md.qmu=extrude(md.qmu,md);
 			md.basalforcings=extrude(md.basalforcings,md);
+			md.outputdefinition=extrude(md.outputdefinition,md);
 
 			%increase connectivity if less than 25:
@@ -915,4 +967,5 @@
 			if isfield(structmd,'lat'), md.mesh.lat=structmd.lat; end
 			if isfield(structmd,'long'), md.mesh.long=structmd.long; end
+			if isfield(structmd,'scale_factor'), md.mesh.scale_factor=structmd.scale_factor; end
 			if isfield(structmd,'segments'), md.mesh.segments=structmd.segments; end
 			if isfield(structmd,'segmentmarkers'), md.mesh.segmentmarkers=structmd.segmentmarkers; end
@@ -1102,5 +1155,5 @@
 			md.debug            = debug();
 			md.verbose          = verbose();
-			md.settings         = settings();
+			md.settings         = issmsettings();
 			md.toolkits         = toolkits();
 			md.cluster          = generic();
@@ -1112,12 +1165,13 @@
 			md.steadystate      = steadystate();
 			md.transient        = transient();
-			md.levelset			  = levelset();
+			md.levelset         = levelset();
 			md.calving          = calving();
-			md.gia				  = giaivins();
+			md.gia              = giaivins();
+			md.love             = fourierlove();
 			md.esa              = esa();
 			md.autodiff         = autodiff();
 			md.inversion        = inversion();
 			md.qmu              = qmu();
-			md.amr				  = amr();
+			md.amr              = amr();
 			md.radaroverlay     = radaroverlay();
 			md.results          = struct();
@@ -1288,4 +1342,5 @@
 			disp(sprintf('%19s: %-22s -- %s','calving'         ,['[1x1 ' class(self.calving) ']'],'parameters for calving'));
 			disp(sprintf('%19s: %-22s -- %s','gia'        ,['[1x1 ' class(self.gia) ']'],'parameters for gia solution'));
+			disp(sprintf('%19s: %-22s -- %s','love'        ,['[1x1 ' class(self.love) ']'],'parameters for love solution'));
 			disp(sprintf('%19s: %-22s -- %s','esa'             ,['[1x1 ' class(self.esa) ']'],'parameters for elastic adjustment solution'));
 			disp(sprintf('%19s: %-22s -- %s','autodiff'        ,['[1x1 ' class(self.autodiff) ']'],'automatic differentiation parameters'));
Index: /issm/trunk/src/m/classes/model.py
===================================================================
--- /issm/trunk/src/m/classes/model.py	(revision 22757)
+++ /issm/trunk/src/m/classes/model.py	(revision 22758)
@@ -18,4 +18,5 @@
 from levelset import levelset 
 from calving import calving
+from fourierlove import fourierlove
 from calvinglevermann import calvinglevermann
 #from calvingpi import calvingpi
@@ -24,4 +25,5 @@
 from flowequation import flowequation
 from timestepping import timestepping
+from timesteppingadaptive import timesteppingadaptive
 from initialization import initialization
 from rifts import rifts
@@ -29,5 +31,5 @@
 from debug import debug
 from verbose import verbose
-from settings import settings
+from issmsettings import issmsettings
 from toolkits import toolkits
 from generic import generic
@@ -36,4 +38,5 @@
 from hexagon import hexagon
 from cyclone import cyclone
+from stallo import stallo
 from balancethickness import balancethickness
 from stressbalance import stressbalance
@@ -46,4 +49,5 @@
 from transient import transient
 from giaivins import giaivins
+from esa import esa
 from autodiff import autodiff
 from inversion import inversion
@@ -63,5 +67,4 @@
 from ElementConnectivity import ElementConnectivity
 from contourenvelope import contourenvelope
-import MatlabFuncs as m
 from DepthAverage import DepthAverage
 #}}}
@@ -94,5 +97,5 @@
 		self.debug            = debug()
 		self.verbose          = verbose()
-		self.settings         = settings()
+		self.settings         = issmsettings()
 		self.toolkits         = toolkits()
 		self.cluster          = generic()
@@ -108,5 +111,7 @@
 		self.levelset         = levelset()
 		self.calving          = calving()
+		self.love             = fourierlove()
 		self.gia              = giaivins()
+		self.esa	      = esa()
 
 		self.autodiff         = autodiff()
@@ -123,42 +128,44 @@
 	def properties(self):    # {{{
 		# ordered list of properties since vars(self) is random
-		return ['mesh',\
-		        'mask',\
-		        'geometry',\
-		        'constants',\
-		        'smb',\
-		        'basalforcings',\
-		        'materials',\
-		        'damage',\
-		        'friction',\
-		        'flowequation',\
-		        'timestepping',\
-		        'initialization',\
-		        'rifts',\
-		        'slr',\
-		        'debug',\
-		        'verbose',\
-		        'settings',\
-		        'toolkits',\
-		        'cluster',\
-		        'balancethickness',\
-		        'stressbalance',\
-		        'groundingline',\
-		        'hydrology',\
-		        'masstransport',\
-		        'thermal',\
-		        'steadystate',\
-		        'transient',\
-		        'levelset',\
-		        'calving',\
-					'gia',\
-		        'autodiff',\
-		        'inversion',\
-		        'qmu',\
-		        'amr',\
-		        'outputdefinition',\
-		        'results',\
-		        'radaroverlay',\
-		        'miscellaneous',\
+		return ['mesh',
+		        'mask',
+		        'geometry',
+		        'constants',
+		        'smb',
+		        'basalforcings',
+		        'materials',
+		        'damage',
+		        'friction',
+		        'flowequation',
+		        'timestepping',
+		        'initialization',
+		        'rifts',
+		        'slr',
+		        'debug',
+		        'verbose',
+		        'settings',
+		        'toolkits',
+		        'cluster',
+		        'balancethickness',
+		        'stressbalance',
+		        'groundingline',
+		        'hydrology',
+		        'masstransport',
+		        'thermal',
+		        'steadystate',
+		        'transient',
+		        'levelset',
+		        'calving',
+			'love',
+			'gia',
+			'esa',
+		        'autodiff',
+		        'inversion',
+		        'qmu',
+		        'amr',
+		        'outputdefinition',
+		        'results',
+		        'radaroverlay',
+		        'miscellaneous',
 		        'private']
 	# }}}
@@ -194,4 +201,7 @@
 		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("levelset","[%s,%s]" % ("1x1",obj.levelset.__class__.__name__),"parameters for moving boundaries (level-set method)"))
 		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("calving","[%s,%s]" % ("1x1",obj.calving.__class__.__name__),"parameters for calving"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("gia","[%s,%s]" % ("1x1",obj.gia.__class__.__name__),"parameters for gia solution"))
+		string="%s\n%s" % (string,'%19s: %-22s -- %s' % ("love","[%s,%s]" % ("1x1",obj.love.__class__.__name__),"parameters for love solution"))
+		string="%s\n%s" % (string,'%19s: %-22s -- %s' % ("esa","[%s,%s]" % ("1x1",obj.esa.__class__.__name__),"parameters for elastic adjustment solution"))
 		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("autodiff","[%s,%s]" % ("1x1",obj.autodiff.__class__.__name__),"automatic differentiation parameters"))
 		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("inversion","[%s,%s]" % ("1x1",obj.inversion.__class__.__name__),"parameters for inverse methods"))
@@ -288,5 +298,5 @@
 			field=getattr(md1,fieldi)
 			fieldsize=np.shape(field)
-			if hasattr(field,'__dict__') and not m.ismember(fieldi,['results'])[0]:    #recursive call
+			if hasattr(field,'__dict__') and not fieldi in ['results']:    #recursive call
 				object_fields=vars(field)
 				for fieldj in object_fields:
@@ -296,5 +306,5 @@
 					if len(fieldsize):
 						#size = number of nodes * n
-						if   fieldsize[0]==numberofvertices1:
+						if fieldsize[0]==numberofvertices1:
 							setattr(getattr(md2,fieldi),fieldj,field[pos_node])
 						elif fieldsize[0]==numberofvertices1+1:
@@ -306,5 +316,5 @@
 				if len(fieldsize):
 					#size = number of nodes * n
-					if   fieldsize[0]==numberofvertices1:
+					if fieldsize[0]==numberofvertices1:
 						setattr(md2,fieldi,field[pos_node])
 					elif fieldsize[0]==numberofvertices1+1:
@@ -357,11 +367,11 @@
 
 		#Edges
-		if m.strcmp(md.mesh.domaintype(),'2Dhorizontal'):
+		if md.mesh.domaintype()=='2Dhorizontal':
 			if np.ndim(md2.mesh.edges)>1 and np.size(md2.mesh.edges,axis=1)>1:    #do not use ~isnan because there are some np.nans...
 				#renumber first two columns
 				pos=np.nonzero(md2.mesh.edges[:,3]!=-1)[0]
-				md2.mesh.edges[:  ,0]=Pnode[md2.mesh.edges[:,0]-1]
-				md2.mesh.edges[:  ,1]=Pnode[md2.mesh.edges[:,1]-1]
-				md2.mesh.edges[:  ,2]=Pelem[md2.mesh.edges[:,2]-1]
+				md2.mesh.edges[:,0]=Pnode[md2.mesh.edges[:,0]-1]
+				md2.mesh.edges[:,1]=Pnode[md2.mesh.edges[:,1]-1]
+				md2.mesh.edges[:,2]=Pelem[md2.mesh.edges[:,2]-1]
 				md2.mesh.edges[pos,3]=Pelem[md2.mesh.edges[pos,3]-1]
 				#remove edges when the 2 vertices are not in the domain.
@@ -466,4 +476,21 @@
 								setattr(fieldr,solutionsubfield,subfield)
 
+		#OutputDefinitions fields
+		if md1.outputdefinition.definitions:
+			for solutionfield,field in md1.outputdefinition.__dict__.iteritems():
+				if isinstance(field,list):
+					#get each definition
+					for i,fieldi in enumerate(field):
+						if fieldi:
+							fieldr=getattr(md2.outputdefinition,solutionfield)[i]
+							#get subfields
+							for solutionsubfield,subfield in fieldi.__dict__.iteritems():
+								if   np.size(subfield)==numberofvertices1:
+									setattr(fieldr,solutionsubfield,subfield[pos_node])
+								elif np.size(subfield)==numberofelements1:
+									setattr(fieldr,solutionsubfield,subfield[pos_elem])
+								else:
+									setattr(fieldr,solutionsubfield,subfield)
+
 		#Keep track of pos_node and pos_elem
 		md2.mesh.extractedvertices=pos_node+1
@@ -545,4 +572,5 @@
 		md.mesh.long                        = mesh2d.long
 		md.mesh.epsg                        = mesh2d.epsg
+		md.mesh.scale_factor                = mesh2d.scale_factor
 
 		md.mesh.vertexonboundary            = mesh2d.vertexonboundary
@@ -616,4 +644,5 @@
 		md.mesh.lat=project3d(md,'vector',md.mesh.lat,'type','node')
 		md.mesh.long=project3d(md,'vector',md.mesh.long,'type','node')
+		md.mesh.scale_factor=project3d(md,'vector',md.mesh.scale_factor,'type','node')
 
 		md.geometry.extrude(md)
@@ -648,4 +677,5 @@
 		md.qmu.extrude(md)
 		md.basalforcings.extrude(md)
+		md.outputdefinition.extrude(md)
 
 		#increase connectivity if less than 25:
@@ -670,37 +700,71 @@
 			raise StandardError("only a 3D model can be collapsed")
 		
+		#dealing with the friction law
 		#drag is limited to nodes that are on the bedrock.
-		md.friction.coefficient=project2d(md,md.friction.coefficient,1)
+		if hasattr(md.friction,'coefficient'): 
+			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)
+		if hasattr(md.friction,'p'): 
+			md.friction.p=project2d(md,md.friction.p,1)
+		if hasattr(md.friction,'q'): 
+			md.friction.q=project2d(md,md.friction.q,1)
+		
+		if hasattr(md.friction,'coefficientcoulomb'): 
+			md.friction.coefficientcoulomb=project2d(md,md.friction.coefficientcoulomb,1)
+		if hasattr(md.friction,'C'): 
+			md.friction.C=project2d(md,md.friction.C,1)
+		if hasattr(md.friction,'As'): 
+			md.friction.As=project2d(md,md.friction.As,1)
+		if hasattr(md.friction,'effective_pressure') and not np.isnan(md.friction.effective_pressure).all():
+			md.friction.effective_pressure=project2d(md,md.friction.effective_pressure,1)
+		if hasattr(md.friction,'water_layer'): 
+			md.friction.water_layer=project2d(md,md.friction.water_layer,1)
+		if hasattr(md.friction,'m'): 
+			md.friction.m=project2d(md,md.friction.m,1)
 
 		#observations
-		if not np.isnan(md.inversion.vx_obs).all(): md.inversion.vx_obs=project2d(md,md.inversion.vx_obs,md.mesh.numberoflayers) 
-		if not np.isnan(md.inversion.vy_obs).all(): md.inversion.vy_obs=project2d(md,md.inversion.vy_obs,md.mesh.numberoflayers) 
-		if not np.isnan(md.inversion.vel_obs).all(): md.inversion.vel_obs=project2d(md,md.inversion.vel_obs,md.mesh.numberoflayers) 
-		if not np.isnan(md.inversion.cost_functions_coefficients).all(): md.inversion.cost_functions_coefficients=project2d(md,md.inversion.cost_functions_coefficients,md.mesh.numberoflayers) 
-                if isinstance(md.inversion.min_parameters,np.ndarray):
-                    if md.inversion.min_parameters.size>1: md.inversion.min_parameters=project2d(md,md.inversion.min_parameters,md.mesh.numberoflayers) 
-                if isinstance(md.inversion.max_parameters,np.ndarray):
-		    if md.inversion.max_parameters.size>1: md.inversion.max_parameters=project2d(md,md.inversion.max_parameters,md.mesh.numberoflayers) 
+		if not np.isnan(md.inversion.vx_obs).all(): 
+			md.inversion.vx_obs=project2d(md,md.inversion.vx_obs,md.mesh.numberoflayers) 
+		if not np.isnan(md.inversion.vy_obs).all(): 
+			md.inversion.vy_obs=project2d(md,md.inversion.vy_obs,md.mesh.numberoflayers) 
+		if not np.isnan(md.inversion.vel_obs).all(): 
+			md.inversion.vel_obs=project2d(md,md.inversion.vel_obs,md.mesh.numberoflayers) 
+		if not np.isnan(md.inversion.cost_functions_coefficients).all(): 
+			md.inversion.cost_functions_coefficients=project2d(md,md.inversion.cost_functions_coefficients,md.mesh.numberoflayers) 
+		if isinstance(md.inversion.min_parameters,np.ndarray):
+			if md.inversion.min_parameters.size>1: 
+				md.inversion.min_parameters=project2d(md,md.inversion.min_parameters,md.mesh.numberoflayers) 
+		if isinstance(md.inversion.max_parameters,np.ndarray):
+			if md.inversion.max_parameters.size>1: 
+				md.inversion.max_parameters=project2d(md,md.inversion.max_parameters,md.mesh.numberoflayers) 
 		if not np.isnan(md.smb.mass_balance).all():
 			md.smb.mass_balance=project2d(md,md.smb.mass_balance,md.mesh.numberoflayers) 
 		
 		#results
-		if not np.isnan(md.initialization.vx).all(): md.initialization.vx=DepthAverage(md,md.initialization.vx)
-		if not np.isnan(md.initialization.vy).all(): md.initialization.vy=DepthAverage(md,md.initialization.vy)
-		if not np.isnan(md.initialization.vz).all(): md.initialization.vz=DepthAverage(md,md.initialization.vz)
-		if not np.isnan(md.initialization.vel).all(): md.initialization.vel=DepthAverage(md,md.initialization.vel)
-		if not np.isnan(md.initialization.temperature).all(): md.initialization.temperature=DepthAverage(md,md.initialization.temperature)
-                if not np.isnan(md.initialization.pressure).all(): md.initialization.pressure=project2d(md,md.initialization.pressure,1)
-                if not np.isnan(md.initialization.sediment_head).all(): md.initialization.sediment_head=project2d(md,md.initialization.sediment_head,1)
-                if not np.isnan(md.initialization.epl_head).all(): md.initialization.epl_head=project2d(md,md.initialization.epl_head,1)
-                if not np.isnan(md.initialization.epl_thickness).all(): md.initialization.epl_thickness=project2d(md,md.initialization.epl_thickness,1)
+		if not np.isnan(md.initialization.vx).all(): 
+			md.initialization.vx=DepthAverage(md,md.initialization.vx)
+		if not np.isnan(md.initialization.vy).all(): 
+			md.initialization.vy=DepthAverage(md,md.initialization.vy)
+		if not np.isnan(md.initialization.vz).all(): 
+			md.initialization.vz=DepthAverage(md,md.initialization.vz)
+		if not np.isnan(md.initialization.vel).all(): 
+			md.initialization.vel=DepthAverage(md,md.initialization.vel)
+		if not np.isnan(md.initialization.temperature).all(): 
+			md.initialization.temperature=DepthAverage(md,md.initialization.temperature)
+		if not np.isnan(md.initialization.pressure).all(): 
+			md.initialization.pressure=project2d(md,md.initialization.pressure,1)
+		if not np.isnan(md.initialization.sediment_head).all(): 
+			md.initialization.sediment_head=project2d(md,md.initialization.sediment_head,1)
+		if not np.isnan(md.initialization.epl_head).all(): 
+			md.initialization.epl_head=project2d(md,md.initialization.epl_head,1)
+		if not np.isnan(md.initialization.epl_thickness).all(): 
+			md.initialization.epl_thickness=project2d(md,md.initialization.epl_thickness,1)
 
 		#giaivins
-		if not np.isnan(md.gia.mantle_viscosity).all(): md.gia.mantle_viscosity=project2d(md,md.gia.mantle_viscosity,1) 
-		if not np.isnan(md.gia.lithosphere_thickness).all(): md.gia.lithosphere_thickness=project2d(md,md.gia.lithosphere_thickness,1) 
+		if not np.isnan(md.gia.mantle_viscosity).all(): 
+			md.gia.mantle_viscosity=project2d(md,md.gia.mantle_viscosity,1) 
+		if not np.isnan(md.gia.lithosphere_thickness).all(): 
+			md.gia.lithosphere_thickness=project2d(md,md.gia.lithosphere_thickness,1) 
 
 		#elementstype
@@ -712,13 +776,12 @@
 			md.flowequation.borderFS=project2d(md,md.flowequation.borderFS,1)
 
-
-                # Hydrologydc variables
-                if hasattr(md.hydrology,'hydrologydc'):
-                    md.hydrology.spcsediment_head=project2d(md,md.hydrology.spcsediment_head,1)
-                    md.hydrology.mask_eplactive_node=project2d(md,md.hydrology.mask_eplactive_node,1)
-                    md.hydrology.sediment_transmitivity=project2d(md,md.hydrology.sediment_transmitivity,1)
-                    md.hydrology.basal_moulin_input=project2d(md,md.hydrology.basal_moulin_input,1)
-                    if md.hydrology.isefficientlayer == 1:
-                        md.hydrology.spcepl_head=project2d(md,md.hydrology.spcepl_head,1)
+		# Hydrologydc variables
+		if hasattr(md.hydrology,'hydrologydc'):
+			md.hydrology.spcsediment_head=project2d(md,md.hydrology.spcsediment_head,1)
+			md.hydrology.mask_eplactive_node=project2d(md,md.hydrology.mask_eplactive_node,1)
+			md.hydrology.sediment_transmitivity=project2d(md,md.hydrology.sediment_transmitivity,1)
+			md.hydrology.basal_moulin_input=project2d(md,md.hydrology.basal_moulin_input,1)
+			if md.hydrology.isefficientlayer == 1:
+				md.hydrology.spcepl_head=project2d(md,md.hydrology.spcepl_head,1)
 
 		#boundary conditions
@@ -729,6 +792,7 @@
 		md.stressbalance.loadingforce=project2d(md,md.stressbalance.loadingforce,md.mesh.numberoflayers)
 		md.masstransport.spcthickness=project2d(md,md.masstransport.spcthickness,md.mesh.numberoflayers)
-		if not np.isnan(md.damage.spcdamage).all(): md.damage.spcdamage=project2d(md,md.damage.spcdamage,md.mesh.numberoflayers-1)
 		md.thermal.spctemperature=project2d(md,md.thermal.spctemperature,md.mesh.numberoflayers-1)
+		if not np.isnan(md.damage.spcdamage).all(): 
+			md.damage.spcdamage=project2d(md,md.damage.spcdamage,md.mesh.numberoflayers-1)
 
 		#materials
@@ -756,8 +820,24 @@
 		md.geometry.thickness=project2d(md,md.geometry.thickness,1)
 		md.geometry.base=project2d(md,md.geometry.base,1)
-                if isinstance(md.geometry.bed,np.ndarray):
-                    md.geometry.bed=project2d(md,md.geometry.bed,1)
+		if isinstance(md.geometry.bed,np.ndarray):
+			md.geometry.bed=project2d(md,md.geometry.bed,1)
 		md.mask.groundedice_levelset=project2d(md,md.mask.groundedice_levelset,1)
 		md.mask.ice_levelset=project2d(md,md.mask.ice_levelset,1)
+
+		#OutputDefinitions
+		if md.outputdefinition.definitions:
+			for solutionfield,field in md.outputdefinition.__dict__.iteritems():
+				if isinstance(field,list):
+					#get each definition
+					for i,fieldi in enumerate(field):
+						if fieldi:
+							fieldr=getattr(md.outputdefinition,solutionfield)[i]
+							#get subfields
+							for solutionsubfield,subfield in fieldi.__dict__.iteritems():
+								if   np.size(subfield)==md.mesh.numberofvertices:
+									setattr(fieldr,solutionsubfield,project2d(md,subfield,1))
+								elif np.size(subfield)==md.mesh.numberofelements:
+									setattr(fieldr,solutionsubfield,project2d(md,subfield,1))
+
 
 		#Initialize with the 2d mesh
@@ -768,12 +848,22 @@
 		mesh.numberofelements=md.mesh.numberofelements2d
 		mesh.elements=md.mesh.elements2d
-		if not np.isnan(md.mesh.vertexonboundary).all(): mesh.vertexonboundary=project2d(md,md.mesh.vertexonboundary,1)
-		if not np.isnan(md.mesh.elementconnectivity).all(): mesh.elementconnectivity=project2d(md,md.mesh.elementconnectivity,1)
+		if not np.isnan(md.mesh.vertexonboundary).all(): 
+			mesh.vertexonboundary=project2d(md,md.mesh.vertexonboundary,1)
+		if not np.isnan(md.mesh.elementconnectivity).all(): 
+			mesh.elementconnectivity=project2d(md,md.mesh.elementconnectivity,1)
 		if isinstance(md.mesh.lat,np.ndarray):
-			if md.mesh.lat.size==md.mesh.numberofvertices:  mesh.lat=project2d(md,md.mesh.lat,1) 
+			if md.mesh.lat.size==md.mesh.numberofvertices:  
+				mesh.lat=project2d(md,md.mesh.lat,1) 
 		if isinstance(md.mesh.long,np.ndarray):
-			if md.mesh.long.size==md.mesh.numberofvertices: mesh.long=project2d(md,md.mesh.long,1) 
+			if md.mesh.long.size==md.mesh.numberofvertices: 
+				md.mesh.long=project2d(md,md.mesh.long,1) 
 		mesh.epsg=md.mesh.epsg
+		if isinstance(md.mesh.scale_factor,np.ndarray):
+			if md.mesh.scale_factor.size==md.mesh.numberofvertices: 
+				md.mesh.scale_factor=project2d(md,md.mesh.scale_factor,1) 
 		md.mesh=mesh
+		md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices)[0]
+		md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity)[0]
+		md.mesh.segments=contourenvelope(md)
 
 		return md
Index: /issm/trunk/src/m/classes/numberedcostfunction.m
===================================================================
--- /issm/trunk/src/m/classes/numberedcostfunction.m	(revision 22758)
+++ /issm/trunk/src/m/classes/numberedcostfunction.m	(revision 22758)
@@ -0,0 +1,122 @@
+%M1QN3INVERSION class definition
+%
+%   Usage:
+%      numberedcostfunction=numberedcostfunction();
+
+classdef numberedcostfunction
+	properties (SetAccess=public) 
+		name								 = '';
+		definitionstring				 = '';
+		cost_functions              = NaN
+		cost_functions_coefficients = NaN
+		vx_obs                      = NaN
+		vy_obs                      = NaN
+		vz_obs                      = NaN
+		vel_obs                     = NaN
+		thickness_obs               = NaN
+		surface_obs                 = NaN
+	end
+	methods
+		function self = numberedcostfunction(varargin) % {{{
+			switch nargin
+				case 0
+					self=setdefaultparameters(self);
+				case 1
+					self=structtoobj(numberedcostfunction(),varargin{1});
+				otherwise
+					error('construtor not supported yet');
+			end
+		end % }}}
+		function self = extrude(self,md) % {{{
+			self.vx_obs=project3d(md,'vector',self.vx_obs,'type','node');
+			self.vy_obs=project3d(md,'vector',self.vy_obs,'type','node');
+			self.vel_obs=project3d(md,'vector',self.vel_obs,'type','node');
+			self.thickness_obs=project3d(md,'vector',self.thickness_obs,'type','node');
+			if numel(self.cost_functions_coefficients)>1,self.cost_functions_coefficients=project3d(md,'vector',self.cost_functions_coefficients,'type','node');end;
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
+
+			%several responses can be used:
+			self.cost_functions=101;
+			
+
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
+
+			num_costfunc=size(md.inversion.cost_functions,2);
+
+			md = checkfield(md,'fieldname','inversion.cost_functions','size',[1 num_costfunc],'values',supportedcostfunctions());
+			md = checkfield(md,'fieldname','inversion.cost_functions_coefficients','size',[md.mesh.numberofvertices num_costfunc],'>=',0);
+
+			if strcmp(solution,'BalancethicknessSolution')
+				md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1,'Inf',1);
+				md = checkfield(md,'fieldname','inversion.surface_obs','size',[md.mesh.numberofvertices 1],'NaN',1,'Inf',1);
+			elseif strcmp(solution,'BalancethicknessSoftSolution')
+				md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1,'Inf',1);
+			else
+				md = checkfield(md,'fieldname','inversion.vx_obs','size',[md.mesh.numberofvertices 1],'NaN',1,'Inf',1);
+				if ~strcmp(domaintype(md.mesh),'2Dvertical'),
+					md = checkfield(md,'fieldname','inversion.vy_obs','size',[md.mesh.numberofvertices 1],'NaN',1,'Inf',1);
+				end
+			end
+		end % }}}
+		function disp(self) % {{{
+			disp(sprintf('   numberedcostfunction parameters:'));
+			fielddisplay(self,'cost_functions','indicate the type of response for each optimization step');
+			fielddisplay(self,'cost_functions_coefficients','cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter');
+			fielddisplay(self,'vx_obs','observed velocity x component [m/yr]');
+			fielddisplay(self,'vy_obs','observed velocity y component [m/yr]');
+			fielddisplay(self,'vel_obs','observed velocity magnitude [m/yr]');
+			fielddisplay(self,'thickness_obs','observed thickness [m]');
+			fielddisplay(self,'surface_obs','observed surface elevation [m]');
+			disp('Available cost functions:');
+			disp('   101: SurfaceAbsVelMisfit');
+			disp('   102: SurfaceRelVelMisfit');
+			disp('   103: SurfaceLogVelMisfit');
+			disp('   104: SurfaceLogVxVyMisfit');
+			disp('   105: SurfaceAverageVelMisfit');
+			disp('   201: ThicknessAbsMisfit');
+			disp('   501: DragCoefficientAbsGradient');
+			disp('   502: RheologyBbarAbsGradient');
+			disp('   503: ThicknessAbsGradient');
+		end % }}}
+		function marshall(self,prefix,md,fid) % {{{
+
+			yts=md.constants.yts;
+
+			WriteData(fid,prefix,'data',self.name,'name','md.numberedcostfunction.name','format','String');
+			WriteData(fid,prefix,'data',self.definitionstring,'name','md.numberedcostfunction.definitionstring','format','String');
+
+			WriteData(fid,prefix,'data',self.cost_functions_coefficients,'name','md.numberedcostfunction.cost_functions_coefficients','format','DoubleMat','mattype',1);
+			WriteData(fid,prefix,'data',self.vx_obs,'name','md.numberedcostfunction.vx_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,prefix,'data',self.vy_obs,'name','md.numberedcostfunction.vy_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,prefix,'data',self.vz_obs,'name','md.numberedcostfunction.vz_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,prefix,'data',self.vel_obs,'name','md.numberedcostfunction.vel_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			if(numel(self.thickness_obs)==md.mesh.numberofelements),
+				mattype=2;
+			else
+				mattype=1;
+			end
+			WriteData(fid,prefix,'data',self.thickness_obs,'name','md.numberedcostfunction.thickness_obs','format','DoubleMat','mattype',mattype);
+			WriteData(fid,prefix,'data',self.surface_obs,'name','md.numberedcostfunction.surface_obs','format','DoubleMat','mattype',mattype);
+
+			%process cost functions
+			num_cost_functions=size(self.cost_functions,2);
+			data=marshallcostfunctions(self.cost_functions);
+			WriteData(fid,prefix,'data',data,'name','md.numberedcostfunction.cost_functions','format','StringArray');
+			WriteData(fid,prefix,'data',num_cost_functions,'name','md.numberedcostfunction.num_cost_functions','format','Integer');
+		end % }}}
+		function savemodeljs(self,fid,modelname) % {{{
+		
+			writejs2Darray(fid,[modelname '.inversion.cost_functions'],self.cost_functions);
+			writejs2Darray(fid,[modelname '.inversion.cost_functions_coefficients'],self.cost_functions_coefficients);
+			writejs1Darray(fid,[modelname '.inversion.vx_obs'],self.vx_obs);
+			writejs1Darray(fid,[modelname '.inversion.vy_obs'],self.vy_obs);
+			writejs1Darray(fid,[modelname '.inversion.vz_obs'],self.vz_obs);
+			writejs1Darray(fid,[modelname '.inversion.vel_obs'],self.vel_obs);
+			writejs1Darray(fid,[modelname '.inversion.thickness_obs'],self.thickness_obs);
+			writejs1Darray(fid,[modelname '.inversion.surface_obs'],self.surface_obs);
+
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/oldclasses/calvingdev.m
===================================================================
--- /issm/trunk/src/m/classes/oldclasses/calvingdev.m	(revision 22758)
+++ /issm/trunk/src/m/classes/oldclasses/calvingdev.m	(revision 22758)
@@ -0,0 +1,12 @@
+%CALVINGDEV class definition
+%
+%   Usage:
+%      calvingdev=calvingdev();
+
+classdef calvingdev
+	properties (SetAccess=public) 
+		stress_threshold_groundedice = 0.;
+		stress_threshold_floatingice = 0.;
+		meltingrate   = NaN;
+	end
+end
Index: /issm/trunk/src/m/classes/outputdefinition.m
===================================================================
--- /issm/trunk/src/m/classes/outputdefinition.m	(revision 22757)
+++ /issm/trunk/src/m/classes/outputdefinition.m	(revision 22758)
@@ -9,4 +9,9 @@
 	end
 	methods
+		function self = extrude(self,md) % {{{
+			for i=1:length(self.definitions)
+				self.definitions{i}=extrude(self.definitions{i},md);
+			end
+		end % }}}
 		function self = outputdefinition(varargin) % {{{
 			switch nargin
Index: /issm/trunk/src/m/classes/outputdefinition.py
===================================================================
--- /issm/trunk/src/m/classes/outputdefinition.py	(revision 22757)
+++ /issm/trunk/src/m/classes/outputdefinition.py	(revision 22758)
@@ -22,4 +22,10 @@
 		return string
 		#}}}
+	def extrude(self,md): # {{{
+		for definition in self.definitions:
+			definition.extrude(md);
+
+		return self
+	 #}}}
 	def setdefaultparameters(self): # {{{
 		return self
Index: /issm/trunk/src/m/classes/plumebasalforcings.py
===================================================================
--- /issm/trunk/src/m/classes/plumebasalforcings.py	(revision 22758)
+++ /issm/trunk/src/m/classes/plumebasalforcings.py	(revision 22758)
@@ -0,0 +1,126 @@
+from fielddisplay import fielddisplay
+from checkfield import checkfield
+from WriteData import WriteData
+from project3d import project3d
+
+class plumebasalforcings(object):
+	'''
+	PLUME BASAL FORCINGS class definition
+
+		Usage:
+			plumebasalforcings=plumebasalforcings()
+	'''
+
+	def __init__(self): # {{{
+		floatingice_melting_rate  = float('NaN')
+		groundedice_melting_rate  = float('NaN')
+		mantleconductivity        = float('NaN')
+		nusselt                   = float('NaN')
+		dtbg                      = float('NaN')
+		plumeradius               = float('NaN')
+		topplumedepth             = float('NaN')
+		bottomplumedepth          = float('NaN')
+		plumex                    = float('NaN')
+		plumey                    = float('NaN')
+		crustthickness            = float('NaN')
+		uppercrustthickness       = float('NaN')
+		uppercrustheat            = float('NaN')
+		lowercrustheat            = float('NaN')
+
+		self.setdefaultparameters()
+	#}}}
+
+	def __repr__(self): # {{{
+		print '   mantle plume basal melt parameterization:'
+
+		string="%s\n%s"%(string,fielddisplay(self,'groundedice_melting_rate','basal melting rate (positive if melting) [m/yr]'))
+		string="%s\n%s"%(string,fielddisplay(self,'floatingice_melting_rate','basal melting rate (positive if melting) [m/yr]'))
+		string="%s\n%s"%(string,fielddisplay(self,'mantleconductivity','mantle heat conductivity [W/m^3]'))
+		string="%s\n%s"%(string,fielddisplay(self,'nusselt','nusselt number, ratio of mantle to plume [1]'))
+		string="%s\n%s"%(string,fielddisplay(self,'dtbg','background temperature gradient [degree/m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'plumeradius','radius of the mantle plume [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'topplumedepth','depth of the mantle plume top below the crust [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'bottomplumedepth','depth of the mantle plume base below the crust [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'plumex','x coordinate of the center of the plume [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'plumey','y coordinate of the center of the plume [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'crustthickness','thickness of the crust [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'uppercrustthickness','thickness of the upper crust [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'uppercrustheat','volumic heat of the upper crust [w/m^3]'))
+		string="%s\n%s"%(string,fielddisplay(self,'lowercrustheat','volumic heat of the lowercrust [w/m^3]'))
+
+		return string
+	#}}}
+
+	def initialize(self,md): #{{{
+		if np.all(np.isnan(self.groundedice_melting_rate)):
+			self.groundedice_melting_rate=np.zeros((md.mesh.numberofvertices,))
+			print '      no basalforcings.groundedice_melting_rate specified: values set as zero'
+		if np.all(np.isnan(self.floatingice_melting_rate)):
+			self.floatingice_melting_rate=np.zeros((md.mesh.numberofvertices,))
+			print '      no basalforcings.floatingice_melting_rate specified: values set as zero'
+		return
+	#}}}
+
+	def extrude(self,md): # {{{
+		self.groundedice_melting_rate=project3d(md,'vector',self.groundedice_melting_rate,'type','node','layer',1);
+		self.floatingice_melting_rate=project3d(md,'vector',self.floatingice_melting_rate,'type','node','layer',1);
+		return self
+	#}}}
+
+	def setdefaultparameters(self): # {{{
+		#default values for melting parameterization
+		self.mantleconductivity     = 2.2
+		self.nusselt                = 300
+		self.dtbg                   = 11/1000.
+		self.plumeradius            = 100000
+		self.topplumedepth          = 10000
+		self.bottomplumedepth       = 1050000
+		self.crustthickness         = 30000
+		self.uppercrustthickness    = 14000
+		self.uppercrustheat         = 1.7*10**-6
+		self.lowercrustheat         = 0.4*10**-6
+		return self
+	#}}}
+
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		if 'MasstransportAnalysis' in analyses and not (solution == 'TransientSolution' and md.transient.ismasstransport==0):
+			md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'timeseries',1)
+			md = checkfield(md,'fieldname','basalforcings.floatingice_melting_rate','NaN',1,'timeseries',1)
+		if 'BalancethicknessAnalysis' in analyses:
+			md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'size',[md.mesh.numberofvertices])
+			md = checkfield(md,'fieldname','basalforcings.floatingice_melting_rate','NaN',1,'size',[md.mesh.numberofvertices])
+		if 'ThermalAnalysis' in analyses and not (solution == 'TransientSolution' and md.transient.isthermal==0):
+			md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'timeseries',1)
+			md = checkfield(md,'fieldname','basalforcings.floatingice_melting_rate','NaN',1,'timeseries',1)
+			md = checkfield(md,'fieldname','basalforcings.mantleconductivity','>=',0,'numel',1)
+			md = checkfield(md,'fieldname','basalforcings.nusselt','>',0,'numel',1)
+			md = checkfield(md,'fieldname','basalforcings.dtbg','>',0,'numel',1)
+			md = checkfield(md,'fieldname','basalforcings.topplumedepth','>',0,'numel',1)
+			md = checkfield(md,'fieldname','basalforcings.bottomplumedepth','>',0,'numel',1)
+			md = checkfield(md,'fieldname','basalforcings.plumex','numel',1)
+			md = checkfield(md,'fieldname','basalforcings.plumey','numel',1)
+			md = checkfield(md,'fieldname','basalforcings.crustthickness','>',0,'numel',1)
+			md = checkfield(md,'fieldname','basalforcings.uppercrustthickness','>',0,'numel',1)
+			md = checkfield(md,'fieldname','basalforcings.uppercrustheat','>',0,'numel',1)
+			md = checkfield(md,'fieldname','basalforcings.lowercrustheat','>',0,'numel',1)
+		return md
+	# }}}
+	def marshall(self,prefix,md,fid):    # {{{
+		yts=md.constants.yts
+
+		WriteData(fid,prefix,'name','md.basalforcings.model','data',4,'format','Integer')
+		WriteData(fid,prefix,'object',self,'fieldname','floatingice_melting_rate','format','DoubleMat','name','md.basalforcings.floatingice_melting_rate','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
+		WriteData(fid,prefix,'object',self,'fieldname','groundedice_melting_rate','format','DoubleMat','name','md.basalforcings.groundedice_melting_rate','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
+		WriteData(fid,prefix,'object',self,'fieldname','mantleconductivity','format','Double')
+		WriteData(fid,prefix,'object',self,'fieldname','nusselt','format','Double')
+		WriteData(fid,prefix,'object',self,'fieldname','dtbg','format','Double')
+		WriteData(fid,prefix,'object',self,'fieldname','plumeradius','format','Double')
+		WriteData(fid,prefix,'object',self,'fieldname','topplumedepth','format','Double')
+		WriteData(fid,prefix,'object',self,'fieldname','bottomplumedepth','format','Double')
+		WriteData(fid,prefix,'object',self,'fieldname','plumex','format','Double')
+		WriteData(fid,prefix,'object',self,'fieldname','plumey','format','Double')
+		WriteData(fid,prefix,'object',self,'fieldname','crustthickness','format','Double')
+		WriteData(fid,prefix,'object',self,'fieldname','uppercrustthickness','format','Double')
+		WriteData(fid,prefix,'object',self,'fieldname','uppercrustheat','format','Double')
+		WriteData(fid,prefix,'object',self,'fieldname','lowercrustheat','format','Double')
+	# }}}
Index: /issm/trunk/src/m/classes/qmu.js
===================================================================
--- /issm/trunk/src/m/classes/qmu.js	(revision 22757)
+++ /issm/trunk/src/m/classes/qmu.js	(revision 22758)
@@ -91,5 +91,5 @@
 	}// }}}
     this.extrude = function(md) {//{{{
-        this.partition=project3d(md,'vector',math.transpose(this.partition),'type','node');
+	if (!isNaN(this.partition)) this.partition=project3d(md,'vector',ArrayTranspose(this.partition),'type','node');
         return this;
     }//}}}
Index: /issm/trunk/src/m/classes/qmu.m
===================================================================
--- /issm/trunk/src/m/classes/qmu.m	(revision 22757)
+++ /issm/trunk/src/m/classes/qmu.m	(revision 22758)
@@ -65,6 +65,6 @@
 			end
 			if ~isempty(md.qmu.partition),
-				if numel(md.qmu.partition)~=md.mesh.numberofvertices,
-					md = checkmessage(md,['user supplied partition for qmu analysis should have size md.mesh.numberofvertices x 1 ']);
+				if numel(md.qmu.partition)~=md.mesh.numberofvertices & numel(md.qmu.partition)~=md.mesh.numberofelements,
+					md = checkmessage(md,['user supplied partition for qmu analysis should have size md.mesh.numberofvertices x 1 or md.mesh.numberofelements x 1']);
 				end
 				if min(md.qmu.partition)~=0,
Index: /issm/trunk/src/m/classes/qmu/@dakota_method/dakota_method.m
===================================================================
--- /issm/trunk/src/m/classes/qmu/@dakota_method/dakota_method.m	(revision 22757)
+++ /issm/trunk/src/m/classes/qmu/@dakota_method/dakota_method.m	(revision 22758)
@@ -106,4 +106,5 @@
                             'centered_parameter_study',...
                             'multidim_parameter_study',...
+									 'bayes_calibration',...
                             };
 
@@ -823,4 +824,26 @@
                                 dm.params.output=false;
                                 dm.params.partitions=[];
+                            case {'bayes_calibration'}
+                                dm.type     ='bayes';
+                                dm.variables={'continuous_design',...
+                                              'normal_uncertain',...
+                                              'uniform_uncertain',...
+                                              'continuous_state'};
+                                dm.lcspec   ={};
+                                dm.responses={'objective_function',...
+                                              'response_function',...
+															'calibration_function'};
+                                dm.ghspec   ={};
+                                dm.params.queso=false;
+										  dm.params.dream=false;
+										  dm.params.gpmsa=false;
+                                dm.params.samples=0;
+										  dm.params.seed=false;
+										  dm.params.output=false;
+										  dm.params.metropolis_hastings=false;
+										  dm.params.proposal_covariance=false;
+										  dm.params.diagonal=false;
+										  dm.params.values=[];
+
 
                             otherwise
Index: /issm/trunk/src/m/classes/qmu/@dakota_method/dmeth_params_write.m
===================================================================
--- /issm/trunk/src/m/classes/qmu/@dakota_method/dmeth_params_write.m	(revision 22757)
+++ /issm/trunk/src/m/classes/qmu/@dakota_method/dmeth_params_write.m	(revision 22758)
@@ -521,4 +521,25 @@
         end
 
+	case {'bayes'}
+		switch dm.method
+				case {'bayes_calibration'}
+               % if (dm.params.queso + ...
+                %    dm.params.dream + ...
+					%	 dm.params.gpmsa ~= 1)
+                %    error('''%s'' method must have one and only one bayes type. YOU SUCK',...
+                 %       dm.method);
+               % end
+                param_write(fid,sbeg,'queso','','\n',dm.params);
+                param_write(fid,sbeg,'dream','','\n',dm.params);
+                param_write(fid,sbeg,'gpmsa','','\n',dm.params);
+                param_write(fid,sbeg,'samples','        = ','\n',dm.params);
+                param_write(fid,sbeg,'seed','      = ','\n',dm.params);
+					 param_write(fid,sbeg,'output','    =','\n',dm.params);
+					 param_write(fid,sbeg,'metropolis_hastings','','\n',dm.params);
+					 param_write(fid,sbeg,'proposal_covariance','','\n',dm.params);
+					 param_write(fid,sbeg,'diagonal','','\n',dm.params);
+					 param_write(fid,sbeg,'values','     = ','\n',dm.params);
+		end
+
     otherwise
         error('Unrecognized method type: ''%s''.',dm.type);
Index: /issm/trunk/src/m/classes/qmu/calibration_function.m
===================================================================
--- /issm/trunk/src/m/classes/qmu/calibration_function.m	(revision 22758)
+++ /issm/trunk/src/m/classes/qmu/calibration_function.m	(revision 22758)
@@ -0,0 +1,125 @@
+%
+%  definition for the calibration_function class.
+%
+%  [cf]=calibration_function(varargin)
+%
+%  where the required varargin are:
+%    descriptor    (char, description, '')
+%  and the optional varargin and defaults are:
+%    scale_type    (char, scaling type, 'none')
+%    scale         (double, scaling factor, 1.)
+%    weight        (double, weighting factor, 1.)
+%
+%  note that zero arguments constructs a default instance; one
+%  argument of the class copies the instance; and one or more
+%  arguments constructs a new instance from the arguments.
+%
+classdef calibration_function
+    properties
+        descriptor='';
+    end
+
+    methods
+        function [cf]=calibration_function(varargin)
+
+            switch nargin
+
+%  create a default object
+
+                case 0
+
+%  copy the object or create the object from the input
+
+                otherwise
+                    if  (nargin == 1) && isa(varargin{1},'calibration_function')
+                        cf=varargin{1};
+							else
+								asizec=num2cell(array_size(varargin{1:min(nargin,4)}));
+								cf(asizec{:})=calibration_function;
+								clear asizec
+
+								if ischar(varargin{1})
+									varargin{1}=cellstr(varargin{1});
+								end
+								for i=1:numel(cf)
+									if (numel(varargin{1}) > 1)
+										cf(i).descriptor=varargin{1}{i};
+									else
+										cf(i).descriptor=[char(varargin{1}) string_dim(cf,i,'vector')];
+									end
+								end
+                    end
+            end
+
+        end
+
+        function []=disp(cf)
+
+%  display the object
+
+            disp(sprintf('\n'));
+            for i=1:numel(cf)
+                disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+                    class(cf),inputname(1),string_dim(cf,i)));
+                disp(sprintf('    descriptor: ''%s'''  ,cf(i).descriptor));
+            end
+
+        end
+
+        function [desc]  =prop_desc(cf,dstr)
+            desc=cell(1,numel(cf));
+            for i=1:numel(cf)
+                if ~isempty(cf(i).descriptor)
+                    desc(i)=cellstr(cf(i).descriptor);
+                elseif ~isempty(inputname(1))
+                    desc(i)=cellstr([inputname(1) string_dim(cf,i,'vector')]);
+                elseif exist('dstr','var')
+                    desc(i)=cellstr([dstr         string_dim(cf,i,'vector')]);
+                else
+                    desc(i)=cellstr(['cf'         string_dim(cf,i,'vector')]);
+                end
+            end
+            desc=allempty(desc);
+			end
+			function [stype] =prop_stype(cf)
+				stype={};
+			end
+			function [weight] =prop_weight(cf)
+				weight=[];
+			end
+			function [lower] =prop_lower(cf)
+				lower=[];
+			end
+			function [upper] =prop_upper(cf)
+				upper=[];
+			end
+			function [target] =prop_target(cf)
+				target=[];
+			end
+			function [scale] =prop_scale(cf)
+				scale=[];
+			end
+
+
+
+
+
+
+
+    end
+    methods (Static)
+        function [rdesc]=dakota_write(fidi,dresp,rdesc)
+
+%  collect only the responses of the appropriate class
+
+            cf=struc_class(dresp,'calibration_function');
+
+%  write responses
+
+            [rdesc]=rlist_write(fidi,'calibration_terms','calibration_function',cf,rdesc);
+        end
+
+        function []=dakota_rlev_write(fidi,dresp,params)
+        end
+    end
+end
Index: /issm/trunk/src/m/classes/qmu/continuous_design.m
===================================================================
--- /issm/trunk/src/m/classes/qmu/continuous_design.m	(revision 22757)
+++ /issm/trunk/src/m/classes/qmu/continuous_design.m	(revision 22758)
@@ -31,197 +31,197 @@
 %
 classdef continuous_design
-    properties
-        descriptor='';
-        initpt    = 0.;
-        lower     =-Inf;
-        upper     = Inf;
-        scale_type='none';
-        scale     = 1.;
-    end
-
-    methods
-        function [cdv]=continuous_design(varargin)
-
-            switch nargin
-
-%  create a default object
-
-                case 0
-
-%  copy the object
-
-                case 1
-                    if isa(varargin{1},'continuous_design')
-                        cdv=varargin{1};
-                    else
-                        error('Object ''%s'' is a ''%s'' class object, not ''%s''.',...
-                            inputname(1),class(varargin{1}),'continuous_design');
-                    end
-
-%  create the object from the input
-
-                otherwise
-                    asizec=num2cell(array_size(varargin{1:min(nargin,6)}));
-                    cdv(asizec{:})=continuous_design;
-                    clear asizec
-
-                    if ischar(varargin{1})
-                        varargin{1}=cellstr(varargin{1});
-                    end
-                    for i=1:numel(cdv)
-                        if (numel(varargin{1}) > 1)
-                            cdv(i).descriptor=varargin{1}{i};
-                        else
-                            cdv(i).descriptor=[char(varargin{1}) string_dim(cdv,i,'vector')];
-                        end
-                    end
-
-                    if (nargin >= 2)
-                        for i=1:numel(cdv)
-                            if (numel(varargin{2}) > 1)
-                                cdv(i).initpt    =varargin{2}(i);
-                            else
-                                cdv(i).initpt    =varargin{2};
-                            end
-                        end
-                        if (nargin >= 3)
-                            for i=1:numel(cdv)
-                                if (numel(varargin{3}) > 1)
-                                    cdv(i).lower     =varargin{3}(i);
-                                else
-                                    cdv(i).lower     =varargin{3};
-                                end
-                            end
-                            if (nargin >= 4)
-                                for i=1:numel(cdv)
-                                    if (numel(varargin{4}) > 1)
-                                        cdv(i).upper     =varargin{4}(i);
-                                    else
-                                        cdv(i).upper     =varargin{4};
-                                    end
-                                end
-                                if (nargin >= 5)
-                                    if ischar(varargin{5})
-                                        varargin{5}=cellstr(varargin{5});
-                                    end
-                                    for i=1:numel(cdv)
-                                        if (numel(varargin{5}) > 1)
-                                            cdv(i).scale_type=varargin{5}{i};
-                                        else
-                                            cdv(i).scale_type=char(varargin{5});
-                                        end
-                                    end
-                                    if (nargin >= 6)
-                                        for i=1:numel(cdv)
-                                            if (numel(varargin{6}) > 1)
-                                                cdv(i).scale     =varargin{6}(i);
-                                            else
-                                                cdv(i).scale     =varargin{6};
-                                            end
-                                        end
-                                        if (nargin > 6)
-                                            warning('continuous_design:extra_arg',...
-                                                'Extra arguments for object of class ''%s''.',...
-                                                class(cdv));
-                                        end
-                                    end
-                                end
-                            end
-                        end
-                    end
-            end
-
-        end
-
-        function []=disp(cdv)
-
-%  display the object
-
-            disp(sprintf('\n'));
-            for i=1:numel(cdv)
-                disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
-                    class(cdv),inputname(1),string_dim(cdv,i)));
-                disp(sprintf('    descriptor: ''%s'''  ,cdv(i).descriptor));
-                disp(sprintf('        initpt: %g'      ,cdv(i).initpt));
-                disp(sprintf('         lower: %g'      ,cdv(i).lower));
-                disp(sprintf('         upper: %g'      ,cdv(i).upper));
-                disp(sprintf('    scale_type: ''%s'''  ,cdv(i).scale_type));
-                disp(sprintf('         scale: %g\n'    ,cdv(i).scale));
-            end
-
-        end
-
-        function [desc]  =prop_desc(cdv,dstr)
-            desc=cell(1,numel(cdv));
-            for i=1:numel(cdv)
-                if ~isempty(cdv(i).descriptor)
-                    desc(i)=cellstr(cdv(i).descriptor);
-                elseif ~isempty(inputname(1))
-                    desc(i)=cellstr([inputname(1) string_dim(cdv,i,'vector')]);
-                elseif exist('dstr','var')
-                    desc(i)=cellstr([dstr         string_dim(cdv,i,'vector')]);
-                else
-                    desc(i)=cellstr(['cdv'        string_dim(cdv,i,'vector')]);
-                end
-            end
-            desc=allempty(desc);
-        end
-        function [initpt]=prop_initpt(cdv)
-            initpt=zeros(1,numel(cdv));
-            for i=1:numel(cdv)
-                initpt(i)=cdv(i).initpt;
-            end
-            initpt=allequal(initpt,0.);
-        end
-        function [lower] =prop_lower(cdv)
-            lower=zeros(1,numel(cdv));
-            for i=1:numel(cdv)
-                lower(i)=cdv(i).lower;
-            end
-            lower=allequal(lower,-Inf);
-        end
-        function [upper] =prop_upper(cdv)
-            upper=zeros(1,numel(cdv));
-            for i=1:numel(cdv)
-                upper(i)=cdv(i).upper;
-            end
-            upper=allequal(upper, Inf);
-        end
-        function [mean]  =prop_mean(cdv)
-            mean=[];
-        end
-        function [stddev]=prop_stddev(cdv)
-            stddev=[];
-        end
-        function [initst]=prop_initst(cdv)
-            initst=[];
-        end
-        function [stype] =prop_stype(cdv)
-            stype=cell(1,numel(cdv));
-            for i=1:numel(cdv)
-                stype(i)=cellstr(cdv(i).scale_type);
-            end
-            stype=allequal(stype,'none');
-        end
-        function [scale] =prop_scale(cdv)
-            scale=zeros(1,numel(cdv));
-            for i=1:numel(cdv)
-                scale(i)=cdv(i).scale;
-            end
-            scale=allequal(scale,1.);
-        end
-    end
-
-    methods (Static)
-        function []=dakota_write(fidi,dvar)
-
-%  collect only the variables of the appropriate class
-
-            cdv=struc_class(dvar,'continuous_design');
-
-%  write variables
-
-            vlist_write(fidi,'continuous_design','cdv',cdv);
-        end
-    end
+	properties
+		descriptor='';
+		initpt    = 0.;
+		lower     =-Inf;
+		upper     = Inf;
+		scale_type='none';
+		scale     = 1.;
+	end
+
+	methods
+		function [cdv]=continuous_design(varargin)
+
+			switch nargin
+
+				%  create a default object
+
+				case 0
+
+					%  copy the object
+
+				case 1
+					if isa(varargin{1},'continuous_design')
+						cdv=varargin{1};
+					else
+						error('Object ''%s'' is a ''%s'' class object, not ''%s''.',...
+							inputname(1),class(varargin{1}),'continuous_design');
+					end
+
+					%  create the object from the input
+
+				otherwise
+					asizec=num2cell(array_size(varargin{1:min(nargin,6)}));
+					cdv(asizec{:})=continuous_design;
+					clear asizec
+
+					if ischar(varargin{1})
+						varargin{1}=cellstr(varargin{1});
+					end
+					for i=1:numel(cdv)
+						if (numel(varargin{1}) > 1)
+							cdv(i).descriptor=varargin{1}{i};
+						else
+							cdv(i).descriptor=[char(varargin{1}) string_dim(cdv,i,'vector')];
+						end
+					end
+
+					if (nargin >= 2)
+						for i=1:numel(cdv)
+							if (numel(varargin{2}) > 1)
+								cdv(i).initpt    =varargin{2}(i);
+							else
+								cdv(i).initpt    =varargin{2};
+							end
+						end
+						if (nargin >= 3)
+							for i=1:numel(cdv)
+								if (numel(varargin{3}) > 1)
+									cdv(i).lower     =varargin{3}(i);
+								else
+									cdv(i).lower     =varargin{3};
+								end
+							end
+							if (nargin >= 4)
+								for i=1:numel(cdv)
+									if (numel(varargin{4}) > 1)
+										cdv(i).upper     =varargin{4}(i);
+									else
+										cdv(i).upper     =varargin{4};
+									end
+								end
+								if (nargin >= 5)
+									if ischar(varargin{5})
+										varargin{5}=cellstr(varargin{5});
+									end
+									for i=1:numel(cdv)
+										if (numel(varargin{5}) > 1)
+											cdv(i).scale_type=varargin{5}{i};
+										else
+											cdv(i).scale_type=char(varargin{5});
+										end
+									end
+									if (nargin >= 6)
+										for i=1:numel(cdv)
+											if (numel(varargin{6}) > 1)
+												cdv(i).scale     =varargin{6}(i);
+											else
+												cdv(i).scale     =varargin{6};
+											end
+										end
+										if (nargin > 6)
+											warning('continuous_design:extra_arg',...
+												'Extra arguments for object of class ''%s''.',...
+												class(cdv));
+										end
+									end
+								end
+							end
+						end
+					end
+			end
+
+		end
+
+		function []=disp(cdv)
+
+			%  display the object
+
+			disp(sprintf('\n'));
+			for i=1:numel(cdv)
+				disp(sprintf('class ''%s'' object ''%s%s'' = \n',...
+					class(cdv),inputname(1),string_dim(cdv,i)));
+				disp(sprintf('    descriptor: ''%s'''  ,cdv(i).descriptor));
+				disp(sprintf('        initpt: %g'      ,cdv(i).initpt));
+				disp(sprintf('         lower: %g'      ,cdv(i).lower));
+				disp(sprintf('         upper: %g'      ,cdv(i).upper));
+				disp(sprintf('    scale_type: ''%s'''  ,cdv(i).scale_type));
+				disp(sprintf('         scale: %g\n'    ,cdv(i).scale));
+			end
+
+		end
+
+		function [desc]  =prop_desc(cdv,dstr)
+			desc=cell(1,numel(cdv));
+			for i=1:numel(cdv)
+				if ~isempty(cdv(i).descriptor)
+					desc(i)=cellstr(cdv(i).descriptor);
+				elseif ~isempty(inputname(1))
+					desc(i)=cellstr([inputname(1) string_dim(cdv,i,'vector')]);
+				elseif exist('dstr','var')
+					desc(i)=cellstr([dstr         string_dim(cdv,i,'vector')]);
+				else
+					desc(i)=cellstr(['cdv'        string_dim(cdv,i,'vector')]);
+				end
+			end
+			desc=allempty(desc);
+		end
+		function [initpt]=prop_initpt(cdv)
+			initpt=zeros(1,numel(cdv));
+			for i=1:numel(cdv)
+				initpt(i)=cdv(i).initpt;
+			end
+			initpt=allequal(initpt,0.);
+		end
+		function [lower] =prop_lower(cdv)
+			lower=zeros(1,numel(cdv));
+			for i=1:numel(cdv)
+				lower(i)=cdv(i).lower;
+			end
+			lower=allequal(lower,-Inf);
+		end
+		function [upper] =prop_upper(cdv)
+			upper=zeros(1,numel(cdv));
+			for i=1:numel(cdv)
+				upper(i)=cdv(i).upper;
+			end
+			upper=allequal(upper, Inf);
+		end
+		function [mean]  =prop_mean(cdv)
+			mean=[];
+		end
+		function [stddev]=prop_stddev(cdv)
+			stddev=[];
+		end
+		function [initst]=prop_initst(cdv)
+			initst=[];
+		end
+		function [stype] =prop_stype(cdv)
+			stype=cell(1,numel(cdv));
+			for i=1:numel(cdv)
+				stype(i)=cellstr(cdv(i).scale_type);
+			end
+			stype=allequal(stype,'none');
+		end
+		function [scale] =prop_scale(cdv)
+			scale=zeros(1,numel(cdv));
+			for i=1:numel(cdv)
+				scale(i)=cdv(i).scale;
+			end
+			scale=allequal(scale,1.);
+		end
+	end
+
+	methods (Static)
+		function []=dakota_write(fidi,dvar)
+
+			%  collect only the variables of the appropriate class
+
+			cdv=struc_class(dvar,'continuous_design');
+
+			%  write variables
+
+			vlist_write(fidi,'continuous_design','cdv',cdv);
+		end
+	end
 end
Index: /issm/trunk/src/m/classes/regionaloutput.m
===================================================================
--- /issm/trunk/src/m/classes/regionaloutput.m	(revision 22758)
+++ /issm/trunk/src/m/classes/regionaloutput.m	(revision 22758)
@@ -0,0 +1,106 @@
+%REGIONALOUTPUT class definition
+%
+%   Usage:
+%      regionaloutput=regionaloutput();
+%      regionaloutput=regionaloutput('name','Volume1','definitionstring','Outputdefinition1','outputnamestring','IceVolume',...
+%                    'mask',mask);
+%      regionaloutput=regionaloutput('name','Volume1','definitionstring','Outputdefinition1','outputnamestring','IceVolume',...
+%                    'maskexpstring','Exp/Mask.exp','model',md)
+% 
+%   where mask is a vectorial field of size md.mesh.numberofvertices,1 : where vertices with values > 0 are to be included in the calculated region.
+%   Alternatively, the user can pass in an Argus file and model object instead of a mask, and mask will be calculated for the user
+%
+%   See also: MISFIT, MASSCON, MASSCONAXPBY
+
+classdef regionaloutput
+	properties (SetAccess=public)
+		%regionaloutput
+		name              = '';
+		definitionstring  = ''; %string that identifies this output definition uniquely, from 'Outputdefinition[1-100]'
+		outputnamestring  = ''; %string that identifies the type of output you want, eg. IceVolume, TotalSmb, GroudedArea
+		mask              = NaN; %mask vectorial field which identifies the region of interest (value > 0 will be included)
+		maskexpstring     = '';
+	end
+	
+	methods
+		function self = extrude(self,md) % {{{
+			if ~isnan(self.mask)
+				self.mask=project3d(md,'vector',self.mask,'type','node');
+			end
+		end % }}}
+		function self = regionaloutput(varargin) % {{{
+			if nargin==0,
+				self=setdefaultparameters(self);
+			else
+				%use provided options to change fields
+				options=pairoptions(varargin{:});
+
+				%get name
+				self.name=getfieldvalue(options,'name','');
+				if nargin==8
+					self.mask=getfieldvalue(options,'mask',NaN);
+					if isnan(self.mask)
+						error('regionaloutput error message: ''mask'' field or ''maskexpstring'' and ''model'' fields should be defined!');
+					end
+				elseif nargin==10
+					modelname=getfieldvalue(options,'model');
+					self.maskexpstring=getfieldvalue(options,'maskexpstring');
+					self=setmaskfromexp(self,modelname);
+				else
+					error('regionaloutput error message: ''mask'' field or ''maskexpstring'' and ''model'' fields should be defined!');
+				end
+		
+				self.definitionstring=getfieldvalue(options,'definitionstring');
+				self.outputnamestring=getfieldvalue(options,'outputnamestring');
+
+			end
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
+		end % }}}
+		function self = setmaskfromexp(self,md) % {{{
+
+			if length(self.maskexpstring)>0
+				self.mask=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,self.maskexpstring,'node',1);
+			end
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
+
+			if ~ischar(self.name),
+				error('regionaloutput error message: ''name'' field should be a string!');
+			end
+			if ~ischar(self.outputnamestring),
+				error('regionaloutput error message: ''outputnamestring'' field should be a string!');
+			end
+			
+			OutputdefinitionStringArray={};
+			for i=1:100
+				OutputdefinitionStringArray{i}=strcat('Outputdefinition',num2str(i));
+			end
+			self=setmaskfromexp(self,md);
+
+			md = checkfield(md,'fieldname','self.definitionstring','field',self.definitionstring,'values',OutputdefinitionStringArray);
+			md = checkfield(md,'fieldname','self.mask','field',self.mask,'size',[md.mesh.numberofvertices 1],'NaN',1,'Inf',1);
+
+		end % }}}
+		function md = disp(self) % {{{
+		
+			disp(sprintf('   Regionaloutput:\n'));
+
+			fielddisplay(self,'name','identifier for this regional response');
+			fielddisplay(self,'definitionstring','string that identifies this output definition uniquely, from ''Outputdefinition[1-100]''');
+			fielddisplay(self,'outputnamestring','string that identifies the type of output you want, eg. IceVolume, TotalSmb, GroudedArea');
+			fielddisplay(self,'mask','mask vectorial field which identifies the region of interest (value > 0 will be included)');
+			fielddisplay(self,'maskexpstring','name of Argus file that can be passed in to define the regional mask');
+
+		end % }}}
+		function md = marshall(self,prefix,md,fid) % {{{
+
+			self=setmaskfromexp(self,md);
+			WriteData(fid,prefix,'data',self.name,'name','md.regionaloutput.name','format','String');
+			WriteData(fid,prefix,'data',self.definitionstring,'name','md.regionaloutput.definitionstring','format','String');
+			WriteData(fid,prefix,'data',self.outputnamestring,'name','md.regionaloutput.outputnamestring','format','String');
+			WriteData(fid,prefix,'data',self.mask,'name','md.regionaloutput.mask','format','DoubleMat','mattype',1);
+
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/regionaloutput.py
===================================================================
--- /issm/trunk/src/m/classes/regionaloutput.py	(revision 22758)
+++ /issm/trunk/src/m/classes/regionaloutput.py	(revision 22758)
@@ -0,0 +1,109 @@
+from project3d import project3d
+from fielddisplay import fielddisplay
+from pairoptions import pairoptions
+from checkfield import checkfield
+from WriteData import WriteData
+from MeshProfileIntersection import MeshProfileIntersection
+from ContourToMesh import ContourToMesh
+import numpy as np
+import os
+
+class regionaloutput(object):
+	"""
+	REGIONALOUTPUT class definition
+	
+	   Usage:
+	      regionaloutput=regionaloutput();
+	      regionaloutput=regionaloutput('name','Volume1','definitionstring','Outputdefinition1','outputnamestring','IceVolume','mask',mask);
+	      regionaloutput=regionaloutput('name','Volume1','definitionstring','Outputdefinition1','outputnamestring','IceVolume','maskexpstring','Exp/Mask.exp','model',md)
+	
+	   where mask is a vectorial field of size md.mesh.numberofvertices,1 : where vertices with values > 1 are to be included in the calculated region.
+	   Alternatively, the user can pass in an Argus file and model object instead of a mask, and mask will be calculated for the user
+	"""
+
+	def __init__(self,*args): # {{{
+
+		self.name              = ''
+		self.definitionstring  = ''
+		self.outputnamestring  = ''
+		self.mask              = float('NaN')
+		self.maskexpstring     = ''
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#use provided options to change fields
+		options=pairoptions(*args)
+
+		#OK get other fields
+		self=options.AssignObjectFields(self)
+
+		#get name
+		if options.getfieldvalue('model',0):
+			if options.getfieldvalue('maskexpstring',0):
+				modelname=options.getfieldvalue('model')
+				self.maskexpstring=options.getfieldvalue('maskexpstring')
+				self.setmaskfromexp(modelname)
+			
+		if (len(self.mask)<=1 & np.any(np.isnan(self.mask))):
+			error('regionaloutput error message: ''mask'' field or ''maskexpstring'' and ''model'' fields should be defined!');
+
+		#}}}
+	def __repr__(self): # {{{
+
+		string="   Regionaloutput:"
+		string="%s\n%s"%(string,fielddisplay(self,'name','identifier for this regional response'))
+		string="%s\n%s"%(string,fielddisplay(self,'definitionstring','string that identifies this output definition uniquely, from Outputdefinition[1-100]'))
+		string="%s\n%s"%(string,fielddisplay(self,'outputnamestring','string that identifies the type of output you want, eg. IceVolume, TotalSmb, GroudedArea'))
+		string="%s\n%s"%(string,fielddisplay(self,'mask','mask vectorial field which identifies the region of interest (value > 0 will be included)'))
+		string="%s\n%s"%(string,fielddisplay(self,'maskexpstring','name of Argus file that can be passed in to define the regional mask'))
+		return string
+		#}}}
+	def extrude(self,md): # {{{
+		self.mask=project3d(md,'vector',self.mask,'type','node')
+		return self
+	   #}}}
+	def setdefaultparameters(self): # {{{
+		return self
+	#}}}
+	def setmaskfromexp(self,md):    # {{{
+		if len(self.maskexpstring) > 0:
+			self.mask=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,self.maskexpstring,'node',1)
+			
+		return self
+	 # }}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		
+		if  not isinstance(self.name, basestring):
+			raise RuntimeError("regionaloutput error message: 'name' field should be a string!")
+			
+		if  not isinstance(self.outputnamestring, basestring):
+			raise RuntimeError("regionaloutput error message: 'outputnamestring' field should be a string!") 
+		
+		if len(self.maskexpstring) > 0:
+			if not os.path.isfile(self.maskexpstring):
+				raise RuntimeError("regionaloutput error message: file name for mask exp does not point to a legitimate file on disk!")
+			else:
+				self.setmaskfromexp(md)
+
+		OutputdefinitionStringArray=[]
+		for i in range(1,100):
+			x='Outputdefinition'+str(i)
+			OutputdefinitionStringArray.append(x)
+
+		md = checkfield(md,'field',self.definitionstring,'values',OutputdefinitionStringArray)
+		md = checkfield(md,'field',self.mask,'size',[md.mesh.numberofvertices],'NaN',1,'Inf',1)
+		return md
+	# }}}
+	def marshall(self,prefix,md,fid):    # {{{
+
+		#before marshalling, make sure mask is set: 
+		self.setmaskfromexp(md)
+
+		#ok, marshall strings and mask: 
+		WriteData(fid,prefix,'data',self.name,'name','md.regionaloutput.name','format','String')
+		WriteData(fid,prefix,'data',self.definitionstring,'name','md.regionaloutput.definitionstring','format','String')
+		WriteData(fid,prefix,'data',self.outputnamestring,'name','md.regionaloutput.outputnamestring','format','String');
+		WriteData(fid,prefix,'data',self.mask,'name','md.regionaloutput.mask','format','DoubleMat','mattype',1);
+
+	# }}}
Index: sm/trunk/src/m/classes/settings.js
===================================================================
--- /issm/trunk/src/m/classes/settings.js	(revision 22757)
+++ 	(revision )
@@ -1,94 +1,0 @@
-//SETTINGS class definition
-//
-//   Usage:
-//      settings=new settings();
-
-function settings (){
-	//methods
-	this.setdefaultparameters = function(){// {{{
-		//are we short in memory ? (0 faster but requires more memory)
-		this.lowmem=0;
-
-		//i/o:
-		this.io_gather=1;
-
-		//results frequency by default every step
-		this.output_frequency=1;
-
-		//checkpoints frequency, by default never: 
-		this.recording_frequency=0;
-
-		//this option can be activated to load automatically the results
-		//onto the model after a parallel run by waiting for the lock file
-		//N minutes that is generated once the solution has converged
-		//0 to deactivate
-		this.waitonlock=Infinity;
-
-		//upload options: 
-		upload_port         = 0;
-		
-		//throw an error if solver residue exceeds this value
-		self.solver_residue_threshold=1e-6;
-
-	}// }}}
-	this.disp= function(){// {{{
-		console.log(sprintf('   settings class echo:'));
-		
-		fielddisplay(this,'results_on_nodes','results are output for all the nodes of each element');
-		fielddisplay(this,'io_gather','I/O gathering strategy for result outputs (default 1)');
-		fielddisplay(this,'lowmem','is the memory limited ? (0 or 1)');
-		fielddisplay(this,'output_frequency','frequency at which results are saved in all solutions with multiple time_steps');
-		fielddisplay(this,'recording_frequency','frequency at which the runs are being recorded, allowing for a restart');
-		fielddisplay(this,'waitonlock','maximum number of minutes to wait for batch results (NaN to deactivate)');
-		fielddisplay(this,'upload_server','server hostname where model should be uploaded');
-		fielddisplay(this,'upload_path','path on server where model should be uploaded');
-		fielddisplay(this,'upload_login','server login');
-		fielddisplay(this,'upload_port','port login (default is 0)');
-		fielddisplay(this,'upload_filename','unique id generated when uploading the file to server');
-		fielddisplay(this,'solver_residue_threshold','throw an error if solver residue exceeds this value');
-
-
-	}// }}}
-	this.classname= function(){// {{{
-		return "settings";
-
-	}// }}}
-		this.checkconsistency = function(md,solution,analyses) { // {{{
-
-			checkfield(md,'fieldname','settings.results_on_nodes','numel',[1],'values',[0, 1]);
-			checkfield(md,'fieldname','settings.io_gather','numel',[1],'values',[0, 1]);
-			checkfield(md,'fieldname','settings.lowmem','numel',[1],'values',[0, 1]);
-			checkfield(md,'fieldname','settings.output_frequency','numel',[1],'>=',1);
-			checkfield(md,'fieldname','settings.recording_frequency','numel',[1],'>=',0);
-			checkfield(md,'fieldname','settings.waitonlock','numel',[1]);
-			checkfield(md,'fieldname','settings.solver_residue_threshold','numel',[1],'>',0);
-		} // }}}
-		this.marshall=function(md,prefix,fid) { //{{{
-			WriteData(fid,prefix,'object',this,'fieldname','results_on_nodes','format','Boolean');
-			WriteData(fid,prefix,'object',this,'fieldname','io_gather','format','Boolean');
-			WriteData(fid,prefix,'object',this,'fieldname','lowmem','format','Boolean');
-			WriteData(fid,prefix,'object',this,'fieldname','output_frequency','format','Integer');
-			WriteData(fid,prefix,'object',this,'fieldname','recording_frequency','format','Integer');
-			WriteData(fid,prefix,'object',this,'fieldname','solver_residue_threshold','format','Double');
-			if (this.waitonlock>0) WriteData(fid,prefix,'name','md.settings.waitonlock','data',true,'format','Boolean');
-			else WriteData(fid,prefix,'name','md.settings.waitonlock','data',false,'format','Boolean');
-		}//}}}
-		this.fix=function() { //{{{
-		}//}}}
-	//properties 
-	// {{{
-	this.results_on_nodes    = 0;
-	this.io_gather           = 0;
-	this.lowmem              = 0;
-	this.output_frequency    = 0;
-	this.recording_frequency   = 0;
-	this.waitonlock          = 0;
-	this.upload_server       = '';
-	this.upload_path         = '';
-	this.upload_login        = '';
-	this.upload_port         = 0;
-	this.upload_filename     = '';
-	this.solver_residue_threshold = 0;
-	this.setdefaultparameters();
-	//}}}
-}
Index: sm/trunk/src/m/classes/settings.m
===================================================================
--- /issm/trunk/src/m/classes/settings.m	(revision 22757)
+++ 	(revision )
@@ -1,110 +1,0 @@
-%SETTINGS class definition
-%
-%   Usage:
-%      settings=settings();
-
-classdef settings
-	properties (SetAccess=public) 
-		results_on_nodes    = 0;
-		io_gather           = 0;
-		lowmem              = 0;
-		output_frequency    = 0;
-		recording_frequency   = 0;
-		waitonlock          = 0;
-		upload_server       = '';
-		upload_path         = '';
-		upload_login        = '';
-		upload_port         = 0;
-		upload_filename     = '';
-		solver_residue_threshold = 0;
-	end
-	methods
-		function self = settings(varargin) % {{{
-			switch nargin
-				case 0
-					self=setdefaultparameters(self);
-				otherwise
-					error('constructor not supported');
-			end
-		end % }}}
-		function self = setdefaultparameters(self) % {{{
-
-			%are we short in memory ? (0 faster but requires more memory)
-			self.lowmem=0;
-
-			%i/o:
-			self.io_gather=1;
-
-			%results frequency by default every step
-			self.output_frequency=1;
-
-			%checkpoints frequency, by default never: 
-			self.recording_frequency=0;
-
-			%this option can be activated to load automatically the results
-			%onto the model after a parallel run by waiting for the lock file
-			%N minutes that is generated once the solution has converged
-			%0 to deactivate
-			self.waitonlock=Inf;
-
-			%upload options: 
-			self.upload_port         = 0;
-
-			%throw an error if solver residue exceeds this value
-			self.solver_residue_threshold = 1e-6;
-
-		end % }}}
-		function md = checkconsistency(self,md,solution,analyses) % {{{
-
-			md = checkfield(md,'fieldname','settings.results_on_nodes','numel',[1],'values',[0 1]);
-			md = checkfield(md,'fieldname','settings.io_gather','numel',[1],'values',[0 1]);
-			md = checkfield(md,'fieldname','settings.lowmem','numel',[1],'values',[0 1]);
-			md = checkfield(md,'fieldname','settings.output_frequency','numel',[1],'>=',1);
-			md = checkfield(md,'fieldname','settings.recording_frequency','numel',[1],'>=',0);
-			md = checkfield(md,'fieldname','settings.waitonlock','numel',[1]);
-			md = checkfield(md,'fieldname','settings.solver_residue_threshold','numel',[1],'>',0);
-
-		end % }}}
-		function disp(self) % {{{
-			disp(sprintf('   general settings parameters:'));
-
-			fielddisplay(self,'results_on_nodes','results are output for all the nodes of each element');
-			fielddisplay(self,'io_gather','I/O gathering strategy for result outputs (default 1)');
-			fielddisplay(self,'lowmem','is the memory limited ? (0 or 1)');
-			fielddisplay(self,'output_frequency','frequency at which results are saved in all solutions with multiple time_steps');
-			fielddisplay(self,'recording_frequency','frequency at which the runs are being recorded, allowing for a restart');
-			fielddisplay(self,'waitonlock','maximum number of minutes to wait for batch results (NaN to deactivate)');
-			fielddisplay(self,'upload_server','server hostname where model should be uploaded');
-			fielddisplay(self,'upload_path','path on server where model should be uploaded');
-			fielddisplay(self,'upload_login','server login');
-			fielddisplay(self,'upload_port','port login (default is 0)');
-			fielddisplay(self,'upload_filename','unique id generated when uploading the file to server');
-			fielddisplay(self,'solver_residue_threshold','throw an error if solver residue exceeds this value (NaN to deactivate)');
-
-		end % }}}
-		function marshall(self,prefix,md,fid) % {{{
-			WriteData(fid,prefix,'object',self,'fieldname','results_on_nodes','format','Boolean');
-			WriteData(fid,prefix,'object',self,'fieldname','io_gather','format','Boolean');
-			WriteData(fid,prefix,'object',self,'fieldname','lowmem','format','Boolean');
-			WriteData(fid,prefix,'object',self,'fieldname','output_frequency','format','Integer');
-			WriteData(fid,prefix,'object',self,'fieldname','recording_frequency','format','Integer');
-			WriteData(fid,prefix,'object',self,'fieldname','waitonlock','data',self.waitonlock>0,'format','Boolean');
-			WriteData(fid,prefix,'object',self,'fieldname','solver_residue_threshold','format','Double');
-		end % }}}
-		function savemodeljs(self,fid,modelname) % {{{
-		
-			writejsdouble(fid,[modelname '.settings.results_on_nodes'],self.results_on_nodes);
-			writejsdouble(fid,[modelname '.settings.io_gather'],self.io_gather);
-			writejsdouble(fid,[modelname '.settings.lowmem'],self.lowmem);
-			writejsdouble(fid,[modelname '.settings.output_frequency'],self.output_frequency);
-			writejsdouble(fid,[modelname '.settings.recording_frequency'],self.recording_frequency);
-			writejsdouble(fid,[modelname '.settings.waitonlock'],self.waitonlock);
-			writejsstring(fid,[modelname '.settings.upload_server'],self.upload_server);
-			writejsstring(fid,[modelname '.settings.upload_path'],self.upload_path);
-			writejsstring(fid,[modelname '.settings.upload_login'],self.upload_login);
-			writejsdouble(fid,[modelname '.settings.upload_port'],self.upload_port);
-			writejsstring(fid,[modelname '.settings.upload_filename'],self.upload_filename);
-			writejsstring(fid,[modelname '.settings.solver_residue_threshold'],self.solver_residue_threshold);
-		end % }}}
-	end
-end
Index: sm/trunk/src/m/classes/settings.py
===================================================================
--- /issm/trunk/src/m/classes/settings.py	(revision 22757)
+++ 	(revision )
@@ -1,86 +1,0 @@
-from fielddisplay import fielddisplay
-from checkfield import checkfield
-from WriteData import WriteData
-
-class settings(object):
-	"""
-	SETTINGS class definition
-
-	   Usage:
-	      settings=settings();
-	"""
-
-	def __init__(self): # {{{
-		self.results_on_nodes    = 0
-		self.io_gather           = 0
-		self.lowmem              = 0
-		self.output_frequency    = 0
-		self.recording_frequency = 0
-		self.waitonlock          = 0
-		self.solver_residue_threshold = 0
-
-		#set defaults
-		self.setdefaultparameters()
-
-		#}}}
-	def __repr__(self): # {{{
-		string="   general settings parameters:"
-
-		string="%s\n%s"%(string,fielddisplay(self,"results_on_nodes","results are output for all the nodes of each element"))
-		string="%s\n%s"%(string,fielddisplay(self,"io_gather","I/O gathering strategy for result outputs (default 1)"))
-		string="%s\n%s"%(string,fielddisplay(self,"lowmem","is the memory limited ? (0 or 1)"))
-		string="%s\n%s"%(string,fielddisplay(self,"output_frequency","frequency at which results are saved in all solutions with multiple time_steps"))
-		string="%s\n%s"%(string,fielddisplay(self,"recording_frequency","frequency at which the runs are being recorded, allowing for a restart"))
-		string="%s\n%s"%(string,fielddisplay(self,"waitonlock","maximum number of minutes to wait for batch results, or return 0"))
-		string="%s\n%s"%(string,fielddisplay(self,"solver_residue_threshold","throw an error if solver residue exceeds this value (NaN to deactivate)"))
-		return string
-		#}}}
-	def setdefaultparameters(self): # {{{
-		
-		#are we short in memory ? (0 faster but requires more memory)
-		self.lowmem=0
-
-		#i/o:
-		self.io_gather=1
-
-		#results frequency by default every step
-		self.output_frequency=1
-
-		#checkpoints frequency, by default never: 
-		self.recording_frequency=0
-
-
-		#this option can be activated to load automatically the results
-		#onto the model after a parallel run by waiting for the lock file
-		#N minutes that is generated once the solution has converged
-		#0 to deactivate
-		self.waitonlock=2**31-1
-
-      #throw an error if solver residue exceeds this value
-		self.solver_residue_threshold=1e-6;
-
-		return self
-	#}}}
-	def checkconsistency(self,md,solution,analyses):    # {{{
-		md = checkfield(md,'fieldname','settings.results_on_nodes','numel',[1],'values',[0,1])
-		md = checkfield(md,'fieldname','settings.io_gather','numel',[1],'values',[0,1])
-		md = checkfield(md,'fieldname','settings.lowmem','numel',[1],'values',[0,1])
-		md = checkfield(md,'fieldname','settings.output_frequency','numel',[1],'>=',1)
-		md = checkfield(md,'fieldname','settings.recording_frequency','numel',[1],'>=',0)
-		md = checkfield(md,'fieldname','settings.waitonlock','numel',[1])
-		md = checkfield(md,'fieldname','settings.solver_residue_threshold','numel',[1],'>',0)
-
-		return md
-	# }}}
-	def marshall(self,prefix,md,fid):    # {{{
-		WriteData(fid,prefix,'object',self,'fieldname','results_on_nodes','format','Boolean')
-		WriteData(fid,prefix,'object',self,'fieldname','io_gather','format','Boolean')
-		WriteData(fid,prefix,'object',self,'fieldname','lowmem','format','Boolean')
-		WriteData(fid,prefix,'object',self,'fieldname','output_frequency','format','Integer')
-		WriteData(fid,prefix,'object',self,'fieldname','recording_frequency','format','Integer')
-		WriteData(fid,prefix,'object',self,'fieldname','solver_residue_threshold','format','Double')
-		if self.waitonlock>0:
-			WriteData(fid,prefix,'name','md.settings.waitonlock','data',True,'format','Boolean');
-		else:
-			WriteData(fid,prefix,'name','md.settings.waitonlock','data',False,'format','Boolean');
-	# }}}
Index: /issm/trunk/src/m/classes/slr.js
===================================================================
--- /issm/trunk/src/m/classes/slr.js	(revision 22757)
+++ /issm/trunk/src/m/classes/slr.js	(revision 22758)
@@ -9,9 +9,9 @@
 		
 		//Convergence criterion: absolute, relative and residual
-		this.reltol=NaN; //default
-		this.abstol=0.001; //1 mm of sea level rise
+		this.reltol=0.01; // 1 per cent 
+		this.abstol=NaN;  //default
 
 		//maximum of non-linear iterations.
-		this.maxiter=10;
+		this.maxiter=5;
 
 		//computational flags: 
@@ -37,4 +37,8 @@
 		//numerical discretization accuracy
 		this.degacc=.01;
+		
+		//steric: 
+		this.steric_rate=0;
+		
 		
 		//output default:
@@ -63,4 +67,5 @@
 			md = checkfield(md,'fieldname','slr.reltol','size',[1, 1]);
 			md = checkfield(md,'fieldname','slr.abstol','size',[1, 1]);
+			md = checkfield(md,'fieldname','slr.steric_rate','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices, 1]);
 			md = checkfield(md,'fieldname','slr.maxiter','size',[1, 1],'>=',1);
 			md = checkfield(md,'fieldname','slr.degacc','size',[1, 1],'>=',1e-10);
@@ -81,27 +86,28 @@
 		this.disp= function(){// {{{
 			
-		console.log(sprintf('   Sealevelrise solution parameters:'));
+			console.log(sprintf('   Sealevelrise solution parameters:'));
 
-		fielddisplay(this,'deltathickness','thickness change (main loading of the slr solution core [m]');
-		fielddisplay(this,'sealevel','current sea level (prior to computation) [m]');
-		fielddisplay(this,'reltol','sea level rise relative convergence criterion, (default, NaN: not applied)');
-		fielddisplay(this,'abstol','sea level rise absolute convergence criterion, NaN: not applied');
-		fielddisplay(this,'maxiter','maximum number of nonlinear iterations');
-		fielddisplay(this,'love_h','load Love number for radial displacement');
-		fielddisplay(this,'love_k','load Love number for gravitational potential perturbation');
-		fielddisplay(this,'love_l','load Love number for horizontal displacements'); 
-		fielddisplay(this,'tide_love_h','tidal love number (degree 2)');
-		fielddisplay(this,'tide_love_k','tidal love number (degree 2)');
-		fielddisplay(this,'fluid_love','secular fluid Love number');
-		fielddisplay(this,'equatorial_moi','mean equatorial moment of inertia [kg m^2]');
-		fielddisplay(this,'polar_moi','polar moment of inertia [kg m^2]');
-		fielddisplay(this,'angular_velocity','mean rotational velocity of earth [per second]'); 
-		fielddisplay(this,'rigid','rigid earth graviational potential perturbation');
-		fielddisplay(this,'elastic','elastic earth graviational potential perturbation');
-		fielddisplay(this,'rotation','rotational earth potential perturbation');
-		fielddisplay(this,'ocean_area_scaling','correction for model representation of ocean area [default: No correction]'); 
-		fielddisplay(this,'degacc',"accuracy (default .01 deg) for numerical discretization of the Green's functions");
-		fielddisplay(this,'transitions','indices into parts of the mesh that will be icecaps');
-		fielddisplay(this,'requested_outputs','additional outputs requested');
+			fielddisplay(this,'deltathickness','thickness change (main loading of the slr solution core [m]');
+			fielddisplay(this,'sealevel','current sea level (prior to computation) [m]');
+			fielddisplay(this,'reltol','sea level rise relative convergence criterion, (NaN: not applied)');
+			fielddisplay(this,'abstol','sea level rise absolute convergence criterion, (default, NaN: not applied');
+			fielddisplay(this,'maxiter','maximum number of nonlinear iterations');
+			fielddisplay(this,'love_h','load Love number for radial displacement');
+			fielddisplay(this,'love_k','load Love number for gravitational potential perturbation');
+			fielddisplay(this,'love_l','load Love number for horizontal displacements'); 
+			fielddisplay(this,'tide_love_h','tidal love number (degree 2)');
+			fielddisplay(this,'tide_love_k','tidal love number (degree 2)');
+			fielddisplay(this,'fluid_love','secular fluid Love number');
+			fielddisplay(this,'equatorial_moi','mean equatorial moment of inertia [kg m^2]');
+			fielddisplay(this,'polar_moi','polar moment of inertia [kg m^2]');
+			fielddisplay(this,'angular_velocity','mean rotational velocity of earth [per second]'); 
+			fielddisplay(this,'rigid','rigid earth graviational potential perturbation');
+			fielddisplay(this,'elastic','elastic earth graviational potential perturbation');
+			fielddisplay(this,'rotation','rotational earth potential perturbation');
+			fielddisplay(this,'ocean_area_scaling','correction for model representation of ocean area [default: No correction]'); 
+			fielddisplay(this,'steric_rate','rate of steric ocean expansion (in mm/yr)'); 
+			fielddisplay(this,'degacc',"accuracy (default .01 deg) for numerical discretization of the Green's functions");
+			fielddisplay(this,'transitions','indices into parts of the mesh that will be icecaps');
+			fielddisplay(this,'requested_outputs','additional outputs requested');
 		} //}}}
 		this.marshall=function(md,prefix,fid) { //{{{
@@ -125,4 +131,5 @@
 			WriteData(fid,prefix,'object',this,'fieldname','rotation','format','Boolean');
 			WriteData(fid,prefix,'object',this,'fieldname','ocean_area_scaling','format','Boolean');
+			WriteData(fid,prefix,'object',this,'fieldname','steric_rate','format','DoubleMat','mattype',1,'scale',1e-3/md.constants.yts);
 			WriteData(fid,prefix,'object',this,'fieldname','degacc','format','Double');
 			WriteData(fid,prefix,'object',this,'fieldname','transitions','format','MatArray');
@@ -158,4 +165,5 @@
 			this.rotation=NullFix(this.rotation,NaN);
 			this.ocean_area_scaling=NullFix(this.ocean_area_scaling,NaN);
+			this.steric_rate=NullFix(this.steric_rate,NaN);
 			this.degacc=NullFix(this.degacc,NaN);
 		}//}}}
@@ -180,4 +188,5 @@
 	this.rotation       = 0;
 	this.ocean_area_scaling = 0;
+	this.steric_rate    = 0; //rate of ocean expansion from steric effects. 
 	this.degacc         = 0;
 	this.requested_outputs = [];
Index: /issm/trunk/src/m/classes/slr.m
===================================================================
--- /issm/trunk/src/m/classes/slr.m	(revision 22757)
+++ /issm/trunk/src/m/classes/slr.m	(revision 22758)
@@ -24,4 +24,5 @@
 		rotation       = 0;
 		ocean_area_scaling = 0;
+		steric_rate    = 0; %rate of ocean expansion from steric effects. 
 		degacc         = 0;
 		requested_outputs      = {};
@@ -40,9 +41,9 @@
 		
 		%Convergence criterion: absolute, relative and residual
-		self.reltol=NaN; %default
-		self.abstol=0.001; %1 mm of sea level rise
+		self.reltol=0.01; % 1 per cent 
+		self.abstol=NaN;  % default 
 
 		%maximum of non-linear iterations.
-		self.maxiter=10;
+		self.maxiter=5;
 
 		%computational flags: 
@@ -68,5 +69,9 @@
 		%numerical discretization accuracy
 		self.degacc=.01;
-		
+
+		%steric: 
+		self.steric_rate=0;
+	
+	
 		%output default:
 		self.requested_outputs={'default'};
@@ -93,4 +98,5 @@
 			md = checkfield(md,'fieldname','slr.abstol','size',[1 1]);
 			md = checkfield(md,'fieldname','slr.maxiter','size',[1 1],'>=',1);
+			md = checkfield(md,'fieldname','slr.steric_rate','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices 1]);
 			md = checkfield(md,'fieldname','slr.degacc','size',[1 1],'>=',1e-10);
 			md = checkfield(md,'fieldname','slr.requested_outputs','stringrow',1);
@@ -118,6 +124,6 @@
 			fielddisplay(self,'deltathickness','thickness change (main loading of the slr solution core [m]');
 			fielddisplay(self,'sealevel','current sea level (prior to computation) [m]');
-			fielddisplay(self,'reltol','sea level rise relative convergence criterion, (default, NaN: not applied)');
-			fielddisplay(self,'abstol','sea level rise absolute convergence criterion, NaN: not applied');
+			fielddisplay(self,'reltol','sea level rise relative convergence criterion, (NaN: not applied)');
+			fielddisplay(self,'abstol','sea level rise absolute convergence criterion, (default, NaN: not applied');
 			fielddisplay(self,'maxiter','maximum number of nonlinear iterations');
 			fielddisplay(self,'love_h','load Love number for radial displacement');
@@ -134,4 +140,5 @@
 			fielddisplay(self,'rotation','earth rotational potential perturbation');
 			fielddisplay(self,'ocean_area_scaling','correction for model representation of ocean area [default: No correction]'); 
+			fielddisplay(self,'steric_rate','rate of steric ocean expansion (in mm/yr)'); 
 			fielddisplay(self,'degacc','accuracy (default .01 deg) for numerical discretization of the Green''s functions');
 			fielddisplay(self,'transitions','indices into parts of the mesh that will be icecaps');
@@ -140,6 +147,6 @@
 		end % }}}
 		function marshall(self,prefix,md,fid) % {{{
-			WriteData(fid,prefix,'object',self,'fieldname','deltathickness','format','DoubleMat','mattype',2);
-			%WriteData(fid,prefix,'object',self,'fieldname','deltathickness','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofelements+1);
+			%WriteData(fid,prefix,'object',self,'fieldname','deltathickness','format','DoubleMat','mattype',2);
+			WriteData(fid,prefix,'object',self,'fieldname','deltathickness','format','DoubleMat','mattype',2,'timeserieslength',md.mesh.numberofelements+1,'yts',md.constants.yts);
 			WriteData(fid,prefix,'object',self,'fieldname','sealevel','mattype',1,'format','DoubleMat','timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
 			WriteData(fid,prefix,'object',self,'fieldname','reltol','format','Double');
@@ -159,4 +166,5 @@
 			WriteData(fid,prefix,'object',self,'fieldname','rotation','format','Boolean');
 			WriteData(fid,prefix,'object',self,'fieldname','ocean_area_scaling','format','Boolean');
+			WriteData(fid,prefix,'object',self,'fieldname','steric_rate','format','DoubleMat','mattype',1,'scale',1e-3/md.constants.yts);
 			WriteData(fid,prefix,'object',self,'fieldname','degacc','format','Double');
 			WriteData(fid,prefix,'object',self,'fieldname','transitions','format','MatArray');
@@ -192,4 +200,5 @@
 			writejsdouble(fid,[modelname '.slr.rotation'],self.rotation);
 			writejsdouble(fid,[modelname '.slr.ocean_area_scaling'],self.ocean_area_scaling);
+			writejs1Darray(fid,[modelname '.slr.steric_rate'],self.steric_rate);
 			writejsdouble(fid,[modelname '.slr.degacc'],self.degacc);
 			writejscellstring(fid,[modelname '.slr.requested_outputs'],self.requested_outputs);
Index: /issm/trunk/src/m/classes/slr.py
===================================================================
--- /issm/trunk/src/m/classes/slr.py	(revision 22757)
+++ /issm/trunk/src/m/classes/slr.py	(revision 22758)
@@ -33,4 +33,5 @@
 		self.rotation          = 0
 		self.ocean_area_scaling = 0;
+		steric_rate					= 0; #rate of ocean expansion from steric effects.
 		self.degacc            = 0
 		self.requested_outputs = []
@@ -43,6 +44,7 @@
 			string='   slr parameters:'
 			string="%s\n%s"%(string,fielddisplay(self,'deltathickness','thickness change (main loading of the slr solution core [m]'))
-			string="%s\n%s"%(string,fielddisplay(self,'reltol','sea level rise relative convergence criterion, (default, NaN: not applied)'))
-			string="%s\n%s"%(string,fielddisplay(self,'abstol','sea level rise absolute convergence criterion, NaN: not applied'))
+			string="%s\n%s"%(string,fielddisplay(self,'sealevel','current sea level (prior to computation) [m]'))
+			string="%s\n%s"%(string,fielddisplay(self,'reltol','sea level rise relative convergence criterion, (NaN: not applied)'))
+			string="%s\n%s"%(string,fielddisplay(self,'abstol','sea level rise absolute convergence criterion, (default, NaN: not applied'))
 			string="%s\n%s"%(string,fielddisplay(self,'maxiter','maximum number of nonlinear iterations'))
 			string="%s\n%s"%(string,fielddisplay(self,'love_h','load Love number for radial displacement'))
@@ -59,4 +61,5 @@
 			string="%s\n%s"%(string,fielddisplay(self,'rotation','earth rotational potential perturbation'))
 			string="%s\n%s"%(string,fielddisplay(self,'ocean_area_scaling','correction for model representation of ocean area [default: No correction]'))
+			string="%s\n%s"%(string,fielddisplay(self,'steric_rate','rate of steric ocean expansion (in mm/yr)'))
 			string="%s\n%s"%(string,fielddisplay(self,'degacc','accuracy (default .01 deg) for numerical discretization of the Green''s functions'))
 			string="%s\n%s"%(string,fielddisplay(self,'transitions','indices into parts of the mesh that will be icecaps'))
@@ -68,9 +71,9 @@
 		
 		#Convergence criterion: absolute, relative and residual
-		self.reltol=float('NaN') #default
-		self.abstol=0.001 #1 mm of sea level rise
+		self.reltol=0.01 # 1 per cent 
+		self.abstol=float('NaN') #default
 
 		#maximum of non-linear iterations.
-		self.maxiter=10
+		self.maxiter=5
 
 		#computational flags: 
@@ -84,5 +87,5 @@
 		self.tide_love_k=0.3055; #degree 2
 		
-                #secular fluid love number: 
+      #secular fluid love number: 
 		self.fluid_love=0.942; 
 		
@@ -96,4 +99,7 @@
 		#numerical discretization accuracy
 		self.degacc=.01
+
+		#steric:
+		self.steric_rate=0;
 		
 		#output default:
@@ -127,4 +133,5 @@
 		md = checkfield(md,'fieldname','slr.abstol','size',[1,1])
 		md = checkfield(md,'fieldname','slr.maxiter','size',[1,1],'>=',1)
+		md = checkfield(md,'fieldname','slr.steric_rate','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices]);
 		md = checkfield(md,'fieldname','slr.degacc','size',[1,1],'>=',1e-10)
 		md = checkfield(md,'fieldname','slr.requested_outputs','stringrow',1)
@@ -157,4 +164,5 @@
 		WriteData(fid,prefix,'object',self,'fieldname','rotation','format','Boolean')
 		WriteData(fid,prefix,'object',self,'fieldname','ocean_area_scaling','format','Boolean')
+		WriteData(fid,prefix,'object',self,'fieldname','steric_rate','format','DoubleMat','mattype',1,'scale',1e-3/md.constants.yts);
 		WriteData(fid,prefix,'object',self,'fieldname','degacc','format','Double')
 		WriteData(fid,prefix,'object',self,'fieldname','transitions','format','MatArray')
Index: /issm/trunk/src/m/classes/snowpack.m
===================================================================
--- /issm/trunk/src/m/classes/snowpack.m	(revision 22757)
+++ /issm/trunk/src/m/classes/snowpack.m	(revision 22758)
@@ -463,5 +463,4 @@
 			WriteData(fid,prefix,'object',self,'class','snowpack','fieldname','isnewton','format','Integer');
 			WriteData(fid,prefix,'object',self,'class','snowpack','fieldname','FSreconditioning','format','Double');
-			WriteData(fid,prefix,'object',self,'class','snowpack','fieldname','viscosity_overshoot','format','Double');
 			WriteData(fid,prefix,'object',self,'class','snowpack','fieldname','maxiter','format','Integer');
 			WriteData(fid,prefix,'object',self,'class','snowpack','fieldname','shelf_dampening','format','Integer');
Index: /issm/trunk/src/m/classes/stressbalance.js
===================================================================
--- /issm/trunk/src/m/classes/stressbalance.js	(revision 22757)
+++ /issm/trunk/src/m/classes/stressbalance.js	(revision 22758)
@@ -21,9 +21,4 @@
 		//Penalty factor applied kappa=max(stiffness matrix)*10^penalty_factor
 		this.penalty_factor=3;
-
-		//coefficient to update the viscosity between each iteration of
-		//a stressbalance according to the following formula
-		//viscosity(n)=viscosity(n)+viscosity_overshoot(viscosity(n)-viscosity(n-1))
-		this.viscosity_overshoot=0;
 
 		//Stop the iterations of rift if below a threshold
@@ -48,5 +43,4 @@
 		fielddisplay(this,'isnewton',"0: Picard's fixed point, 1: Newton's method, 2: hybrid");
 		fielddisplay(this,'maxiter','maximum number of nonlinear iterations');
-		fielddisplay(this,'viscosity_overshoot','over-shooting constant new=new+C*(new-old)');
 
 		console.log(sprintf('\n      %s','boundary conditions:'));
@@ -97,5 +91,4 @@
 		checkfield(md,'fieldname','stressbalance.isnewton','numel',[1],'values',[0, 1, 2]);
 		checkfield(md,'fieldname','stressbalance.FSreconditioning','size',[1, 1],'NaN',1,'Inf',1);
-		checkfield(md,'fieldname','stressbalance.viscosity_overshoot','size',[1, 1],'NaN',1,'Inf',1);
 		checkfield(md,'fieldname','stressbalance.maxiter','size',[1, 1],'>=',1);
 		checkfield(md,'fieldname','stressbalance.referential','size',[md.mesh.numberofvertices, 6]);
@@ -158,5 +151,4 @@
 		WriteData(fid,prefix,'object',this,'class','stressbalance','fieldname','isnewton','format','Integer');
 		WriteData(fid,prefix,'object',this,'class','stressbalance','fieldname','FSreconditioning','format','Double');
-		WriteData(fid,prefix,'object',this,'class','stressbalance','fieldname','viscosity_overshoot','format','Double');
 		WriteData(fid,prefix,'object',this,'class','stressbalance','fieldname','maxiter','format','Integer');
 		WriteData(fid,prefix,'object',this,'class','stressbalance','fieldname','shelf_dampening','format','Integer');
@@ -214,5 +206,4 @@
 	this.isnewton               = 0;
 	this.FSreconditioning       = 0;
-	this.viscosity_overshoot    = 0;
 	this.maxiter                = 0;
 	this.shelf_dampening        = 0;
Index: /issm/trunk/src/m/classes/stressbalance.m
===================================================================
--- /issm/trunk/src/m/classes/stressbalance.m	(revision 22757)
+++ /issm/trunk/src/m/classes/stressbalance.m	(revision 22758)
@@ -14,5 +14,4 @@
 		isnewton               = 0;
 		FSreconditioning       = 0;
-		viscosity_overshoot    = 0;
 		maxiter                = 0;
 		shelf_dampening        = 0;
@@ -68,9 +67,4 @@
 			 self.penalty_factor=3;
 
-			 %coefficient to update the viscosity between each iteration of
-			 %a stressbalance according to the following formula
-			 %viscosity(n)=viscosity(n)+viscosity_overshoot(viscosity(n)-viscosity(n-1))
-			 self.viscosity_overshoot=0;
-
 			 %Stop the iterations of rift if below a threshold
 			 self.rift_penalty_threshold=0;
@@ -99,5 +93,4 @@
 			md = checkfield(md,'fieldname','stressbalance.isnewton','numel',[1],'values',[0 1 2]);
 			md = checkfield(md,'fieldname','stressbalance.FSreconditioning','size',[1 1],'NaN',1,'Inf',1);
-			md = checkfield(md,'fieldname','stressbalance.viscosity_overshoot','size',[1 1],'NaN',1,'Inf',1);
 			md = checkfield(md,'fieldname','stressbalance.maxiter','size',[1 1],'>=',1);
 			md = checkfield(md,'fieldname','stressbalance.referential','size',[md.mesh.numberofvertices 6]);
@@ -150,5 +143,4 @@
 			fielddisplay(self,'isnewton','0: Picard''s fixed point, 1: Newton''s method, 2: hybrid');
 			fielddisplay(self,'maxiter','maximum number of nonlinear iterations');
-			fielddisplay(self,'viscosity_overshoot','over-shooting constant new=new+C*(new-old)');
 
 			disp(sprintf('\n      %s','boundary conditions:'));
@@ -187,5 +179,4 @@
 			WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','isnewton','format','Integer');
 			WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','FSreconditioning','format','Double');
-			WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','viscosity_overshoot','format','Double');
 			WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','maxiter','format','Integer');
 			WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','shelf_dampening','format','Integer');
@@ -220,5 +211,4 @@
 			writejsdouble(fid,[modelname '.stressbalance.isnewton'],self.isnewton);
 			writejsdouble(fid,[modelname '.stressbalance.FSreconditioning'],self.FSreconditioning);
-			writejsdouble(fid,[modelname '.stressbalance.viscosity_overshoot'],self.viscosity_overshoot);
 			writejsdouble(fid,[modelname '.stressbalance.maxiter'],self.maxiter);
 			writejsdouble(fid,[modelname '.stressbalance.shelf_dampening'],self.shelf_dampening);
Index: /issm/trunk/src/m/classes/stressbalance.py
===================================================================
--- /issm/trunk/src/m/classes/stressbalance.py	(revision 22757)
+++ /issm/trunk/src/m/classes/stressbalance.py	(revision 22758)
@@ -17,23 +17,22 @@
 
 	def __init__(self): # {{{
-		self.spcvx                    = float('NaN')
-		self.spcvy                    = float('NaN')
-		self.spcvz                    = float('NaN')
-		self.restol                   = 0
-		self.reltol                   = 0
-		self.abstol                   = 0
-		self.isnewton                 = 0
-		self.FSreconditioning     = 0
-		self.viscosity_overshoot      = 0
-		self.icefront                 = float('NaN')
-		self.maxiter                  = 0
-		self.shelf_dampening          = 0
-		self.vertex_pairing           = float('NaN')
-		self.penalty_factor           = float('NaN')
-		self.rift_penalty_lock        = float('NaN')
-		self.rift_penalty_threshold   = 0
-		self.referential              = float('NaN')
-		self.loadingforce             = float('NaN')
-		self.requested_outputs        = []
+		self.spcvx                  = float('NaN')
+		self.spcvy                  = float('NaN')
+		self.spcvz                  = float('NaN')
+		self.restol                 = 0
+		self.reltol                 = 0
+		self.abstol                 = 0
+		self.isnewton               = 0
+		self.FSreconditioning       = 0
+		self.icefront               = float('NaN')
+		self.maxiter                = 0
+		self.shelf_dampening        = 0
+		self.vertex_pairing         = float('NaN')
+		self.penalty_factor         = float('NaN')
+		self.rift_penalty_lock      = float('NaN')
+		self.rift_penalty_threshold = 0
+		self.referential            = float('NaN')
+		self.loadingforce           = float('NaN')
+		self.requested_outputs      = []
 
 		#set defaults
@@ -50,5 +49,4 @@
 		string="%s\n%s"%(string,fielddisplay(self,'isnewton',"0: Picard's fixed point, 1: Newton's method, 2: hybrid"))
 		string="%s\n%s"%(string,fielddisplay(self,'maxiter','maximum number of nonlinear iterations'))
-		string="%s\n%s"%(string,fielddisplay(self,'viscosity_overshoot','over-shooting constant new=new+C*(new-old)'))
 
 		string="%s\n%s"%(string,'\n      boundary conditions:')
@@ -98,9 +96,4 @@
 		#Penalty factor applied kappa=max(stiffness matrix)*10^penalty_factor
 		self.penalty_factor=3
-
-		#coefficient to update the viscosity between each iteration of
-		#a stressbalance according to the following formula
-		#viscosity(n)=viscosity(n)+viscosity_overshoot(viscosity(n)-viscosity(n-1))
-		self.viscosity_overshoot=0
 
 		#Stop the iterations of rift if below a threshold
@@ -141,5 +134,4 @@
 		md = checkfield(md,'fieldname','stressbalance.isnewton','numel',[1],'values',[0,1,2])
 		md = checkfield(md,'fieldname','stressbalance.FSreconditioning','size',[1],'NaN',1,'Inf',1)
-		md = checkfield(md,'fieldname','stressbalance.viscosity_overshoot','size',[1],'NaN',1,'Inf',1)
 		md = checkfield(md,'fieldname','stressbalance.maxiter','size',[1],'>=',1)
 		md = checkfield(md,'fieldname','stressbalance.referential','size',[md.mesh.numberofvertices,6])
@@ -187,5 +179,4 @@
 		WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','isnewton','format','Integer')
 		WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','FSreconditioning','format','Double')
-		WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','viscosity_overshoot','format','Double')
 		WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','maxiter','format','Integer')
 		WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','shelf_dampening','format','Integer')
Index: /issm/trunk/src/m/classes/taoinversion.py
===================================================================
--- /issm/trunk/src/m/classes/taoinversion.py	(revision 22757)
+++ /issm/trunk/src/m/classes/taoinversion.py	(revision 22758)
@@ -6,29 +6,31 @@
 from IssmConfig import IssmConfig
 from marshallcostfunctions import marshallcostfunctions
+from supportedcontrols import *
+from supportedcostfunctions import *
 
-
-class taoinversion:
+class taoinversion(object):
 	def __init__(self):
-		iscontrol                   = 0
-		incomplete_adjoint          = 0
-		control_parameters          = float('NaN')
-		maxsteps                    = 0
-		maxiter                     = 0
-		fatol                       = 0
-		frtol                       = 0
-		gatol                       = 0
-		grtol                       = 0
-		gttol                       = 0
-		algorithm                   = ''
-		cost_functions              = float('NaN')
-		cost_functions_coefficients = float('NaN')
-		min_parameters              = float('NaN')
-		max_parameters              = float('NaN')
-		vx_obs                      = float('NaN')
-		vy_obs                      = float('NaN')
-		vz_obs                      = float('NaN')
-		vel_obs                     = float('NaN')
-		thickness_obs               = float('NaN')
-		surface_obs                 = float('NaN')
+		self.iscontrol                   = 0
+		self.incomplete_adjoint          = 0
+		self.control_parameters          = float('NaN')
+		self.maxsteps                    = 0
+		self.maxiter                     = 0
+		self.fatol                       = 0
+		self.frtol                       = 0
+		self.gatol                       = 0
+		self.grtol                       = 0
+		self.gttol                       = 0
+		self.algorithm                   = ''
+		self.cost_functions              = float('NaN')
+		self.cost_functions_coefficients = float('NaN')
+		self.min_parameters              = float('NaN')
+		self.max_parameters              = float('NaN')
+		self.vx_obs                      = float('NaN')
+		self.vy_obs                      = float('NaN')
+		self.vz_obs                      = float('NaN')
+		self.vel_obs                     = float('NaN')
+		self.thickness_obs               = float('NaN')
+		self.surface_obs                 = float('NaN')
+		self.setdefaultparameters()
 
 	def __repr__(self):
@@ -98,5 +100,4 @@
 		#several responses can be used:
 		self.cost_functions=101;
-
 		return self
 
@@ -119,5 +120,5 @@
 
 	def checkconsistency(self,md,solution,analyses):
-		if not self.control:
+		if not self.iscontrol:
 			return md
 		if not IssmConfig('_HAVE_TAO_')[0]:
@@ -125,9 +126,9 @@
 
 
-		num_controls= np.numel(md.inversion.control_parameters)
-		num_costfunc= np.size(md.inversion.cost_functions,2)
+		num_controls= np.size(md.inversion.control_parameters)
+		num_costfunc= np.size(md.inversion.cost_functions)
 
 		md = checkfield(md,'fieldname','inversion.iscontrol','values',[0, 1])
-		md = checkfield(md,'fieldname','inversion.incomplete_adjoint','values',[0, 1])
+		md = checkfield(md,'fieldname','inversion.incomplete_adjoint','values',[0,1])
 		md = checkfield(md,'fieldname','inversion.control_parameters','cell',1,'values',supportedcontrols())
 		md = checkfield(md,'fieldname','inversion.maxsteps','numel',1,'>=',0)
@@ -143,10 +144,10 @@
 		PETSCMINOR = IssmConfig('_PETSC_MINOR_')[0]
 		if(PETSCMAJOR>3 or (PETSCMAJOR==3 and PETSCMINOR>=5)):
-			md = checkfield(md,'fieldname','inversion.algorithm','values',{'blmvm','cg','lmvm'})
+			md = checkfield(md,'fieldname','inversion.algorithm','values',['blmvm','cg','lmvm'])
 		else:
-			md = checkfield(md,'fieldname','inversion.algorithm','values',{'tao_blmvm','tao_cg','tao_lmvm'})
+			md = checkfield(md,'fieldname','inversion.algorithm','values',['tao_blmvm','tao_cg','tao_lmvm'])
 
 
-		md = checkfield(md,'fieldname','inversion.cost_functions','size',[1, num_costfunc],'values',supportedcostfunctions())
+		md = checkfield(md,'fieldname','inversion.cost_functions','size', [num_costfunc],'values',supportedcostfunctions())
 		md = checkfield(md,'fieldname','inversion.cost_functions_coefficients','size',[md.mesh.numberofvertices, num_costfunc],'>=',0)
 		md = checkfield(md,'fieldname','inversion.min_parameters','size',[md.mesh.numberofvertices, num_controls])
@@ -162,37 +163,37 @@
 			md = checkfield(md,'fieldname','inversion.vy_obs','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1)
 
-		def marshall(self, md, fid):
+	def marshall(self,prefix,md,fid):
 
-			yts=md.constants.yts;
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','iscontrol','format','Boolean')
-			WriteData(fid,prefix,'name','md.inversion.type','data',1,'format','Integer')
-			if not self.iscontrol:
-				return
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','incomplete_adjoint','format','Boolean')
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','maxsteps','format','Integer')
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','maxiter','format','Integer')
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','fatol','format','Double')
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','frtol','format','Double')
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','gatol','format','Double')
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','grtol','format','Double')
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','gttol','format','Double')
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','algorithm','format','String')
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1)
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','min_parameters','format','DoubleMat','mattype',3)
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','max_parameters','format','DoubleMat','mattype',3)
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts)
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts)
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts)
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','thickness_obs','format','DoubleMat','mattype',1)
-			WriteData(fid,prefix,'object',self,'class','inversion','fieldname','surface_obs','format','DoubleMat','mattype',1)
+		yts=md.constants.yts;
+		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','iscontrol','format','Boolean')
+		WriteData(fid,prefix,'name','md.inversion.type','data',1,'format','Integer')
+		if not self.iscontrol:
+			return
+		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','incomplete_adjoint','format','Boolean')
+		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','maxsteps','format','Integer')
+		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','maxiter','format','Integer')
+		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','fatol','format','Double')
+		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','frtol','format','Double')
+		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','gatol','format','Double')
+		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','grtol','format','Double')
+		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','gttol','format','Double')
+		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','algorithm','format','String')
+		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1)
+		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','min_parameters','format','DoubleMat','mattype',3)
+		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','max_parameters','format','DoubleMat','mattype',3)
+		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts)
+		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts)
+		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts)
+		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','thickness_obs','format','DoubleMat','mattype',1)
+		WriteData(fid,prefix,'object',self,'class','inversion','fieldname','surface_obs','format','DoubleMat','mattype',1)
 
-			#process control parameters
-			num_control_parameters = np.numel(self.control_parameters)
-			WriteData(fid,prefix,'object',self,'fieldname','control_parameters','format','StringArray')
-			WriteData(fid,prefix,'data',num_control_parameters,'name','md.inversion.num_control_parameters','format','Integer')
+		#process control parameters
+		num_control_parameters = np.size(self.control_parameters)
+		WriteData(fid,prefix,'object',self,'fieldname','control_parameters','format','StringArray')
+		WriteData(fid,prefix,'data',num_control_parameters,'name','md.inversion.num_control_parameters','format','Integer')
 
-			#process cost functions
-			num_cost_functions = np.size(self.cost_functions,2)
-			data= marshallcostfunctions(self.cost_functions)
-			WriteData(fid,prefix,'data',data,'name','md.inversion.cost_functions','format','StringArray')
-			WriteData(fid,prefix,'data',num_cost_functions,'name','md.inversion.num_cost_functions','format','Integer')
+		#process cost functions
+		num_cost_functions = np.size(self.cost_functions)
+		data= marshallcostfunctions(self.cost_functions)
+		WriteData(fid,prefix,'data',data,'name','md.inversion.cost_functions','format','StringArray')
+		WriteData(fid,prefix,'data',num_cost_functions,'name','md.inversion.num_cost_functions','format','Integer')
Index: /issm/trunk/src/m/classes/thermal.js
===================================================================
--- /issm/trunk/src/m/classes/thermal.js	(revision 22757)
+++ /issm/trunk/src/m/classes/thermal.js	(revision 22758)
@@ -28,4 +28,7 @@
 		//will basal boundary conditions be set dynamically
 		this.isdynamicbasalspc=0;
+		
+		//Linear elements by default
+		this.fe='P1';
 
 		//default output
@@ -46,4 +49,5 @@
 		fielddisplay(this,'isenthalpy','use an enthalpy formulation to include temperate ice (default is 0)');
 		fielddisplay(this,'isdynamicbasalspc','enable dynamic setting of basal forcing. required for enthalpy formulation (default is 0)');
+		fielddisplay(this,'fe','Finite Element type: "P1" (default), "P1xP2"');
 		fielddisplay(this,'requested_outputs','additional outputs requested');
 
@@ -55,9 +59,26 @@
         this.spctemperature=project3d(md,'vector',this.spctemperature,'type','node','layer',md.mesh.numberoflayers,'padding',NaN);
         if (md.initialization.temperature.length===md.mesh.numberofvertices) {
-            this.spctemperature = ArrayFill2D(Create2DArray(md.mesh.numberofvertices, 1), NaN);
-            var pos=ArrayFindNot2D(md.mesh.vertexonsurface, 0);
-            pos.forEach(function(x) { // impose observed temperature on surface
-                this.spctemperature[x] = md.initialization.temperature[x];
-            });
+            this.spctemperature = NewArrayFill(md.mesh.numberofvertices, NaN);
+            var pos=ArrayFindNot(md.mesh.vertexonsurface, 0);
+			// impose observed temperature on surface
+			for (var i=0,posIndex=0,count=0;i<md.initialization.temperature.length;i++){
+				if(count===pos[posIndex]){
+					this.spctemperature[i] = md.initialization.temperature[i][0];
+					posIndex++;
+				}
+				count++;
+			}
+//            this.spctemperature = NewArrayFill2D(md.mesh.numberofvertices, 1, NaN);
+//            var pos=ArrayFindNot2D(md.mesh.vertexonsurface, 0);
+//			// impose observed temperature on surface
+//			for (var i=0,posIndex=0,count=0;i<md.initialization.temperature.length;i++){
+//				for (var j=0;j<md.initialization.temperature[i].length;j++){
+//					if(count===pos[posIndex]){
+//						this.spctemperature[i][j] = md.initialization.temperature[i][j];
+//						posIndex++;
+//					}
+//					count++;
+//				}
+//			}
         }
 
@@ -71,4 +92,5 @@
 		checkfield(md,'fieldname','thermal.stabilization','numel',[1],'values',[0 ,1, 2]);
 		checkfield(md,'fieldname','thermal.spctemperature','Inf',1,'timeseries',1);
+		checkfield(md,'fieldname','thermal.fe','values',['P1','P1xP2','P1xP3']);
 		if(ArrayAnyEqual(ArrayIsMember('EnthalpyAnalysis',analyses),1) & md.thermal.isenthalpy & md.mesh.dimension() == 3){
 			
@@ -105,4 +127,5 @@
 			WriteData(fid,prefix,'object',this,'fieldname','penalty_factor','format','Double');
 			WriteData(fid,prefix,'object',this,'fieldname','isenthalpy','format','Boolean');
+			WriteData(fid,prefix,'object',this,'fieldname','fe','format','String');
 			WriteData(fid,prefix,'object',this,'fieldname','isdynamicbasalspc','format','Boolean');
 
@@ -132,5 +155,5 @@
 	this.penalty_threshold = 0;
 	this.stabilization     = 0;
-	this.reltol				= 0;
+	this.reltol			   = 0;
 	this.maxiter           = 0;
 	this.penalty_lock      = 0;
@@ -138,4 +161,5 @@
 	this.isenthalpy        = 0;
 	this.isdynamicbasalspc = 0;
+	this.fe                = 'P1';
 	this.requested_outputs = [];
 
Index: /issm/trunk/src/m/classes/thermal.py
===================================================================
--- /issm/trunk/src/m/classes/thermal.py	(revision 22757)
+++ /issm/trunk/src/m/classes/thermal.py	(revision 22758)
@@ -101,12 +101,16 @@
 
 		if 'EnthalpyAnalysis' in analyses and md.thermal.isenthalpy and md.mesh.dimension()==3:
-			pos=np.where(~np.isnan(md.thermal.spctemperature[0:md.mesh.numberofvertices]))
+			TEMP = md.thermal.spctemperature[:-1].flatten(-1)
+			pos=np.where(~np.isnan(TEMP))
 			try:
 				spccol=np.size(md.thermal.spctemperature,1)
 			except IndexError:
 				spccol=1
-			replicate=np.tile(md.geometry.surface-md.mesh.z,(spccol))
-			control=md.materials.meltingpoint-md.materials.beta*md.materials.rho_ice*md.constants.g*replicate
-			md = checkfield(md,'fieldname','thermal.spctemperature','field',md.thermal.spctemperature[pos],'<=',control[pos],'message',"spctemperature should be below the adjusted melting point")
+
+			replicate=np.tile(md.geometry.surface-md.mesh.z,(spccol)).flatten(-1)
+
+			control=md.materials.meltingpoint-md.materials.beta*md.materials.rho_ice*md.constants.g*replicate+10**-5
+
+			md = checkfield(md,'fieldname','thermal.spctemperature','field',md.thermal.spctemperature.flatten(-1)[pos],'<=',control[pos],'message',"spctemperature should be below the adjusted melting point")
 			md = checkfield(md,'fieldname','thermal.isenthalpy','numel',[1],'values',[0,1])
 			md = checkfield(md,'fieldname','thermal.isdynamicbasalspc','numel',[1],'values',[0,1]);
Index: /issm/trunk/src/m/classes/timestepping.js
===================================================================
--- /issm/trunk/src/m/classes/timestepping.js	(revision 22757)
+++ /issm/trunk/src/m/classes/timestepping.js	(revision 22758)
@@ -13,8 +13,4 @@
 		this.final_time=10.*this.time_step;
 
-		//time adaptation? 
-		this.time_adapt=0;
-		this.cfl_coefficient=0.5;
-
 		//should we interpolate forcings between timesteps?
 		this.interp_forcings=1;
@@ -28,7 +24,6 @@
 		fielddisplay(this,'final_time','final time to stop the simulation ['+ unit + ']');
 		fielddisplay(this,'time_step','length of time steps [' +unit+ ']');
-		fielddisplay(this,'time_adapt','use cfl condition to define time step ? (0 or 1) ');
-		fielddisplay(this,'cfl_coefficient','coefficient applied to cfl condition');
 		fielddisplay(this,'interp_forcings','interpolate in time between requested forcing values ? (0 or 1)');
+		fielddisplay(this,'coupling_time','length of coupling time steps with ocean model [' +unit+ ']');
 
 	}// }}}
@@ -37,31 +32,30 @@
 
 	}// }}}
-		this.checkconsistency = function(md,solution,analyses) { //{{{
-			
-			checkfield(md,'fieldname','timestepping.start_time','numel',[1],'NaN',1,'Inf',1);
-			checkfield(md,'fieldname','timestepping.final_time','numel',[1],'NaN',1,'Inf',1);
-			checkfield(md,'fieldname','timestepping.time_step','numel',[1],'>=',0,'NaN',1,'Inf',1);
-			checkfield(md,'fieldname','timestepping.time_adapt','numel',[1],'values',[0,1]);
-			checkfield(md,'fieldname','timestepping.cfl_coefficient','numel',[1],'>',0,'<=',1);
-			checkfield(md,'fieldname','timestepping.interp_forcings','numel',[1],'values',[0,1]);
-			if (this.final_time-this.start_time<0){
-				md.checkmessage('timestepping.final_time should be larger than timestepping.start_time');
-			}
-		} // }}}
-		this.marshall=function(md,prefix,fid) { //{{{
+	this.checkconsistency = function(md,solution,analyses) { //{{{
 
-			var scale;
-			scale = md.constants.yts;
-			
-			WriteData(fid,prefix,'object',this,'fieldname','start_time','format','Double','scale',scale);
-			WriteData(fid,prefix,'object',this,'fieldname','final_time','format','Double','scale',scale);
-			WriteData(fid,prefix,'object',this,'fieldname','time_step','format','Double','scale',scale);
-			WriteData(fid,prefix,'object',this,'fieldname','time_adapt','format','Boolean');
-			WriteData(fid,prefix,'object',this,'fieldname','cfl_coefficient','format','Double');
-			WriteData(fid,prefix,'object',this,'fieldname','interp_forcings','format','Boolean');
+		checkfield(md,'fieldname','timestepping.start_time','numel',[1],'NaN',1,'Inf',1);
+		checkfield(md,'fieldname','timestepping.final_time','numel',[1],'NaN',1,'Inf',1);
+		checkfield(md,'fieldname','timestepping.time_step','numel',[1],'>=',0,'NaN',1,'Inf',1);
+		checkfield(md,'fieldname','timestepping.interp_forcings','numel',[1],'values',[0,1]);
+		checkfield(md,'fieldname','timestepping.coupling_time','numel',[1],'>=',0,'NaN',1,'Inf',1);
+		if (this.final_time-this.start_time<0){
+			md.checkmessage('timestepping.final_time should be larger than timestepping.start_time');
+		}
+	} // }}}
+	this.marshall=function(md,prefix,fid) { //{{{
 
-		}//}}}
-		this.fix=function() { //{{{
-		}//}}}
+		var scale;
+		scale = md.constants.yts;
+
+		WriteData(fid,prefix,'name','md.timestepping.type','data',1,'format','Integer');
+		WriteData(fid,prefix,'object',this,'fieldname','start_time','format','Double','scale',scale);
+		WriteData(fid,prefix,'object',this,'fieldname','final_time','format','Double','scale',scale);
+		WriteData(fid,prefix,'object',this,'fieldname','time_step','format','Double','scale',scale);
+		WriteData(fid,prefix,'object',this,'fieldname','interp_forcings','format','Boolean');
+		WriteData(fid,prefix,'object',this,'fieldname','coupling_time','format','Double','scale',scale);
+
+	}//}}}
+	this.fix=function() { //{{{
+	}//}}}
 	//properties 
 	// {{{
@@ -69,7 +63,6 @@
 	this.final_time      = 0.;
 	this.time_step       = 0.;
-	this.time_adapt      = 0;
-	this.cfl_coefficient = 0.;
 	this.interp_forcings = 1;
+	this.coupling_time   = 0.;
 
 	this.setdefaultparameters();
Index: /issm/trunk/src/m/classes/timestepping.m
===================================================================
--- /issm/trunk/src/m/classes/timestepping.m	(revision 22757)
+++ /issm/trunk/src/m/classes/timestepping.m	(revision 22758)
@@ -9,7 +9,6 @@
 		final_time      = 0.;
 		time_step       = 0.;
-		time_adapt      = 0;
-		cfl_coefficient = 0.;
 		interp_forcings = 1;
+		coupling_time   = 0.;
 	end
 	methods
@@ -18,4 +17,6 @@
 				case 0
 					self=setdefaultparameters(self);
+				case 1
+					self=structtoobj(timestepping(),varargin{1});
 				otherwise
 					error('constructor not supported');
@@ -30,8 +31,4 @@
 			self.final_time=10.*self.time_step;
 
-			%time adaptation? 
-			self.time_adapt=0;
-			self.cfl_coefficient=0.5;
-
 			%should we interpolate forcings between timesteps?
 			self.interp_forcings=1;
@@ -42,10 +39,12 @@
 			md = checkfield(md,'fieldname','timestepping.final_time','numel',[1],'NaN',1,'Inf',1);
 			md = checkfield(md,'fieldname','timestepping.time_step','numel',[1],'>=',0,'NaN',1,'Inf',1);
-			md = checkfield(md,'fieldname','timestepping.time_adapt','numel',[1],'values',[0 1]);
-			md = checkfield(md,'fieldname','timestepping.cfl_coefficient','numel',[1],'>',0,'<=',1);
 			md = checkfield(md,'fieldname','timestepping.interp_forcings','numel',[1],'values',[0 1]);
 			if self.final_time-self.start_time<0,
 				md = checkmessage(md,'timestepping.final_time should be larger than timestepping.start_time');
 			end 
+			if strcmp(solution,'TransientSolution'),
+				md = checkfield(md,'fieldname','timestepping.time_step','numel',[1],'>',0,'NaN',1,'Inf',1);
+				md = checkfield(md,'fieldname','timestepping.time_step','numel',[1],'>=',0,'NaN',1,'Inf',1);
+			end
 		end % }}}
 		function disp(self) % {{{
@@ -56,7 +55,6 @@
 			fielddisplay(self,'final_time',['final time to stop the simulation [' unit ']']);
 			fielddisplay(self,'time_step',['length of time steps [' unit ']']);
-			fielddisplay(self,'time_adapt','use cfl condition to define time step ? (0 or 1) ');
-			fielddisplay(self,'cfl_coefficient','coefficient applied to cfl condition');
 			fielddisplay(self,'interp_forcings','interpolate in time between requested forcing values ? (0 or 1)');
+			fielddisplay(self,'coupling_time',['length of coupling time step with ocean model  [' unit ']']);
 
 		end % }}}
@@ -64,10 +62,10 @@
 
 			scale = md.constants.yts;
+			WriteData(fid,prefix,'name','md.timestepping.type','data',1,'format','Integer');
 			WriteData(fid,prefix,'object',self,'fieldname','start_time','format','Double','scale',scale);
 			WriteData(fid,prefix,'object',self,'fieldname','final_time','format','Double','scale',scale);
 			WriteData(fid,prefix,'object',self,'fieldname','time_step','format','Double','scale',scale);
-			WriteData(fid,prefix,'object',self,'fieldname','time_adapt','format','Boolean');
-			WriteData(fid,prefix,'object',self,'fieldname','cfl_coefficient','format','Double');
 			WriteData(fid,prefix,'object',self,'fieldname','interp_forcings','format','Boolean');
+			WriteData(fid,prefix,'object',self,'fieldname','coupling_time','format','Double','scale',scale);
 		end % }}}
 		function savemodeljs(self,fid,modelname) % {{{
@@ -76,6 +74,4 @@
 			writejsdouble(fid,[modelname '.timestepping.final_time'],self.final_time);
 			writejsdouble(fid,[modelname '.timestepping.time_step'],self.time_step);
-			writejsdouble(fid,[modelname '.timestepping.time_adapt'],self.time_adapt);
-			writejsdouble(fid,[modelname '.timestepping.cfl_coefficient'],self.cfl_coefficient);
 			writejsdouble(fid,[modelname '.timestepping.interp_forcings'],self.interp_forcings);
 
Index: /issm/trunk/src/m/classes/timestepping.py
===================================================================
--- /issm/trunk/src/m/classes/timestepping.py	(revision 22757)
+++ /issm/trunk/src/m/classes/timestepping.py	(revision 22758)
@@ -15,7 +15,6 @@
 		self.final_time      = 0.
 		self.time_step       = 0.
-		self.time_adapt      = 0
-		self.cfl_coefficient = 0.
 		self.interp_forcings = 1
+		self.coupling_time   = 0.
 		
 		#set defaults
@@ -28,7 +27,6 @@
 		string="%s\n%s"%(string,fielddisplay(self,"final_time","final time to stop the simulation [yr]"))
 		string="%s\n%s"%(string,fielddisplay(self,"time_step","length of time steps [yr]"))
-		string="%s\n%s"%(string,fielddisplay(self,"time_adapt","use cfl condition to define time step ? (0 or 1) "))
-		string="%s\n%s"%(string,fielddisplay(self,"cfl_coefficient","coefficient applied to cfl condition"))
 		string="%s\n%s"%(string,fielddisplay(self,"interp_forcings","interpolate in time between requested forcing values ? (0 or 1)"))
+		string="%s\n%s"%(string,fielddisplay(self,"coupling_time","length of coupling time steps with ocean model [yr]"))
 		return string
 		#}}}
@@ -41,8 +39,4 @@
 		self.final_time=10.*self.time_step
 
-		#time adaptation? 
-		self.time_adapt=0
-		self.cfl_coefficient=0.5
-		
 		#should we interpolate forcings between timesteps?
 		self.interp_forcings=1
@@ -55,8 +49,7 @@
 		md = checkfield(md,'fieldname','timestepping.final_time','numel',[1],'NaN',1,'Inf',1)
 		md = checkfield(md,'fieldname','timestepping.time_step','numel',[1],'>=',0,'NaN',1,'Inf',1)
-		md = checkfield(md,'fieldname','timestepping.time_adapt','numel',[1],'values',[0,1])
-		md = checkfield(md,'fieldname','timestepping.cfl_coefficient','numel',[1],'>',0,'<=',1)
 		if self.final_time-self.start_time<0:
 			md.checkmessage("timestepping.final_time should be larger than timestepping.start_time")
+			md = checkfield(md,'fieldname','timestepping.coupling_time','numel',[1],'>=',0,'NaN',1,'Inf',1)
 		md = checkfield(md,'fieldname','timestepping.interp_forcings','numel',[1],'values',[0,1])
 
@@ -66,9 +59,9 @@
 
 		yts=md.constants.yts
+		WriteData(fid,prefix,'name','md.timestepping.type','data',1,'format','Integer');
 		WriteData(fid,prefix,'object',self,'fieldname','start_time','format','Double','scale',yts)
 		WriteData(fid,prefix,'object',self,'fieldname','final_time','format','Double','scale',yts)
 		WriteData(fid,prefix,'object',self,'fieldname','time_step','format','Double','scale',yts)
-		WriteData(fid,prefix,'object',self,'fieldname','time_adapt','format','Boolean')
-		WriteData(fid,prefix,'object',self,'fieldname','cfl_coefficient','format','Double')
 		WriteData(fid,prefix,'object',self,'fieldname','interp_forcings','format','Boolean')
+		WriteData(fid,prefix,'object',self,'fieldname','coupling_time','format','Double','scale',yts)
 	# }}}
Index: /issm/trunk/src/m/classes/timesteppingadaptive.js
===================================================================
--- /issm/trunk/src/m/classes/timesteppingadaptive.js	(revision 22758)
+++ /issm/trunk/src/m/classes/timesteppingadaptive.js	(revision 22758)
@@ -0,0 +1,82 @@
+//TIMESTEPPINGADAPTIVE class definition
+//
+//   Usage:
+//      timesteppingadaptive=new timesteppingadaptive();
+
+function timesteppingadaptive (){
+	//methods
+	this.setdefaultparameters = function(){// {{{
+		//time between 2 time steps
+		this.time_step_min=0.01;
+		this.time_step_max=10.;
+
+		//final time
+		this.final_time=10.*this.time_step_max;
+
+		//time adaptation? 
+		this.cfl_coefficient=0.5;
+
+		//should we interpolate forcings between timesteps?
+		this.interp_forcings=1;
+	}// }}}
+	this.disp= function(){// {{{
+
+		var unit;
+		console.log(sprintf('   timesteppingadaptive parameters:'));
+		unit = 'yr';
+		fielddisplay(this,'start_time','simulation starting time ['+ unit + ']');
+		fielddisplay(this,'final_time','final time to stop the simulation ['+ unit + ']');
+		fielddisplay(this,'time_step_min','minimum length of time steps [' +unit+ ']');
+		fielddisplay(this,'time_step_max','maximum length of time steps [' +unit+ ']');
+		fielddisplay(this,'cfl_coefficient','coefficient applied to cfl condition');
+		fielddisplay(this,'interp_forcings','interpolate in time between requested forcing values ? (0 or 1)');
+		fielddisplay(this,'coupling_time','coupling time steps with ocean model [' +unit+ ']');
+
+	}// }}}
+	this.classname= function(){// {{{
+		return "timesteppingadaptive";
+
+	}// }}}
+	this.checkconsistency = function(md,solution,analyses) { //{{{
+
+		checkfield(md,'fieldname','timestepping.start_time','numel',[1],'NaN',1,'Inf',1);
+		checkfield(md,'fieldname','timestepping.final_time','numel',[1],'NaN',1,'Inf',1);
+		checkfield(md,'fieldname','timestepping.time_step_min','numel',[1],'>=',0,'NaN',1,'Inf',1);
+		checkfield(md,'fieldname','timestepping.time_step_max','numel',[1],'>=',md.timestepping.time_step_max,'NaN',1,'Inf',1);
+		checkfield(md,'fieldname','timestepping.cfl_coefficient','numel',[1],'>',0,'<=',1);
+		checkfield(md,'fieldname','timestepping.interp_forcings','numel',[1],'values',[0,1]);
+		if (this.final_time-this.start_time<0){
+			md.checkmessage('timestepping.final_time should be larger than timestepping.start_time');
+		}
+		checkfield(md,'fieldname','timestepping.coupling_time','numel',[1],'>=',0,'NaN',1,'Inf',1);
+	} // }}}
+	this.marshall=function(md,prefix,fid) { //{{{
+
+		var scale;
+		scale = md.constants.yts;
+
+		WriteData(fid,prefix,'name','md.timestepping.type','data',2,'format','Integer');
+		WriteData(fid,prefix,'object',this,'class','timestepping','fieldname','start_time','format','Double','scale',scale);
+		WriteData(fid,prefix,'object',this,'class','timestepping','fieldname','final_time','format','Double','scale',scale);
+		WriteData(fid,prefix,'object',this,'class','timestepping','fieldname','time_step_min','format','Double','scale',scale);
+		WriteData(fid,prefix,'object',this,'class','timestepping','fieldname','time_step_max','format','Double','scale',scale);
+		WriteData(fid,prefix,'object',this,'class','timestepping','fieldname','cfl_coefficient','format','Double');
+		WriteData(fid,prefix,'object',this,'class','timestepping','fieldname','interp_forcings','format','Boolean');
+		WriteData(fid,prefix,'object',this,'class','timestepping','fieldname','coupling_time','format','Double','scale',scale);
+
+	}//}}}
+	this.fix=function() { //{{{
+	}//}}}
+	//properties 
+	// {{{
+	this.start_time      = 0.;
+	this.final_time      = 0.;
+	this.time_step_min   = 0.;
+	this.time_step_max   = 0.;
+	this.cfl_coefficient = 0.;
+	this.interp_forcings = 1;
+	this.coupling_time   = 0.;
+
+	this.setdefaultparameters();
+	//}}}
+}
Index: /issm/trunk/src/m/classes/timesteppingadaptive.m
===================================================================
--- /issm/trunk/src/m/classes/timesteppingadaptive.m	(revision 22758)
+++ /issm/trunk/src/m/classes/timesteppingadaptive.m	(revision 22758)
@@ -0,0 +1,92 @@
+%TIMESTEPPINGADAPTIVE Class definition
+%
+%   Usage:
+%      timesteppingadaptive=timesteppingadaptive();
+
+classdef timesteppingadaptive
+	properties (SetAccess=public) 
+		start_time      = 0.;
+		final_time      = 0.;
+		time_step_min   = 0.;
+		time_step_max   = 0.;
+		cfl_coefficient = 0.;
+		interp_forcings = 1;
+		coupling_time   = 0.;
+	end
+	methods
+		function self = timesteppingadaptive(varargin) % {{{
+			switch nargin
+				case 0
+					self=setdefaultparameters(self);
+				case 1
+					self=structtoobj(timesteppingadaptive(),varargin{1});
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
+
+			%time between 2 time steps
+			self.time_step_min = 0.01;
+			self.time_step_max = 10.;
+
+			%final time
+			self.final_time=10.*self.time_step_max;
+
+			%default CFL coefficient
+			self.cfl_coefficient=0.5;
+
+			%should we interpolate forcings between timesteps?
+			self.interp_forcings=1;
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
+
+			md = checkfield(md,'fieldname','timestepping.start_time','numel',[1],'NaN',1,'Inf',1);
+			md = checkfield(md,'fieldname','timestepping.final_time','numel',[1],'NaN',1,'Inf',1);
+			md = checkfield(md,'fieldname','timestepping.time_step_min','numel',[1],'>=',0,'NaN',1,'Inf',1);
+			md = checkfield(md,'fieldname','timestepping.time_step_max','numel',[1],'>=',md.timestepping.time_step_min,'NaN',1,'Inf',1);
+			md = checkfield(md,'fieldname','timestepping.cfl_coefficient','numel',[1],'>',0,'<=',1);
+			md = checkfield(md,'fieldname','timestepping.interp_forcings','numel',[1],'values',[0 1]);
+			md = checkfield(md,'fieldname','timestepping.coupling_time','numel',[1],'>=',md.timestepping.coupling_time,'NaN',1,'Inf',1);
+			if self.final_time-self.start_time<0,
+				md = checkmessage(md,'timestepping.final_time should be larger than timestepping.start_time');
+			end 
+		end % }}}
+		function disp(self) % {{{
+			disp(sprintf('   timesteppingadaptive parameters:'));
+
+			unit = 'yr';
+			fielddisplay(self,'start_time',['simulation starting time [' unit ']']);
+			fielddisplay(self,'final_time',['final time to stop the simulation [' unit ']']);
+			fielddisplay(self,'time_step_min',['minimum length of time step [' unit ']']);
+			fielddisplay(self,'time_step_max',['maximum length of time step [' unit ']']);
+			fielddisplay(self,'cfl_coefficient','coefficient applied to cfl condition');
+			fielddisplay(self,'interp_forcings','interpolate in time between requested forcing values ? (0 or 1)');
+			fielddisplay(self,'coupling_time',['coupling time step with ocean model [' unit ']']);
+
+		end % }}}
+		function marshall(self,prefix,md,fid) % {{{
+
+			scale = md.constants.yts;
+			WriteData(fid,prefix,'name','md.timestepping.type','data',2,'format','Integer');
+			WriteData(fid,prefix,'object',self,'class','timestepping','fieldname','start_time','format','Double','scale',scale);
+			WriteData(fid,prefix,'object',self,'class','timestepping','fieldname','final_time','format','Double','scale',scale);
+			WriteData(fid,prefix,'object',self,'class','timestepping','fieldname','time_step_min','format','Double','scale',scale);
+			WriteData(fid,prefix,'object',self,'class','timestepping','fieldname','time_step_max','format','Double','scale',scale);
+			WriteData(fid,prefix,'object',self,'class','timestepping','fieldname','cfl_coefficient','format','Double');
+			WriteData(fid,prefix,'object',self,'class','timestepping','fieldname','interp_forcings','format','Boolean');
+			WriteData(fid,prefix,'object',self,'class','timestepping','fieldname','coupling_time','format','Double','scale',scale);
+		end % }}}
+		function savemodeljs(self,fid,modelname) % {{{
+		
+			writejsdouble(fid,[modelname '.timesteppingadaptive.start_time'],self.start_time);
+			writejsdouble(fid,[modelname '.timesteppingadaptive.final_time'],self.final_time);
+			writejsdouble(fid,[modelname '.timesteppingadaptive.time_step_min'],self.time_step_min);
+			writejsdouble(fid,[modelname '.timesteppingadaptive.time_step_max'],self.time_step_max);
+			writejsdouble(fid,[modelname '.timesteppingadaptive.cfl_coefficient'],self.cfl_coefficient);
+			writejsdouble(fid,[modelname '.timesteppingadaptive.interp_forcings'],self.interp_forcings);
+			writejsdouble(fid,[modelname '.timesteppingadaptive.coupling_time'],self.time_step_max);
+
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/timesteppingadaptive.py
===================================================================
--- /issm/trunk/src/m/classes/timesteppingadaptive.py	(revision 22758)
+++ /issm/trunk/src/m/classes/timesteppingadaptive.py	(revision 22758)
@@ -0,0 +1,91 @@
+from fielddisplay import fielddisplay
+from checkfield import checkfield
+from WriteData import WriteData
+
+class timesteppingadaptive(object):
+	"""
+	TIMESTEPPINGADAPTIVE Class definition
+
+	   Usage:
+	      timesteppingadaptive=timesteppingadaptive();
+	"""
+
+	def __init__(self,*args): # {{{
+		if not len(args):
+			self.start_time      = 0.
+			self.final_time      = 0.
+			self.time_step_min   = 0.
+			self.time_step_max   = 0.
+			self.cfl_coefficient = 0.
+			self.interp_forcings = 1
+			self.coupling_time   = 0.
+			
+			#set defaults
+			self.setdefaultparameters()
+
+		elif len(args)==1 and args[0].__module__=='timestepping':
+			old=args[0]
+			#first call setdefaultparameters: 
+			self.setdefaultparameters()
+			self.start_time      = old.start_time      
+			self.final_time      = old.final_time      
+			self.interp_forcings = old.interp_forcings 
+                        self.coupling_time   = old.coupling_time
+
+		else:
+			raise Exception('constructor not supported')
+		#}}}
+	def __repr__(self): # {{{
+		string="   timesteppingadaptive parameters:"
+		string="%s\n%s"%(string,fielddisplay(self,"start_time","simulation starting time [yr]"))
+		string="%s\n%s"%(string,fielddisplay(self,"final_time","final time to stop the simulation [yr]"))
+		string="%s\n%s"%(string,fielddisplay(self,"time_step_min","minimum length of time steps [yr]"))
+		string="%s\n%s"%(string,fielddisplay(self,"time_step_max","maximum length of time steps [yr]"))
+		string="%s\n%s"%(string,fielddisplay(self,"cfl_coefficient","coefficient applied to cfl condition"))
+		string="%s\n%s"%(string,fielddisplay(self,"interp_forcings","interpolate in time between requested forcing values ? (0 or 1)"))
+		string="%s\n%s"%(string,fielddisplay(self,"coupling_time","coupling time steps with ocean model [yr]"))
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		
+		#time between 2 time steps
+		self.time_step_min=0.01
+		self.time_step_max=10.
+
+		#final time
+		self.final_time=10.*self.time_step_max
+
+		#time adaptation? 
+		self.cfl_coefficient=0.5
+		
+		#should we interpolate forcings between timesteps?
+		self.interp_forcings=1
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		md = checkfield(md,'fieldname','timestepping.start_time','numel',[1],'NaN',1,'Inf',1)
+		md = checkfield(md,'fieldname','timestepping.final_time','numel',[1],'NaN',1,'Inf',1)
+		md = checkfield(md,'fieldname','timestepping.time_step_min','numel',[1],'>=',0,'NaN',1,'Inf',1)
+		md = checkfield(md,'fieldname','timestepping.time_step_max','numel',[1],'>=',md.timestepping.time_step_min,'NaN',1,'Inf',1)
+		md = checkfield(md,'fieldname','timestepping.cfl_coefficient','numel',[1],'>',0,'<=',1)
+		if self.final_time-self.start_time<0:
+			md.checkmessage("timestepping.final_time should be larger than timestepping.start_time")
+		md = checkfield(md,'fieldname','timestepping.interp_forcings','numel',[1],'values',[0,1])
+		md = checkfield(md,'fieldname','timestepping.coupling_time','numel',[1],'>=',0,'NaN',1,'Inf',1)
+
+		return md
+	# }}}
+	def marshall(self,prefix,md,fid):    # {{{
+
+		yts=md.constants.yts
+		WriteData(fid,prefix,'name','md.timestepping.type','data',2,'format','Integer');
+		WriteData(fid,prefix,'object',self,'class','timestepping','fieldname','start_time','format','Double','scale',yts)
+		WriteData(fid,prefix,'object',self,'class','timestepping','fieldname','final_time','format','Double','scale',yts)
+		WriteData(fid,prefix,'object',self,'class','timestepping','fieldname','time_step_min','format','Double','scale',yts)
+		WriteData(fid,prefix,'object',self,'class','timestepping','fieldname','time_step_max','format','Double','scale',yts)
+		WriteData(fid,prefix,'object',self,'class','timestepping','fieldname','cfl_coefficient','format','Double')
+		WriteData(fid,prefix,'object',self,'class','timestepping','fieldname','interp_forcings','format','Boolean')
+		WriteData(fid,prefix,'object',self,'class','timestepping','fieldname','coupling_time','format','Double','scale',yts)
+	# }}}
Index: /issm/trunk/src/m/classes/trans.js
===================================================================
--- /issm/trunk/src/m/classes/trans.js	(revision 22757)
+++ /issm/trunk/src/m/classes/trans.js	(revision 22758)
@@ -9,16 +9,18 @@
 
 		//full analysis: Stressbalance, Masstransport and Thermal but no groundingline migration for now
-		this.issmb           = 1;
-		this.ismasstransport = 1;
-		this.isstressbalance = 1;
-		this.isthermal       = 1;
-		this.isgroundingline = 0;
-		this.isgia           = 0;
+		this.issmb             = 1;
+		this.ismasstransport   = 1;
+		this.isstressbalance   = 1;
+		this.isthermal         = 0;
+		this.isgroundingline   = 0;
+		this.isgia             = 0;
+		this.isesa             = 0;
 		this.isdamageevolution = 0;
-		this.ismovingfront   = 0;
-		this.ishydrology     = 0;
-		this.isslr           = 0;
-		this.iscoupler       = 0;
-		this.amr_frequency   = 1;
+		this.ismovingfront     = 0;
+		this.ishydrology       = 0;
+		this.isslr             = 0;
+		this.isoceancoupling   = 0;
+		this.iscoupler         = 0;
+		this.amr_frequency     = 0;
 
 		//default output
@@ -36,8 +38,10 @@
 		fielddisplay(this,'isgroundingline','indicates whether a groundingline migration is used in the transient');
 		fielddisplay(this,'isgia','indicates whether a postglacial rebound model is used in the transient');
+		fielddisplay(this,'isesa','indicates whether an elastic adjustment model is used in the transient');
 		fielddisplay(this,'isdamageevolution','indicates whether damage evolution is used in the transient');
 		fielddisplay(this,'ismovingfront','indicates whether a moving front capability is used in the transient');
 		fielddisplay(this,'ishydrology','indicates whether an hydrology model is used');
 		fielddisplay(this,'isslr','indicates whether a sea-level rise model is used');
+		fielddisplay(this,'isoceancoupling','indicates whether a coupling with an ocean model is used in the transient');
 		fielddisplay(this,'iscoupler','indicates whether different models are being run with need for coupling');
 		fielddisplay(this,'amr_frequency','frequency at which mesh is refined in simulations with multiple time_steps');
@@ -54,15 +58,17 @@
 			if (solution!='TransientSolution') return;
 
-			checkfield(md,'fieldname','trans.issmb','numel',[1],'values',[0 ,1]);
-			checkfield(md,'fieldname','trans.ismasstransport','numel',[1],'values',[0 ,1]);
-			checkfield(md,'fieldname','trans.isstressbalance','numel',[1],'values',[0 ,1]);
-			checkfield(md,'fieldname','trans.isthermal','numel',[1],'values',[0 ,1]);
+			checkfield(md,'fieldname','trans.issmb','numel',[1],'values',[0, 1]);
+			checkfield(md,'fieldname','trans.ismasstransport','numel',[1],'values',[0, 1]);
+			checkfield(md,'fieldname','trans.isstressbalance','numel',[1],'values',[0, 1]);
+			checkfield(md,'fieldname','trans.isthermal','numel',[1],'values',[0, 1]);
 			checkfield(md,'fieldname','trans.isgroundingline','numel',[1],'values',[0, 1]);
 			checkfield(md,'fieldname','trans.isgia','numel',[1],'values',[0, 1]);
+			checkfield(md,'fieldname','trans.isesa','numel',[1],'values',[0, 1]);
 			checkfield(md,'fieldname','trans.isdamageevolution','numel',[1],'values',[0, 1]);
 			checkfield(md,'fieldname','trans.ismovingfront','numel',[1],'values',[0, 1]);
-			checkfield(md,'fieldname','trans.ishydrology','numel',[1],'values',[0 ,1]);
-			checkfield(md,'fieldname','trans.iscoupler','numel',[1],'values',[0 ,1]);
-			checkfield(md,'fieldname','trans.isslr','numel',[1],'values',[0 ,1]);
+			checkfield(md,'fieldname','trans.ishydrology','numel',[1],'values',[0, 1]);
+			checkfield(md,'fieldname','trans.isslr','numel',[1],'values',[0, 1]);
+			checkfield(md,'fieldname','trans.isoceancoupling','numel',[1],'values',[0, 1]);
+			checkfield(md,'fieldname','trans.iscoupler','numel',[1],'values',[0, 1]);
 			checkfield(md,'fieldname','trans.amr_frequency','numel',[1],'>=',0,'NaN',1,'Inf',1);
 			checkfield(md,'fieldname','trans.requested_outputs','stringrow',1);
@@ -77,8 +83,10 @@
 			WriteData(fid,prefix,'object',this,'fieldname','isgroundingline','format','Boolean');
 			WriteData(fid,prefix,'object',this,'fieldname','isgia','format','Boolean');
+			WriteData(fid,prefix,'object',this,'fieldname','isesa','format','Boolean');
 			WriteData(fid,prefix,'object',this,'fieldname','isdamageevolution','format','Boolean');
 			WriteData(fid,prefix,'object',this,'fieldname','ishydrology','format','Boolean');
 			WriteData(fid,prefix,'object',this,'fieldname','ismovingfront','format','Boolean');
 			WriteData(fid,prefix,'object',this,'fieldname','isslr','format','Boolean');
+			WriteData(fid,prefix,'object',this,'fieldname','isoceancoupling','format','Boolean');
 			WriteData(fid,prefix,'object',this,'fieldname','iscoupler','format','Boolean');
 			WriteData(fid,prefix,'object',this,'fieldname','amr_frequency','format','Integer');
@@ -110,10 +118,12 @@
 	this.isgroundingline   = 0;
 	this.isgia             = 0;
+	this.isesa             = 0;
 	this.isdamageevolution = 0;
 	this.ismovingfront     = 0;
 	this.ishydrology       = 0;
 	this.isslr             = 0;
+	this.isoceancoupling   = 0;
 	this.iscoupler         = 0;
-	this.amr_frequency	  = 0;
+	this.amr_frequency	   = 0;
 	this.requested_outputs = [];
 
Index: /issm/trunk/src/m/classes/transient.m
===================================================================
--- /issm/trunk/src/m/classes/transient.m	(revision 22757)
+++ /issm/trunk/src/m/classes/transient.m	(revision 22758)
@@ -68,5 +68,5 @@
 			self.isoceancoupling = 0;
 			self.iscoupler       = 0;
-			self.amr_frequency	= 1;
+			self.amr_frequency	= 0;
 
 			%default output
Index: /issm/trunk/src/m/classes/transient.py
===================================================================
--- /issm/trunk/src/m/classes/transient.py	(revision 22757)
+++ /issm/trunk/src/m/classes/transient.py	(revision 22758)
@@ -12,5 +12,5 @@
 
 	def __init__(self): # {{{
-		self.issmb   = False
+		self.issmb   	       = False
 		self.ismasstransport   = False
 		self.isstressbalance   = False
@@ -23,7 +23,7 @@
 		self.ishydrology       = False
 		self.isslr             = False
+		self.iscoupler         = False
+		self.amr_frequency     = 0
 		self.isoceancoupling   = False
-		self.iscoupler         = False
-		amr_frequency			  = 0
 		self.requested_outputs = []
 
@@ -81,21 +81,41 @@
 		return self
 	#}}}
+	def deactivateall(self):#{{{
+		self.issmb             = False
+		self.ismasstransport   = False
+		self.isstressbalance   = False
+		self.isthermal         = False
+		self.isgroundingline   = False
+		self.isgia             = False
+		self.isesa             = False
+		self.isdamageevolution = False
+		self.ismovingfront     = False
+		self.ishydrology       = False
+		self.isslr             = False
+		self.isoceancoupling   = False
+		self.iscoupler         = False
+		self.amr_frequency     = 0
+
+		#default output
+		self.requested_outputs=[]
+		return self
+	#}}}
 	def setdefaultparameters(self): # {{{
 		
 		#full analysis: Stressbalance, Masstransport and Thermal but no groundingline migration for now
-		self.issmb = True
-		self.ismasstransport = True
-		self.isstressbalance = True
-		self.isthermal       = True
-		self.isgroundingline = False
-		self.isgia           = False
-		self.isesa           = False
+		self.issmb             = True
+		self.ismasstransport   = True
+		self.isstressbalance   = True
+		self.isthermal         = True
+		self.isgroundingline   = False
+		self.isgia             = False
+		self.isesa             = False
 		self.isdamageevolution = False
-		self.ismovingfront   = False
-		self.ishydrology     = False
-		self.isslr           = False
-		self.isoceancoupling = False
-		self.iscoupler       = False
-		self.amr_frequency	= 1
+		self.ismovingfront     = False
+		self.ishydrology       = False
+		self.isslr             = False
+		self.isoceancoupling   = False
+		self.iscoupler         = False
+		self.amr_frequency     = 0
 
 		#default output
Index: /issm/trunk/src/m/consistency/checkfield.m
===================================================================
--- /issm/trunk/src/m/consistency/checkfield.m	(revision 22757)
+++ /issm/trunk/src/m/consistency/checkfield.m	(revision 22758)
@@ -150,4 +150,5 @@
 	field2=reshape(field,prod(size(field)),1);
 	if getfieldvalue(options,'timeseries',0), field2=reshape(field(1:end-1,:),prod(size(field(1:end-1,:))),1); end
+	if getfieldvalue(options,'singletimeseries',0), field2=reshape(field(1,:),prod(size(field(1,:))),1); end
 	if any(field2<lowerbound),
 		md = checkmessage(md,getfieldvalue(options,'message',...
@@ -159,4 +160,5 @@
 	field2=reshape(field,prod(size(field)),1);
 	if getfieldvalue(options,'timeseries',0), field2=reshape(field(1:end-1,:),prod(size(field(1:end-1,:))),1); end
+	if getfieldvalue(options,'singletimeseries',0), field2=reshape(field(1,:),prod(size(field(1,:))),1); end
 	if any(field2<=lowerbound),
 		md = checkmessage(md,getfieldvalue(options,'message',...
@@ -170,4 +172,5 @@
 	field2=reshape(field,prod(size(field)),1);
 	if getfieldvalue(options,'timeseries',0), field2=reshape(field(1:end-1,:),prod(size(field(1:end-1,:))),1); end
+	if getfieldvalue(options,'singletimeseries',0), field2=reshape(field(1,:),prod(size(field(1,:))),1); end
 	if any(field2>upperbound),
 		md = checkmessage(md,getfieldvalue(options,'message',...
@@ -179,4 +182,5 @@
 	field2=reshape(field,prod(size(field)),1);
 	if getfieldvalue(options,'timeseries',0), field2=reshape(field(1:end-1,:),prod(size(field(1:end-1,:))),1); end
+	if getfieldvalue(options,'singletimeseries',0), field2=reshape(field(1,:),prod(size(field(1,:))),1); end
 	if any(field2>=upperbound),
 		md = checkmessage(md,getfieldvalue(options,'message',...
@@ -244,7 +248,12 @@
 				['field ''' fieldname ''' columns must not contain duplicate timesteps']));
 		end
-	else
-		md = checkmessage(md,getfieldvalue(options,'message',...
-			['field ''' fieldname ''' should have 2 lines']));
-	end
-end
+	elseif size(field,1)==1,
+		if size(field,2)~=1, 
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' should be either a scalar or have 2 lines']));
+		end
+	else
+		md = checkmessage(md,getfieldvalue(options,'message',...
+			['field ''' fieldname ''' should have 2 lines or be a scalar']));
+	end
+end
Index: /issm/trunk/src/m/consistency/checkfield.py
===================================================================
--- /issm/trunk/src/m/consistency/checkfield.py	(revision 22757)
+++ /issm/trunk/src/m/consistency/checkfield.py	(revision 22758)
@@ -84,5 +84,5 @@
 	if options.exist('numel'):
 		fieldnumel=options.getfieldvalue('numel')
-		if np.size(field) not in fieldnumel:
+		if (type(fieldnumel) == int and np.size(field) != fieldnumel) or (type(fieldnumel) == list and np.size(field) not in fieldnumel):
 			if   len(fieldnumel)==1:
 				md = md.checkmessage(options.getfieldvalue('message',\
@@ -101,4 +101,5 @@
 				"NaN values found in field '%s'" % fieldname))
 
+
 	#check Inf
 	if options.getfieldvalue('Inf',0):
@@ -106,4 +107,5 @@
 			md = md.checkmessage(options.getfieldvalue('message',\
 				"Inf values found in field '%s'" % fieldname))
+
 
 	#check cell
@@ -129,11 +131,26 @@
 	#check greater
 	if options.exist('>='):
-		lowerbound=options.getfieldvalue('>=')
-		if np.any(field<lowerbound):
+		lowerbound = options.getfieldvalue('>=')
+		field2 = np.reshape(field,(np.prod(np.shape(field)),1),order='F').copy()
+		if options.getfieldvalue('timeseries',0):
+			field2 = np.reshape(field[:-1],np.prod(np.shape(field[:-1])),1)
+
+		if options.getfieldvalue('singletimeseries',0):
+			field2 = np.reshape(field[0],np.prod(np.shape(field[0])),1)
+
+		if np.any(field2<lowerbound):
 			md = md.checkmessage(options.getfieldvalue('message',\
 				"field '%s' should have values above %d" % (fieldname,lowerbound)))
+
 	if options.exist('>'):
 		lowerbound=options.getfieldvalue('>')
-		if np.any(field<=lowerbound):
+		field2 = np.reshape(field,(np.prod(np.shape(field)),1),order='F').copy()
+		if options.getfieldvalue('timeseries',0):
+			field2 = np.reshape(field[:-1],np.prod(np.shape(field[:-1])),1)
+
+		if options.getfieldvalue('singletimeseries',0):
+			field2 = np.reshape(field[0],np.prod(np.shape(field[0])),1)
+
+		if np.any(field2<=lowerbound):
 			md = md.checkmessage(options.getfieldvalue('message',\
 				"field '%s' should have values above %d" % (fieldname,lowerbound)))
@@ -142,10 +159,24 @@
 	if options.exist('<='):
 		upperbound=options.getfieldvalue('<=')
-		if np.any(field>upperbound):
+		field2 = np.reshape(field,(np.prod(np.shape(field)),1),order='F').copy()
+		if options.getfieldvalue('timeseries',0):
+			field2 = np.reshape(field[:-1],np.prod(np.shape(field[:-1])),1)
+
+		if options.getfieldvalue('singletimeseries',0):
+			field2 = np.reshape(field[0],np.prod(np.shape(field[0])),1)
+
+		if np.any(field2>upperbound):
 			md = md.checkmessage(options.getfieldvalue('message',\
 				"field '%s' should have values below %d" % (fieldname,upperbound)))
 	if options.exist('<'):
 		upperbound=options.getfieldvalue('<')
-		if np.any(field>=upperbound):
+		field2 = np.reshape(field,(np.prod(np.shape(field)),1),order='F').copy()
+		if options.getfieldvalue('timeseries',0):
+			field2 = np.reshape(field[:-1],np.prod(np.shape(field[:-1])),1)
+
+		if options.getfieldvalue('singletimeseries',0):
+			field2 = np.reshape(field[0],np.prod(np.shape(field[0])),1)
+
+		if np.any(field2>=upperbound):
 			md = md.checkmessage(options.getfieldvalue('message',\
 				"field '%s' should have values below %d" % (fieldname,upperbound)))
@@ -164,13 +195,13 @@
 	#Check forcings (size and times)
 	if options.getfieldvalue('timeseries',0):
-		if   np.size(field,0)==md.mesh.numberofvertices:
+		if np.size(field,0)==md.mesh.numberofvertices or np.size(field,0)==md.mesh.numberofelements:
 			if np.ndim(field)>1 and not np.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 np.size(field,0)==md.mesh.numberofvertices+1 or np.size(field,0)==2:
-			if not all(field[-1,:]==np.sort(field[-1,:])):
+		elif np.size(field,0)==md.mesh.numberofvertices+1 or np.size(field,0)==md.mesh.numberofelements+1:
+			if np.ndim(field) > 1 and not all(field[-1,:]==np.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:]):
+			if np.ndim(field) > 1 and any(field[-1,0:-1]==field[-1,1:]):
 				md = md.checkmessage(options.getfieldvalue('message',\
 					"field '%s' columns must not contain duplicate timesteps" % fieldname))
@@ -188,8 +219,13 @@
 				md = md.checkmessage(options.getfieldvalue('message',\
 						"field '%s' columns must not contain duplicate timesteps" % fieldname))
+		elif np.size(field,0) == 1:
+			if np.ndim(field) > 1 and not np.size(field,1) == 1:
+				md = md.checkmessage(options.getfieldvalue('message',\
+				"field '%s' should be either a scalar or have 2 lines" % fieldname))
 		else:
 				md = md.checkmessage(options.getfieldvalue('message',\
-				"field '%s' should have 2 lines" % fieldname))
+				"field '%s' should have 2 lines or be a scalar" % fieldname))
 
 	return md
 
+
Index: /issm/trunk/src/m/consistency/ismodelselfconsistent.m
===================================================================
--- /issm/trunk/src/m/consistency/ismodelselfconsistent.m	(revision 22757)
+++ /issm/trunk/src/m/consistency/ismodelselfconsistent.m	(revision 22758)
@@ -66,4 +66,6 @@
 	elseif strcmp(solutiontype,'GiaSolution')
 		analyses={'GiaIvinsAnalysis'};
+	elseif strcmp(solutiontype,'LoveSolution')
+		analyses={'LoveAnalysis'};
 	elseif strcmp(solutiontype,'EsaSolution')
 		analyses={'EsaAnalysis'};
Index: /issm/trunk/src/m/consistency/ismodelselfconsistent.py
===================================================================
--- /issm/trunk/src/m/consistency/ismodelselfconsistent.py	(revision 22757)
+++ /issm/trunk/src/m/consistency/ismodelselfconsistent.py	(revision 22758)
@@ -33,4 +33,7 @@
 	elif solutiontype == 'GiaSolution':
 		analyses=['GiaIvinsAnalysis']
+
+        elif solutiontype == 'LoveSolution':
+                analyses=['LoveAnalysis']
 
 	elif solutiontype == 'TransientSolution':
Index: /issm/trunk/src/m/contrib/tsantos/AMRexportVTK.m
===================================================================
--- /issm/trunk/src/m/contrib/tsantos/AMRexportVTK.m	(revision 22757)
+++ /issm/trunk/src/m/contrib/tsantos/AMRexportVTK.m	(revision 22758)
@@ -37,5 +37,5 @@
 end
 
-%this is the result structure
+%this is the result structure (just the Transient solution)
 res_struct=model.results;
 %checking for results
@@ -51,5 +51,5 @@
 		if(size(sol_struct{i},2)>num_of_timesteps);
 			num_of_timesteps=size(sol_struct{i},2);
-      outstep=model.timestepping.time_step*model.settings.output_frequency;
+			outstep=model.timestepping.time_step*model.settings.output_frequency;
 	  end
   end
@@ -60,8 +60,17 @@
 	
 	timestep=step;
-
-	points=[model.results.TransientSolution(step).MeshX model.results.TransientSolution(step).MeshY zeros(size(model.results.TransientSolution(step).MeshX))];
+ 	if(isfield(model.results.TransientSolution,'MeshElements'))
+   	index = model.results.TransientSolution(step).MeshElements;
+   	x     = model.results.TransientSolution(step).MeshX;
+   	y     = model.results.TransientSolution(step).MeshY;
+   else
+   	index = model.mesh.elements;
+   	x     = model.mesh.x;
+   	y     = model.mesh.y;
+   end
+	
+	points=[x y zeros(size(x))];
 	[num_of_points,dim]=size(points);
-	[num_of_elt]=size(model.results.TransientSolution(step).MeshElements,1);
+	[num_of_elt]=size(index,1);
 
 	fid = fopen(strcat(path,filesep,name,filesep,'timestep.vtk',int2str(timestep),'.vtk'),'w+');
@@ -86,5 +95,5 @@
   end
 	s=cell2mat(horzcat(s,{'\n'}));
-		fprintf(fid,s,[(point_per_elt)*ones(num_of_elt,1)	model.results.TransientSolution(step).MeshElements-1]');
+		fprintf(fid,s,[(point_per_elt)*ones(num_of_elt,1) index-1]');
 	
 	fprintf(fid,'CELL_TYPES %d\n',num_of_elt);
@@ -101,5 +110,5 @@
 			else
 				timestep = size(sol_struct{j},2);
-	    end
+			end
 			
 			%getting the number of fields in the solution
@@ -120,6 +129,21 @@
 					s='%e\n';
 					fprintf(fid,s,sol_struct{j}(timestep).(fieldnames{k}));
-		    end		
-	    end 
+				end
+			end
+			fprintf(fid,'CELL_DATA %s \n',num2str(num_of_elt));
+			for k=1:num_of_fields
+				if ((numel(sol_struct{j}(timestep).(fieldnames{k})))==num_of_elt);
+					%paraview does not like NaN, replacing
+					nanval=find(isnan(sol_struct{j}(timestep).(fieldnames{k})));
+					sol_struct{j}(timestep).(fieldnames{k})(nanval)=-9999;
+					%also checking for verry small value that mess up
+					smallval=(abs(sol_struct{j}(timestep).(fieldnames{k}))<1.0e-20);
+					sol_struct{j}(timestep).(fieldnames{k})(smallval)=0.0;
+					fprintf(fid,'SCALARS %s float 1 \n',fieldnames{k});
+					fprintf(fid,'LOOKUP_TABLE default\n');
+					s='%e\n';
+					fprintf(fid,s,sol_struct{j}(timestep).(fieldnames{k}));
+				end		
+			end
 	  end
   end
Index: /issm/trunk/src/m/contrib/tsantos/mismip/gl_position.m
===================================================================
--- /issm/trunk/src/m/contrib/tsantos/mismip/gl_position.m	(revision 22757)
+++ /issm/trunk/src/m/contrib/tsantos/mismip/gl_position.m	(revision 22758)
@@ -3,7 +3,13 @@
 		%initialization of some variables
 		data					= md.results.TransientSolution(step).MaskGroundediceLevelset;
-		index					= md.results.TransientSolution(step).MeshElements;
-		x						= md.results.TransientSolution(step).MeshX;
-		y						= md.results.TransientSolution(step).MeshY;
+		if(isfield(md.results.TransientSolution,'MeshElements'))
+			index					= md.results.TransientSolution(step).MeshElements;
+			x						= md.results.TransientSolution(step).MeshX;
+			y						= md.results.TransientSolution(step).MeshY;
+		else
+			index					= md.mesh.elements;
+			x						= md.mesh.x;
+			y						= md.mesh.y;
+		end
 		numberofelements	= size(index,1);
 		elementslist		= 1:numberofelements;
Index: /issm/trunk/src/m/contrib/tsantos/mismip/ice_evolution.m
===================================================================
--- /issm/trunk/src/m/contrib/tsantos/mismip/ice_evolution.m	(revision 22757)
+++ /issm/trunk/src/m/contrib/tsantos/mismip/ice_evolution.m	(revision 22758)
@@ -2,32 +2,116 @@
 %iv: ice volume
 %ivaf: ice volume above floatation
-%GLy40 : grounding line position @ y=40km
+%GL_y : grounding line position @ y (y comes in m)
 %nelem : number of elements
+% usage:
+%
+% Default: y=40km, i0=1
+% [ga iv ivaf GL_y IF_y nelem t] = ice_evolution(md);
+%
+% Default: y=40km
+% [ga iv ivaf GL_y IF_y nelem t] = ice_evolution(md,i0);
+%
+% Use this for y the borders (y=0 or y=ymax)
+% [ga iv ivaf GL_y IF_y nelem t] = ice_evolution(md,i0,y);
+%
+%
 
-function [ga iv ivaf GLy40 nelem t] = ice_evolution(md),
+function [ga iv ivaf GL_y IF_y nelem t] = ice_evolution(varargin),
 
 	ga			= [];
 	iv			= [];
 	ivaf		= [];
-	GLy40		= [];
+	GL_y		= [];
+	IF_y		= [];
 	nelem		= [];
 	t			= [];
+
+	if(nargin==0)
+		error('it is necessary the model!')
+	elseif(nargin==1)
+		% Defoult is y=40km
+		i0	= 1;
+		y0	= 35000;
+		y1 = 45000;
+		dy = 100;
+		y  = 40000;
+	elseif(nargin==2)
+		i0=varargin{2};
+		% Defoult is y=40km
+		y0	= 35000;
+		y1 = 45000;
+		dy = 100;
+		y  = 40000;
+	elseif(nargin==3)
+		i0 = varargin{2};
+		y  = varargin{3};
+		dy = 10;
+		y0	= y-dy;
+		y1 = y+dy;
+	else
+		error('number of inputs is more than 3');
+	end
+	%set the model
+	md			=varargin{1};
 	nsteps	= length(md.results.TransientSolution);
 
-	for i=1:nsteps,
+
+	for i=i0:nsteps,
 		ga(i)			= md.results.TransientSolution(i).GroundedArea;
 		iv(i)			= md.results.TransientSolution(i).IceVolume;
 		ivaf(i)		= md.results.TransientSolution(i).IceVolumeAboveFloatation;
-		nelem(i)		= size(md.results.TransientSolution(i).MeshElements,1);
+		if(isfield(md.results.TransientSolution,'MeshElements'))
+			nelem(i)		= size(md.results.TransientSolution(i).MeshElements,1);
+		else
+			nelem(i)		= md.mesh.numberofelements;
+		end
 		t(i)			= md.results.TransientSolution(i).time;	
-		%find GL position at y=40km
+		%find GL position between y0 and y1 {{{
 		[glx gly]	= gl_position(md,i,0);
-		pos=find(gly<45000 & gly > 35000);
-		x=gly(pos);
-		v=glx(pos);
-		xq=[38000:100:42000];
-		vq = interp1(x,v,xq,'linear');
-		pos=find(xq==40000);
-		GLy40(i)=vq(pos);
+		pos			= find(gly<y1 & gly>y0);
+		x				= gly(pos);
+		v				= glx(pos);
+		if(length(pos)==0)
+			error('pos is null')
+		elseif(length(pos)==1)
+			%this should be used for y=0 or y=ymax
+			GL_y(i)	= v;
+		else
+			%this should be used when y is inside the domain; so, use linear interpolation
+			xq			= [y0:dy:y1];
+			vq			= interp1(x,v,xq,'linear');
+			pos		= find(xq==y);
+			if(pos)
+				GL_y(i)	= vq(pos);
+			else
+				error('pos is null')
+			end
+		end
+		%}}}	
+		%find IF position between y0 and y1 {{{
+		[ifx ify]	= if_position(md,i,0);
+		if(length(ifx)==0)
+			continue
+		end
+		pos			= find(ify<y1 & ify>y0);
+		x				= ify(pos);
+		v				= ifx(pos);
+		if(length(pos)==0)
+			error('pos is null')
+		elseif(length(pos)==1)
+			%this should be used for y=0 or y=ymax
+			IF_y(i)	= v;
+		else
+			%this should be used when y is inside the domain; so, use linear interpolation
+			xq			= [y0:dy:y1];
+			vq			= interp1(x,v,xq,'linear');
+			pos		= find(xq==y);
+			if(pos)
+				IF_y(i)	= vq(pos);
+			else
+				error('pos is null')
+			end
+		end
+		%}}}
 	end
 
Index: /issm/trunk/src/m/contrib/tsantos/remesh.m
===================================================================
--- /issm/trunk/src/m/contrib/tsantos/remesh.m	(revision 22757)
+++ /issm/trunk/src/m/contrib/tsantos/remesh.m	(revision 22758)
@@ -58,5 +58,5 @@
 NewModel.geometry.surface				= md.results.TransientSolution(end).Surface;
 NewModel.geometry.base					= md.results.TransientSolution(end).Base;
-%NewModel.geometry.bed					= md.geometry.bed; %use from parameterize
+NewModel.geometry.bed					= md.results.TransientSolution(end).Bed;%md.geometry.bed; %use from parameterize
 NewModel.geometry.thickness			= md.results.TransientSolution(end).Thickness;
 NewModel.mask.groundedice_levelset  = md.results.TransientSolution(end).MaskGroundediceLevelset;
@@ -72,4 +72,5 @@
 NewModel.cluster                = md.cluster;
 NewModel.transient              = md.transient;
+NewModel.amr                    = md.amr;
 
 mdOut = NewModel;
Index: /issm/trunk/src/m/coordsystems/gdaltransform.m
===================================================================
--- /issm/trunk/src/m/coordsystems/gdaltransform.m	(revision 22757)
+++ /issm/trunk/src/m/coordsystems/gdaltransform.m	(revision 22758)
@@ -22,16 +22,21 @@
 %      To get proj.4 string from EPSG, use gdalsrsinfo. Example:    gdalsrsinfo "EPSG:4326" | grep "PROJ.4"
 
-	%give ourselves a unique temporary directory: 
-	temproot=tempname; mkdir(temproot);
+	%give ourselves unique file names
+	filename_in  = tempname();
+	filename_out = tempname();
 
-	fid=fopen([temproot '/.rand1234.txt'],'w');
+	fid=fopen(filename_in,'w');
 	fprintf(fid,'%8g %8g\n',[x(:) y(:)]');
 	fclose(fid);
 
-	[s,r]=system(['gdaltransform -s_srs ',proj_in,' -t_srs ',proj_out,'  < ' temproot '/.rand1234.txt > ' temproot '/.rand1235.txt']);
+	[s,r]=system(['gdaltransform -s_srs ',proj_in,' -t_srs ',proj_out,'  < ' filename_in ' > ' filename_out]);
 	if s~=0 | ~isempty(deblank(r)),
 		error(r);
 	end
-	A=load([temproot '/.rand1235.txt']);
+	A=load(filename_out);
 	xout=A(:,1); xout=reshape(xout,size(x));
 	yout=A(:,2); yout=reshape(yout,size(y));
+
+	%clean up
+	delete(filename_in);
+	delete(filename_out);
Index: /issm/trunk/src/m/coordsystems/gmtmask.m
===================================================================
--- /issm/trunk/src/m/coordsystems/gmtmask.m	(revision 22757)
+++ /issm/trunk/src/m/coordsystems/gmtmask.m	(revision 22758)
@@ -31,5 +31,7 @@
 	%First, write our lat,long file for gmt:
 	nv=length(lat);
-	dlmwrite('./all_vertices.txt',[long lat (1:nv)'],'delimiter','\t','precision',10);
+	filename_all = ['all_vertices-' num2str(feature('GetPid')) '.txt']; 
+	filename_oce = ['oce_vertices-' num2str(feature('GetPid')) '.txt']; 
+	dlmwrite(filename_all,[long lat (1:nv)'],'delimiter','\t','precision',10);
 
 	%Avoid bypassing of the ld library path by Matlab (:()
@@ -40,5 +42,5 @@
 
 	%figure out which vertices are on the ocean, which one on the continent:
-	[status,result] = system('gmt gmtselect ./all_vertices.txt -h0 -Df -R0/360/-90/90  -A0 -JQ180/200 -Nk/s/s/k/s > ./oce_vertices.txt');
+	[status,result] = system(['gmt gmtselect ./' filename_all ' -h0 -Df -R0/360/-90/90  -A0 -JQ180/200 -Nk/s/s/k/s > ./' filename_oce]);
 	if status~=0,
 		error(result);
@@ -50,5 +52,5 @@
 	end
 	%read the con_vertices.txt file and flag our mesh vertices on the continent
-	fid=fopen('./oce_vertices.txt','r');
+	fid=fopen(['./' filename_oce],'r');
 	line=fgets(fid); 
 	line=fgets(fid);
@@ -64,4 +66,4 @@
 	mask(oce_vertices)=1;
 	
-	system('rm -rf ./all_vertices.txt ./oce_vertices.txt ./gmt.history');
+	system(['rm -rf ./' filename_all ' ./' filename_oce ' ./gmt.history']);
 	if ~recursive, disp(sprintf('gmtmask: done')); end;
Index: /issm/trunk/src/m/coordsystems/gmtmask.py
===================================================================
--- /issm/trunk/src/m/coordsystems/gmtmask.py	(revision 22757)
+++ /issm/trunk/src/m/coordsystems/gmtmask.py	(revision 22758)
@@ -21,12 +21,12 @@
 
 	if recursive:
-		string='             recursing: num vertices #i'+str(lenlat)
+		print '             recursing: num vertices #'+str(lenlat)
 	else:
-		string='gmtmask: num vertices #i'+str(lenlat)
+		print 'gmtmask: num vertices #'+str(lenlat)
 	
 	#Check lat and long size is not more than 50,000 If so, recursively call gmtmask: 
 
 	if lenlat>50000:
-		for i in range(ceil(lenlat/50000)):
+		for i in range(int(ceil(lenlat/50000))):
 			j=(i+1)*50000-1
 			if j>lenlat:
@@ -72,9 +72,9 @@
 	fid.close()
 
-	mask=np.zeros([nv,1])
+	mask=np.zeros(nv)
 	mask[oce_vertices]=1
 	
 	subprocess.call('rm -rf ./all_vertices.txt ./oce_vertices.txt ./gmt.history',shell=True)
 	if not recursive:
-		string='gmtmask: done'
+		print 'gmtmask: done'
 	return mask
Index: /issm/trunk/src/m/coordsystems/ll2xy.m
===================================================================
--- /issm/trunk/src/m/coordsystems/ll2xy.m	(revision 22757)
+++ /issm/trunk/src/m/coordsystems/ll2xy.m	(revision 22758)
@@ -1,11 +1,14 @@
-function [x,y] = ll2xy(lat,lon,sgn,central_meridian,standard_parallel)  
+function [x,y,scale_factor] = 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.
+%   Optional scale factor provides the scaling factor needed to correct projection error
+%   in areas and volumes
 %   Author: Michael P. Schodlok, December 2003 (map2ll)
 %
 %   Usage:
 %      [x,y] = ll2xy(lat,lon,sgn)
+%      [x,y,scale_factor] = ll2xy(lat,lon,sgn)
 %      [x,y] = ll2xy(lat,lon,sgn,central_meridian,standard_parallel)
 %
@@ -29,4 +32,9 @@
 else
 	help ll2xy
+	error('bad usage');
+end
+
+if nargout~=3 & nargout~=2,
+	help xy2ll
 	error('bad usage');
 end
@@ -65,2 +73,7 @@
 	y(cnt1) = 0.0;
 end
+
+if nargout==3,
+	m=((1+sin(abs(slat)*pi/180))*ones(length(lat),1)./(1+sin(abs(lat)*pi/180)));
+	scale_factor=(1./m).^2;
+end
Index: /issm/trunk/src/m/coordsystems/xy2ll.m
===================================================================
--- /issm/trunk/src/m/coordsystems/xy2ll.m	(revision 22757)
+++ /issm/trunk/src/m/coordsystems/xy2ll.m	(revision 22758)
@@ -1,3 +1,3 @@
-function [lat,lon] = xy2ll(x,y,sgn,central_meridian,standard_parallel)
+function [lat,lon,scale_factor] = xy2ll(x,y,sgn,central_meridian,standard_parallel)
 %XY2LL - converts xy to lat long
 %
@@ -5,8 +5,11 @@
 %   latitude and longitude Stereographic (X,Y) coordinates for the polar
 %   regions.
+%   Optional scale factor provides the scaling factor needed to correct projection error
+%   in areas and volumes
 %   Author: Michael P. Schodlok, December 2003 (map2xy.m)
 %
 %   Usage:
 %      [lat,lon] = xy2ll(x,y,sgn);
+%      [lat,lon,scale_factor] = xy2ll(x,y,sgn);
 %      [lat,lon] = xy2ll(x,y,sgn,central_meridian,standard_parallel);
 %
@@ -29,4 +32,9 @@
 	end
 else
+	help xy2ll
+	error('bad usage');
+end
+
+if nargout~=3 & nargout~=2,
 	help xy2ll
 	error('bad usage');
@@ -64,5 +72,5 @@
 [res1,res2] = find(rho(:) <= 0.1);
 if res1
-	lat(res1) = 90. * sgn;
+	lat(res1) = pi/2. * sgn;
 	lon(res1) = 0.0;
 end
@@ -71,2 +79,6 @@
 lat = lat * 180. / pi;
 lon = lon - delta; 
+if nargout==3,
+	m=((1+sin(abs(slat)*pi/180))*ones(length(lat),1)./(1+sin(abs(lat)*pi/180)));
+	scale_factor=(1./m).^2;
+end
Index: /issm/trunk/src/m/coordsystems/xy2ll.py
===================================================================
--- /issm/trunk/src/m/coordsystems/xy2ll.py	(revision 22757)
+++ /issm/trunk/src/m/coordsystems/xy2ll.py	(revision 22758)
@@ -73,5 +73,5 @@
 	res1 = np.nonzero(rho <= 0.1)[0]
 	if len(res1) > 0:
-		lat[res1] = 90. * sgn
+		lat[res1] = pi/2. * sgn
 		lon[res1] = 0.0
 	
Index: /issm/trunk/src/m/dev/devpath.py
===================================================================
--- /issm/trunk/src/m/dev/devpath.py	(revision 22757)
+++ /issm/trunk/src/m/dev/devpath.py	(revision 22758)
@@ -19,4 +19,7 @@
 				if root not in sys.path:
 					sys.path.append(root)
+
+#Also add the Nightly run directory
+sys.path.append(ISSM_DIR + '/test/NightlyRun')
 				
 sys.path.append(ISSM_DIR + '/lib')
@@ -31,4 +34,5 @@
 #Manual imports for commonly used functions
 from plotmodel import plotmodel
+from runme import runme
 
 #c = get_ipython().config
Index: /issm/trunk/src/m/exp/contourlevelzero.m
===================================================================
--- /issm/trunk/src/m/exp/contourlevelzero.m	(revision 22757)
+++ /issm/trunk/src/m/exp/contourlevelzero.m	(revision 22758)
@@ -19,5 +19,5 @@
 
 if isempty(mask), error('mask provided is empty'); end
-	if length(mask)~=md.mesh.numberofvertices, error('mask provided should be specified at the vertices of the mesh'); end
+if length(mask)~=md.mesh.numberofvertices, error('mask provided should be specified at the vertices of the mesh'); end
 
 %initialization of some variables
@@ -59,7 +59,7 @@
 
 %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);
+pos1=(Range1(:,1)<level & Range1(:,2)>=level);
+pos2=(Range2(:,1)<level & Range2(:,2)>=level);
+pos3=(Range3(:,1)<level & Range3(:,2)>=level);
 
 %get elements
Index: /issm/trunk/src/m/exp/expcoarsen.m
===================================================================
--- /issm/trunk/src/m/exp/expcoarsen.m	(revision 22757)
+++ /issm/trunk/src/m/exp/expcoarsen.m	(revision 22758)
@@ -1,3 +1,3 @@
-function expcoarsen(newfile,oldfile,resolution)
+function expcoarsen(newfile,varargin)
 %EXPCOARSEN - coarsen an exp contour
 %
@@ -7,4 +7,5 @@
 %   Usage:
 %      expcoarsen(newfile,oldfile,resolution)
+%      expcoarsen(file,resolution)
 %
 %   Example:
@@ -12,8 +13,16 @@
 
 %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'])
+if nargin==2,
+	resolution = varargin{1};
+	oldfile= newfile;
+elseif nargin==3,
+	oldfile = varargin{1};
+	resolution = varargin{2};
+else
+	error('bad usage');
+end
+
+if ~exist(oldfile)
+	error(['expcoarsen error message: file ''' oldfile ''' does not exist'])
 elseif exist(newfile),
 	choice=input(['A file ' newfile ' already exists, do you want to modify it? (y/n)'],'s');
Index: /issm/trunk/src/m/exp/expread.m
===================================================================
--- /issm/trunk/src/m/exp/expread.m	(revision 22757)
+++ /issm/trunk/src/m/exp/expread.m	(revision 22758)
@@ -65,4 +65,7 @@
 	Struct(count).x=A(1,:)';
 	Struct(count).y=A(2,:)';
+	if any(isnan(A))
+		warning('NaNs found in coordinates, note that some tools like exptool will not work properly with NaNs');
+	end
 
 	if(Struct(count).nods~=length(Struct(count).x))error(['Profile ' num2str(count) ' reports incorrect length']); end;
@@ -78,4 +81,5 @@
 end
 
+
 %close file
 fclose(fid);
Index: /issm/trunk/src/m/exp/exptool.m
===================================================================
--- /issm/trunk/src/m/exp/exptool.m	(revision 22757)
+++ /issm/trunk/src/m/exp/exptool.m	(revision 22758)
@@ -99,5 +99,5 @@
 
 %get current figure
-nofigurecopy=getfieldvalue(options,'nofigurecopy',1);
+nofigurecopy=getfieldvalue(options,'nofigurecopy',0);
 if ~nofigurecopy,
 	if ~isempty(get(0,'children')),%if there is already a figure (return the number of opened figures)
Index: /issm/trunk/src/m/exp/functionSignatures.json
===================================================================
--- /issm/trunk/src/m/exp/functionSignatures.json	(revision 22758)
+++ /issm/trunk/src/m/exp/functionSignatures.json	(revision 22758)
@@ -0,0 +1,18 @@
+{
+	"expdisp":
+	  {
+		"inputs":
+		  [
+			 {"name":"filename1", "kind":"required",   "type":"filepath"},
+			 {"name":"varargin", "kind":"optional", "multiplicity":"append"}
+		]
+	  },
+	"exptool":
+	  {
+		"inputs":
+		  [
+			 {"name":"filename1", "kind":"required",   "type":"filepath"},
+			 {"name":"varargin", "kind":"optional", "multiplicity":"append"}
+		]
+	  }
+}
Index: /issm/trunk/src/m/extrusion/project3d.js
===================================================================
--- /issm/trunk/src/m/extrusion/project3d.js	(revision 22757)
+++ /issm/trunk/src/m/extrusion/project3d.js	(revision 22758)
@@ -1,115 +1,91 @@
-project3d = function() {
-    //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:
-    // md.extruded_vector=project3d(md,'vector',vector2d,'type','node','layer',1,'padding',null);
-    // md.extruded_vector=project3d(md,'vector',vector2d,'type','element','padding',0);
-    // md.extruded_vector=project3d(md,'vector',vector2d,'type','node');
+function project3d() {
+	//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:
+	// md.extruded_vector=project3d(md,'vector',vector2d,'type','node','layer',1,'padding',null);
+	// md.extruded_vector=project3d(md,'vector',vector2d,'type','element','padding',0);
+	// md.extruded_vector=project3d(md,'vector',vector2d,'type','node');
 
-    //some regular checks
-    
-    function remove_first_n(start, arglist) { // Using slice() on arguments is discouraged because it prevents optimizations in engines such as V8
-        var args = [];
+	//some regular checks
+	if (arguments.length===1 || arguments.length===0) {
+		console.error('project3d bad usage');
+	}
+	if (md.mesh.elementtype() !== 'Penta') {
+		console.error('input model is not 3d');
+	}
 
-        for (var i = start; i < arglist.length; i++) {
-            args.push(arglist[i]);
-        }
+	//retrieve parameters from options.
+	var options      = new pairoptions(Array.prototype.slice.call(arguments, 1)); // slice to remove md
+	var vector2d     = options.getfieldvalue('vector');     //mandatory
+	var type         = options.getfieldvalue('type');       //mandatory
+	var layer        = options.getfieldvalue('layer',0);    //optional (do all layers default:)
+	var paddingvalue = options.getfieldvalue('padding',0);  //0 by default
 
-        return args;
-    }
+	if (Number.isNaN(vector2d) || vector2d === 0 || vector2d.length === 1) { // NaN treated as length 1 in MATLAB
+		projected_vector=vector2d;
+	} else if (type.toLowerCase() === 'node') {
+		//Initialize 3d vector
+		if (vector2d.length===md.mesh.numberofvertices2d) {
+			projected_vector=NewArrayFill(md.mesh.numberofvertices,paddingvalue);
+		} else if (vector2d.length===md.mesh.numberofvertices2d+1) {
+			projected_vector=NewArrayFill(md.mesh.numberofvertices+1,paddingvalue);
+			projected_vector[projected_vector.length-1] = vector2d[vector2d.length-1];
+			vector2d.pop();
+		} else {
+			console.error('vector length not supported')
+		}
 
-    if (arguments.length===1 || arguments.length===0) {
-        //help project3d
-        console.error('project3d bad usage');
-    }
+		//Fill in
+		if (layer===0) {
+			for (var i = 1; i <= md.mesh.numberoflayers; ++i) {
+				for (var j = (i-1)*md.mesh.numberofvertices2d, k = 0; j < i*md.mesh.numberofvertices2d; j++, k++) {
+					projected_vector[j] = vector2d[k];
+				}
+			}
+		} else {
+			for (var j = (layer-1)*md.mesh.numberofvertices2d, k = 0; j < layer*md.mesh.numberofvertices2d; j++, k++) {
+				projected_vector[j] = vector2d[k];
+			}
+		}
+	} else if (type.toLowerCase() === 'element') {
+		//Initialize 3d vector
+		//var vector2d_size2 = Array.isArray(vector2d[0]) ? vector2d[0].length : 1; //get size of vector2d's 2nd axis
+		if (vector2d.length===md.mesh.numberofelements2d) {
+			projected_vector=NewArrayFill(md.mesh.numberofelements,paddingvalue);
+		} else if (vector2d.length===md.mesh.numberofelements2d+1) {
+			projected_vector=NewArrayFill(md.mesh.numberofelements+1,paddingvalue);
+			projected_vector[projected_vector.length-1] = vector2d[vector2d.length-1];
+			vector2d.pop();
+		} else {
+			console.error('vector length not supported')
+		}
 
-    var md = arguments[0];
+		//Fill in
+		if (layer===0) {
+			for (var i = 1; i <= md.mesh.numberoflayers-1; ++i) {
+				for (var j = (i-1)*md.mesh.numberofelements2d, k = 0; j < i*md.mesh.numberofelements2d; j++, k++) {
+					projected_vector[j] = vector2d[k];
+				}
+			}
+		} else {
+			for (var j = (layer-1)*md.mesh.numberofelements2d, k = 0; j < layer*md.mesh.numberofelements2d; j++, k++) {
+				projected_vector[j] = vector2d[k];
+			}
+		}
+	} else {
+		console.error('project3d error message: unknown projection type');
+	}
 
-    if (md.mesh.elementtype() !== 'Penta') {
-        console.error('input model is not 3d');
-    }
-
-    //retrieve parameters from options.
-    options      = new pairoptions(remove_first_n(1, arguments)); // slice to remove md
-    vector2d     = options.getfieldvalue('vector');     //mandatory
-    type         = options.getfieldvalue('type');       //mandatory
-    layer        = options.getfieldvalue('layer',0);    //optional (do all layers default:)
-    paddingvalue = options.getfieldvalue('padding',0);  //0 by default
-
-    if (isNaN(vector2d) || vector2d === 0 || vector2d.length === 1) { // NaN treated as length 1 in MATLAB
-        projected_vector=vector2d;
-    } else if (type.toLowerCase() === 'node') {
-
-        //Initialize 3d vector
-        if (vector2d.length===md.mesh.numberofvertices2d) {
-                projected_vector=ones(md.mesh.numberofvertices,  vector2d[0].length).map(function(arr) { return arr.fill(paddingvalue); });
-        } else if (vector2d.length===md.mesh.numberofvertices2d+1) {
-            projected_vector=ones(md.mesh.numberofvertices+1,vector2d[0].length).map(function(arr) { return arr.fill(paddingvalue); });
-            projected_vector[projected_vector.length-1] = projected_vector[projected_vector.length-1].map(function(element, index) { return vector2d[vector2d.length-1][index]; });
-            vector2d.pop(); // Remove last array
-        } else {
-            console.error('vector length not supported')
-        }
-
-            //Fill in
-        if (layer===0) {
-            for (var i = 1; i < md.mesh.numberoflayers; ++i) {
-                var vec_idx = 0;
-
-                for (var j = (i-1)*md.mesh.numberofvertices2d+1, vec_idx = 0; j <= i * md.mesh.numberofvertices2d && vec_idx < vector2d.length; ++j, ++vec_idx) {
-                    projected_vector[j].map(function(element, index) { return vector2d[vec_idx][index]; });
-                }
-
-            }
-        } else {
-            var vec_idx = 0;
-
-            for (var i = (layer-1)*md.mesh.numberofvertices2d+1, vec_idx = 0; i <= layer * md.mesh.numberofvertices2d && vec_idx < vector2d.length; ++i, ++vec_idx) {
-                projected_vector[i] = vector2d[vec_idx];
-            }
-        }
-    } else if (type.toLowerCase() === 'element') {
-            //Initialize 3d vector
-        if (vector2d.length===md.mesh.numberofelements2d) {
-                projected_vector = ones(md.mesh.numberofelements,  vector2d[0].length).map(function(arr) { return arr.fill(paddingvalue); });
-        } else if (vector2d.length===md.mesh.numberofelements2d+1) {
-            projected_vector = ones(md.mesh.numberofelements+1,  vector2d[0].length).map(function(arr) { return arr.fill(paddingvalue); });
-
-            projected_vector[projected_vector.length-1].map(function(element, index) { return vector2d[vector2d.length-1][index]; });
-
-            vector2d.pop();
-        } else {
-            console.error('vector length not supported')
-        }
-
-            //Fill in
-        if (layer===0) {
-            for (var i = 1; i < md.mesh.numberoflayers-1; ++i) {
-                var vec_idx=0;
-                for (var j = (i-1)*md.mesh.numberofelements2d+1, vec_idx = 0; j <= i * md.mesh.numberofelements2d && vec_idx < vector2d.length; ++j, ++vec_idx) {
-                    projected_vector[j].map(function(element, index) { return vector2d[vec_idx][index]; });
-                }
-            }
-        } else {
-            var vec_idx=0;
-            for (var i = (layer-1)*md.mesh.numberofelements2d+1, vec_idx = 0; i <= layer * md.mesh.numberofelements2d && vec_idx < vector2d.length; ++i, ++vec_idx) {
-                projected_vector[i].map(function(element, index) { return vector2d[vec_idx][index]; });
-            }
-        }
-    } else {
-        console.error('project3d error message: unknown projection type');
-    }
-
-    return projected_vector;
+	return projected_vector;
 };
Index: /issm/trunk/src/m/geometry/NowickiProfile.py
===================================================================
--- /issm/trunk/src/m/geometry/NowickiProfile.py	(revision 22758)
+++ /issm/trunk/src/m/geometry/NowickiProfile.py	(revision 22758)
@@ -0,0 +1,44 @@
+import numpy as np
+
+def NowickiProfile(x):
+	"""
+	NOWICKIPROFILE - Create profile at the transition zone based on Sophie Nowicki's thesis
+
+	Usage:
+		[b h] = NowickiProfile(x)
+
+		- h = ice thickness
+		- b = ice base
+		- x = along flow coordinate
+	"""
+	#Constant for theoretical profile
+	delta = 0.1		#ratio of water density and ice density -1
+	hg    = 1.		#ice thickness at grounding line
+	sea   = hg / (1+delta)	#sea level
+	lamda = 0.1		#ration of deviatoric stress and water pressure
+	beta  = 5.		#friction coefficient
+	ms    = 0.005		#surface accumulation rat
+	mu    = 5.		#viscosity
+	q     = 0.801		#ice mass flux
+
+	#mesh parameters
+	b = np.zeros((np.size(x),))
+	h = np.zeros((np.size(x),))
+	s = np.zeros((np.size(x),))
+
+	#upstream of the GL
+	for i in range(np.size(x) / 2):
+		ss = np.roots([1, 4 * lamda * beta, 0, 0, 6 * lamda * ms * x[i]**2 +
+				12 * lamda * q * x[i] - hg**4 - 4 * lamda * beta * hg**3])
+		for j in range(4):
+			if (np.isreal(ss[j]) > 0) and (np.imag(ss[j]) == 0):
+				s[i] = ss[j]
+		h[i] = s[i]
+		b[i] = 0.
+
+	#downstream of the GL
+	for i in range(np.size(x) / 2, np.size(x)):
+		h[i] = (x[i] / (4. * (delta+1) * q) + hg**(-2))**(-0.5) # ice thickness for ice shelf from (3.1)
+		b[i] = sea - h[i] * (1. / (1+delta))
+
+	return [b, h, sea]
Index: sm/trunk/src/m/geometry/ThicknessCorrection.m
===================================================================
--- /issm/trunk/src/m/geometry/ThicknessCorrection.m	(revision 22757)
+++ 	(revision )
@@ -1,77 +1,0 @@
-function md=ThicknessCorrection(md,varargin)
-%THICKNESSCORRECTION - correct the thickness of the ice shelf near the grounding line
-%
-%   This routine corrects the thickness and the bed on the transition zone
-%   by forcing the hydrostatic equilibrium.
-%   the thickness is modified as follows:
-%      thickness = (1-coeff) * thickness_observation + coeff * thickness_hydrostatic
-%   where:
-%      coeff=(d/distance)^2;
-%      distance=10km by default but can be specified
-%
-%   Usage:
-%      md=ThicknessCorrection(md,varargin);
-%
-%   Example:
-%      md=ThicknessCorrection(md);
-%      md=ThicknessCorrection(md,15000);
-
-%initialize thickness with the observations, and get hydrostatic thickness from the dem
-thickness=md.geometry.thickness;
-thickness_hydro=md.geometry.surface/(1-md.materials.rho_ice/md.materials.rho_water);
-hydrostatic_ratio=zeros(size(md.geometry.thickness));
-
-%get nodes on ice sheet and on ice shelf
-pos_shelf=find(md.mask.groundedice_levelset<0.);
-pos_GL=intersect(unique(md.mesh.elements(find(md.mask.elementongroundedice),:)),unique(md.mesh.elements(find(md.mask.elementonfloatingice),:)));
-debug=(length(pos_shelf)>50000);
-
-%check that there is a GL
-if isempty(pos_GL)
-	error('ThicknessCorrection error message: no grounding line has been detected. Check the model mask');
-end
-
-%get distance
-if nargin==2,
-	distance=varargin{1};
-else
-	distance=10000;
-end
-
-%modify thickness
-if (debug), fprintf('%s','      correction progress:   0.00 %'); end
-for i=1:length(pos_shelf)
-
-	if (debug & mod(i,100)==0),
-		fprintf('\b\b\b\b\b\b\b%5.2f%s',i/length(pos_shelf)*100,' %');
-	end
-
-	%search the node on ice sheet the closest to i
-	[d posd]=min(sqrt((md.mesh.x(pos_shelf(i))-md.mesh.x(pos_GL)).^2+(md.mesh.y(pos_shelf(i))-md.mesh.y(pos_GL)).^2));
-
-	if d>distance,
-
-		%if d > 15km, hydrostatic equilibrium
-		hydrostatic_ratio(pos_shelf(i))=1;
-		thickness(pos_shelf(i))=thickness_hydro(pos_shelf(i));
-
-	else
-
-		%else: quadratic combination of hydrostatic equilibrium and observations
-		hydrostatic_ratio(pos_shelf(i))=(d/distance)^2;
-		thickness(pos_shelf(i))=(1-hydrostatic_ratio(pos_shelf(i)))*thickness(pos_shelf(i))+hydrostatic_ratio(pos_shelf(i))*thickness_hydro(pos_shelf(i));
-
-	end
-end
-if (debug), fprintf('\b\b\b\b\b\b\b%5.2f%s\n',100,' %'); end
-
-%check the computed thickness
-minth=1/(1-md.materials.rho_ice/md.materials.rho_water);
-pos=find(isnan(thickness) | (thickness<=0));
-thickness(pos)=minth;
-hydrostatic_ratio(pos)=-1;
-
-%change bed to take into account the changes in thickness
-md.geometry.thickness=thickness;
-md.geometry.hydrostatic_ratio=hydrostatic_ratio;
-md.geometry.base=md.geometry.surface-md.geometry.thickness;
Index: /issm/trunk/src/m/geometry/VolumeAboveFloatation.m
===================================================================
--- /issm/trunk/src/m/geometry/VolumeAboveFloatation.m	(revision 22758)
+++ /issm/trunk/src/m/geometry/VolumeAboveFloatation.m	(revision 22758)
@@ -0,0 +1,39 @@
+function V = VolumeAboveFloatation(md)
+%VOLUMEABOVEFLOATATION - returns volume above floatation
+%
+%   Usage:
+%      V = VolumeAboveFloatation(md)
+
+%Special case if 3d
+if isa(md.mesh,'mesh3dprisms')
+	index = md.mesh.elements2d;
+	x = md.mesh.x2d;
+	y = md.mesh.y2d;
+elseif isa(md.mesh,'mesh2d'),
+	index = md.mesh.elements;
+	x = md.mesh.x;
+	y = md.mesh.y;
+else
+	error('not supported yet');
+end
+%1. get some parameters
+rho_ice   = md.materials.rho_ice;
+rho_water = md.materials.rho_water;
+
+%2. compute averages
+base        = mean(md.geometry.base(index),2);
+surface     = mean(md.geometry.surface(index),2);
+bathymetry  = mean(md.geometry.bed(index),2);
+
+%3. get areas of all triangles
+areas = GetAreas(index,x,y);
+
+%4. Compute volume above floatation
+V = areas.*(surface-base+min(rho_water/rho_ice*bathymetry,0.));
+
+%5. take out the ones that are outside of levelset or floating
+pos = find(min(md.mask.ice_levelset(index),[],2)>0 | min(md.mask.groundedice_levelset(index),[],2)<0);
+V(pos) = 0;
+
+%sum individual contributions
+V = sum(V);
Index: /issm/trunk/src/m/geometry/slope.py
===================================================================
--- /issm/trunk/src/m/geometry/slope.py	(revision 22757)
+++ /issm/trunk/src/m/geometry/slope.py	(revision 22758)
@@ -34,6 +34,6 @@
 
 	summation=np.array([[1],[1],[1]])
-	sx=np.dot(surf[index-1]*alpha,summation).reshape(-1,)
-	sy=np.dot(surf[index-1]*beta,summation).reshape(-1,)
+	sx=np.dot(surf[index-1,0]*alpha,summation).reshape(-1,)
+	sy=np.dot(surf[index-1,0]*beta,summation).reshape(-1,)
 
 	s=np.sqrt(sx**2+sy**2)
Index: /issm/trunk/src/m/kml/kmlimagesc.m
===================================================================
--- /issm/trunk/src/m/kml/kmlimagesc.m	(revision 22757)
+++ /issm/trunk/src/m/kml/kmlimagesc.m	(revision 22758)
@@ -46,9 +46,9 @@
 
 %figure out nlines and ncols in our image
-nlines=(maxlat-minlat)/posting;
-ncols=(maxlong-minlong)/posting;
+x_m = minlong:posting:maxlong;
+y_m = minlat:posting:maxlat;
 
 %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=InterpFromMeshToGrid(md.mesh.elements,md.mesh.long,md.mesh.lat,field,x_m,y_m,NaN);
 field=flipud(field);
 
Index: /issm/trunk/src/m/mech/basalstress.m
===================================================================
--- /issm/trunk/src/m/mech/basalstress.m	(revision 22757)
+++ /issm/trunk/src/m/mech/basalstress.m	(revision 22758)
@@ -19,5 +19,5 @@
 
 %compute basal drag
-bx=(md.constants.g*(md.materials.rho_ice*md.geometry.thickness+md.materials.rho_water*md.geometry.base)).^r.*(md.friction.coefficient).^2.*ubx.^s;
-by=(md.constants.g*(md.materials.rho_ice*md.geometry.thickness+md.materials.rho_water*md.geometry.base)).^r.*(md.friction.coefficient).^2.*uby.^s;
-b=(md.constants.g*(md.materials.rho_ice*md.geometry.thickness+md.materials.rho_water*md.geometry.base)).^r.*(md.friction.coefficient).^2.*ub.^s;
+bx = - (md.constants.g*(md.materials.rho_ice*md.geometry.thickness+md.materials.rho_water*md.geometry.base)).^r.*(md.friction.coefficient).^2.*ubx.^s;
+by = - (md.constants.g*(md.materials.rho_ice*md.geometry.thickness+md.materials.rho_water*md.geometry.base)).^r.*(md.friction.coefficient).^2.*uby.^s;
+b  = sqrt(bx.^2+by.^2);
Index: /issm/trunk/src/m/mech/calcbackstress.m
===================================================================
--- /issm/trunk/src/m/mech/calcbackstress.m	(revision 22757)
+++ /issm/trunk/src/m/mech/calcbackstress.m	(revision 22758)
@@ -56,5 +56,6 @@
 	D=md.damage.D
 else
-	D=0.
+	D=0;
+end
 
 [a0,b0,theta0,ex0]=thomasparams(md,'eq','Thomas','smoothing',smoothing,'coordsys',coordsys);
Index: /issm/trunk/src/m/mech/mechanicalproperties.m
===================================================================
--- /issm/trunk/src/m/mech/mechanicalproperties.m	(revision 22757)
+++ /issm/trunk/src/m/mech/mechanicalproperties.m	(revision 22758)
@@ -111,16 +111,4 @@
 %plug onto the model
 %NB: Matlab sorts the eigen value in increasing order, we want the reverse
-%NOTE: all stresses below are deviatoric
-stress=struct('xx',[],'yy',[],'xy',[],'principalvalue1',[],'principalaxis1',[],'principalvalue2',[],'principalaxis2',[],'effectivevalue',[]);
-stress.xx=tau_xx;
-stress.yy=tau_yy;
-stress.xy=tau_xy;
-stress.principalvalue1=valuesstress(:,1);
-stress.principalaxis1=directionsstress(:,1:2);
-stress.principalvalue2=valuesstress(:,2);
-stress.principalaxis2=directionsstress(:,3:4);
-stress.effectivevalue=1/sqrt(2)*sqrt(stress.xx.^2+stress.yy.^2+2*stress.xy.^2); % effective shear stress (sqrt(J2))
-md.results.stress=stress;
-
 strainrate=struct('xx',[],'yy',[],'xy',[],'principalvalue1',[],'principalaxis1',[],'principalvalue2',[],'principalaxis2',[],'effectivevalue',[]);
 strainrate.xx=ux*md.constants.yts; %strain rate in 1/a instead of 1/s
Index: /issm/trunk/src/m/mech/mechanicalproperties.py
===================================================================
--- /issm/trunk/src/m/mech/mechanicalproperties.py	(revision 22757)
+++ /issm/trunk/src/m/mech/mechanicalproperties.py	(revision 22758)
@@ -125,14 +125,4 @@
 	##plug onto the model
 	##NB: Matlab sorts the eigen value in increasing order, we want the reverse
-	stress=results()
-	stress.xx=tau_xx
-	stress.yy=tau_yy
-	stress.xy=tau_xy
-	stress.principalvalue1=valuesstress[:,0]
-	stress.principalaxis1=directionsstress[:,0:2]
-	stress.principalvalue2=valuesstress[:,1]
-	stress.principalaxis2=directionsstress[:,2:4]
-	stress.effectivevalue=1./np.sqrt(2.)*np.sqrt(stress.xx**2+stress.yy**2+2.*stress.xy**2)
-	md.results.stress=stress
 	
 	strainrate=results()
Index: /issm/trunk/src/m/mech/newforcing.py
===================================================================
--- /issm/trunk/src/m/mech/newforcing.py	(revision 22758)
+++ /issm/trunk/src/m/mech/newforcing.py	(revision 22758)
@@ -0,0 +1,34 @@
+import numpy as np
+
+def newforcing(t0,t1,deltaT,f0,f1,nodes):
+	'''
+FUNCTION NEWFORCING Build forcing that extends temporally from t0 to t1, and in magnitude from f0 to f1. Equal time 
+                    and magnitude spacing. 
+
+       Usage: forcing=newforcing(t0,t1,deltaT,f0,f1,nodes);  
+       Where: 
+          t0:t1: time interval. 
+          deltaT: time step
+          f0:f1: magnitude interval.
+          nodes: number of vertices where we have a temporal forcing
+
+       Example: 
+           md.smb.mass_balance=newforcing(md.timestepping.start_time,md.timestepping.final_time,
+                                          md.timestepping.time_step,-1,+2,md.mesh.numberofvertices)
+	'''
+	#Number of time steps: 
+	nsteps = (t1 - t0) / deltaT + 1
+
+	#delta forcing:
+	deltaf = (f1 - f0) / (nsteps - 1)
+
+	#creates times:
+	times = np.arange(t0,t1+deltaT,deltaT)	#Add deltaT to fix python/matlab discrepency
+
+	#create forcing:
+	forcing = np.arange(f0,f1+deltaf,deltaf)#Add deltaf to fix python/matlab discrepency
+
+	#replicate for all nodes
+	forcing = np.tile(forcing, (nodes+1,1))
+	forcing[-1,:] = times
+	return forcing
Index: /issm/trunk/src/m/mesh/argusmesh.m
===================================================================
--- /issm/trunk/src/m/mesh/argusmesh.m	(revision 22757)
+++ /issm/trunk/src/m/mesh/argusmesh.m	(revision 22758)
@@ -9,5 +9,5 @@
 %
 %   Example:
-%     md=argusmesh(md,'TriMesh.exp')
+%     md=argusmesh(md,'Domain.exp')
 
 %some argument check: 
Index: /issm/trunk/src/m/mesh/bamg.m
===================================================================
--- /issm/trunk/src/m/mesh/bamg.m	(revision 22757)
+++ /issm/trunk/src/m/mesh/bamg.m	(revision 22758)
@@ -5,4 +5,8 @@
 %
 %   - domain :            followed by an ARGUS file that prescribes the domain outline
+%   - holes :             followed by an ARGUS file that prescribes the holes
+%   - subdomains :        followed by an ARGUS file that prescribes the list of
+%                         subdomains (that need to be inside domain)
+%
 %   - hmin :              minimum edge length (default is 10^-100)
 %   - hmax :              maximum edge length (default is 10^100)
@@ -22,11 +26,11 @@
 %                         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)
+%   - NoBoundaryRefinment: do not refine boundary, only follow contour provided (default 0)
 %   - 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)
+%   - Metrictype :        0 -> absolute error          c/(err coeff^2) * Abs(H)        (default)
+%                         1 -> relative error          c/(err coeff^2) * Abs(H)/max(s,cutoff*max(s))
+%                         2 -> 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)
@@ -34,5 +38,4 @@
 %   - 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)
 %
@@ -59,4 +62,6 @@
 bamg_mesh=bamgmesh();
 
+subdomain_ref = 1;
+hole_ref = 1;
 % Bamg Geometry parameters {{{
 if exist(options,'domain'),
@@ -82,4 +87,47 @@
 	end
 
+	holes = [];
+	if exist(options,'holes'),
+		holesfile=getfieldvalue(options,'holes');
+		if ischar(holesfile),
+			if ~exist(holesfile,'file') error(['bamg error message: file ' holesfile ' not found']); end
+
+			%read holes according to its extension: 
+			[path,name,ext]=fileparts(holesfile);
+			if strcmp(ext,'.exp'),
+				holes=expread(holesfile);
+			elseif strcmp(ext,'.shp'),
+				holes=shpread(holesfile);
+			else
+				error(['bamg error message: file ' holesfile ' format not supported (.shp or .exp)']);
+			end
+		elseif isstruct(holesfile),
+			holes = holesfile;
+		else
+			error('''holes'' type not supported yet');
+		end
+	end
+	subdomains = [];
+	if exist(options,'subdomains'),
+		subdomainsfile=getfieldvalue(options,'subdomains');
+		if ischar(subdomainsfile),
+			if ~exist(subdomainsfile,'file') error(['bamg error message: file ' subdomainsfile ' not found']); end
+
+			%read subdomains according to its extension: 
+			[path,name,ext]=fileparts(subdomainsfile);
+			if strcmp(ext,'.exp'),
+				subdomains=expread(subdomainsfile);
+			elseif strcmp(ext,'.shp'),
+				subdomains=shpread(subdomainsfile);
+			else
+				error(['bamg error message: file ' subdomainsfile ' format not supported (.shp or .exp)']);
+			end
+		elseif isstruct(subdomainsfile),
+			subdomains = subdomainsfile;
+		else
+			error('''subdomains'' type not supported yet');
+		end
+	end
+
 	%Build geometry 
 	count=0;
@@ -99,9 +147,74 @@
 		end
 
+		%Check orientation
+		nods=domain(i).nods-1; %the domain are closed 1=end;
+		test = sum([(domain(i).x(2:nods+1) - domain(i).x(1:nods)).*(domain(i).y(2:nods+1) + domain(i).y(1:nods))]);
+		if (i==1 && test>0) || (i>1 && test<0),
+			disp('At least one contour was not correctly oriented and has been re-oriented');
+			domain(i).x = flipud(domain(i).x); domain(i).y = flipud(domain(i).y);
+		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 -subdomain_ref]; subdomain_ref = subdomain_ref+1;
+		else
+			bamg_geometry.SubDomains=[bamg_geometry.SubDomains; 2 count+1 1 0];
+		end
+
+		%update counter
+		count=count+nods;
+	end
+	for i=1:length(holes),
+
+		%Check that the subdomains is closed
+		if (holes(i).x(1)~=holes(i).x(end) | holes(i).y(1)~=holes(i).y(end)),
+			error('bamg error message: all contours provided in ''holes'' should be closed');
+		end
+
+		%Checks that all holes are INSIDE the principle domain outline
+		flags=ContourToNodes(holes(i).x,holes(i).y,domain(1),0);
+		if any(~flags), error('bamg error message: All holes should be strictly inside the principal domain'); end
+
+		%Check that hole is correctly oriented
+		nods=holes(i).nods-1; %the holes are closed 1=end;
+		if(sum([(holes(i).x(2:nods+1) - holes(i).x(1:nods)).*(holes(i).y(2:nods+1) + holes(i).y(1:nods))]))<0
+			disp('At least one hole was not correctly oriented and has been re-oriented');
+			holes(i).x = flipud(holes(i).x); holes(i).y = flipud(holes(i).y);
+		end
+
+		%Add all points to bamg_geometry
+		bamg_geometry.Vertices=[bamg_geometry.Vertices; [holes(i).x(1:nods) holes(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
+		bamg_geometry.SubDomains=[bamg_geometry.SubDomains; 2 count+1 1 -hole_ref]; hole_ref = hole_ref+1;
+
+		%update counter
+		count=count+nods;
+	end
+	for i=1:length(subdomains),
+
+		%Check that the subdomains is closed
+		if (subdomains(i).x(1)~=subdomains(i).x(end) | subdomains(i).y(1)~=subdomains(i).y(end)),
+			error('bamg error message: all contours provided in ''subdomains'' should be closed');
+		end
+
+		%Checks that all holes are INSIDE the principle domain outline
+		flags=ContourToNodes(subdomains(i).x,subdomains(i).y,domain(1),0);
+		if any(~flags),
+			error('bamg error message: All holes should be strictly inside the principal domain');
+		end
+
+		%Check that hole is correctly oriented
+		nods=subdomains(i).nods-1; %the subdomains are closed 1=end;
+		if(sum([(subdomains(i).x(2:nods+1) - subdomains(i).x(1:nods)).*(subdomains(i).y(2:nods+1) + subdomains(i).y(1:nods))]))>0
+			disp('At least one subdomain was not correctly oriented and has been re-oriented');
+			subdomains(i).x = flipud(subdomains(i).x); subdomains(i).y = flipud(subdomains(i).y);
+		end
+
+		%Add all points to bamg_geometry
+		bamg_geometry.Vertices=[bamg_geometry.Vertices; [subdomains(i).x(1:nods) subdomains(i).y(1:nods) ones(nods,1)]];
+		bamg_geometry.Edges   =[bamg_geometry.Edges;    [transpose(count+1:count+nods) transpose([count+2:count+nods count+1])  1.*ones(nods,1)]];
+		bamg_geometry.SubDomains=[bamg_geometry.SubDomains; 2 count+1 1 subdomain_ref]; subdomain_ref = subdomain_ref+1;
 
 		%update counter
@@ -288,4 +401,9 @@
 		count=count+nods;
 
+	end
+
+	%Deal with RequiredEdges
+	if getfieldvalue(options,'NoBoundaryRefinment',0)==1,
+		bamg_geometry.RequiredEdges=[1:size(bamg_geometry.Edges,1)]';
 	end
 
@@ -330,5 +448,4 @@
 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.);
@@ -340,6 +457,4 @@
 bamg_options.power=getfieldvalue(options,'power',1.);
 bamg_options.splitcorners=getfieldvalue(options,'splitcorners',1);
-bamg_options.geometricalmetric=getfieldvalue(options,'geometricalmetric',0);
-bamg_options.random=getfieldvalue(options,'rand',true);
 bamg_options.verbose=getfieldvalue(options,'verbose',1);
 %}}}
@@ -408,5 +523,5 @@
 %Check for orphan
 if any(~ismember(1:md.mesh.numberofvertices,sort(unique(reshape(md.mesh.elements,3*md.mesh.numberofelements,1)))))
-	error('Output mesh has orphans. Decrease MaxCornerAngle to prevent outside points (ex: 0.01)');
+	error('Output mesh has orphans. Check your Domain and/or RequiredVertices');
 end
 end 
Index: /issm/trunk/src/m/mesh/bamg.py
===================================================================
--- /issm/trunk/src/m/mesh/bamg.py	(revision 22757)
+++ /issm/trunk/src/m/mesh/bamg.py	(revision 22758)
@@ -1,5 +1,7 @@
 import os.path
 import numpy as  np
-from mesh2d import mesh2d
+from mesh2d import *
+from mesh2dvertical import *
+from mesh3dsurface import *
 from collections import OrderedDict
 from pairoptions import pairoptions
@@ -20,4 +22,8 @@
 
 	   - domain :            followed by an ARGUS file that prescribes the domain outline
+	   - holes :             followed by an ARGUS file that prescribes the holes
+     - subdomains :        followed by an ARGUS file that prescribes the list of
+	                         subdomains (that need to be inside domain)
+
 	   - hmin :              minimum edge length (default is 10^-100)
 	   - hmax :              maximum edge length (default is 10^100)
@@ -37,5 +43,4 @@
 	                         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)
@@ -49,5 +54,4 @@
 	   - 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)
 
@@ -74,26 +78,40 @@
 	bamg_mesh=bamgmesh()
 
+	subdomain_ref = 1
+	hole_ref = 1
+
 	# Bamg Geometry parameters {{{
 	if options.exist('domain'):
-
 		#Check that file exists
 		domainfile=options.getfieldvalue('domain')
-		if not os.path.exists(domainfile):
-			raise IOError("bamg error message: file '%s' not found" % domainfile)
-		domain=expread(domainfile)
+		if type(domainfile) == str:
+			if not os.path.exists(domainfile):
+				raise IOError("bamg error message: file '%s' not found" % domainfile)
+			domain=expread(domainfile)
+		else:
+			domain=domainfile
 
 		#Build geometry 
 		count=0
 		for i,domaini in enumerate(domain):
-
 			#Check that the domain is closed
 			if (domaini['x'][0]!=domaini['x'][-1] or domaini['y'][0]!=domaini['y'][-1]):
 				raise RuntimeError("bamg error message: all contours provided in ''domain'' should be closed")
 
-			#Checks that all holes are INSIDE the principle domain outline
+			#Checks that all holes are INSIDE the principle domain outline princial domain should be index 0
 			if i:
 				flags=ContourToNodes(domaini['x'],domaini['y'],domainfile,0)[0]
 				if np.any(np.logical_not(flags)):
 					raise RuntimeError("bamg error message: All holes should be strictly inside the principal domain")
+
+			#Check orientation
+			nods=domaini['nods']-1#the domain are closed 1=end;
+
+			test = np.sum((domaini['x'][1:nods+1] - domaini['x'][0:nods])*(domaini['y'][1:nods+1] + domaini['y'][0:nods]))
+			if (i==0 and test>0) or (i>0 and test<0):
+				print('At least one contour was not correctly oriented and has been re-oriented')
+				domaini['x'] = np.flipud(domaini['x'])
+				domaini['y'] = np.flipud(domaini['y'])
+
 
 			#Add all points to bamg_geometry
@@ -102,13 +120,91 @@
 			bamg_geometry.Edges   =np.vstack((bamg_geometry.Edges,np.vstack((np.arange(count+1,count+nods+1),np.hstack((np.arange(count+2,count+nods+1),count+1)),1.*np.ones((nods)))).T))
 			if i:
-				bamg_geometry.SubDomains=np.vstack((bamg_geometry.SubDomains,[2,count+1,1,1]))
-
-			# bamg_geometry.Vertices=np.hstack((bamg_geometry.Vertices,np.vstack((domaini['x'][0:nods].reshape(-1),domaini['y'][0:nods].reshape(-1),np.ones((nods))))))
-			# bamg_geometry.Edges   =np.vstack((bamg_geometry.Edges,np.hstack((np.arange(count+1,count+nods+1).reshape(-1,),np.hstack((np.arange(count+2,count+nods+1),count+1)).reshape(-1,),1.*np.ones((nods,))))))
-			# if i:
-			# 	bamg_geometry.SubDomains=np.vstack((bamg_geometry.SubDomains,[2,count+1,1,1]))
-
+				bamg_geometry.SubDomains=np.vstack((bamg_geometry.SubDomains,[2,count+1,1,-subdomain_ref]))
+				subdomain_ref = subdomain_ref+1;
+			else:
+				bamg_geometry.SubDomains=np.vstack((bamg_geometry.SubDomains,[2,count+1,1,0]))
+			
 			#update counter
 			count+=nods
+
+		#Deal with domain holes
+		if options.exist('holes'):
+			holesfile=options.getfieldvalue('holes')
+			if type(holesfile) == str:
+				if not os.path.exists(holesfile):
+					raise IOError("bamg error message: file '%s' not found" % holesfile)
+				holes=expread(holesfile)
+			else:
+				holes=holesfile
+
+			#Build geometry 
+			for i,holei in enumerate(holes):
+				#Check that the hole is closed
+				if (holei['x'][0]!=holei['x'][-1] or holei['y'][0]!=holei['y'][-1]):
+					raise RuntimeError("bamg error message: all contours provided in ''hole'' should be closed")
+
+				#Checks that all holes are INSIDE the principle domain outline princial domain should be index 0
+				flags=ContourToNodes(holei['x'],holei['y'],domainfile,0)[0]
+				if np.any(np.logical_not(flags)):
+					raise RuntimeError("bamg error message: All holes should be strictly inside the principal domain")
+
+				#Check orientation
+				nods=holei['nods']-1#the hole are closed 1=end;
+				test = np.sum((holei['x'][1:nods+1] - holei['x'][0:nods])*(holei['y'][1:nods+1] + holei['y'][0:nods]))
+				if test<0:
+					print('At least one hole was not correctly oriented and has been re-oriented')
+					holei['x'] = np.flipud(holei['x'])
+					holei['y'] = np.flipud(holei['y'])
+
+				#Add all points to bamg_geometry
+				nods=holei['nods']-1    #the hole are closed 0=end
+				bamg_geometry.Vertices=np.vstack((bamg_geometry.Vertices,np.vstack((holei['x'][0:nods],holei['y'][0:nods],np.ones((nods)))).T))
+				bamg_geometry.Edges   =np.vstack((bamg_geometry.Edges,np.vstack((np.arange(count+1,count+nods+1),np.hstack((np.arange(count+2,count+nods+1),count+1)),1.*np.ones((nods)))).T))
+				#update counter
+				count+=nods
+
+		#And subdomains
+		if options.exist('subdomains'):
+			subdomainfile=options.getfieldvalue('subdomains')
+			if type(subdomainfile) == str:
+				if not os.path.exists(subdomainfile):
+					raise IOError("bamg error message: file '%s' not found" % subdomainfile)
+				subdomains=expread(subdomainfile)
+			else:
+				subdomains=subdomainfile
+
+			#Build geometry 
+			for i,subdomaini in enumerate(subdomains):
+				#Check that the subdomain is closed
+				if (subdomaini['x'][0]!=subdomaini['x'][-1] or subdomaini['y'][0]!=subdomaini['y'][-1]):
+					raise RuntimeError("bamg error message: all contours provided in ''subdomain'' should be closed")
+
+				#Checks that all subdomains are INSIDE the principle subdomain outline princial domain should be index 0
+				if i:
+					flags=ContourToNodes(subdomaini['x'],subdomaini['y'],domainfile,0)[0]
+					if np.any(np.logical_not(flags)):
+						raise RuntimeError("bamg error message: All subdomains should be strictly inside the principal subdomain")
+
+				#Check orientation
+				nods=subdomaini['nods']-1#the subdomain are closed 1=end;
+
+				test = np.sum((subdomaini['x'][1:nods+1] - subdomaini['x'][0:nods])*(subdomaini['y'][1:nods+1] + subdomaini['y'][0:nods]))
+				if test>0:
+					print('At least one subcontour was not correctly oriented and has been re-oriented')
+					subdomaini['x'] = np.flipud(subdomaini['x'])
+					subdomaini['y'] = np.flipud(subdomaini['y'])
+
+				#Add all points to bamg_geometry
+				nods=subdomaini['nods']-1    #the subdomain are closed 0=end
+				bamg_geometry.Vertices=np.vstack((bamg_geometry.Vertices,np.vstack((subdomaini['x'][0:nods],subdomaini['y'][0:nods],np.ones((nods)))).T))
+				bamg_geometry.Edges   =np.vstack((bamg_geometry.Edges,np.vstack((np.arange(count+1,count+nods+1),np.hstack((np.arange(count+2,count+nods+1),count+1)),1.*np.ones((nods)))).T))
+				#update counter
+				count+=nods
+			
+		if options.getfieldvalue('vertical',0):
+			if np.size(options.getfieldvalue('Markers',[]))!=np.size(bamg_geometry.Edges,0):
+				raise RuntimeError('for 2d vertical mesh, ''Markers'' option is required, and should be of size ' + str(np.size(bamg_geometry.Edges,0)))
+			if np.size(options.getfieldvalue('Markers',[]))==np.size(bamg_geometry.Edges,0):
+				bamg_geometry.Edges[:,2]=options.getfieldvalue('Markers')
 
 		#take care of rifts
@@ -303,5 +399,4 @@
 	bamg_options['hVertices']=options.getfieldvalue('hVertices',np.empty((0,1)))
 	bamg_options['KeepVertices']=options.getfieldvalue('KeepVertices',1)
-	bamg_options['MaxCornerAngle']=options.getfieldvalue('MaxCornerAngle',10.)
 	bamg_options['maxnbv']=options.getfieldvalue('maxnbv',10**6)
 	bamg_options['maxsubdiv']=options.getfieldvalue('maxsubdiv',10.)
@@ -313,6 +408,4 @@
 	bamg_options['power']=options.getfieldvalue('power',1.)
 	bamg_options['splitcorners']=options.getfieldvalue('splitcorners',1)
-	bamg_options['geometricalmetric']=options.getfieldvalue('geometricalmetric',0)
-	bamg_options['random']=options.getfieldvalue('rand',True)
 	bamg_options['verbose']=options.getfieldvalue('verbose',1)
 	#}}}
@@ -322,21 +415,62 @@
 
 	# plug results onto model
+	if options.getfieldvalue('vertical',0):
+		md.mesh=mesh2dvertical()
+		md.mesh.x=bamgmesh_out['Vertices'][:,0].copy()
+		md.mesh.y=bamgmesh_out['Vertices'][:,1].copy()
+		md.mesh.elements=bamgmesh_out['Triangles'][:,0:3].astype(int)
+		md.mesh.edges=bamgmesh_out['IssmEdges'].astype(int)
+		md.mesh.segments=bamgmesh_out['IssmSegments'][:,0:3].astype(int)
+		md.mesh.segmentmarkers=bamgmesh_out['IssmSegments'][:,3].astype(int)
+
+		#Fill in rest of fields:
+		md.mesh.numberofelements=np.size(md.mesh.elements,axis=0)
+		md.mesh.numberofvertices=np.size(md.mesh.x)
+		md.mesh.numberofedges=np.size(md.mesh.edges,axis=0)
+		md.mesh.vertexonboundary=np.zeros(md.mesh.numberofvertices,bool)
+		md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1]=True
+
+		#Now, build the connectivity tables for this mesh. Doubled in matlab for some reason
+		md.mesh.vertexonboundary=np.zeros(md.mesh.numberofvertices,)
+		md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1]=1
+
+	elif options.getfieldvalue('3dsurface',0):
+		md.mesh=mesh3dsurface()
+		md.mesh.x=bamgmesh_out['Vertices'][:,0].copy()
+		md.mesh.y=bamgmesh_out['Vertices'][:,1].copy()
+		md.mesh.z=md.mesh.x
+		md.mesh.z[:]=0
+		md.mesh.elements=bamgmesh_out['Triangles'][:,0:3].astype(int)
+		md.mesh.edges=bamgmesh_out['IssmEdges'].astype(int)
+		md.mesh.segments=bamgmesh_out['IssmSegments'][:,0:3].astype(int)
+		md.mesh.segmentmarkers=bamgmesh_out['IssmSegments'][:,3].astype(int)
+
+		#Fill in rest of fields:
+		md.mesh.numberofelements=np.size(md.mesh.elements,axis=0)
+		md.mesh.numberofvertices=np.size(md.mesh.x)
+		md.mesh.numberofedges=np.size(md.mesh.edges,axis=0)
+		md.mesh.vertexonboundary=np.zeros(md.mesh.numberofvertices,bool)
+		md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1]=True
+
+	else:
+		md.mesh=mesh2d()
+		md.mesh.x=bamgmesh_out['Vertices'][:,0].copy()
+		md.mesh.y=bamgmesh_out['Vertices'][:,1].copy()
+		md.mesh.elements=bamgmesh_out['Triangles'][:,0:3].astype(int)
+		md.mesh.edges=bamgmesh_out['IssmEdges'].astype(int)
+		md.mesh.segments=bamgmesh_out['IssmSegments'][:,0:3].astype(int)
+		md.mesh.segmentmarkers=bamgmesh_out['IssmSegments'][:,3].astype(int)
+
+		#Fill in rest of fields:
+		md.mesh.numberofelements=np.size(md.mesh.elements,axis=0)
+		md.mesh.numberofvertices=np.size(md.mesh.x)
+		md.mesh.numberofedges=np.size(md.mesh.edges,axis=0)
+		md.mesh.vertexonboundary=np.zeros(md.mesh.numberofvertices,bool)
+		md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1]=True
+
+	#Bamg private fields
 	md.private.bamg=OrderedDict()
 	md.private.bamg['mesh']=bamgmesh(bamgmesh_out)
 	md.private.bamg['geometry']=bamggeom(bamggeom_out)
-	md.mesh = mesh2d()
-	md.mesh.x=bamgmesh_out['Vertices'][:,0].copy()
-	md.mesh.y=bamgmesh_out['Vertices'][:,1].copy()
-	md.mesh.elements=bamgmesh_out['Triangles'][:,0:3].astype(int)
-	md.mesh.edges=bamgmesh_out['IssmEdges'].astype(int)
-	md.mesh.segments=bamgmesh_out['IssmSegments'][:,0:3].astype(int)
-	md.mesh.segmentmarkers=bamgmesh_out['IssmSegments'][:,3].astype(int)
-
-	#Fill in rest of fields:
-	md.mesh.numberofelements=np.size(md.mesh.elements,axis=0)
-	md.mesh.numberofvertices=np.size(md.mesh.x)
-	md.mesh.numberofedges=np.size(md.mesh.edges,axis=0)
-	md.mesh.vertexonboundary=np.zeros(md.mesh.numberofvertices,bool)
-	md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1]=True
 	md.mesh.elementconnectivity=md.private.bamg['mesh'].ElementConnectivity
 	md.mesh.elementconnectivity[np.nonzero(np.isnan(md.mesh.elementconnectivity))]=0
@@ -345,5 +479,5 @@
 	#Check for orphan
 	if np.any(np.logical_not(np.in1d(np.arange(1,md.mesh.numberofvertices+1),md.mesh.elements.flat))):
-		raise RuntimeError("Output mesh has orphans. Decrease MaxCornerAngle to prevent outside points (ex: 0.01)")
+		raise RuntimeError("Output mesh has orphans. Check your Domain and/or RequiredVertices")
 
 	return md
Index: /issm/trunk/src/m/mesh/bamgflowband.py
===================================================================
--- /issm/trunk/src/m/mesh/bamgflowband.py	(revision 22758)
+++ /issm/trunk/src/m/mesh/bamgflowband.py	(revision 22758)
@@ -0,0 +1,47 @@
+import numpy as  np
+from model import *
+from collections import OrderedDict
+from bamg import *
+from mesh2dvertical import *
+
+def bamgflowband(md,x,surf,base,*args):
+	"""
+	BAMGFLOWBAND - create flowband mesh with bamg
+
+	Usage:
+		md=bamgflowband(md,x,surf,base,OPTIONS)
+
+		surf and bed are the surface elevation and base for each x provided
+		x must be increasing
+		OPTIONS are bamg options
+
+	Example:
+		x =np.arrange(1,3001,100)
+		h=linspace(1000,300,numel(x))
+		b=-917/1023*h
+		md=bamgflowband(model,b+h,b,'hmax',80,'vertical',1,'Markers',m)
+	"""
+
+	#Write expfile with domain outline
+	A = OrderedDict()
+	A['x'] = np.concatenate((x,np.flipud(x),[x[0]]))
+	A['y'] = np.concatenate((base,np.flipud(surf),[base[0]]))
+	A['nods'] = np.size(A['x'])
+
+	#markers:
+	m                          	= np.ones((np.size(A['x'])-1,))	# base        = 1
+	m[np.size(x) - 1]                	= 2			# right side  = 2
+	m[np.size(x):2 * np.size(x) - 1] 	= 3			# top surface = 3
+	m[2 * np.size(x) - 1]              	= 4			# left side   = 4
+
+	#mesh domain
+	md = bamg(model(),'domain',[A],'vertical',1,'Markers',m,*args)
+	#print md.mesh.numberofvertices
+
+	#Deal with vertices on bed
+	md.mesh.vertexonbase = np.zeros((md.mesh.numberofvertices,))
+	md.mesh.vertexonbase[np.where(md.mesh.vertexflags(1))] = 1
+	md.mesh.vertexonsurface = np.zeros((md.mesh.numberofvertices,))
+	md.mesh.vertexonsurface[np.where(md.mesh.vertexflags(3))] = 1
+
+	return md
Index: /issm/trunk/src/m/mesh/rifts/meshprocessrifts.m
===================================================================
--- /issm/trunk/src/m/mesh/rifts/meshprocessrifts.m	(revision 22757)
+++ /issm/trunk/src/m/mesh/rifts/meshprocessrifts.m	(revision 22758)
@@ -25,7 +25,7 @@
 
 %Call MEX file
-[md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers,md.rifts.riftstruct]=TriMeshProcessRifts(md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers);
+[md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers,md.rifts.riftstruct]=ProcessRifts(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');
+	error('ProcessRifts did not find any rift');
 end
 
Index: /issm/trunk/src/m/mesh/rifts/meshprocessrifts.py
===================================================================
--- /issm/trunk/src/m/mesh/rifts/meshprocessrifts.py	(revision 22757)
+++ /issm/trunk/src/m/mesh/rifts/meshprocessrifts.py	(revision 22758)
@@ -1,4 +1,4 @@
 import numpy as np
-from TriMeshProcessRifts import TriMeshProcessRifts
+from ProcessRifts import ProcessRifts
 from ContourToMesh import ContourToMesh
 from meshprocessoutsiderifts import meshprocessoutsiderifts
@@ -22,5 +22,5 @@
 
 	#Call MEX file
-	md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers,md.rifts.riftstruct=TriMeshProcessRifts(md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers)
+	md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers,md.rifts.riftstruct=ProcessRifts(md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers)
 	md.mesh.elements=md.mesh.elements.astype(int)
 	md.mesh.x=md.mesh.x.reshape(-1)
@@ -29,5 +29,5 @@
 	md.mesh.segmentmarkers=md.mesh.segmentmarkers.astype(int)
 	if not isinstance(md.rifts.riftstruct,list) or not md.rifts.riftstruct:
-		raise RuntimeError("TriMeshProcessRifts did not find any rift")
+		raise RuntimeError("ProcessRifts did not find any rift")
 
 	#Fill in rest of fields:
Index: /issm/trunk/src/m/mesh/roundmesh.m
===================================================================
--- /issm/trunk/src/m/mesh/roundmesh.m	(revision 22757)
+++ /issm/trunk/src/m/mesh/roundmesh.m	(revision 22758)
@@ -10,18 +10,18 @@
 
 %First we have to create the domain outline 
+expname = [tempname() '.exp'];
 
 %Get number of points on the circle
-pointsonedge=floor((2.*pi*radius) / resolution);
+pointsonedge=floor((2.*pi*radius) / resolution)+1; %+1 to close the outline
 
 %Calculate the cartesians coordinates of the points
-x_list=ones(pointsonedge,1); y_list=ones(pointsonedge,1);
-theta=(0.:2.*pi/pointsonedge:2.*pi*(1.-1./pointsonedge))';
-x_list=roundsigfig(radius*x_list.*cos(theta),12);
-y_list=roundsigfig(radius*y_list.*sin(theta),12);
+theta=linspace(0,2*pi,pointsonedge)';
+x_list=roundsigfig(radius*cos(theta),12);
+y_list=roundsigfig(radius*sin(theta),12);
 A=struct('x',x_list,'y',y_list,'density',1.);
-expwrite(A,'RoundDomainOutline.exp');
+expwrite(A,expname);
 
 %Call Bamg
-md=triangle(md,'RoundDomainOutline.exp',resolution);
+md=triangle(md,expname,resolution);
 %md=bamg(md,'domain','RoundDomainOutline.exp','hmin',resolution);
 
@@ -32,5 +32,5 @@
 
 %delete domain
-delete('RoundDomainOutline.exp')
+delete(expname);
 end
 
Index: /issm/trunk/src/m/mesh/roundmesh.py
===================================================================
--- /issm/trunk/src/m/mesh/roundmesh.py	(revision 22757)
+++ /issm/trunk/src/m/mesh/roundmesh.py	(revision 22758)
@@ -20,12 +20,10 @@
 
 	#Get number of points on the circle
-	pointsonedge=np.floor((2.*np.pi*radius) / resolution)
+	pointsonedge=np.floor((2.*np.pi*radius) / resolution)+1 #+1 to close the outline
 
 	#Calculate the cartesians coordinates of the points
-	x_list=np.ones(pointsonedge)
-	y_list=np.ones(pointsonedge)
-	theta=np.linspace(0.,2.*np.pi,num=pointsonedge,endpoint=False)
-	x_list=roundsigfig(radius*x_list*np.cos(theta),12)
-	y_list=roundsigfig(radius*y_list*np.sin(theta),12)
+	theta=np.linspace(0.,2.*np.pi,pointsonedge)
+	x_list=roundsigfig(radius*np.cos(theta),12)
+	y_list=roundsigfig(radius*np.sin(theta),12)
 	A=OrderedDict()
 	A['x']=[x_list]
Index: /issm/trunk/src/m/mesh/squaremesh.m
===================================================================
--- /issm/trunk/src/m/mesh/squaremesh.m	(revision 22757)
+++ /issm/trunk/src/m/mesh/squaremesh.m	(revision 22758)
@@ -1,3 +1,3 @@
-function md=squaremesh(md,Lx,Ly,nx,ny)
+function md=squaremesh(md,Lx,Ly,nx,ny,computeconnectivity)
 %SQUAREMESH - create a structured square mesh 
 %
@@ -10,36 +10,71 @@
 %      [md]=squaremesh(md,Lx,Ly,nx,ny)
 
+%process options
+if nargin == 5,
+	computeconnectivity = 1;
+end
+
 %get number of elements and number of nodes
 nel=(nx-1)*(ny-1)*2;
 nods=nx*ny;
 
-%initialization
-index=zeros(nel,3);
-x=zeros(nx*ny,1);
-y=zeros(nx*ny,1);
+%Old method
+if 0,
+	%initialization
+	index=zeros(nel,3);
+	x=zeros(nx*ny,1);
+	y=zeros(nx*ny,1);
 
-%create coordinates
-for n=1:nx,
-	for m=1:ny,
-		x((n-1)*ny+m)=(n-1.);
-		y((n-1)*ny+m)=(m-1.);
+	%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;
+else
+	%New method (faster!)
+	x = repmat(linspace(0,Lx,nx),[ny 1]);
+	x = reshape(x,[nx*ny 1]);
+	y = repmat(linspace(0,Ly,ny)',[1 nx]);
+	y = reshape(y,[nx*ny 1]);
+
+	%do first column of elements first
+	nels1 = 2*(ny-1);
+	index = ones(nels1,3);
+	%First column
+	index(2:2:nels1,1) = 2:ny;
+	index(3:2:nels1,1) = 2:ny-1;
+	%2d column
+	index(1:2:nels1,2) = ny+1:2*ny-1;
+	index(2:2:nels1,2) = ny+1:2*ny-1;
+	%3rd column
+	index(1:2:nels1,3) = 2:ny;
+	index(2:2:nels1,3) = ny+2:2*ny;
+
+	%Now copy column and offset with ny, nx times
+	index = repmat(index,[nx-1 1]);
+	offset = repmat([0:ny:(nx-2)*ny],[nels1 1]);
+	offset = reshape(offset,[(nx-1)*nels1,1]);
+	offset = repmat(offset,[1,3]);
+	index = index + offset;
 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
@@ -67,4 +102,6 @@
 
 %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);
+if computeconnectivity,
+	md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+	md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+end
Index: /issm/trunk/src/m/mesh/triangle.js
===================================================================
--- /issm/trunk/src/m/mesh/triangle.js	(revision 22757)
+++ /issm/trunk/src/m/mesh/triangle.js	(revision 22758)
@@ -2,5 +2,5 @@
 //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
+//   This routine creates a model mesh using Triangle 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
@@ -36,5 +36,5 @@
 
 	//Call mesher: 
-	var return_array=TriMesh(md, domain, rifts, area); 
+	var return_array=Triangle(md, domain, rifts, area); 
 
 	//Plug into md:
Index: /issm/trunk/src/m/mesh/triangle.m
===================================================================
--- /issm/trunk/src/m/mesh/triangle.m	(revision 22757)
+++ /issm/trunk/src/m/mesh/triangle.m	(revision 22758)
@@ -2,5 +2,5 @@
 %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
+%   This routine creates a model mesh using Triangle 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
@@ -42,6 +42,6 @@
 end
 
-%Mesh using TriMesh
-[elements,x,y,segments,segmentmarkers]=TriMesh(domainname,riftname,area);
+%Mesh using Triangle
+[elements,x,y,segments,segmentmarkers]=Triangle(domainname,riftname,area);
 
 %check that all the created nodes belong to at least one element
Index: /issm/trunk/src/m/mesh/triangle.py
===================================================================
--- /issm/trunk/src/m/mesh/triangle.py	(revision 22757)
+++ /issm/trunk/src/m/mesh/triangle.py	(revision 22758)
@@ -2,5 +2,5 @@
 import numpy as np
 from mesh2d import mesh2d
-from TriMesh import TriMesh
+from Triangle import Triangle
 from NodeConnectivity import NodeConnectivity
 from ElementConnectivity import ElementConnectivity
@@ -11,5 +11,5 @@
 	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
+	   This routine creates a model mesh using Triangle 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
@@ -48,7 +48,7 @@
 		raise IOError("file '%s' not found" % domainname)
 
-	#Mesh using TriMesh
+	#Mesh using Triangle
 	md.mesh=mesh2d()
-	md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers=TriMesh(domainname,riftname,area)
+	md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers=Triangle(domainname,riftname,area)
 	md.mesh.elements=md.mesh.elements.astype(int)
 	md.mesh.segments=md.mesh.segments.astype(int)
Index: /issm/trunk/src/m/mesh/triangle2dvertical.m
===================================================================
--- /issm/trunk/src/m/mesh/triangle2dvertical.m	(revision 22757)
+++ /issm/trunk/src/m/mesh/triangle2dvertical.m	(revision 22758)
@@ -2,5 +2,5 @@
 %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
+%   This routine creates a model mesh using Triangle 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
@@ -24,6 +24,6 @@
 area=resolution^2;
 
-%Mesh using TriMesh
-[elements,x,z,segments,segmentmarkers]=TriMesh(domainname,'',area);
+%Mesh using Triangle
+[elements,x,z,segments,segmentmarkers]=Triangle(domainname,'',area);
 
 %check that all the created nodes belong to at least one element
Index: /issm/trunk/src/m/miscellaneous/colorbars.js
===================================================================
--- /issm/trunk/src/m/miscellaneous/colorbars.js	(revision 22757)
+++ /issm/trunk/src/m/miscellaneous/colorbars.js	(revision 22758)
@@ -48,19 +48,19 @@
 [1.000000,1.000000,0.750000],
 [1.000000,1.000000,1.000000]];
-colorbars["gray"]=[[0.000000,0.000000,0.000000],
-[0.066667,0.066667,0.066667],
-[0.133333,0.133333,0.133333],
-[0.200000,0.200000,0.200000],
-[0.266667,0.266667,0.266667],
-[0.333333,0.333333,0.333333],
-[0.400000,0.400000,0.400000],
+colorbars["gray"]=[[0.200000,0.200000,0.200000],
+[0.253333,0.253333,0.253333],
+[0.306667,0.306667,0.306667],
+[0.360000,0.360000,0.360000],
+[0.413333,0.413333,0.413333],
 [0.466667,0.466667,0.466667],
-[0.533333,0.533333,0.533333],
-[0.600000,0.600000,0.600000],
-[0.666667,0.666667,0.666667],
+[0.520000,0.520000,0.520000],
+[0.573333,0.573333,0.573333],
+[0.626667,0.626667,0.626667],
+[0.680000,0.680000,0.680000],
 [0.733333,0.733333,0.733333],
-[0.800000,0.800000,0.800000],
-[0.866667,0.866667,0.866667],
-[0.933333,0.933333,0.933333],
+[0.786667,0.786667,0.786667],
+[0.840000,0.840000,0.840000],
+[0.893333,0.893333,0.893333],
+[0.946667,0.946667,0.946667],
 [1.000000,1.000000,1.000000]];
 colorbars["bone"]=[[0.000000,0.000000,0.020833],
@@ -288,2 +288,35 @@
 [0.933333,0.966667,0.400000],
 [1.000000,1.000000,0.400000]];
+colorbars["land"]=[[0.000000,0.000000,0.500000],
+[0.160000,0.266700,0.766700],
+[0.326700,0.513400,1.000000],
+[0.540500,0.620200,1.000000],
+[0.521000,0.934200,0.521000],
+[0.200400,0.667000,0.200400],
+[0.120000,0.540000,0.040000],
+[0.440000,0.646700,0.146700],
+[0.573300,0.660000,0.186700],
+[0.520000,0.580000,0.160000],
+[0.466700,0.500000,0.133300],
+[0.413300,0.420000,0.106700],
+[0.360000,0.340000,0.080000],
+[0.306700,0.260000,0.053300],
+[0.253300,0.180000,0.026700],
+[0.200000,0.100000,0.000000]];
+colorbars["sea"]=[[0.000000,0.000000,0.2000],
+[0.000000,0.000000,0.2930],
+[0.000000,0.000000,0.3859],
+[0.000000,0.000000,0.4789],
+[0.000000,0.000000,0.5718],
+[0.000000,0.000000,0.6648],
+[0.000000,0.000000,0.7577],
+[0.000000,0.000000,0.8507],
+[0.000000,0.000000,0.9436],
+[0.000000,0.102400,1.0000],
+[0.000000,0.362700,1.0000],
+[0.000000,0.622900,1.0000],
+[0.093600,0.810400,1.0000],
+[0.386600,0.843000,1.0000],
+[0.679500,0.875500,1.0000],
+[0.800000,0.400000,0.4000]];
+
Index: /issm/trunk/src/m/miscellaneous/diagnostics.m
===================================================================
--- /issm/trunk/src/m/miscellaneous/diagnostics.m	(revision 22757)
+++ /issm/trunk/src/m/miscellaneous/diagnostics.m	(revision 22758)
@@ -46,9 +46,8 @@
 		yposting=getfieldvalue(options,'velposting',500);
 
-		xmin=min(md.mesh.x); ymax=max(md.mesh.y); 
-		ncols=(max(md.mesh.x)-min(md.mesh.x))/xposting+1;
-		nlines=(max(md.mesh.y)-min(md.mesh.y))/yposting+1;
+		xm=min(md.mesh.x):posting:max(md.mesh.x);
+		ym=min(md.mesh.y):posting:max(md.mesh.y);
 		
-		[xm,ym,vel]=InterpFromMeshToGrid(md.mesh.elements,md.mesh.x,md.mesh.y,vel,xmin,ymax,xposting,yposting,nlines,ncols,0);
+		vel=InterpFromMeshToGrid(md.mesh.elements,md.mesh.x,md.mesh.y,vel,xm,ym,0.);
 		vel=uint16(flipud(vel));
 
Index: /issm/trunk/src/m/miscellaneous/fielddisplay.m
===================================================================
--- /issm/trunk/src/m/miscellaneous/fielddisplay.m	(revision 22757)
+++ /issm/trunk/src/m/miscellaneous/fielddisplay.m	(revision 22758)
@@ -13,5 +13,5 @@
 end %function
 
-function parsedisplay(offset,name,field,comment) %{{{
+function parsedisplay(offset,name,field,comment) % {{{
 
 	%string
@@ -27,13 +27,16 @@
 	elseif isnumeric(field)
 
-		%get size
-		fieldsize=size(field);
-
 		%double
-		if max(fieldsize)==1,
+		if numel(field)==1,
 			displayunit(offset,name,num2str(field),comment),
 		%matrix
 		else
-			displayunit(offset,name,['(' num2str(fieldsize(1)) 'x' num2str(fieldsize(2)) ')'],comment),
+			fieldsize=size(field);
+			string = '(';
+			for i=1:numel(fieldsize)
+				string = [string num2str(fieldsize(i)) 'x' ];
+			end
+			string = [string(1:end-1) ')'];
+			displayunit(offset,name,string,comment),
 		end
 
Index: /issm/trunk/src/m/miscellaneous/transientrestart.m
===================================================================
--- /issm/trunk/src/m/miscellaneous/transientrestart.m	(revision 22757)
+++ /issm/trunk/src/m/miscellaneous/transientrestart.m	(revision 22758)
@@ -1,10 +1,21 @@
-function md = transientrestart(md)
+function md = transientrestart(md,step)
 %TRANSIENTRESTART - reinitialize model from last transient step
 %
 %   Usage:
 %      md = transientrestart(md)
+%      md = transientrestart(md,step)
+%
+%   By default, transientrestart will use the last step provided in md.results.TransientSolution
 
 %Get result and save it again
-results = md.results.TransientSolution(end);
+if nargin==1,
+	step = numel(md.results.TransientSolution);
+end
+if step<1,
+	error('step needs to be >0');
+elseif step>numel(md.results.TransientSolution)
+	error(['md.results.TransientSolution has only ' num2str(numel(md.results.TransientSolution)) ' steps']);
+end
+results = md.results.TransientSolution(step);
 
 newname = ['TransientSolution' num2str(numel(fields(md.results))+1)];
Index: /issm/trunk/src/m/modules/InterpFromMeshToGrid.m
===================================================================
--- /issm/trunk/src/m/modules/InterpFromMeshToGrid.m	(revision 22757)
+++ /issm/trunk/src/m/modules/InterpFromMeshToGrid.m	(revision 22758)
@@ -1,4 +1,7 @@
-function [x_m,y_m,griddata] = InterpFromMeshToGrid(index,x,y,data,xmin,ymax,xposting,yposting,nlines,ncols,default_value);
+function grid = InterpFromMeshToGrid(index,x,y,data,xgrid,ygrid,default_value);
 %INTERPFROMMESHTOGRID - Interpolation of a data defined on a mesh onto a grid
+%
+%   Usage:
+%      grid = InterpFromMeshToGrid(index,x,y,data,xgrid,ygrid,default_value)
 %
 %   This function is a multi-threaded mex file that interpolates a field defined on a triangular
@@ -8,9 +11,9 @@
 %   meshdata:	vertex values of data to be interpolated
 %
-%   xmin,ymax,posting,nlines,ncols: parameters that define the grid
-%   default_value:	value of points located out of the mesh
+%   xgrid,ygrid:   parameters that define the grid
+%   default_value: value of points located out of the mesh
 
 % Check usage
-if nargin~=11
+if nargin~=7
 	help InterpFromMeshToGrid
 	error('Wrong usage (see above)');
@@ -18,3 +21,3 @@
 
 % Call mex module
-[x_m,y_m,griddata] = InterpFromMeshToGrid_matlab(index,x,y,data,xmin,ymax,xposting,yposting,nlines,ncols,default_value);
+grid = InterpFromMeshToGrid_matlab(index,x,y,data,xgrid,ygrid,default_value);
Index: /issm/trunk/src/m/modules/InterpFromMeshToGrid.py
===================================================================
--- /issm/trunk/src/m/modules/InterpFromMeshToGrid.py	(revision 22757)
+++ /issm/trunk/src/m/modules/InterpFromMeshToGrid.py	(revision 22758)
@@ -1,5 +1,5 @@
 from InterpFromMeshToGrid_python import InterpFromMeshToGrid_python
 
-def InterpFromMeshToGrid(index,x,y,data,xmin,ymax,xposting,yposting,nlines,ncols,default_value):
+def InterpFromMeshToGrid(index,x,y,data,xgrid,ygrid,default_value):
 	"""
 	INTERPFROMMESHTOGRID - Interpolation of a data defined on a mesh onto a grid
@@ -11,9 +11,9 @@
 		meshdata:	vertex values of data to be interpolated
 
-		xmin,ymax,posting,nlines,ncols:	parameters that define the grid
+		xgrid,ygrid,:	parameters that define the grid
 		default_value:	value of points located out of the mesh
 	"""
 	# Call mex module
-	x_m,y_m,griddata=InterpFromMeshToGrid_python(index,x,y,data,xmin,ymax,xposting,yposting,nlines,ncols,default_value)
+	grid=InterpFromMeshToGrid_python(index,x,y,data,xgrid,ygrid,default_value)
 	# Return
-	return x_m,y_m,griddate
+	return grid
Index: /issm/trunk/src/m/modules/Kriging.m
===================================================================
--- /issm/trunk/src/m/modules/Kriging.m	(revision 22757)
+++ /issm/trunk/src/m/modules/Kriging.m	(revision 22758)
@@ -1,3 +1,3 @@
-function predictions = Kriging(x,y,observations,x_interp,y_interp,varargin);
+function [predictions errors]= Kriging(x,y,observations,x_interp,y_interp,varargin);
 %KRIGING - Linear predictor
 %   Usage: predictions = Kriging(x,y,observations,x_interp,y_interp,'options');
@@ -20,3 +20,3 @@
 
 % Call mex module
-predictions = Kriging_matlab(x,y,observations,x_interp,y_interp,varargin{:});
+[predictions errors]= Kriging_matlab(x,y,observations,x_interp,y_interp,varargin{:});
Index: /issm/trunk/src/m/modules/MeshPartition.m
===================================================================
--- /issm/trunk/src/m/modules/MeshPartition.m	(revision 22757)
+++ /issm/trunk/src/m/modules/MeshPartition.m	(revision 22758)
@@ -1,7 +1,7 @@
-function [element_partitioning, node_partitioning] = MeshPartition(md.mesh,numpartitions);
+function [element_partitioning, node_partitioning] = MeshPartition(md,numpartitions)
 %MESHPARTITION - Partition mesh according to the number of areas, using Metis library.
 %
 %	   Usage:
-%			[element_partitioning,node_partitioning]=MeshPartition(md.mesh,numpartitions)");
+%			[element_partitioning,node_partitioning]=MeshPartition(md,numpartitions)");
 %
 %	   element_partitioning: Vector of partitioning area numbers, for every element.
@@ -14,4 +14,24 @@
 end
 
+%Get mesh info from md.mesh
+numberofvertices = md.mesh.numberofvertices;
+numberofelements = md.mesh.numberofelements;
+elements         = md.mesh.elements;
+numberofelements2d = 0;
+numberofvertices2d = 0;
+numberoflayers     = 1;
+elements2d         = [];
+if isa(md.mesh,'mesh3dprisms')
+	elementtype = 'Penta';
+	numberofelements2d = md.mesh.numberofelements2d;
+	numberofvertices2d = md.mesh.numberofvertices2d;
+	numberoflayers     = md.mesh.numberoflayers;
+	elements2d         = md.mesh.elements2d;
+elseif isa(md.mesh,'mesh2d')
+	elementtype = 'Tria';
+elseif isa(md.mesh,'mesh2dvertical')
+	elementtype = 'Tria';
+end
+
 % Call mex module
-[element_partitioning, node_partitioning] = MeshPartition_matlab(md.mesh,numpartitions);
+[element_partitioning, node_partitioning] = MeshPartition_matlab(numberofvertices,elements,numberofvertices2d,elements2d,numberoflayers,meshelementtype,numpartitions);
Index: /issm/trunk/src/m/modules/ProcessRifts.m
===================================================================
--- /issm/trunk/src/m/modules/ProcessRifts.m	(revision 22758)
+++ /issm/trunk/src/m/modules/ProcessRifts.m	(revision 22758)
@@ -0,0 +1,17 @@
+function [index2,x2,y2,segments2,segmentmarkers2,rifts2] = ProcessRifts(index1,x1,y1,segments1,segmentmarkers1);
+%TRIMESHPROCESSRIFTS - Split a mesh where a rift (or fault) is present
+%
+%   Usage: 
+%      [index2,x2,y2,segments2,segmentmarkers2,rifts2]=ProcessRifts(index1,x1,y1,segments1,segmentmarkers1); 
+%   
+%   (index1,x1,y1,segments1,segmentmarkers1):	An initial triangulation.
+%   [index2,x2,y2,segments2,segmentmarkers2,rifts2]:	The resulting triangulation where rifts have been processed.
+
+% Check usage
+if nargin~=5 && nargout~=6
+	help ProcessRifts
+	error('Wrong usage (see above)');
+end
+
+% Call mex module
+[index2,x2,y2,segments2,segmentmarkers2,rifts2] = ProcessRifts_matlab(index1,x1,y1,segments1,segmentmarkers1);
Index: /issm/trunk/src/m/modules/ProcessRifts.py
===================================================================
--- /issm/trunk/src/m/modules/ProcessRifts.py	(revision 22758)
+++ /issm/trunk/src/m/modules/ProcessRifts.py	(revision 22758)
@@ -0,0 +1,16 @@
+from ProcessRifts_python import ProcessRifts_python
+
+def ProcessRifts(index1,x1,y1,segments1,segmentmarkers1):
+	"""
+	TRIMESHPROCESSRIFTS - Split a mesh where a rift (or fault) is present
+
+	   Usage: 
+		   [index2,x2,y2,segments2,segmentmarkers2,rifts2]=ProcessRifts(index1,x1,y1,segments1,segmentmarkers1);
+
+	   (index1,x1,y1,segments1,segmentmarkers1):	An initial triangulation.
+	   [index2,x2,y2,segments2,segmentmarkers2,rifts2]:	The resulting triangulation where rifts have been processed.
+	"""
+	# Call mex module
+	index2,x2,y2,segments2,segmentmarkers2,rifts2 = ProcessRifts_python(index1,x1,y1,segments1,segmentmarkers1)
+	# Return
+	return index2,x2,y2,segments2,segmentmarkers2,rifts2
Index: sm/trunk/src/m/modules/TriMesh.m
===================================================================
--- /issm/trunk/src/m/modules/TriMesh.m	(revision 22757)
+++ 	(revision )
@@ -1,21 +1,0 @@
-function [index,x,y,segments,segmentmarkers] = TriMesh(domainoutlinefilename,rifts,mesh_area);
-%TRIMESH - Mesh a domain using an .exp file
-%
-%   Usage: 
-%     [index,x,y,segments,segmentmarkers]=TriMesh(domainoutlinefilename,rifts,mesh_area);
-%	      
-%   index,x,y:	Defines a triangulation 
-%   segments:	Array made of exterior segments to the mesh domain outline 
-%   segmentmarkers:	Array flagging each segment
-%
-%   domainoutlinefilename:	Argus domain outline file
-%   mesh_area:	Maximum area desired for any element of the resulting mesh
-
-% Check usage
-if nargin~=3 && nargout~=5
-	help TriMesh
-	error('Wrong usage (see above)');
-end
-
-% Call mex module
-[index,x,y,segments,segmentmarkers]=TriMesh_matlab(domainoutlinefilename,rifts,mesh_area);
Index: sm/trunk/src/m/modules/TriMesh.py
===================================================================
--- /issm/trunk/src/m/modules/TriMesh.py	(revision 22757)
+++ 	(revision )
@@ -1,21 +1,0 @@
-from TriMesh_python import TriMesh_python
-
-def TriMesh(domainoutlinefilename,rifts,mesh_area):
-	"""
-	TRIMESH - Mesh a domain using an .exp file
-
-	   Usage: 
-			[index,x,y,segments,segmentmarkers]=TriMesh(domainoutlinefilename,rifts,mesh_area); 
-
-	   index,x,y: defines a triangulation 
-		segments: An array made of exterior segments to the mesh domain outline 
-		segmentmarkers: An array flagging each segment
-
-	   domainoutlinefilename: an Argus domain outline file
-		mesh_area: The maximum area desired for any element of the resulting mesh
-	"""
-	# Call mex module
-	index,x,y,segments,segmentmarkers=TriMesh_python(domainoutlinefilename,rifts,mesh_area)
-	# Return
-	return index,x,y,segments,segmentmarkers
-
Index: sm/trunk/src/m/modules/TriMeshProcessRifts.m
===================================================================
--- /issm/trunk/src/m/modules/TriMeshProcessRifts.m	(revision 22757)
+++ 	(revision )
@@ -1,17 +1,0 @@
-function [index2,x2,y2,segments2,segmentmarkers2,rifts2] = TriMeshProcessRifts(index1,x1,y1,segments1,segmentmarkers1);
-%TRIMESHPROCESSRIFTS - Split a mesh where a rift (or fault) is present
-%
-%   Usage: 
-%      [index2,x2,y2,segments2,segmentmarkers2,rifts2]=TriMeshProcessRifts(index1,x1,y1,segments1,segmentmarkers1); 
-%   
-%   (index1,x1,y1,segments1,segmentmarkers1):	An initial triangulation.
-%   [index2,x2,y2,segments2,segmentmarkers2,rifts2]:	The resulting triangulation where rifts have been processed.
-
-% Check usage
-if nargin~=5 && nargout~=6
-	help TriMeshProcessRifts
-	error('Wrong usage (see above)');
-end
-
-% Call mex module
-[index2,x2,y2,segments2,segmentmarkers2,rifts2] = TriMeshProcessRifts_matlab(index1,x1,y1,segments1,segmentmarkers1);
Index: sm/trunk/src/m/modules/TriMeshProcessRifts.py
===================================================================
--- /issm/trunk/src/m/modules/TriMeshProcessRifts.py	(revision 22757)
+++ 	(revision )
@@ -1,16 +1,0 @@
-from TriMeshProcessRifts_python import TriMeshProcessRifts_python
-
-def TriMeshProcessRifts(index1,x1,y1,segments1,segmentmarkers1):
-	"""
-	TRIMESHPROCESSRIFTS - Split a mesh where a rift (or fault) is present
-
-	   Usage: 
-		   [index2,x2,y2,segments2,segmentmarkers2,rifts2]=TriMeshProcessRifts(index1,x1,y1,segments1,segmentmarkers1);
-
-	   (index1,x1,y1,segments1,segmentmarkers1):	An initial triangulation.
-	   [index2,x2,y2,segments2,segmentmarkers2,rifts2]:	The resulting triangulation where rifts have been processed.
-	"""
-	# Call mex module
-	index2,x2,y2,segments2,segmentmarkers2,rifts2 = TriMeshProcessRifts_python(index1,x1,y1,segments1,segmentmarkers1)
-	# Return
-	return index2,x2,y2,segments2,segmentmarkers2,rifts2
Index: /issm/trunk/src/m/modules/Triangle.m
===================================================================
--- /issm/trunk/src/m/modules/Triangle.m	(revision 22758)
+++ /issm/trunk/src/m/modules/Triangle.m	(revision 22758)
@@ -0,0 +1,21 @@
+function [index,x,y,segments,segmentmarkers] = Triangle(domainoutlinefilename,rifts,mesh_area);
+%TRIMESH - Mesh a domain using an .exp file
+%
+%   Usage: 
+%     [index,x,y,segments,segmentmarkers]=Triangle(domainoutlinefilename,rifts,mesh_area);
+%	      
+%   index,x,y:	Defines a triangulation 
+%   segments:	Array made of exterior segments to the mesh domain outline 
+%   segmentmarkers:	Array flagging each segment
+%
+%   domainoutlinefilename:	Argus domain outline file
+%   mesh_area:	Maximum area desired for any element of the resulting mesh
+
+% Check usage
+if nargin~=3 && nargout~=5
+	help Triangle
+	error('Wrong usage (see above)');
+end
+
+% Call mex module
+[index,x,y,segments,segmentmarkers]=Triangle_matlab(domainoutlinefilename,rifts,mesh_area);
Index: /issm/trunk/src/m/modules/Triangle.py
===================================================================
--- /issm/trunk/src/m/modules/Triangle.py	(revision 22758)
+++ /issm/trunk/src/m/modules/Triangle.py	(revision 22758)
@@ -0,0 +1,21 @@
+from Triangle_python import Triangle_python
+
+def Triangle(domainoutlinefilename,rifts,mesh_area):
+	"""
+	TRIMESH - Mesh a domain using an .exp file
+
+	   Usage: 
+			[index,x,y,segments,segmentmarkers]=Triangle(domainoutlinefilename,rifts,mesh_area); 
+
+	   index,x,y: defines a triangulation 
+		segments: An array made of exterior segments to the mesh domain outline 
+		segmentmarkers: An array flagging each segment
+
+	   domainoutlinefilename: an Argus domain outline file
+		mesh_area: The maximum area desired for any element of the resulting mesh
+	"""
+	# Call mex module
+	index,x,y,segments,segmentmarkers=Triangle_python(domainoutlinefilename,rifts,mesh_area)
+	# Return
+	return index,x,y,segments,segmentmarkers
+
Index: /issm/trunk/src/m/os/issmdir.m
===================================================================
--- /issm/trunk/src/m/os/issmdir.m	(revision 22757)
+++ /issm/trunk/src/m/os/issmdir.m	(revision 22758)
@@ -7,15 +7,15 @@
 %Initialize output ISSM_DIR
 ISSM_DIR='';
-slash=filesep();
 
 %Get ISSM_DIR from function path (we do not want to force users to edit their bashrc)
-path=which('issmdir');
+path = mfilename('fullpath');
 
 %issmdir might be in bin,
-pos=strfind(path,['bin' slash 'issmdir.m']);
+slash = filesep();
+pos   = strfind(path,['bin' slash 'issmdir']);
 if ~isempty(pos),
 	ISSM_DIR=path(1:pos-1);
 else
-	pos=strfind(path,['src' slash 'm' slash 'os' slash 'issmdir.m']);
+	pos=strfind(path,['src' slash 'm' slash 'os' slash 'issmdir']);
 	if ~isempty(pos),
 		ISSM_DIR=path(1:pos-1);
Index: /issm/trunk/src/m/os/oshostname.m
===================================================================
--- /issm/trunk/src/m/os/oshostname.m	(revision 22757)
+++ /issm/trunk/src/m/os/oshostname.m	(revision 22758)
@@ -5,10 +5,21 @@
 %      hostname=oshostname();
 
-%See http://www.mathworks.com/help/matlab/ref/system.html "tips" section
-%We need to add < /dev/null otherwise what is in the clipboard is added
-[status,hostname]=system('hostname < /dev/null');
+%Initialize output
+hostname = '';
 
-% If that command did not work, we have an alternative
-if status~=0,
+%First try using java (most stable way)
+if usejava('jvm'),
+	hostname = char(getHostName(java.net.InetAddress.getLocalHost));
+end
+
+%Method 2: use system command (MATLAB bug includes what's in the clipboard)
+if isempty(hostname),
+	%See http://www.mathworks.com/help/matlab/ref/system.html "tips" section
+	%We need to add < /dev/null otherwise what is in the clipboard is added
+	[status,hostname]=system('hostname < /dev/null');
+end
+
+%Method 3, last chance
+if isempty(hostname),
 	if ispc
 		hostname = getenv('COMPUTERNAME');
Index: /issm/trunk/src/m/parameterization/reinitializelevelset.m
===================================================================
--- /issm/trunk/src/m/parameterization/reinitializelevelset.m	(revision 22758)
+++ /issm/trunk/src/m/parameterization/reinitializelevelset.m	(revision 22758)
@@ -0,0 +1,16 @@
+function levelsetnew = reinitializelevelset(md,levelset)
+%REINITIALIZELEVELSET - reinitialize levelset as a signed distance function
+%
+%   Usage:
+%      levelsetnew = reinitializelevelset(md,levelset)
+
+
+%First: extract segments
+contours=contourlevelzero(md,levelset,0);
+
+%Now, make this a distance field (might not be closed)
+levelsetnew=abs(ExpToLevelSet(md.mesh.x,md.mesh.y,contours));
+
+%Finally, change sign
+pos = find(levelset<0);
+levelsetnew(pos) = -levelsetnew(pos);
Index: /issm/trunk/src/m/parameterization/setmask.py
===================================================================
--- /issm/trunk/src/m/parameterization/setmask.py	(revision 22757)
+++ /issm/trunk/src/m/parameterization/setmask.py	(revision 22758)
@@ -23,5 +23,4 @@
 	"""
 	#some checks on list of arguments
-	print type(md)
 	if not isinstance(md,model):
 		raise TypeError("setmask error message")
Index: /issm/trunk/src/m/partition/partitioner.m
===================================================================
--- /issm/trunk/src/m/partition/partitioner.m	(revision 22757)
+++ /issm/trunk/src/m/partition/partitioner.m	(revision 22758)
@@ -41,4 +41,5 @@
 	md.qmu.vertex_weight=[];
 	md.mesh.vertexconnectivity=[];
+	recomputeadjacency='on';
 end
 
@@ -80,16 +81,23 @@
 	if strcmpi(getfieldvalue(options,'weighting'),'on'),
 		weights=floor(md.qmu.vertex_weight/min(md.qmu.vertex_weight));
+	else
+		weights=[];
 	end
 	maptab=Scotch(md.qmu.adjacency,[],weights,[],'cmplt',[npart]);
 
-	part=maptab(:,2);%index partitions from 1 up. like metis.
+	part=maptab(:,2)+1;%index partitions from 1 up. like metis.
 
 elseif strcmpi(package,'linear'),
 
-	part=1:1:md.mesh.numberofvertices;
+	if npart==md.mesh.numberofelements | md.qmu.numberofpartitions==md.mesh.numberofelements
+		part=1:1:md.mesh.numberofelements;
+		disp('Linear partitioner requesting partitions on elements');
+	else
+		part=1:1:md.mesh.numberofvertices;
+	end
 
 elseif strcmpi(package,'metis'),
 
-	[element_partitioning,part]=MeshPartition(md.mesh,md.qmu.numberofpartitions);
+	[element_partitioning,part]=MeshPartition(md,md.qmu.numberofpartitions);
 
 else
Index: /issm/trunk/src/m/plot/applyoptions.js
===================================================================
--- /issm/trunk/src/m/plot/applyoptions.js	(revision 22757)
+++ /issm/trunk/src/m/plot/applyoptions.js	(revision 22758)
@@ -1,3 +1,3 @@
-function applyoptions(md, data, datatype, options, canvas, gl, node){ //{{{
+function applyoptions(md, data, options, canvas){ //{{{
 	//APPLYOPTIONS - apply colobar, text, cloud, and expdisp options to current plot
 	//
@@ -6,34 +6,48 @@
 	//
 	//   See also: PLOTMODEL, PARSE_OPTIONS
-	
+
 	//{{{ colorbar
+	var gl = canvas.gl;
 	if (options.exist('colorbar')) {
 		if (options.getfieldvalue('colorbar')==1) {
-			//{{{ Handle movie data
-			if (datatype == 5) {
-				data = data[0];
-			} //}}}
 			//{{{ Variable options initialization
-			var caxis = options.getfieldvalue('caxis',[ArrayMin(data), ArrayMax(data)]);
+			var caxis = options.getfieldvalue('caxis');
 			var colorbarinnerlabels = options.getfieldvalue('colorbarinnerlabels','off');
 			var ccanvasid, ctitleid, clabelsid, ccanvas, ctitle, clabels, ccontext, cmap, colorbar, cwidth, cheight, cgradient, color, y, x;
 			//}}}
-			//{{{ Create colorbar labels 
+			//{{{ Create colorbar labels
 			var labels = [];
 			var cdivisions = options.getfieldvalue('colorbarnticks', 6);
 			var caxisdelta = caxis[1] - caxis[0];
 			var precision = options.getfieldvalue('colorbarprecision', 3);
+			var format = options.getfieldvalue('colorbarformat', 'f').toLowerCase();
 			if (options.getfieldvalue('log','off')!='off') {
 				for (var i=cdivisions; i >= 0; i--) {
 					var scale = (Math.log10(caxis[1])-Math.log10(caxis[0]))/Math.log10(options.getfieldvalue('log', 10));
-					labels[i] = (Math.pow(options.getfieldvalue('log', 10), Math.log10(caxis[0])/Math.log10(options.getfieldvalue('log', 10))+scale*(cdivisions-i)/cdivisions)).toFixed(precision);
+					if (format === 'f') {
+						labels[i] = (Math.pow(options.getfieldvalue('log', 10), Math.log10(caxis[0])/Math.log10(options.getfieldvalue('log', 10))+scale*(cdivisions-i)/cdivisions)).toFixed(precision);
+					}
+					else if (format === 'e') {
+						labels[i] = (Math.pow(options.getfieldvalue('log', 10), Math.log10(caxis[0])/Math.log10(options.getfieldvalue('log', 10))+scale*(cdivisions-i)/cdivisions)).toPrecision(precision);
+					}
+					else {
+						labels[i] = (Math.pow(options.getfieldvalue('log', 10), Math.log10(caxis[0])/Math.log10(options.getfieldvalue('log', 10))+scale*(cdivisions-i)/cdivisions)).toFixed(precision);
+					}
 				}
 			} else {
 				for (var i=cdivisions; i >= 0; i--) {
-					labels[i] = (caxisdelta*(cdivisions-i)/cdivisions+caxis[0]).toFixed(precision);
+					if (format === 'f') {
+						labels[i] = (caxisdelta*(cdivisions-i)/cdivisions+caxis[0]).toFixed(precision);
+					}
+					else if (format === 'e') {
+						labels[i] = (caxisdelta*(cdivisions-i)/cdivisions+caxis[0]).toPrecision(precision);
+					}
+					else {
+						labels[i] = (caxisdelta*(cdivisions-i)/cdivisions+caxis[0]).toFixed(precision);
+					}
 				}
 			} //}}}
 			//{{{ Initialize colorbar canvas
-			ccanvasid = options.getfieldvalue('colorbarid', options.getfieldvalue('canvasid').replace('canvas','colorbar-canvas'));			
+			ccanvasid = options.getfieldvalue('colorbarid', options.getfieldvalue('canvasid').replace('canvas','colorbar-canvas'));
 			ccanvas = $('#'+ccanvasid)[0];
 			cwidth = ccanvas.width*options.getfieldvalue('colorbarwidth', 1);
@@ -47,8 +61,12 @@
 			//}}}
 			//{{{ Draw colorbar gradient
+			var position;
+			var offset = 1 / (colorbar.length - 1) / 2;
+			var scaling = 1 - 2 * offset;
 			for (var i=0; i < colorbar.length; i++) {
 				color = colorbar[colorbar.length-i-1];
-				color = [Math.round(color[0]*255), Math.round(color[1]*255), Math.round(color[2]*255)];	
-				cgradient.addColorStop(i/colorbar.length*(cdivisions/(cdivisions+1.0))+(1.0/(cdivisions+1.0)),'rgba('+color.toString()+', 1.0)');
+				color = [Math.round(color[0]*255), Math.round(color[1]*255), Math.round(color[2]*255)];
+				position = (i / (colorbar.length - 1) * scaling) + offset;
+				cgradient.addColorStop(position, 'rgba(' + color.toString() + ', 1.0)');
 			}
 			ccontext.fillStyle=cgradient;
@@ -93,5 +111,5 @@
 			if (options.exist('colorbartitle')) { ctitle.html(options.getfieldvalue('colorbartitle')); }
 			//}}}
-		} 
+		}
 	} //}}}
 	//{{{ texture canvas
@@ -105,267 +123,80 @@
 	tcontext = tcanvas.getContext('2d');
 	tgradient = tcontext.createLinearGradient(0, 0, 0, 256);
-		
+	
 	var cmap = options.getfieldvalue('colormap','jet');
 	var colorbar = colorbars[cmap];
-	for (var i=0; i < colorbar.length; i++) {
-		color = colorbar[colorbar.length-i-1];
-		color = [Math.round(color[0]*255), Math.round(color[1]*255), Math.round(color[2]*255)];	
-		tgradient.addColorStop(i/colorbar.length,'rgba('+color.toString()+', 1.0)');
+	for (var i = 0; i < colorbar.length; i++) {
+		color = colorbar[colorbar.length - i - 1];
+		color = [Math.round(color[0] * 255), Math.round(color[1] * 255), Math.round(color[2] * 255)];
+		tgradient.addColorStop(i / (colorbar.length - 1), 'rgba(' + color.toString() + ', 1.0)');
+	}
+	tcontext.fillStyle = tgradient;
+	tcontext.fillRect(0, 0, 256, 256);
+	
+	//Allow for special texture colors, drawing each color in equal width vertical rectangles. The last rectanglar section is reserved for the colormap.
+	if (options.exist('maskregion')) {
+		var maskObject = options.getfieldvalue('maskregion',{'enabled':false});
+		if (maskObject.enabled && !VESL.Helpers.isEmptyOrUndefined(maskObject.colors)) {
+			var x = 0;
+			var sections = Object.keys(maskObject.colors).length + 1;
+			var size = 256;
+			var width = Math.floor(1 / sections * size);
+			for (var color in maskObject.colors) {
+				tcontext.fillStyle = maskObject.colors[color];
+				tcontext.fillRect(x++ * width, 0, width, size);
+			}
+		}
 	}
 	
-	tcontext.fillStyle = tgradient;
-	tcontext.fillRect(0, 0, 256, 256);
 	tURL = tcanvas.toDataURL();
-	node.texture = initTexture(gl, tURL);
-	node.textureCanvas = tcanvas;
-	node.caxis = options.getfieldvalue('caxis',[ArrayMin(data), ArrayMax(data)]);
+	if (options.getfieldvalue('clf','on')=='off') {
+		canvas.nodes['unit' + (Object.keys(canvas.nodes).length - 1)].texture = initTexture(canvas.gl, tURL);
+	} else {
+		canvas.nodes.unit.texture = initTexture(canvas.gl, tURL);
+	}
 	//}}}
-	//{{{ expdisp contours
-	if (options.exist('expdisp')) {
-		canvas.nodes.expdisp = Node(gl, options);
-		var node = canvas.nodes.expdisp;
+	//{{{ text display
+	var overlaycanvasid = options.getfieldvalue('overlayid', options.getfieldvalue('canvasid')+'-overlay');
+	var overlaycanvas = $('#'+overlaycanvasid)[0];
+	if (!VESL.Helpers.isEmptyOrUndefined(overlaycanvas)) {
+		//Get drawing context and save reference on main WebGL canvas
+		var ctx = overlaycanvas.getContext('2d');
+		canvas.overlaycanvas = overlaycanvas;
 		
-		//declare variables:  {{{
-		var vertices = [];
-		var indices = [];
-		var colors = [];
-		var rgbcolor = [];
-		var xmin, xmax;
-		var ymin, ymax;
-		var zmin, zmax;
-		var scale;
+		//Resize interal viewport coordinates to match screenspace coordinates
+		var rect = overlaycanvas.getBoundingClientRect();
+		overlaycanvas.width  = rect.width;
+		overlaycanvas.height = rect.height;
 		
-		//Process data and model
-		var x = options.getfieldvalue('expdisp').x;
-		var y = options.getfieldvalue('expdisp').y;
-		var z = Array.apply(null, Array(x.length)).map(Number.prototype.valueOf, 0);
-		
-		if (options.getfieldvalue('expdisp').z) {
-			z = options.getfieldvalue('expdisp').z;
-		}
-		//}}}
-
-		//Compute coordinates and data range: //{{{
-		var modelxlim = [ArrayMin(x), ArrayMax(x)];
-		var modelylim = [ArrayMin(y), ArrayMax(y)];
-		var modelzlim = [ArrayMin(z), ArrayMax(z)];
-		var xlim = options.getfieldvalue('xlim', modelxlim);
-		var ylim = options.getfieldvalue('ylim', modelylim);
-		var zlim = options.getfieldvalue('zlim', modelzlim);
-		xmin = xlim[0];
-		xmax = xlim[1];
-		ymin = ylim[0];
-		ymax = ylim[1];
-		zmin = zlim[0];
-		zmax = zlim[1];
-		//}}}
-
-		//Compute scaling: //{{{
-		var scale = 1 / (xmax - xmin);
-		node.shaderName = 'colored';
-		node.shader = gl.shaders[node.shaderName].program;
-		node.scale = [scale, scale, scale*options.getfieldvalue('heightscale', 1)];
-		node.translation = [(xmin + xmax) / (-2 / scale), (ymin + ymax) / (-2 / scale), (zmin + zmax) / (-2 / scale)];
-		node.modelMatrix = updateModelMatrix(node);
-		node.drawMode = gl.LINE_LOOP;
-		node.drawOrder = 0;
-		node.useIndexBuffer = false;
-		node.disableDepthTest = true;
-		//}}}
-
-		//some defaults:
-		colors.itemSize = 4;
-
-		//retrieve some options
-		var linewidth=options.getfieldvalue('linewidth', 1);
-		var edgecolor=options.getfieldvalue('edgecolor','black'); //RGBCOLOR?
-
-		vertices.itemSize = 3;
-		for(var i=0; i < x.length; i++){
-			vertices[vertices.length] = x[i];
-			vertices[vertices.length] = y[i];
-			vertices[vertices.length] = z[i];
-
-			//edgecolor
-			rgbcolor = [0.0, 0.0, 0.0];
-			colors[colors.length] = rgbcolor[0];
-			colors[colors.length] = rgbcolor[1];
-			colors[colors.length] = rgbcolor[2];
-			colors[colors.length] = 1.0;
-		}
-
-		//Initalize buffers:
-		node.arrays = [vertices, colors];
-		node.buffers = initBuffers(gl, node.arrays);
-	} //}}}
-	//{{{ cloud of points
-	if (options.exist('cloud')) {
-		canvas.nodes.cloud = Node(gl, options);
-		var node = canvas.nodes.cloud;
-
-		//declare variables:  {{{
-		var vertices = [];
-		var indices = [];
-		var colors = [];
-		var rgbcolor = [];
-		var xmin, xmax;
-		var ymin, ymax;
-		var zmin, zmax;
-		var scale;
-		
-		//Process data and model
-		var x = options.getfieldvalue('cloud').x;
-		var y = options.getfieldvalue('cloud').y;
-		var z = Array.apply(null, Array(x.length)).map(Number.prototype.valueOf, 0);
-		
-		if (options.getfieldvalue('cloud').z) {
-			z = options.getfieldvalue('cloud').z;
-		}
-		//}}}
-
-		//Compute coordinates and data range: //{{{
-		var modelxlim = [ArrayMin(x), ArrayMax(x)];
-		var modelylim = [ArrayMin(y), ArrayMax(y)];
-		var modelzlim = [ArrayMin(z), ArrayMax(z)];
-		var xlim = options.getfieldvalue('xlim', modelxlim);
-		var ylim = options.getfieldvalue('ylim', modelylim);
-		var zlim = options.getfieldvalue('zlim', modelzlim);
-		xmin = xlim[0];
-		xmax = xlim[1];
-		ymin = ylim[0];
-		ymax = ylim[1];
-		zmin = zlim[0];
-		zmax = zlim[1];
-		//}}}
-
-		//Compute scaling: //{{{
-		var scale = 1 / (xmax - xmin);
-		node.shaderName = 'colored';
-		node.shader = gl.shaders[node.shaderName].program;
-		node.scale = [scale, scale, scale*options.getfieldvalue('heightscale', 1)];
-		node.translation = [(xmin + xmax) / (-2 / scale), (ymin + ymax) / (-2 / scale), (zmin + zmax) / (-2 / scale)];
-		node.modelMatrix = updateModelMatrix(node);
-		node.drawMode = gl.POINTS;
-		node.drawOrder = 0;
-		node.useIndexBuffer = false;
-		node.disableDepthTest = true;
-		//}}}
-
-		//some defaults:
-		colors.itemSize = 4;
-
-		//retrieve some options
-		var linewidth=options.getfieldvalue('linewidth', 1);
-		var edgecolor=options.getfieldvalue('edgecolor','black'); //RGBCOLOR?
-
-		vertices.itemSize = 3;
-		for(var i=0; i < x.length; i++){
-			vertices[vertices.length] = x[i];
-			vertices[vertices.length] = y[i];
-			vertices[vertices.length] = z[i];
-
-			//edgecolor
-			rgbcolor = [0.0, 0.0, 0.0];
-			colors[colors.length] = rgbcolor[0];
-			colors[colors.length] = rgbcolor[1];
-			colors[colors.length] = rgbcolor[2];
-			colors[colors.length] = 1.0;
-		}
-
-		//Initalize buffers:
-		node.arrays = [vertices, colors];
-		node.buffers = initBuffers(gl, node.arrays);
-	} //}}}
-	//{{{ text display
-	if (options.exist('textlabels')) {
-		var textcanvas, textcanvasid;	
-		textcanvasid = options.getfieldvalue('textcanvasid', options.getfieldvalue('canvasid')+'-text');
-		textcanvas = $('#'+textcanvasid);
-		textcanvas.textlabels = options.getfieldvalue('textlabels',[]);
-		
-		//setup drawing function for text canvas draw calls
-		textcanvas.draw = function(canvas) {
-			var textcontext, textlabels, textlabel, textcanvaswidth, textcanvasheight, textcoordinates;	
-			var textposition = vec3.create();
-			var mvpMatrix = mat4.create();
-			
-			//ensure correct canvas coordinate scaling
-			textcanvaswidth = this[0].clientWidth;
-			textcanvasheight = this[0].clientHeight;
-			this[0].width  = textcanvaswidth;
-			this[0].height = textcanvasheight;
-			
-			textcontext = this[0].getContext('2d');
-			textlabels = options.getfieldvalue('textlabels',[]);
-			textcontext.clearRect(0, 0, textcanvaswidth, textcanvasheight);
-			
-			//worldspace to screenspace transformation for text
-			for (text in textlabels) {
-				textlabel = textlabels[text];
-				mat4.multiply(mvpMatrix, canvas.camera.vpMatrix, canvas.nodes.overlay.modelMatrix);
-				textposition = vec3.transformMat4(textposition, textlabel.pos, mvpMatrix);
-				if (textposition[2] > 1) { //clip coordinates with z > 1
-					continue;
-				}
-				textcoordinates = [(textposition[0]+1.0)/2.0*textcanvaswidth, (-textposition[1]+1.0)/2.0*textcanvasheight]; //NDC to screenspace
-				textcontext.font = String(options.getfieldvalue('colorbarfontsize', 18))+'px "Lato", Helvetica, Arial, sans-serif';
-				textcontext.fillStyle = options.getfieldvalue('colorbarfontcolor','black');
-				textcontext.strokeStyle = options.getfieldvalue('colorbarfontcolor','black');
-				textcontext.textAlign = 'center';
-				textcontext.textBaseline = 'middle';
-				textcontext.fillText(textlabel.text, textcoordinates[0], textcoordinates[1]);
-				textcontext.strokeText(textlabel.text, textcoordinates[0], textcoordinates[1]);
-			}
-		}
-		canvas.textcanvas = textcanvas;
-	} //}}}
+		//Clear canvas each frame for any new drawings
+		canvas.overlayHandlers['draw'] = function(overlaycanvas) {
+			ctx.clearRect(0, 0, overlaycanvas.width, overlaycanvas.height);
+		}
+	}
 	//{{{ lat long overlay
 	if (options.exist('latlongoverlay')) {
-		var overlaycanvasid = options.getfieldvalue('latlongoverlayid', options.getfieldvalue('canvasid')+'-overlay');
-		var overlaycanvas = $('#'+overlaycanvasid)[0];
 		var latitudes = {
-			//"-90": 1,
-			//"-65": .999,
-			"-60": 0.994046875,
-			//"-55": 0.983187500000002,
-			//"-50": 0.97173550854167,
-			"-45": 0.955729166666666,
-			//"-40": 0.94218750000000218,
-			//"-35": 0.94218750000000218,
-			"-30": 0.9226562500000024,
-			//"-25": 0.87934895833333526,
-			//"-20": 0.856572916666669,
-			//"-15": 0.830729166666665,
-			//"-10": 0.803552708333336,
-			//"-5": 0.77395833333333541,
-			"0": 0.74218749999999811,
-			//"5": 0.70950364583333347,
-			//"10": 0.67479166666666823,
-			//"15": 0.63932291666666663,
-			//"20": 0.60171875,
-			//"25": 0.563453125,
-			"30": 0.523390625000001,
-			//"35": 0.48401875,
-			//"40": 0.44296875,
-			"45": 0.4020001,
-			//"50": 0.3578125,
-			//"55": 0.311875,
-			"60": 0.26953124999999978,
-			//"65": 0.225390625,
-			//"70": 0.18125,
-			//"75": 0.13541666666666671,
-			//"80": 0.08953125,
-			//"85": 0.046250000000000013,
-			//"90": 0.0,
+			//'-90': 1,
+			//'-65': .999,
+			'-60': 0.994046875,
+			'-45': 0.955729166666666,
+			'-30': 0.9226562500000024,
+			//'-15': 0.830729166666665,
+			'0': 0.74218749999999811,
+			//'15': 0.63932291666666663,
+			'30': 0.523390625000001,
+			'45': 0.4020001,
+			'60': 0.26953124999999978,
+			//'65': 0.225390625,
+			//'90': 0.0,
 		}
 		var longitudes = [-150, -120, -90, -60, -30, 0, 30, 60, 90, 120, 150, 180];
-		overlaycanvas.draw = function(canvas) {
-			var rect = overlaycanvas.getBoundingClientRect();
-			overlaycanvas.width  = rect.width;
-			overlaycanvas.height = rect.height;
-			var ctx = overlaycanvas.getContext('2d');
+		canvas.overlayHandlers['latlong'] = function(canvas) {
+			//Transform from world space to viewport space
 			var centerx = overlaycanvas.width / 2;
 			var centery = overlaycanvas.height / 2;
 			var radius = (overlaycanvas.height) / 2;
+
+			//Draw latitudes
 			ctx.setLineDash([5, 10]);
 			for(latitude in latitudes) {
@@ -373,5 +204,5 @@
 				ctx.arc(centerx, centery, radius * latitudes[latitude], 0, 2 * Math.PI);
 				ctx.stroke();
-				ctx.font = String(options.getfieldvalue('colorbarfontsize', 18))+'px "Lato", Helvetica, Arial, sans-serif';
+				ctx.font = 'bold ' + String(options.getfieldvalue('colorbarfontsize', 18))+'px "Lato", Helvetica, Arial, sans-serif';
 				ctx.fillStyle = options.getfieldvalue('colorbarfontcolor','black');
 				ctx.strokeStyle = options.getfieldvalue('colorbarfontcolor','black');
@@ -381,4 +212,5 @@
 				ctx.strokeText(latitude, centerx, centery + radius * latitudes[latitude]);
 			}
+			//Draw longitudes
 			ctx.setLineDash([1, 0]);
 			for (longitude in longitudes) {
@@ -389,107 +221,248 @@
 			}
 		}
-		canvas.overlaycanvas = overlaycanvas;
+	} //}}}
+	if (options.exist('textlabels')) {
+		//Attatch new overlay handler to display text labels
+		var textLabels = options.getfieldvalue('textlabels',[]);
+		canvas.overlayHandlers['text'] = function(canvas) {
+			for (var i = 0; i < textLabels.length; i++) {
+				//Get text label to display
+				var textLabel = textLabels[i];
+				textLabel = {
+					position: defaultFor(textLabel.position, vec3.create()),
+					text: defaultFor(textLabel.text, ''),
+					fontSize: defaultFor(textLabel.fontSize, 18),
+					fontColor: defaultFor(textLabel.fontColor, 'black'),
+
+				};
+				
+				// function declared in slr-gfm sim-front-end-controller.js
+				// if labels are behind the globe sphere then skip iteartion and do not display them
+				if (VESL.UI.isLabelVisible(textLabel)) {
+					//Transform from world space to viewport space
+					var screenPoint = vec3.transformMat4(vec3.create(), textLabel.position, canvas.camera.vpMatrix);
+					var x = (screenPoint[0] + 1.0) * (canvas.width / 2) + canvas.selector.offset().left;
+					var y = (-screenPoint[1] + 1.0) * (canvas.height / 2) + canvas.selector.offset().top;
+					
+					//Draw text
+					ctx.font = 'bold ' + String(textLabel.fontSize) + 'px Arial Black, sans-serif';
+					ctx.fillStyle = textLabel.fontColor;
+					ctx.strokeStyle = 'white';
+					ctx.textAlign = 'center';
+					ctx.textBaseline = 'middle';
+					ctx.fillText(textLabel.text, x, y);
+					ctx.strokeText(textLabel.text, x, y);
+				}
+			}
+		}
 	} //}}}
 	//{{{ additional rendering nodes
 	if (options.exist('render')) {
 		var meshresults = processmesh(md, data, options);
-		var x = meshresults[0]; 
-		var y = meshresults[1]; 
-		var z = meshresults[2]; 
+		var x = meshresults[0];
+		var y = meshresults[1];
+		var z = meshresults[2];
 		var elements = meshresults[3];
-		var is2d = meshresults[4]; 
+		var is2d = meshresults[4];
 		var isplanet = meshresults[5];
-		
-		var modelxlim = [ArrayMin(x), ArrayMax(x)];
-		var modelylim = [ArrayMin(y), ArrayMax(y)];
-		var modelzlim = [ArrayMin(z), ArrayMax(z)];
-		var xlim = options.getfieldvalue('xlim', modelxlim);
-		var ylim = options.getfieldvalue('ylim', modelylim);
-		var zlim = options.getfieldvalue('zlim', modelzlim);
-		xmin = xlim[0];
-		xmax = xlim[1];
-		ymin = ylim[0];
-		ymax = ylim[1];
-		zmin = zlim[0];
-		zmax = zlim[1];
-		
-		var global = vec3.length([(xmin + xmax) / 2, (ymin + ymax) / 2, (zmin + zmax) / 2]) < 6371000/10; //tolerance for global models = center is 637100 meters away from center of earth
-		var atmosphereScale = 1.25;
-		var translation = global ? [(xmin + xmax) / 2, (ymin + ymax) / 2, (zmin + zmax) / 2] : [(xmin + xmax) / 2, (ymin + ymax) - 6371000, (zmin + zmax) / 2];
-		
-		if (options.getfieldvalue('render',[]).indexOf('sky')!=-1) {	
-			//atmosphere
-			var node = Node(gl);
-			node.name = "atmosphere";
-			node.shaderName = "SkyFromSpace";
-			node.shader = gl.shaders[node.shaderName];
-			node.drawOrder = 1;
-			node.cullFace = gl.FRONT;
-			node.enableCullFace = true;
-			node.mesh = GL.Mesh.icosahedron({size: 6371000*atmosphereScale, subdivisions: 6});
-			node.rotation = [0, 0, 0];
-			node.translation = translation;
-			node.center = [0, 0, 0];
-			updateModelMatrix(node);
-			canvas.nodes[node.name] = node;
-		}
-		if (options.getfieldvalue('render',[]).indexOf('space')!=-1) {	
-			//skysphere
-			node = Node(gl);
-			node.name = "skysphere";
-			node.shaderName = "Textured";
-			node.shader = gl.shaders[node.shaderName];
-			node.drawOrder = 2;
-			node.cullFace = gl.FRONT;
-			node.enableCullFace = true;
-			node.mesh = GL.Mesh.sphere({size: 6371000*20});
-			node.texture = initTexture(gl, canvas.rootPath+'textures/TychoSkymapII_t4_2k.jpg');
-			node.rotation = [0, 0, 0];
-			node.translation = translation;
-			node.center = [0, 0, 0];
-			updateModelMatrix(node);
-			canvas.nodes[node.name] = node;
-		}
-		if (canvas.clouds.enabled) {
-			//clouds
-			for (var i = 0; i < canvas.clouds.quantity; i++) {
-				node = Node(gl);
-				node.name = "clouds" + i;
-				node.shaderName = "Clouds";
-				node.shader = gl.shaders[node.shaderName];
-				node.drawOrder = 2;
-				node.cullFace = gl.BACK;
-				node.enableCullFace = true;
-				node.mesh = GL.Mesh.fromURL(canvas.rootPath+'obj/cloud.obj');
-				node.rotation = [0, 0, 0];
-				node.scale = [2500, 2500, 2500];
-				node.translation = [translation[0], translation[1] - 405000, translation[2]];
-				node.center = [0, 0, 0];
-				node.animation = {"time": Date.now(),"target": node.translation,"current": node.translation};
-				updateModelMatrix(node);
-				canvas.nodes[node.name] = node;
-				//canvas.clouds.list
-			}
-			//TODO: Steven, please add <canvas.clouds.quantity> total cloud nodes, randomly spread over the mesh, giving each one a new name and adding them to the canvas.clouds.list so that we can track them later.
-			
-		}
-		if (options.getfieldvalue('render',[]).indexOf('latlong')!=-1) {	
-			//latlong
-			node = Node(gl);
-			node.name = "clouds";
-			node.shaderName = "Clouds";
-			node.shader = gl.shaders[node.shaderName];
-			node.drawOrder = 2;
-			node.cullFace = gl.BACK;
-			node.enableCullFace = true;
-			node.mesh = GL.Mesh.fromURL(canvas.rootPath+'obj/cloud.obj');
-			node.rotation = [0, 0, 0];
-			node.scale = [2500, 2500, 2500];
-			node.translation = [translation[0], translation[1] - 405000, translation[2]];
-			node.center = [0, 0, 0];
-			node.animation = {"time": Date.now(),"target": node.translation,"current": node.translation};
-			updateModelMatrix(node);
-			canvas.nodes[node.name] = node;
+
+		var xlim = options.getfieldvalue('xlim', [ArrayMin(x), ArrayMax(x)]);
+		var ylim = options.getfieldvalue('ylim', [ArrayMin(y), ArrayMax(y)]);
+		var zlim = options.getfieldvalue('zlim', [ArrayMin(z), ArrayMax(z)]);
+
+		var global = vec3.length([(xlim[0] + xlim[1]) / 2, (ylim[0] + ylim[1]) / 2, (zlim[0] + zlim[1]) / 2]) < 6371000/10; //tolerance for global models = center is 637100 meters away from center of earth
+		var translation = global ? [(xlim[0] + xlim[1]) / 2, (ylim[0] + ylim[1]) / 2, (zlim[0] + zlim[1]) / 2] : canvas.view.position;
+
+		var renderObjects = options.getfieldvalue('render',{});
+		for (var renderObject in renderObjects) {
+			//Modify renderObejct?
+			var object = renderObjects[renderObject];
+			object = {
+				enabled: defaultFor(object.enabled, true),					//Toggle display of the render object node
+				scale: defaultFor(object.scale, 1),							//Model matrix scaling
+				x: defaultFor(object.x, [0.0, 1.0, 0.0, 0.0, 0.0, 0.0]),	//x coordinate array
+				y: defaultFor(object.y, [0.0, 0.0, 0.0, 1.0, 0.0, 0.0]),	//y coordinate array
+				z: defaultFor(object.z, [0.0, 0.0, 0.0, 0.0, 0.0, 1.0]),	//z coordinate array
+				indices: defaultFor(object.indices, []),					//indices array
+				name: defaultFor(object.name, 'NY'),						//Text to display for cities.
+				size: defaultFor(object.size, 1),							//Physical size of the object in meters
+				color: defaultFor(object.color, 'black'),					//Diffuse color of object
+				height: defaultFor(object.height, 25000),					//Height of object along y axis, currently for clouds only
+				range: defaultFor(object.range, 120000),						//Range of sz plane to spawn object, currently for clouds only
+				quantity: defaultFor(object.quantity, 15)					//Quantity of objects to display, currently for clouds only
+			};
+			if (!object.enabled) { continue; }
+			if ('sky' === renderObject && !('sky' in canvas.nodes)) {
+				var mesh = GL.Mesh.icosahedron({size: 6371000 * canvas.atmosphere.scaleHeight, subdivisions: 5});
+				var texture = initTexture(gl, canvas.assetsPath + '/textures/TychoSkymapII_t4_2k.jpg');
+				node = new Node(
+					'canvas', canvas,
+					'options', options,
+					'renderObject', object,
+					'name', 'sky',
+					'shaderName', 'SkyFromSpace',
+					'cullFace', gl.FRONT,
+					'mesh', mesh,
+					'texture',texture,
+					'translation',translation
+				);
+			}
+			if ('space' === renderObject && !('space' in canvas.nodes)) {
+				var mesh = GL.Mesh.sphere({size: 6371000 * 20});
+				var texture = initTexture(gl, canvas.assetsPath + '/textures/TychoSkymapII_t4_2k.jpg');
+				node = new Node(
+					'canvas', canvas,
+					'options', options,
+					'renderObject', object,
+					'name', 'space',
+					'shaderName', 'Textured',
+					'cullFace', gl.FRONT,
+					'drawOrder', 2,
+					'mesh', mesh,
+					'texture',texture,
+					'translation',translation
+				);
+			}
+			if ('coastlines' === renderObject) {
+				node = new Node(
+					'canvas', canvas,
+					'options', options,
+					'renderObject', object,
+					'name', 'coastlines',
+					'shaderName', 'Colored',
+					'drawMode', gl.LINE_STRIP,
+					'lineWidth', options.getfieldvalue('linewidth', 1),
+					'scale', [object.scale, object.scale, object.scale],
+					'rotation', [-90, 0, 0]
+				);
+				node.patch('Vertices', [object.x, object.y, object.z], 'FaceColor', 'none');
+			}
+			if ('graticule' === renderObject && !('graticule' in canvas.nodes)) {
+				node = new Node(
+					'canvas', canvas,
+					'options', options,
+					'renderObject', object,
+					'name', 'graticule',
+					'shaderName', 'Colored',
+					'drawMode', gl.LINE_STRIP,
+					'lineWidth', options.getfieldvalue('linewidth', 1),
+					'scale', [object.scale, object.scale, object.scale],
+					'rotation', [-90, 180, 0]
+				);
+				node.patch('Vertices', [object.x, object.y, object.z], 'FaceColor', 'none');
+			}
+			if ('cities' === renderObject && !('cities' in canvas.nodes)) {
+				var mesh = GL.Mesh.icosahedron({size: object.size, subdivisions: 1});
+				node = new Node(
+					'canvas', canvas,
+					'options', options,
+					'renderObject', object,
+					'name', 'cities',
+					'shaderName', 'ColoredDiffuse',
+					'diffuseColor', object.color,
+					'lineWidth', options.getfieldvalue('linewidth', 1),
+					'scale', [object.scale, object.scale, object.scale],
+					'rotation', [-90, 0, 0]
+				);
+				node.geometryShader('Mesh', mesh, 'Vertices', [object.x, object.y, object.z], 'Indices', object.indices);
+			}
+			if ('axis' === renderObject && !('axis' in canvas.nodes)) {		
+				node = new Node(
+					'canvas', canvas,
+					'options', options,
+					'renderObject', object,
+					'name', 'axis',
+					'shaderName', 'Colored',
+					'drawMode', gl.LINES,
+					'diffuseColor', [1.0, 0.0, 0.0, 1.0],
+					'lineWidth', options.getfieldvalue('linewidth', 1),
+					'scale', [object.scale, object.scale, object.scale],
+					'rotation', [0, 0, 0]
+				);
+				node.patch('Vertices', [object.x, object.y, object.z], 'FaceColor', 'none');
+			}
+			if ('city' === renderObject) {
+				//city
+				var mesh = GL.Mesh.sphere({size: object.size});
+				node = new Node(
+					'canvas', canvas,
+					'options', options,
+					'renderObject', object,
+					'name', 'city',
+					'shaderName', 'ColoredDiffuse',
+					'diffuseColor', object.color,
+					'mesh', mesh,
+					'translation', [object.x, object.z, -object.y]
+				);
+				//Attatch new overlay handler to display city name
+				canvas.overlayHandlers['city'] = function(canvas) {
+					var node = canvas.nodes['city'];
+					var object = node.renderObject;
+					var screenPoint = vec3.transformMat4(vec3.create(), node.translation, canvas.camera.vpMatrix);
+					var x = (screenPoint[0] + 1.0) * (canvas.width / 2) + canvas.selector.offset().left;
+					var y = (-screenPoint[1] + 1.0) * (canvas.height / 2) + canvas.selector.offset().top;
+
+					ctx.font = 'bold ' + String(options.getfieldvalue('colorbarfontsize', 22))+'px Arial Black, sans-serif';
+					ctx.fillStyle = options.getfieldvalue('colorbarfontcolor','black');
+					ctx.strokeStyle = 'white';
+					ctx.textAlign = 'center';
+					ctx.textBaseline = 'middle';
+					ctx.fillText(object.name, x, y);
+					ctx.strokeText(object.name, x, y);
+				}
+			}
+			if ('clouds' === renderObject && !('clouds0' in canvas.nodes)) {
+				//clouds				
+				var mesh = GL.Mesh.fromURL(canvas.assetsPath + '/obj/cloud.obj');
+				for (var i = 0; i < object.quantity; i++) {
+					//TODO: More options, less magic numbers. Add animation. Better shading.
+					var offset = [randomizeAxis(translation[0], object.range), 
+												randomizeCloudHeight(translation[1], object), 
+												randomizeAxis(translation[2], object.range)];
+					var randomSize = randomizeCloudSize(object.scale);
+					var randomColor = randomizeCloudColor();
+					node = new Node(
+						'canvas', canvas,
+						'options', options,
+						'renderObject', object,
+						'name', 'clouds' + i,
+						'shaderName', 'ColoredDiffuse',
+						'diffuseColor', [randomColor, randomColor, randomColor, 1.0],
+						'specularColor', [0.1, 0.1, 0.1, 1.0],
+						'mesh', mesh,
+						'scale', [randomSize, randomSize, randomSize],
+						'translation', offset
+					);
+				}
+			}
 		}
 	} //}}}
 } //}}}
+
+function randomizeCloudHeight(canvasGroundHeight, object) {
+		// -+7000 seems a reasonable range
+		var maxHeight = object.height + 7000;
+		var minHeigth = object.height - 7000;
+		var randomHeight = (Math.random() * (maxHeight - minHeigth)) + minHeigth;
+		
+		return canvasGroundHeight + randomHeight;
+}
+
+// assumes that originAxisValue is the mid-value between min and max.
+function randomizeAxis(originAxisValue, range) {
+		return originAxisValue + (Math.random() - 0.5) * (range * 2); 
+}
+
+function randomizeCloudSize(scale) {
+	var maxResize = 1.3;
+	var minResize = 0.5;
+	var randomizationFactor = Math.random() * (maxResize - minResize) + minResize; 
+	return scale * randomizationFactor;
+}
+
+function randomizeCloudColor() {
+	var lighestColor = 1;
+	var darkestColor = 0.9;
+	var randomColor = Math.random() * (lighestColor - darkestColor) + darkestColor;
+	return randomColor;
+}
Index: /issm/trunk/src/m/plot/applyoptions.m
===================================================================
--- /issm/trunk/src/m/plot/applyoptions.m	(revision 22757)
+++ /issm/trunk/src/m/plot/applyoptions.m	(revision 22758)
@@ -379,4 +379,7 @@
 	if exist(options,'basin'),
 		[mdx mdy]=basinzoom(options);
+	elseif exist(options,'xlim') | exist(options,'ylim'),
+		mdx=getfieldvalue(options,'xlim');
+		mdy=getfieldvalue(options,'ylim');
 	else
 		mdx=[min(md.mesh.x)-offset max(md.mesh.x)+offset];
@@ -392,6 +395,10 @@
 
 %flag edges of a partition
-if exist(options,'partitionedges')
-	[xsegments ysegments]=flagedges(md.mesh.elements,md.mesh.x,md.mesh.y,md.qmu.partition);
+if exist(options,'partitionedges') & ~strcmp(getfieldvalue(options,'partitionedges','off'),'off')
+	mdp=getfieldvalue(options,'partitionedges','off');
+	if ischar(mdp)
+		mdp=md;
+	end
+	[xsegments ysegments]=flagedges(mdp.mesh.elements,mdp.mesh.x,mdp.mesh.y,mdp.qmu.partition);
 	xsegments=xsegments*getfieldvalue(options,'unit',1);
 	ysegments=ysegments*getfieldvalue(options,'unit',1);
@@ -400,5 +407,9 @@
 	hold on;
 	for i=1:length(xsegments),
-		plot(xsegments(i,:),ysegments(i,:),color,'LineWidth',linewidth);
+		if (isnumeric(color))
+			h=plot(xsegments(i,:),ysegments(i,:),'Color',color,'LineWidth',linewidth);
+		else
+			plot(xsegments(i,:),ysegments(i,:),color,'LineWidth',linewidth);
+		end
 	end
 end
Index: /issm/trunk/src/m/plot/googlemaps.m
===================================================================
--- /issm/trunk/src/m/plot/googlemaps.m	(revision 22757)
+++ /issm/trunk/src/m/plot/googlemaps.m	(revision 22758)
@@ -4,4 +4,5 @@
 %   Usage:
 %       md = googlemaps(md)
+%       md = googlemaps(md,zoom)
 %       md = googlemaps(md,ullat,ullon,lrlat,lrlon)
 %       md = googlemaps(md,ullat,ullon,lrlat,lrlon,options)
@@ -23,8 +24,20 @@
 end
 
+%Check that no temp.* exists
+if exist('temp.tiff','file'),
+	error('File temp.tiff already exists, remove first');
+end
+if exist('temp.png','file'),
+	error('File temp.png already exists, remove first');
+end
+
+if nargin==2,
+	options=addfielddefault(options,'zoom',ullat);
+end
+
 if md.mesh.epsg==0,
 	error('md.mesh.epsg not defined');
 end
-if nargin==1,
+if nargin<3,
 	%Get xlim and ylim (used to extract Google maps image)
 	xlim=getfieldvalue(options,'xlim',[min(md.mesh.x) max(md.mesh.x)]);
@@ -141,4 +154,7 @@
 	elseif md.mesh.epsg==3031,
 		[X Y]=ll2xy(LAT,LON,-1,0,71);
+	elseif md.mesh.epsg==4326,
+		X=LON;
+		Y=LAT;
 	else
 		error('EPSG code not supported yet');
@@ -165,4 +181,7 @@
 	elseif md.mesh.epsg==3031,
 		[X Y]=ll2xy(LAT,LON,-1,0,71);
+	elseif md.mesh.epsg==4326,
+		X=LON;
+		Y=LAT;
 	else
 		error('EPSG code not supported yet');
Index: /issm/trunk/src/m/plot/kmlgridded.m
===================================================================
--- /issm/trunk/src/m/plot/kmlgridded.m	(revision 22757)
+++ /issm/trunk/src/m/plot/kmlgridded.m	(revision 22758)
@@ -25,5 +25,7 @@
 
 %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);
+x_m = xlim(1):post:xlim(2);
+y_m = ylim(1):post:ylim(2);
+data_grid=InterpFromMeshToGrid(elements,x,y,data,x_m,y_m,NaN);
 if size(data_grid,1)<3 | size(data_grid,2)<3,
 	error('data_grid size too small, check posting and units');
Index: /issm/trunk/src/m/plot/kmlgroundoverlay.m
===================================================================
--- /issm/trunk/src/m/plot/kmlgroundoverlay.m	(revision 22757)
+++ /issm/trunk/src/m/plot/kmlgroundoverlay.m	(revision 22758)
@@ -28,11 +28,22 @@
 
 %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);
+if strcmpi(getfieldvalue(options,'coord',''),'latlon'),
+	%need to plot with option 'coord','latlon'
+	XLIM=xlim();
+	YLIM=ylim();
+	west=XLIM(1);
+	east=XLIM(2);
+	south=YLIM(1);
+	north=YLIM(2);
+else
+	west=min(md.mesh.long);
+	east=max(md.mesh.long);
+	south=min(md.mesh.lat);
+	north=max(md.mesh.lat);
+end
 
 %print image at high resolution
-export_fig([kmlroot '/' kmlimagename],'-transparent','-zbuffer'); %zbuffer to avoid "Bad data returned by HARDCOPY. Not calling IMWRITE"
+%export_fig([kmlroot '/' kmlimagename],'-transparent','-zbuffer'); %zbuffer to avoid "Bad data returned by HARDCOPY. Not calling IMWRITE"
+export_fig([kmlroot '/' kmlimagename],'-transparent');
 %printmodel([kmlroot '/' kmlimagename],kmlimagetype,'trim','on','resolution',kmlresolution,'margin','off','frame','off');
 
@@ -61,2 +72,12 @@
 
 fclose(fid);
+
+if strcmpi(getfieldvalue(options,'kmz','on'),'on')
+	disp('Converting to kmz...');
+	system(['cat ' kmlroot '/' kmlfilename '| sed -e "s/' kmlimagename '\.png/files\/' kmlimagename '.png/g" > doc.kml']);
+	system('mkdir files');
+	system(['mv ' kmlroot '/' kmlimagename  '.png files/']);
+	system(['zip -r  ' kmlfilename '.zip  files doc.kml']);
+	system(['mv ' kmlfilename '.zip ' kmlfilename]);
+	system(['rm -rf  files doc.kml']);
+end
Index: /issm/trunk/src/m/plot/manualcb.m
===================================================================
--- /issm/trunk/src/m/plot/manualcb.m	(revision 22757)
+++ /issm/trunk/src/m/plot/manualcb.m	(revision 22758)
@@ -7,4 +7,5 @@
 %   Available options:
 %      - 'fontsize'    : default is 12
+%      - 'fontcolor'   : default is 'k'
 %      - 'smallbars'   : bars next to each tick (default is false)
 %      - 'position'    : colorbar position in normalized units
@@ -33,4 +34,5 @@
 end
 fontsize  = getfieldvalue(options,'fontsize',12);
+fontcolor = getfieldvalue(options,'fontcolor','k');
 smallbars = getfieldvalue(options,'smallbars',false);
 
@@ -97,5 +99,5 @@
 	end
 end
-patch([0,0,1,1],[0,1,1,0],'k','FaceColor','none','Clipping','off')
+patch([0,0,1,1],[0,1,1,0],fontcolor,'FaceColor','none','Clipping','off','Edgecolor',fontcolor)
 
 %Add ticks
@@ -103,21 +105,21 @@
 	%Use FOR LOOP otherwise numbers are not correcly centered
 	if getfieldvalue(options,'inverttickposition',0)==1,
-		for i=1:length(ytick), text(-0.5,ytick(i),num2str(ztick(i)),'HorizontalAlignment','right','VerticalAlignment','middle','FontSize',fontsize); end
+		for i=1:length(ytick), text(-0.5,ytick(i),num2str(ztick(i)),'HorizontalAlignment','right','VerticalAlignment','middle','FontSize',fontsize,'Color',fontcolor); end
 	else
-		for i=1:length(ytick), text(1.5,ytick(i),num2str(ztick(i)),'HorizontalAlignment','left','VerticalAlignment','middle','FontSize',fontsize); end
+		for i=1:length(ytick), text(1.5,ytick(i),num2str(ztick(i)),'HorizontalAlignment','left','VerticalAlignment','middle','FontSize',fontsize,'Color',fontcolor); end
 	end
 	if smallbars,
 		for i=1:numel(ztick)
-			patch([0.8 1.0],[ytick(i) ytick(i)],'k')
-			patch([0.0 0.2],[ytick(i) ytick(i)],'k')
+			patch([0.8 1.0],[ytick(i) ytick(i)],fontcolor,'Edgecolor',fontcolor)
+			patch([0.0 0.2],[ytick(i) ytick(i)],fontcolor,'Edgecolor',fontcolor)
 		end
 	end
 else
 	%Use FOR LOOP otherwise numbers are not correcly centered
-	for i=1:length(ytick), text(ytick(i),-0.5,num2str(ztick(i)),'HorizontalAlignment','center','VerticalAlignment','top','FontSize',fontsize); end
+	for i=1:length(ytick), text(ytick(i),-0.5,num2str(ztick(i)),'HorizontalAlignment','center','VerticalAlignment','top','FontSize',fontsize,'Color',fontcolor); end
 	if smallbars,
 		for i=1:numel(ztick)
-			patch([ytick(i) ytick(i)],[0.8 1.0],[ytick(i) ytick(i)],'k')
-			patch([ytick(i) ytick(i)],[0.0 0.2],[ytick(i) ytick(i)],'k')
+			patch([ytick(i) ytick(i)],[0.8 1.0],[ytick(i) ytick(i)],fontcolor,'Edgecolor',fontcolor)
+			patch([ytick(i) ytick(i)],[0.0 0.2],[ytick(i) ytick(i)],fontcolor,'Edgecolor',fontcolor)
 		end
 	end
@@ -125,12 +127,12 @@
 
 if exist(options,'title'),
-	title(getfieldvalue(options,'title'),'FontSize',getfieldvalue(options,'titlefontsize',fontsize));
+	title(getfieldvalue(options,'title'),'FontSize',getfieldvalue(options,'titlefontsize',fontsize),'Color',fontcolor);
 end
 if exist(options,'ylabel'),
 	if strcmpi(getfieldvalue(options,'orientation','vertical'),'horizontal'),
-		th=title(getfieldvalue(options,'title'),'FontSize',fontsize);
+		th=title(getfieldvalue(options,'title'),'FontSize',fontsize,'Color',fontcolor);
 		set(th,'Position',[ytick(end)+0.075,-0.3]);
 	else
-		ylabel(getfieldvalue(options,'ylabel'),'FontSize',fontsize);
+		ylabel(getfieldvalue(options,'ylabel'),'FontSize',fontsize,'Color',fontcolor);
 	end
 end
Index: /issm/trunk/src/m/plot/plot_contour.m
===================================================================
--- /issm/trunk/src/m/plot/plot_contour.m	(revision 22757)
+++ /issm/trunk/src/m/plot/plot_contour.m	(revision 22758)
@@ -270,5 +270,5 @@
 	else
 		%clabel(c,h,'color',color,'FontSize',10,'labelspacing',20000);
-		clabel(c,h,'FontSize',10,'labelspacing',20000);
-	end
-end
+		%clabel(c,h,'FontSize',10,'labelspacing',20000);
+	end
+end
Index: /issm/trunk/src/m/plot/plot_googlemaps.m
===================================================================
--- /issm/trunk/src/m/plot/plot_googlemaps.m	(revision 22757)
+++ /issm/trunk/src/m/plot/plot_googlemaps.m	(revision 22758)
@@ -62,12 +62,7 @@
 %Prepare grid
 if size(md.radaroverlay.x,1)==1 | size(md.radaroverlay.x,2)==1,
-	xmin=min(md.radaroverlay.x);
-	ymax=max(md.radaroverlay.y);
-	xspacing=md.radaroverlay.x(2)-md.radaroverlay.x(1);
-	yspacing=md.radaroverlay.y(2)-md.radaroverlay.y(1);
-	nlines=length(md.radaroverlay.y);
-	ncols =length(md.radaroverlay.x);
-		[x_m y_m data_grid]=InterpFromMeshToGrid(elements,x/getfieldvalue(options,'unit',1),y/getfieldvalue(options,'unit',1),...
-			data,xmin,ymax,xspacing,yspacing,nlines,ncols,NaN);
+	x_m = md.radaroverlay.x;
+	y_m = md.radaroverlay.y;
+	data_grid=InterpFromMeshToGrid(elements,x/getfieldvalue(options,'unit',1),y/getfieldvalue(options,'unit',1),data,x_m,y_m,NaN);
 else
 	X = md.radaroverlay.x;
@@ -89,4 +84,26 @@
 colorm = getcolormap(options);
 image_rgb = ind2rgb(uint16((data_grid - data_min)*(length(colorm)/(data_max-data_min))),colorm);
+
+if exist(options,'shaded'),
+	a    = -45;
+	scut = 0.2;
+	c    = 1;
+	% computes lighting from elevation gradient
+	[fx,fy] = gradient(data_grid,x_m,y_m);
+	fxy = -fx*sind(a) - fy*cosd(a);
+	clear fx fy % free some memory...
+	fxy(isnan(fxy)) = 0;
+
+	% computes maximum absolute gradient (median-style), normalizes, saturates and duplicates in 3-D matrix
+	r = repmat(max(min(fxy/nmedian(abs(fxy),1 - scut/100),1),-1),[1,1,3]);
+
+	% applies contrast using exponent
+	rp = (1 - abs(r)).^c;
+	image_rgb = image_rgb.*rp;
+
+	% lighter for positive gradient
+	k = find(r > 0);
+	image_rgb(k) = image_rgb(k) + (1 - rp(k));
+end
 
 alpha=ones(size(data_grid));
Index: /issm/trunk/src/m/plot/plot_gridded.m
===================================================================
--- /issm/trunk/src/m/plot/plot_gridded.m	(revision 22757)
+++ /issm/trunk/src/m/plot/plot_gridded.m	(revision 22758)
@@ -23,5 +23,7 @@
 
 %Interpolating data on grid
-[x_m y_m data_grid]=InterpFromMeshToGrid(elements,x,y,data,xlim(1),ylim(2),postx,posty,round(diff(ylim)/posty),round(diff(xlim)/postx),NaN);
+x_m = xlim(1):postx:xlim(2);
+y_m = ylim(1):posty:ylim(2);
+data_grid=InterpFromMeshToGrid(elements,x,y,data,x_m,y_m,NaN);
 data_grid_save = data_grid;
 if size(data_grid,1)<3 | size(data_grid,2)<3,
@@ -49,9 +51,15 @@
 image_rgb = ind2rgb(uint16((data_grid - data_min)*(length(map)/(data_max-data_min))),map);
 if exist(options,'shaded'),
+
+	if exist(options,'dem'),
+		dem_grid=InterpFromMeshToGrid(elements,x,y,getfieldvalue(options,'dem'),x_m,y_m,NaN);
+	else
+		dem_grid=data_grid_save;
+	end
 	a    = -45;
 	scut = 0.2;
 	c    = 1;
 	% computes lighting from elevation gradient
-	[fx,fy] = gradient(data_grid_save,x_m,y_m);
+	[fx,fy] = gradient(dem_grid,x_m,y_m);
 	fxy = -fx*sind(a) - fy*cosd(a);
 	clear fx fy % free some memory...
Index: /issm/trunk/src/m/plot/plot_manager.js
===================================================================
--- /issm/trunk/src/m/plot/plot_manager.js	(revision 22757)
+++ /issm/trunk/src/m/plot/plot_manager.js	(revision 22758)
@@ -14,5 +14,5 @@
 	var canvas = initCanvas(options);
 	var gl = canvas.gl;
-	//TODO: each plot_ should add their node to the canvas.node array
+
 	//figure out if this is a special plot
 	if (typeof data === 'string'){
@@ -81,7 +81,7 @@
 				return;
 			case 'none':
-				if (!(options.exist('overlay'))){
-					plot_none(md,options,nlines,ncols,i);
-				}
+				//if (!(options.exist('overlay'))){
+				//	plot_none(md,options,nlines,ncols,i);
+				//}
 				return;
 			case 'penalties':
@@ -151,5 +151,5 @@
 				return;
 			case 'transient_movie':
-				plot_transient_movie(md,options,subplotwidth,i);
+				plot_transient_movie(md,options,canvas);
 				return;
 			case 'transient_results':
@@ -205,4 +205,4 @@
 	plot_unit(md,data2,datatype,options,canvas);
 
-	applyoptions(md,data2,datatype,options,canvas,gl,canvas.nodes[canvas.nodes.length-1]);
+	applyoptions(md,data2,options,canvas);
 } //}}}
Index: /issm/trunk/src/m/plot/plot_mesh.js
===================================================================
--- /issm/trunk/src/m/plot/plot_mesh.js	(revision 22757)
+++ /issm/trunk/src/m/plot/plot_mesh.js	(revision 22758)
@@ -7,16 +7,9 @@
 	//   See also: PLOTMODEL, PLOT_MANAGER
 
+	//if ('mesh' in  canvas.nodes && options.getfieldvalue('cachenodes','on') === 'on') return;
+	
 	//{{{ declare variables:
-	var vertices = [];
-	var indices = [];
-	var colors = [];
-	var nanindices = {};
-	var xmin, xmax;
-	var ymin, ymax;
-	var zmin, zmax;
-	var scale, matrixscale, vertexscale;
-	
 	//Process data and model
-	var meshresults = processmesh(md,[], options);
+	var meshresults = processmesh(md, [], options);
 	var x = meshresults[0]; 
 	var y = meshresults[1]; 
@@ -26,60 +19,40 @@
 	var isplanet = meshresults[5];
 		
-	//Compue scaling through matrices for 2d meshes and vertices for 3d meshes
-	if (!md.geometry.surface) {
-		md.geometry.surface=NewArrayFill(md.mesh.x.length, 0);
-	}
-	if (md.mesh.classname() == 'mesh3dsurface') {
-		matrixscale = 1;
-		vertexscale = options.getfieldvalue('heightscale', 1);
+	//Compute coordinates and data range:
+	var xlim = options.getfieldvalue('xlim', [ArrayMin(x), ArrayMax(x)]);
+	var ylim = options.getfieldvalue('ylim', [ArrayMin(y), ArrayMax(y)]);
+	var zlim = options.getfieldvalue('zlim', [ArrayMin(z), ArrayMax(z)]);
+	
+	//Handle heightscale
+	var vertices, scale;
+	if (md.mesh.classname() !== 'mesh3dsurface') {
+		vertices = [x, y, z];
+		scale = [1, 1, options.getfieldvalue('heightscale', 1)];
 	}
 	else {
-		if (md.geometry.surface) {
-			z=md.geometry.surface;
-		}	
-		matrixscale = options.getfieldvalue('heightscale', 1);
-		vertexscale = 0;
+		vertices = Node.prototype.scaleVertices(md, x, y, z, elements, options.getfieldvalue('heightscale', 1), options.getfieldvalue('maskregion',{'enabled':false}));
+		scale = [1, 1, 1];
 	}
+	
+	//Compute gl variables:
+	var edgecolor = options.getfieldvalue('edgecolor', 'black');
+	var node = new Node(
+		'canvas', canvas,
+		'options', options,
+		'name', 'mesh',
+		'shaderName', 'Colored',
+		'alpha', options.getfieldvalue('alpha', 1.0),
+		//'center', [(xlim[0] + xlim[1]) / 2, (ylim[0] + ylim[1]) / 2, md.mesh.classname() === 'mesh3dsurface' ? (zlim[0] + zlim[1]) / 2 : zlim[0]],
+		'center', [(xlim[0] + xlim[1]) / 2, (ylim[0] + ylim[1]) / 2, (zlim[0] + zlim[1]) / 2],
+		'drawMode', canvas.gl.LINES,
+		'diffuseColor', edgecolor,
+		'lineWidth', options.getfieldvalue('linewidth', 1),
+		'maskEnabled', options.getfieldvalue('innermask','off') == 'on',
+		'maskHeight', options.getfieldvalue('innermaskheight', 150.0) / options.getfieldvalue('heightscale', 1),
+		'maskColor', options.getfieldvalue('innermaskcolor',[0.0, 0.0, 1.0, 1.0]),
+		'rotation', [-90, 0, 0],
+		'scale', scale
+	);
 	//}}}
-
-	//Compute coordinates and data range:
-	var modelxlim = [ArrayMin(x), ArrayMax(x)];
-	var modelylim = [ArrayMin(y), ArrayMax(y)];
-	var modelzlim = [ArrayMin(z), ArrayMax(z)];
-	var xlim = options.getfieldvalue('xlim', modelxlim);
-	var ylim = options.getfieldvalue('ylim', modelylim);
-	var zlim = options.getfieldvalue('zlim', modelzlim);
-	xmin = xlim[0];
-	xmax = xlim[1];
-	ymin = ylim[0];
-	ymax = ylim[1];
-	zmin = zlim[0];
-	zmax = zlim[1];
-
-	//Compute gl variables:
-	var gl = canvas.gl;
-	gl.makeCurrent();
-	var node = Node(gl);
-	canvas.nodes[canvas.nodes.length] = node;
-	node.name = "mesh";
-	node.shaderName = "Colored";
-	node.shader = gl.shaders[node.shaderName];
-	node.lineWidth = options.getfieldvalue('linewidth', 1);
-	node.scale = [1, 1, matrixscale];
-	node.rotation = [-90, 0, 0];
-	node.translation = [0, 0, 0];
-	node.center = [(xmin + xmax) / 2, (ymin + ymax) / 2, (zmin + zmax) / 2];
-	node.drawMode = gl.LINES;
-	node.drawOrder = 0;
-	node.maskEnabled = options.getfieldvalue('innermask','off') == 'on';
-	node.maskHeight = options.getfieldvalue('innermaskheight', 150.0)*options.getfieldvalue('heightscale', 1);
-	node.maskColor = options.getfieldvalue('innermaskcolor',[0.0, 0.0, 1.0, 1.0]);
-	updateModelMatrix(node);
-
-	//retrieve some options
-	var edgecolor = new RGBColor(options.getfieldvalue('edgecolor','black'));
-	if (edgecolor.ok) edgecolor = [edgecolor.r/255.0, edgecolor.g/255.0, edgecolor.b/255.0, 1.0];
-	else throw Error(sprintf("s%s%s\n","initWebGL error message: cound not find out edgecolor color for curent canvas ", canvas));
-
 	//{{{ node plot
 	if (elements[0].length==6){ //prisms
@@ -88,52 +61,9 @@
 	}
 	else{ //2D triangular elements
-		var xyz = vec3.create();
-		var direction = vec3.create();
-		var vertex = vec3.create();
-		var magnitude;
-		var color = edgecolor;
-		for(var i = 0; i < x.length; i++){
-			//Check for NaN values and remove from indices array as necessary, but preserve vertex array spacing
-			if (isNaN(x[i]) || isNaN(y[i]) || isNaN(z[i])) {
-				nanindices[i] = i;
-				vertices[vertices.length] = vertex[0];
-				vertices[vertices.length] = vertex[1];
-				vertices[vertices.length] = vertex[2];
-				
-				colors[colors.length] = color[0];
-				colors[colors.length] = color[1];
-				colors[colors.length] = color[2];
-				colors[colors.length] = color[3];
-				continue;
-			}
-			//Scale vertices
-			xyz = vec3.fromValues(x[i], y[i], z[i]);
-			magnitude = vec3.length(xyz) + md.geometry.surface[i] * vertexscale;
-			vec3.normalize(direction, xyz);
-			vec3.scale(vertex, direction, magnitude);
-			vertices[vertices.length] = vertex[0];
-			vertices[vertices.length] = vertex[1];
-			vertices[vertices.length] = vertex[2];
-
-			colors[colors.length] = color[0];
-			colors[colors.length] = color[1];
-			colors[colors.length] = color[2];
-			colors[colors.length] = color[3];
-		}
-		
-		//linearize the elements array: 
-		var element;
-		for(var i = 0; i < elements.length; i++){
-			element = [elements[i][0] - 1, elements[i][1] - 1, elements[i][2] - 1];
-			if (element[0] in nanindices || element[1] in nanindices || element[2] in nanindices) continue;
-			indices[indices.length] = element[0];
-			indices[indices.length] = element[1];
-			indices[indices.length] = element[1];
-			indices[indices.length] = element[2];
-			indices[indices.length] = element[2];
-			indices[indices.length] = element[0];
-		}
+		node.patch('Faces', elements, 'Vertices', vertices, 'FaceColor', 'none', 'EdgeColor', edgecolor);
 	}
 	//}}}
-	node.mesh = GL.Mesh.load({vertices: vertices, colors: colors, triangles: indices}, null, null, gl);
+	//options=options.addfielddefault('title','Mesh');
+	//options=addfielddefault('colorbar','off');
+	//applyoptions(md,[],options,canvas);
 } //}}}
Index: /issm/trunk/src/m/plot/plot_overlay.js
===================================================================
--- /issm/trunk/src/m/plot/plot_overlay.js	(revision 22757)
+++ /issm/trunk/src/m/plot/plot_overlay.js	(revision 22758)
@@ -7,16 +7,9 @@
 	//   See also: PLOTMODEL, PLOT_MANAGER
 
+	if ('overlay' in  canvas.nodes && options.getfieldvalue('cachenodes','on') === 'on') return;
+	
 	//{{{ declare variables:
-	var vertices = [];
-	var indices = [];
-	var texcoords = [];
-	var nanindices = {};
-	var xmin, xmax;
-	var ymin, ymax;
-	var zmin, zmax;
-	var matrixscale, vertexscale;
-
 	//Process data and model
-	var meshresults = processmesh(md, data, options);
+	var meshresults = processmesh(md, [], options);
 	var x = meshresults[0]; 
 	var y = meshresults[1]; 
@@ -25,138 +18,75 @@
 	var is2d = meshresults[4]; 
 	var isplanet = meshresults[5];
-
-	//Compue scaling through matrices for 2d meshes and vertices for 3d meshes
-	if (!md.geometry.surface) {
-		md.geometry.surface=NewArrayFill(md.mesh.x.length, 0);
+	if (md.mesh.classname() !== 'mesh3dsurface') z = md.geometry.surface;
+	
+	//Compute coordinates and data range:
+	var xlim = options.getfieldvalue('xlim', [ArrayMin(x), ArrayMax(x)]);
+	var ylim = options.getfieldvalue('ylim', [ArrayMin(y), ArrayMax(y)]);
+	var zlim = options.getfieldvalue('zlim', [ArrayMin(md.geometry.surface), ArrayMax(md.geometry.surface)]);
+	
+	//Handle radaroverlay
+	if (md.radaroverlay.outerx) {
+		var result = Node.prototype.mergeVertices(x, y, z, elements, md.radaroverlay.outerx, md.radaroverlay.outery, md.radaroverlay.outerheight, md.radaroverlay.outerindex);
+		x = result.x;
+		y = result.y;
+		z = result.z;
+		elements = result.elements;
 	}
-	if (md.mesh.classname() == 'mesh3dsurface') {
-		matrixscale = 1;
-		vertexscale = options.getfieldvalue('heightscale', 1);
+	
+	//Handle heightscale
+	var vertices, scale;
+	if (md.mesh.classname() !== 'mesh3dsurface') {
+		vertices = [x, y, z];
+		scale = [1, 1, options.getfieldvalue('heightscale', 1)];
 	}
 	else {
-		if (md.geometry.surface) {
-			z=md.geometry.surface;
-		}	
-		matrixscale = options.getfieldvalue('heightscale', 1);
-		vertexscale = 0;
-	}
-	//}}}
-	
-	//Compute coordinates and data range:
-	var modelxlim = [ArrayMin(x), ArrayMax(x)];
-	var modelylim = [ArrayMin(y), ArrayMax(y)];
-	var modelzlim = [ArrayMin(z), ArrayMax(z)];
-	var xlim = options.getfieldvalue('xlim', modelxlim);
-	var ylim = options.getfieldvalue('ylim', modelylim);
-	var zlim = options.getfieldvalue('zlim', modelzlim);
-	xmin = xlim[0];
-	xmax = xlim[1];
-	ymin = ylim[0];
-	ymax = ylim[1];
-	zmin = zlim[0];
-	zmax = zlim[1];
-		
-	//Compute gl variables:
-	var gl = canvas.gl;
-	var node = Node(gl);
-	canvas.nodes[canvas.nodes.length] = node;
-	node.name = "overlay";
-	node.shaderName = (options.getfieldvalue('render',[]).indexOf('ground')!=-1) ? "GroundFromSpace" : "Textured";
-	node.shader = gl.shaders[node.shaderName];
-	node.scale = [1, 1, matrixscale];
-	node.rotation = [-90, 0, 0];
-	node.translation = [0, 0, 0];
-	node.center = [(xmin + xmax) / 2, (ymin + ymax) / 2, (zmin + zmax) / 2];
-	node.texture = initTexture(gl, options.getfieldvalue('overlay_image'));
-	node.alpha = options.getfieldvalue('outeralpha', 1.0);
-	node.drawOrder = 1;
-	node.maskEnabled = options.getfieldvalue('outermask','off') == 'on';
-	node.maskHeight = options.getfieldvalue('outermaskheight', 150.0);
-	node.maskColor = options.getfieldvalue('outermaskcolor',[0.0, 0.0, 1.0, 1.0]);
-	updateModelMatrix(node);
-	
-	//Handle outer radaroverlay
-	if (md.radaroverlay.outerx) {
-		var newelements = [];
-		for (var i = 0; i < md.radaroverlay.outerindex.length; i++) {
-			newelements[newelements.length] = [md.radaroverlay.outerindex[i][0] + x.length, md.radaroverlay.outerindex[i][1] + y.length, md.radaroverlay.outerindex[i][2] + z.length];
-		}
-		x = [].concat(x, md.radaroverlay.outerx);
-		y = [].concat(y, md.radaroverlay.outery);
-		z = [].concat(z, md.radaroverlay.outerheight);
-		elements = [].concat(elements, newelements);
-		
-		//Reclaculate bounds based on otuer radaroverlay
-		modelxlim = [ArrayMin(x), ArrayMax(x)];
-		modelylim = [ArrayMin(y), ArrayMax(y)];
-		modelzlim = [ArrayMin(z), ArrayMax(z)];
-		xmin = xlim[0];
-		xmax = xlim[1];
-		ymin = ylim[0];
-		ymax = ylim[1];
-		zmin = zlim[0];
-		zmax = zlim[1];
-		
-		node.center = [node.center[0], node.center[1], -zmax];
+		vertices = Node.prototype.scaleVertices(md, x, y, z, elements, options.getfieldvalue('heightscale', 1), options.getfieldvalue('maskregion',{'enabled':false}));
+		scale = [1, 1, 1];
 	}
 	
-	var xrange = modelxlim[1] - modelxlim[0];
-	var yrange = modelylim[1] - modelylim[0];
+	//Compute gl variables:
+	var edgecolor = options.getfieldvalue('edgecolor', 'black');
+	var texture = initTexture(gl, options.getfieldvalue('overlay_image'));
+	var node = new Node(
+		'canvas', canvas,
+		'options', options,
+		'name', 'overlay',
+		'shaderName', 'ground' in options.getfieldvalue('render', {}) ? 'GroundFromSpace' : 'TexturedDiffuse',
+		'alpha', options.getfieldvalue('outeralpha', 1.0),
+		//'center', [(xlim[0] + xlim[1]) / 2, (ylim[0] + ylim[1]) / 2, md.mesh.classname() === 'mesh3dsurface' ? (zlim[0] + zlim[1]) / 2 : zlim[0]],
+		'center', [(xlim[0] + xlim[1]) / 2, (ylim[0] + ylim[1]) / 2, (zlim[0] + zlim[1]) / 2],
+		'ambientColor', [0.1, 0.1, 0.1 ,1.0],
+		'diffuseColor', [1.0, 1.0, 1.0 ,1.0],
+		'specularStrength', 0.0,
+		'maskEnabled', options.getfieldvalue('outermask','off') == 'on',
+		'maskHeight', options.getfieldvalue('outermaskheight', 150.0),
+		'maskColor', options.getfieldvalue('outermaskcolor',[0.0, 0.0, 1.0, 1.0]),
+		'texture', texture,
+		'rotation', [-90, 0, 0],
+		'scale', scale
+	);
+	//}}}
+
+	var xRange = xlim[1] - xlim[0];
+	var yRange = ylim[1] - ylim[0];
+	var coordArray = [new Array(x.length), new Array(x.length)];
 	
-	var xyz = vec3.create();
-	var direction = vec3.create();
-	var vertex = vec3.create();
-	var magnitude;
-
 	//generate mesh:
-	for(var i = 0; i < x.length; i++){
-		//Check for NaN values and remove from indices array as necessary, but preserve vertex array spacing
-		if (isNaN(x[i]) || isNaN(y[i]) || isNaN(z[i])) {
-			nanindices[i] = i;
-			vertices[vertices.length] = vertex[0];
-			vertices[vertices.length] = vertex[1];
-			vertices[vertices.length] = vertex[2];
-			
-			texcoords[texcoords.length] = 0.0;
-			texcoords[texcoords.length] = 0.0;
-			continue;
-		}
-
-		if (md.mesh.classname() == 'mesh3dsurface') {
-			//Scale vertices
-			xyz = vec3.fromValues(x[i], y[i], z[i]);
-			magnitude = vec3.length(xyz) + md.geometry.surface[i] * vertexscale;
-			vec3.normalize(direction, xyz);
-			vec3.scale(vertex, direction, magnitude);
-			vertices[vertices.length] = vertex[0];
-			vertices[vertices.length] = vertex[1];
-			vertices[vertices.length] = vertex[2];
-			
-			texcoords[texcoords.length] = Math.atan2(vertex[1], vertex[0]) / (2 * Math.PI) + 0.5;
-			texcoords[texcoords.length] = Math.asin(vertex[2] / magnitude) / Math.PI + 0.5;
-		}
-		else {
-			//Scale vertices
-			xyz = vec3.fromValues(x[i], y[i], z[i]);
+	if (md.mesh.classname() == 'mesh3dsurface') {
+		var xyz, magnitude;
+		for(var i = 0; i < x.length; i++){
+			xyz = vec3.fromValues(vertices[0][i], vertices[1][i], vertices[2][i]);
 			magnitude = vec3.length(xyz);
-			vec3.normalize(direction, xyz);
-			vec3.scale(vertex, direction, magnitude);
-			vertices[vertices.length] = vertex[0];
-			vertices[vertices.length] = vertex[1];
-			vertices[vertices.length] = vertex[2];
-			
-			texcoords[texcoords.length] = (x[i] - modelxlim[0]) / xrange;
-			texcoords[texcoords.length] = (y[i] - modelylim[0]) / yrange;
+		
+			coordArray[0][i] = Math.atan2(xyz[1], xyz[0]) / (2 * Math.PI) + 0.5;
+			coordArray[1][i] = Math.asin(xyz[2] / magnitude) / Math.PI + 0.5;
 		}
 	}
-	//linearize the elements array:
-	var element;
-	for(var i = 0; i < elements.length; i++){
-		element = [elements[i][0] - 1, elements[i][1] - 1, elements[i][2] - 1];
-		if (element[0] in nanindices || element[1] in nanindices || element[2] in nanindices) continue;
-		indices[indices.length] = element[0];
-		indices[indices.length] = element[1];
-		indices[indices.length] = element[2];
+	else {
+		for(var i = 0; i < x.length; i++){
+			coordArray[0][i] = (vertices[0][i] - xlim[0]) / xRange;
+			coordArray[1][i] = (vertices[1][i] - ylim[0]) / yRange;
+		}
 	}
-	node.mesh = GL.Mesh.load({vertices: vertices, coords: texcoords, triangles: indices}, null, null, gl);
+	node.patch('Faces', elements, 'Vertices', vertices, 'FaceVertexCData', coordArray, 'FaceColor', 'interp');
 } //}}}
Index: /issm/trunk/src/m/plot/plot_overlay.m
===================================================================
--- /issm/trunk/src/m/plot/plot_overlay.m	(revision 22757)
+++ /issm/trunk/src/m/plot/plot_overlay.m	(revision 22758)
@@ -41,27 +41,28 @@
 end
 contrast = getfieldvalue(options,'contrast',1);  
-radar = (md.radaroverlay.pwr).^(contrast);
-radar = radar./max(radar(:));
+radar    = md.radaroverlay.pwr;
 if size(radar,3)>1,
 	disp('WARNING: color image converted to greyscale intensity image');
-	radar=sum(radar,3)/3;
+	if strcmp(class(radar),'uint8'),
+		radar=double(sum(radar,3))/(255*3);
+	else
+		radar=sum(radar,3)/3;
+	end
 end
-%radar(find(radar==0))=1; %Change background from black to white
+radar = radar.^(contrast);
+radar = radar./max(radar(:));
+
+if getfieldvalue(options,'backgroundbtw',0)
+	radar(find(radar==0))=1; %Change background from black to white
+end
 
 %InterpFromMeshToGrid
-xmin=min(md.radaroverlay.x);
-ymax=max(md.radaroverlay.y);
-xspacing=(max(md.radaroverlay.x)-min(md.radaroverlay.x))/(length(md.radaroverlay.x));
-yspacing=(max(md.radaroverlay.y)-min(md.radaroverlay.y))/(length(md.radaroverlay.y));
-nlines=length(md.radaroverlay.y);
-ncols =length(md.radaroverlay.x);
 disp('Interpolating data on grid...');
+x_m = md.radaroverlay.x;
+y_m = md.radaroverlay.y;
 if radaronly,
-	x_m=xmin:xspacing:xmin+ncols*xspacing;
-	y_m=ymax-nlines*yspacing:yspacing:ymax;
-	data_grid=NaN*ones(nlines,ncols);
+	data_grid=NaN(size(radar));
 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);
+	data_grid=InterpFromMeshToGrid(elements,x/getfieldvalue(options,'unit',1),y/getfieldvalue(options,'unit',1),data,x_m,y_m,NaN);
 end
 
@@ -138,5 +139,5 @@
 
 %Plot: 
-imagesc(md.radaroverlay.x*getfieldvalue(options,'unit',1),md.radaroverlay.y*getfieldvalue(options,'unit',1),image_rgb);set(gca,'YDir','normal');
+imagesc(x_m*getfieldvalue(options,'unit',1),y_m*getfieldvalue(options,'unit',1),image_rgb);set(gca,'YDir','normal');
 
 %last step: mesh overlay?
Index: /issm/trunk/src/m/plot/plot_quiver.js
===================================================================
--- /issm/trunk/src/m/plot/plot_quiver.js	(revision 22757)
+++ /issm/trunk/src/m/plot/plot_quiver.js	(revision 22758)
@@ -1,3 +1,3 @@
-function plot_quiver(md, options, canvas, updateVel) { //{{{
+function plot_quiver(md, options, canvas, noCacheNodesOverride) { //{{{
 	//PLOT_QUIVER - quiver plot with colors
 	//
@@ -7,16 +7,12 @@
 	//   See also: PLOTMODEL, PLOT_MANAGER
 
+	//Disabling for now, since quivers are "sticky" - once turned on, they won't turn off. This is due to cachenodes, but should find better way to handle it.
+	return;
+	
+	if ('quiver' in  canvas.nodes && noCacheNodesOverride && options.getfieldvalue('cachenodes','on') === 'on') return;
+	
 	//{{{ declare variables:
-	var vertices = [];
-	var indices = [];
-	var colors = [];
-	var xmin, xmax;
-	var ymin, ymax;
-	var zmin, zmax;
-	var scale, matrixscale, vertexscale;
-	
 	//Process data and model
-	var meshresults = processmesh(md,[], options);
-
+	var meshresults = processmesh(md, [], options);
 	var x = meshresults[0]; 
 	var y = meshresults[1]; 
@@ -25,64 +21,48 @@
 	var is2d = meshresults[4]; 
 	var isplanet = meshresults[5];
-	var v = updateVel != undefined ? updateVel.vel : md.initialization.vel;
-	var vx = updateVel != undefined ? updateVel.vx : md.initialization.vx;
-	var vy = updateVel != undefined ? updateVel.vy : md.initialization.vy;
+	if (md.mesh.classname() !== 'mesh3dsurface') z = md.geometry.surface;
 		
-	//Compue scaling through matrices for 2d meshes and vertices for 3d meshes
-	if (!md.geometry.surface) {
-		md.geometry.surface=NewArrayFill(md.mesh.x.length, 0);
-	}
-	if (md.mesh.classname() == 'mesh3dsurface') {
-		matrixscale = 1;
-		vertexscale = options.getfieldvalue('heightscale', 1);
+	//Compute coordinates and data range:
+	var xlim = options.getfieldvalue('xlim', [ArrayMin(x), ArrayMax(x)]);
+	var ylim = options.getfieldvalue('ylim', [ArrayMin(y), ArrayMax(y)]);
+	var zlim = options.getfieldvalue('zlim', [ArrayMin(z), ArrayMax(z)]);
+
+	//Only displaying velocity fields for now
+	var v = VESL.Helpers.isEmptyOrUndefined(md.results) ?  md.initialization.vel : md.results[canvas.animation.frame].Vel;
+	var vx = VESL.Helpers.isEmptyOrUndefined(md.results) ? md.initialization.vx : md.results[canvas.animation.frame].Vx;
+	var vy = VESL.Helpers.isEmptyOrUndefined(md.results) ? md.initialization.vy : md.results[canvas.animation.frame].Vy;
+
+	//Handle heightscale
+	var vertices, scale;
+	if (md.mesh.classname() !== 'mesh3dsurface') {
+		vertices = [x, y, z];
+		scale = [1, 1, options.getfieldvalue('heightscale', 1)];
 	}
 	else {
-		if (md.geometry.surface) {
-			z=md.geometry.surface;
-		}	
-		matrixscale = options.getfieldvalue('heightscale', 1);
-		vertexscale = 0;
+		vertices = Node.prototype.scaleVertices(md, x, y, z, elements, options.getfieldvalue('heightscale', 1), options.getfieldvalue('maskregion',{'enabled':false}));
+		scale = [1, 1, 1];
 	}
-	//}}}
-
-	//Compute coordinates and data range:
-	var modelxlim = [ArrayMin(x), ArrayMax(x)];
-	var modelylim = [ArrayMin(y), ArrayMax(y)];
-	var modelzlim = [ArrayMin(z), ArrayMax(z)];
-	var xlim = options.getfieldvalue('xlim', modelxlim);
-	var ylim = options.getfieldvalue('ylim', modelylim);
-	var zlim = options.getfieldvalue('zlim', modelzlim);
-	xmin = xlim[0];
-	xmax = xlim[1];
-	ymin = ylim[0];
-	ymax = ylim[1];
-	zmin = zlim[0];
-	zmax = zlim[1];
-
+	
 	//Compute gl variables:
-	var gl = canvas.gl;
-	var node = Node(gl);
-	canvas.nodes["velocity"] = node;
-	node.name = "quiver";
-	node.shaderName = "Colored";
-	node.shader = gl.shaders[node.shaderName];
-	node.lineWidth = options.getfieldvalue('linewidth', 1);
-	node.scale = [1, 1, matrixscale];
-	node.rotation = [-90, 0, 0];
-	node.translation = [0, 0, 0];
-	node.center = [(xmin + xmax) / 2, (ymin + ymax) / 2, (zmin + zmax) / 2];
-	node.drawMode = gl.LINES;
-	node.useIndexBuffer = false;
-	node.drawOrder = 0;
-	node.maskEnabled = options.getfieldvalue('innermask','off') == 'on';
-	node.maskHeight = options.getfieldvalue('innermaskheight', 150.0)*options.getfieldvalue('heightscale', 1);
-	node.maskColor = options.getfieldvalue('innermaskcolor',[0.0, 0.0, 1.0, 1.0]);
-	updateModelMatrix(node);
-
-	//retrieve some options
-	var edgecolor=new RGBColor(options.getfieldvalue('edgecolor','black'));
-	if (edgecolor.ok) edgecolor = [edgecolor.r/255.0, edgecolor.g/255.0, edgecolor.b/255.0, 1.0];
-	else throw Error(sprintf("s%s%s\n","initWebGL error message: cound not find out edgecolor color for curent canvas ", canvas));
-
+	var edgecolor = options.getfieldvalue('edgecolor', 'black');
+	var node = new Node(
+		'canvas', canvas,
+		'options', options,
+		'name', 'quiver',
+		'shaderName', 'Colored',
+		'alpha', options.getfieldvalue('alpha', 1.0),
+		//'center', [(xlim[0] + xlim[1]) / 2, (ylim[0] + ylim[1]) / 2, md.mesh.classname() === 'mesh3dsurface' ? (zlim[0] + zlim[1]) / 2 : zlim[0]],
+		'center', [(xlim[0] + xlim[1]) / 2, (ylim[0] + ylim[1]) / 2, (zlim[0] + zlim[1]) / 2],
+		'drawMode', canvas.gl.LINES,
+		'diffuseColor', edgecolor,
+		'lineWidth', options.getfieldvalue('linewidth', 1),
+		'maskEnabled', options.getfieldvalue('innermask','off') == 'on',
+		'maskHeight', options.getfieldvalue('innermaskheight', 150.0) / options.getfieldvalue('heightscale', 1),
+		'maskColor', options.getfieldvalue('innermaskcolor',[0.0, 0.0, 1.0, 1.0]),
+		'rotation', [-90, 0, 0],
+		'scale', scale
+	);
+	
+	
 	//{{{ node plot
 	if (elements[0].length==6){ //prisms
@@ -91,48 +71,36 @@
 	}
 	else{ //2D triangular elements
+		//Create arow vertices, and use vx/vy to determine rotation before adding to quiver mesh.
+		var verticesArrow = [vec3.fromValues(0.0, 0.0, 0.0), vec3.fromValues(1.0, 0.0, 0.0), vec3.fromValues(0.667, -0.167, 0.0), vec3.fromValues(1.0, 0.0, 0.0), vec3.fromValues(0.667, 0.166, 0.0), vec3.fromValues(1.0, 0.0, 0.0)];
+		
+		var newX = [];
+		var newY = [];
+		var newZ = [];
 		var xyz = vec3.create();
-		var xyz = vec3.create();
-		var direction = vec3.create();
 		var vertex = vec3.create();
-		var vertexBase = vec3.create();
-		var verticesArrow = [vec3.fromValues(0.0, 0.0, 0.0), vec3.fromValues(1.0, 0.0, 0.0), vec3.fromValues(0.667, -0.167, 0.0), vec3.fromValues(1.0, 0.0, 0.0), vec3.fromValues(0.667, 0.166, 0.0), vec3.fromValues(1.0, 0.0, 0.0)];
-		var magnitude;
-		var color = edgecolor;
 		var scaling = options.getfieldvalue('scaling', 1);
-		var scale;
-		for(var i = 0; i < x.length; i++){
-			//Check for NaN values and remove from indices array as necessary, but preserve vertex array spacing
-			if (isNaN(x[i]) || isNaN(y[i]) || isNaN(z[i])) continue;
-			//Scale vertices
+		var heightScale = options.getfieldvalue('heightscale', 1);
+		var arrowScale;
+		var modelMatrix = mat4.create();
+		var scaleMatrix = mat4.create();
+		var rotationMatrix = mat4.create();
+		
+		for(var i = 0, iX = 0, iY = 0, iZ = 0; i < x.length; i++){
 			xyz = vec3.fromValues(x[i], y[i], z[i]);
-			magnitude = vec3.length(xyz) + md.geometry.surface[i] * vertexscale;
-			vec3.normalize(direction, xyz);
-			vec3.scale(vertex, direction, magnitude);
-			vec3.copy(vertexBase, vertex);
-			
-			scale = scaling*v[i];
-			var modelMatrix = mat4.create();
-			var scaleMatrix = mat4.create();
-			var rotationMatrix = mat4.create();
-			mat4.scale(scaleMatrix, scaleMatrix, vec3.fromValues(scale, scale, scale));
-			mat4.rotate(rotationMatrix, rotationMatrix, Math.atan2(vy[i], vx[i]), [0.0, 0.0, 1.0]);
+			arrowScale = v[i] * scaling;
+			scaleMatrix = mat4.create();
+			mat4.scale(scaleMatrix, mat4.create(), vec3.fromValues(arrowScale, arrowScale, arrowScale));
+			mat4.rotate(rotationMatrix, mat4.create(), Math.atan2(vy[i], vx[i]), [0.0, 0.0, 1.0]);
 			mat4.multiply(modelMatrix, rotationMatrix, scaleMatrix);
-
-			var temp = vec3.fromValues(0.0, 0.0, 0.0);
 			for (var j = 0; j < 6; j++){
 				vec3.transformMat4(vertex, verticesArrow[j], modelMatrix);
-				vec3.add(vertex, vertex, vertexBase);
-				vertices[vertices.length] = vertex[0];
-				vertices[vertices.length] = vertex[1];
-				vertices[vertices.length] = vertex[2];
-				
-				colors[colors.length] = color[0];
-				colors[colors.length] = color[1];
-				colors[colors.length] = color[2];
-				colors[colors.length] = color[3];
+				vec3.add(vertex, vertex, xyz);
+				newX[iX++] = vertex[0];
+				newY[iY++] = vertex[1];
+				newZ[iZ++] = vertex[2];
 			}
 		}
+		node.patch('Vertices', [newX, newY, newZ], 'FaceColor', 'none');
 	}
 	//}}}
-	node.mesh = GL.Mesh.load({vertices: vertices, colors: colors}, null, null, gl);
 } //}}}
Index: /issm/trunk/src/m/plot/plot_scatter.m
===================================================================
--- /issm/trunk/src/m/plot/plot_scatter.m	(revision 22757)
+++ /issm/trunk/src/m/plot/plot_scatter.m	(revision 22758)
@@ -8,4 +8,5 @@
 %      'caxis'      : default is full range
 %      'MarkerSize' : default is 3
+%      'subset'     : only plot the indices provided
 %      'Line'       : use line instead of circles
 %      'Cutoff'     : cut the line if the distance between 2 points is
@@ -21,4 +22,11 @@
 if numel(x)~=numel(y) | numel(x)~=numel(level),
 	error('x, y and data should have the same size');
+end
+
+if exist(options,'subset'),
+	pos=getfieldvalue(options,'subset');
+	x=x(pos);
+	y=y(pos);
+	level=level(pos);
 end
 
@@ -59,4 +67,5 @@
 else
 	palette=getcolormap(options);
+	colormap(palette);
 	numcolors=size(palette,1);
 	levels=round_ice(linspace(Min,Max,numcolors+1),2);
@@ -76,5 +85,6 @@
 	for i=1:numcolors
 		pos=find(colorind==i);
-		hprime=plot3(x(pos),y(pos),ones(size(x(pos))),...
+	%	hprime=plot3(x(pos),y(pos),ones(size(x(pos))),...
+		hprime=plot(x(pos),y(pos),...
 			'o','MarkerSize',getfieldvalue(options,'MarkerSize',3),'MarkerEdgeColor',palette(i,:),...
 			'MarkerFaceColor',palette(i,:));
Index: /issm/trunk/src/m/plot/plot_transient_movie.js
===================================================================
--- /issm/trunk/src/m/plot/plot_transient_movie.js	(revision 22758)
+++ /issm/trunk/src/m/plot/plot_transient_movie.js	(revision 22758)
@@ -0,0 +1,110 @@
+function plot_transient_movie(md, options, canvas) { //{{{
+	//PLOT_TRANSIENT_MOVIE - plot a transient result as a movie
+	//
+	//   Usage:
+	//      plot_transient_movie(md, options, canvas);
+	//
+	//   See also: PLOTMODEL, PLOT_MANAGER
+	
+	//loop over the time steps
+	var data = options.getfieldvalue('transient_field_data');
+	var datatype;
+	var steps = new Array(data.length); 
+	for (i = 0; i < steps.length; i++) {
+		steps[i] = i;
+	}
+	
+	//calculate caxis
+	if (!options.exist('caxis')) {
+		var range = [Infinity, -Infinity];
+		var	dataresults;
+		for (var i in steps) {
+			dataresults = processdata(md, data[i], options);
+			range[0] = Math.min(range[0], ArrayMin(dataresults[1]));
+			range[1] = Math.max(range[1], ArrayMax(dataresults[1]));
+		}
+		datatype = dataresults[1];
+		options.addfielddefault('caxis', range);
+		
+	}
+	
+	//Create unit node if it does not already exist
+	if (!('unit' in canvas.nodes)) {
+		var	dataresults = processdata(md, data[0],options);
+		var	data2 = dataresults[0]; 
+		var	datatype = dataresults[1];
+	
+		//plot unit
+		plot_unit(md,data2,datatype,options,canvas);
+	}
+	
+	//Setup rendering node
+	var node = canvas.nodes.unit;
+	node.options = options;
+	node.alpha = options.getfieldvalue('alpha', 1.0);
+	node.caxis = options.getfieldvalue('caxis');
+	node.enabled = options.getfieldvalue('nodata', 'off') == 'off';
+	node.log = options.getfieldvalue('log', false);
+	
+	//process data
+	var	dataresults;
+	var processedData = [];
+	for (var i in steps) {
+		dataresults = processdata(md, data[i].slice(), options);
+		processedData[i] = dataresults[0];
+	}
+	
+	//display movie
+	canvas.unitMovieData = processedData;
+	canvas.animation.frame = 0;
+	canvas.animation.handler = setInterval(function () {
+		//Update current animation frame
+		var frame = canvas.animation.frame;
+		if (canvas.animation.play) {
+			if (canvas.animation.increment) {
+				if (frame >= steps.length - 1) {
+					if (canvas.animation.loop) {
+						frame = 0;
+					}
+					else {
+						toggleMoviePlay(canvas);
+					}
+				}
+				else {
+					frame = (frame + 1) % steps.length;
+				}
+			}
+		}
+		
+		//If frame has changed, update unit node and data marker display.
+		if (frame !== canvas.animation.lastFrame) {
+			node.updateBuffer('Coords', processedData[frame]);
+			canvas.unitData = processedData[frame];
+			if (canvas.dataMarkers.enabled) {
+				updateMarker(canvas, false);
+			}
+			if (canvas.playbackSlider) {
+				canvas.playbackSlider.val(frame).slider('refresh');
+			}
+			if (canvas.playbackTextProgress) {
+				canvas.playbackTextProgress.html(steps[frame].toFixed(0) + " " + options.getfieldvalue("movietimeunit","yr"));
+			}
+			if (!VESL.Helpers.isEmptyOrUndefined(canvas.nodes.quiver)) {
+				plot_quiver(md,options,canvas,false);
+			}
+		}
+		
+		//Save new frame info.
+		canvas.animation.lastFrame = canvas.animation.frame;
+		canvas.animation.frame = frame;
+	}, canvas.animation.interval);
+	
+	//Update progress bar with new frame info.
+	if (canvas.playbackSlider) {
+		canvas.playbackSlider.val(canvas.animation.frame);
+		canvas.playbackSlider.attr('max', steps.length - 1);
+		canvas.playbackSlider.slider('refresh');
+	}
+				
+	applyoptions(md, [], options, canvas);
+} //}}}
Index: /issm/trunk/src/m/plot/plot_transient_movie.m
===================================================================
--- /issm/trunk/src/m/plot/plot_transient_movie.m	(revision 22757)
+++ /issm/trunk/src/m/plot/plot_transient_movie.m	(revision 22758)
@@ -7,5 +7,5 @@
 
 	%prepare subplot
-	subplot(width,width,i); 
+	subplot(width,width,i);
 
 	%xlim
Index: /issm/trunk/src/m/plot/plot_unit.js
===================================================================
--- /issm/trunk/src/m/plot/plot_unit.js	(revision 22757)
+++ /issm/trunk/src/m/plot/plot_unit.js	(revision 22758)
@@ -7,5 +7,20 @@
 	//   See also: PLOTMODEL, PLOT_MANAGER
 
-	//{{{ declare variables: 
+	var name = 'unit';
+	if ('unit' in canvas.nodes) {
+		if (options.getfieldvalue('clf','on')=='on') {
+			for (var node in canvas.nodes) {
+				if (node.startsWith('unit')) {
+					delete canvas.octrees[node];
+					delete canvas.nodes[node];
+				}
+			}
+		}
+		else {
+			name = 'unit' + Object.keys(canvas.nodes).length;
+		}
+	}
+
+	//{{{ declare variables:
 	//Process data and model
 	var meshresults = processmesh(md, data, options);
@@ -16,70 +31,62 @@
 	var is2d = meshresults[4]; 
 	var isplanet = meshresults[5];
+	if (md.mesh.classname() !== 'mesh3dsurface') z = md.geometry.surface;
 	
-	var vertices = new Float32Array(x.length * 3);
-	var texcoords = new Float32Array(x.length * 2);
-	var indices = new Uint16Array(elements.length * 3);
-	var nanindices = {};
-	var xmin, xmax;
-	var ymin, ymax;
-	var zmin, zmax;
-	var datamin, datamax, datadelta;
-	var matrixscale, vertexscale;
-	//Compue scaling through matrices for 2d meshes and vertices for 3d meshes
-	if (!md.geometry.surface) {
-		md.geometry.surface=NewArrayFill(md.mesh.x.length, 0);
-	}
-	if (md.mesh.classname() == 'mesh3dsurface') {
-		matrixscale = 1;
-		vertexscale = options.getfieldvalue('heightscale', 1);
+	//Compute coordinates and data range:
+	var xlim = options.getfieldvalue('xlim', [ArrayMin(x), ArrayMax(x)]);
+	var ylim = options.getfieldvalue('ylim', [ArrayMin(y), ArrayMax(y)]);
+	var zlim = options.getfieldvalue('zlim', [ArrayMin(z), ArrayMax(z)]);
+	
+	//Handle heightscale
+	var vertices, scale;
+	if (md.mesh.classname() !== 'mesh3dsurface') {
+		vertices = [x, y, z];
+		scale = [1, 1, options.getfieldvalue('heightscale', 1)];
 	}
 	else {
-		if (md.geometry.surface) {
-			z=md.geometry.surface;
-		}	
-		matrixscale = options.getfieldvalue('heightscale', 1);
-		vertexscale = 0;
+		vertices = Node.prototype.scaleVertices(md, x, y, z, elements, options.getfieldvalue('heightscale', 1), options.getfieldvalue('maskregion',{'enabled':false}));
+		scale = [1, 1, 1];
+	}
+	
+	//Compute gl variables:
+	var edgecolor = options.getfieldvalue('edgecolor', [1.0, 1.0, 1.0 ,1.0]);
+	var maskzeros = options.getfieldvalue('maskzeros', {});
+	var render = options.getfieldvalue('render', {});
+	var cullFace = ("unit" in render) ? canvas.gl[render.unit.cullFace] : canvas.gl.BACK;
+	var node = new Node(
+		'canvas', canvas,
+		'options', options,
+		'name', name,
+		'shaderName', 'TexturedDiffuse',
+		'alpha', options.getfieldvalue('alpha', 1.0),
+		'caxis', options.getfieldvalue('caxis',[ArrayMin(data), ArrayMax(data)]),
+		'center', [(xlim[0] + xlim[1]) / 2, (ylim[0] + ylim[1]) / 2, (zlim[0] + zlim[1]) / 2],
+		'cullFace', cullFace,
+		'lightingBias', canvas.view.lightingBias,
+		'diffuseColor', edgecolor,
+		'specularStrength', 0.0,
+		'enabled', options.getfieldvalue('nodata','off') == 'off' || (("unit" in render) && render.unit.enabled),
+		'log', options.getfieldvalue('log',false),
+		'maskEnabled', options.getfieldvalue('innermask','off') == 'on',
+		'maskHeight', options.getfieldvalue('innermaskheight', 150.0) / options.getfieldvalue('heightscale', 1),
+		'maskColor', options.getfieldvalue('innermaskcolor',[0.0, 0.0, 1.0, 1.0]),
+		'maskObject', options.getfieldvalue('maskregion',{'enabled':false}),
+		'maskZerosColor', defaultFor(maskzeros.color,[1.0, 1.0, 1.0, 1.0]),
+		'maskZerosEnabled', defaultFor(maskzeros.enabled,false),
+		'maskZerosTolerance', defaultFor(maskzeros.tolerance,1e-3),
+		'maskZerosZeroValue', defaultFor(maskzeros.zeroValue,0.5),
+		'rotation', [-90, 0, 0],
+		'scale', ("unit" in render) ? [render.unit.scale, render.unit.scale, render.unit.scale] : scale
+	);
+	//}
+	if (options.getfieldvalue('clf','on')=='on') {
+		canvas.unitNode = node;
+		canvas.unitData = data;
 	}
 	//}}}
-
-	//Compute coordinates and data range:
-	var modelxlim = [ArrayMin(x), ArrayMax(x)];
-	var modelylim = [ArrayMin(y), ArrayMax(y)];
-	var modelzlim = [ArrayMin(z), ArrayMax(z)];
-	var xlim = options.getfieldvalue('xlim', modelxlim);
-	var ylim = options.getfieldvalue('ylim', modelylim);
-	var zlim = options.getfieldvalue('zlim', modelzlim);
-	xmin = xlim[0];
-	xmax = xlim[1];
-	ymin = ylim[0];
-	ymax = ylim[1];
-	zmin = zlim[0];
-	zmax = zlim[1];
-	var caxis;
-
-	//Compute gl variables:
-	var gl = canvas.gl;
-	var node = Node(gl);
-	canvas.nodes[canvas.nodes.length] = node;
-	canvas.unitNode = node;
-	canvas.unitData = data;
-	node.name = "unit";
-	node.shaderName = "Textured";
-	node.shader = gl.shaders[node.shaderName];
-	node.scale = [1, 1, matrixscale];
-	node.rotation = [-90, 0, 0];
-	node.translation = [0, 0, 0];
-	node.center = [(xmin + xmax) / 2, (ymin + ymax) / 2, (zmin + zmax) / 2];
-	node.alpha = options.getfieldvalue('alpha', 1.0);
-	node.drawOrder = 1;
-	node.maskEnabled = options.getfieldvalue('innermask','off') == 'on';
-	node.maskHeight = options.getfieldvalue('innermaskheight', 150.0);
-	node.maskColor = options.getfieldvalue('innermaskcolor',[0.0, 0.0, 1.0, 1.0]);
-	node.enabled = options.getfieldvalue('nodata','off') == 'off';
-	updateModelMatrix(node);
-
 	switch(datatype){
 		//{{{ element plot
 		case 1:
+			//WARNING: NaN are not properly found (NaN != NaN = true)
 			pos=ArrayFindNot(data, NaN); //needed for element on water
 			if (elements[0].length==6){ //prisms
@@ -87,5 +94,6 @@
 			else if (elements[0].length==4){ //tetras
 			}
-			else{ //2D triangular elements
+			else{ //triangular elements
+				node.patch('Faces', elements, 'Vertices', vertices, 'FaceVertexCData', data, 'FaceColor', 'flat', 'EdgeColor', edgecolor);
 			}
 			break;
@@ -98,53 +106,6 @@
 			}
 			else{ //triangular elements	
-				caxis = options.getfieldvalue('caxis',[ArrayMin(data), ArrayMax(data)]);
-				if (options.getfieldvalue('log','off')!='off') caxis = [Math.log10(caxis[0])/Math.log10(options.getfieldvalue('log', 10)), Math.log10(caxis[1])/Math.log10(options.getfieldvalue('log', 10))];
-				datamin = caxis[0];
-				datamax = caxis[1];
-				datadelta = datamax - datamin;
-
-				var xyz = vec3.create();
-				var direction = vec3.create();
-				var vertex = vec3.create();
-				var magnitude;
-
-				for(var i = 0, vindex = 0, tindex = 0; i < x.length; i++){
-					//Check for NaN values and remove from indices array as necessary, but preserve vertex array spacing
-					if (isNaN(x[i]) || isNaN(y[i]) || isNaN(z[i]) || isNaN(data[i])) {
-						nanindices[i] = i;
-						vertices[vindex++] = vertex[0];
-						vertices[vindex++] = vertex[1];
-						vertices[vindex++] = vertex[2];
-						
-						texcoords[tindex++] = 0.5;
-						texcoords[tindex++] = 0.0;
-						continue;
-					}
-
-					//Scale vertices
-					xyz = vec3.fromValues(x[i], y[i], z[i]);
-					magnitude = vec3.length(xyz) + md.geometry.surface[i] * vertexscale;
-					vec3.normalize(direction, xyz);
-					vec3.scale(vertex, direction, magnitude);
-					vertices[vindex++] = vertex[0];
-					vertices[vindex++] = vertex[1];
-					vertices[vindex++] = vertex[2];
-
-					texcoords[tindex++] = 0.5;
-					texcoords[tindex++] = clamp((data[i] - datamin) / datadelta, 0.0, 1.0);
-				}
-
-				//linearize the elements array: 
-				var element;
-				for(var i = 0, iindex = 0; i < elements.length; i++){
-					element = [elements[i][0] - 1, elements[i][1] - 1, elements[i][2] - 1];
-					if (element[0] in nanindices || element[1] in nanindices || element[2] in nanindices) continue;
-					indices[iindex++] = element[0];
-					indices[iindex++] = element[1];
-					indices[iindex++] = element[2];
-				}
+				node.patch('Faces', elements, 'Vertices', vertices, 'FaceVertexCData', data, 'FaceColor', 'interp', 'EdgeColor', edgecolor);
 			}
-			node.mesh = GL.Mesh.load({vertices: vertices, coords: texcoords, triangles: indices}, null, null, gl);
-			node.mesh.octree = new GL.Octree(node.mesh);
 			break;
 		//}}}
@@ -159,134 +120,6 @@
 			break;
 		//}}}
-		//{{{ node transient plot
-		case 5:
-			if (elements[0].length==6){ //prisms
-			}
-			else if (elements[0].length==4){//tetras
-			}
-			else{ //triangular elements
-				var xyz = vec3.create();
-				var direction = vec3.create();
-				var vertex = vec3.create();
-				var magnitude;
-				var timestamps = data[data.length-1];
-				for(var i = 0, vindex = 0, tindex = 0; i < x.length; i++){
-					//Check for NaN values and remove from indices array as necessary, but preserve vertex array spacing
-					if (isNaN(x[i]) || isNaN(y[i]) || isNaN(z[i]) || isNaN(data[i][0])) {
-						nanindices[i] = i;
-					}
-					else {
-						//Scale vertices
-						xyz = vec3.fromValues(x[i], y[i], z[i]);
-						magnitude = vec3.length(xyz) + md.geometry.surface[i] * vertexscale;
-						vec3.normalize(direction, xyz);
-						vec3.scale(vertex, direction, magnitude);
-					}
-					vertices[vindex++] = vertex[0];
-					vertices[vindex++] = vertex[1];
-					vertices[vindex++] = vertex[2];
-				}	
-				//Transpose data to obtain column addressable data matrix
-				data = data[0].map(function(col, i) { 
-					return data.map(function(row) { 
-						return row[i]
-					})
-				});
-				//Prevent evaluation of datasubarray min/max if caxis exists
-				if (options.exist('caxis')) caxis = options.getfieldvalue('caxis');
-				else caxis = [ArrayMin(data[0]), ArrayMax(data[0].slice(0,-1))];
-				if (options.getfieldvalue('log','off')!='off') caxis = [Math.log10(caxis[0])/Math.log10(options.getfieldvalue('log', 10)), Math.log10(caxis[1])/Math.log10(options.getfieldvalue('log', 10))];
-				//Prepare texcoords to hold array of data values
-				texcoords = [];
-				for(var i = 0; i < data.length; i++){					
-					datamin = caxis[0];
-					datamax = caxis[1];
-					datadelta = datamax - datamin;
-					//Precalculate arrays for each datasubarray, trimming off timestamp value by using x.length instead of data[i].length
-					texcoords[i] = new Float32Array(x.length * 2);
-					for(var j = 0, index = 0; j < x.length; j++){
-						texcoords[i][index++] = 0.5;
-						texcoords[i][index++] = clamp((data[i][j] - datamin) / datadelta, 0.0, 1.0);
-					}
-				}
-				
-				//linearize the elements array:
-				var element;
-				for(var i = 0, iindex = 0; i < elements.length; i++){
-					element = [elements[i][0] - 1, elements[i][1] - 1, elements[i][2] - 1];
-					if (element[0] in nanindices || element[1] in nanindices || element[2] in nanindices) continue;
-					indices[iindex++] = element[0];
-					indices[iindex++] = element[1];
-					indices[iindex++] = element[2];
-				}
-			
-				//Initialize movie loop
-				node.movieLoop = canvas.animation.loop;
-				node.movieInterval = 1000 / canvas.animation.fps;
-				node.movieTimestamps = timestamps;
-				node.movieLength = timestamps.length;
-				node.movieFrame = 0;
-				canvas.dataMarkers.values = [];
-				var quiverVelFrames = {};
-				for(var i=0; i < md.results.length; i++){
-					quiverVelFrames[Math.floor(md.results[i].time)] = md.results[i];
-				}
-
-				if (canvas.animation.handler !== 0) {
-					console.log("clearing...");
-					clearInterval(canvas.animation.handler)
-				}
-				//TODO: Move this into webgl.js
-				canvas.animation.handler = setInterval(function () {
-					node.movieFrame = canvas.animation.frame;
-					if (canvas.animation.play && canvas.animation.increment) {
-						if (node.movieFrame == node.movieLength - 1) {
-							if (node.movieLoop) {
-								node.movieFrame = 0;
-							}
-							else { 
-								toggleMoviePlay(canvas);
-							}
-						}
-						else {
-							node.movieFrame = node.movieFrame + 1;
-						}
-						if (canvas.animation.lastFrame != canvas.animation.frame) {
-							updateMarker(canvas, false);
-						}
-					}
-					
-					if (canvas.progressBar) {
-						canvas.progressBar.val(node.movieFrame);
-						canvas.progressBar.slider('refresh');
-					}
-					if (canvas.timeLabel) { canvas.timeLabel.html(node.movieTimestamps[node.movieFrame].toFixed(0) + " " + options.getfieldvalue("movietimeunit","yr")); }
-					
-					var buffer = node.mesh.getBuffer("coords");
-					buffer.data = texcoords[node.movieFrame];
-					buffer.upload(canvas.gl.DYNAMIC_DRAW);
-					node.mesh.octree = new GL.Octree(node.mesh);
-					node.texcoords = texcoords;
-					if(options.getfieldvalue('quiver') == 'on'){
-						plot_quiver(md, options, canvas, {vel: quiverVelFrames[node.movieFrame].Vel, vx: quiverVelFrames[node.movieFrame].Vx, vy: quiverVelFrames[node.movieFrame].Vy});
-					}
-					canvas.animation.lastFrame = canvas.animation.frame;
-					canvas.animation.frame = node.movieFrame;					
-				}, node.movieInterval);
-				
-				if (canvas.progressBar) {
-					canvas.animation.frame = 0;
-					canvas.progressBar.val(0);
-					canvas.progressBar.attr('max', node.movieLength-1);
-					canvas.progressBar.slider('refresh');
-				}
-				
-			}
-			node.mesh = GL.Mesh.load({vertices: vertices, coords: texcoords[0], triangles: indices}, null, null, gl);
-			node.mesh.octree = new GL.Octree(node.mesh);
-			break;
-		//}}}
 		default:
-			throw Error(sprintf("%s%i%s\n",'case ', datatype,' not supported'));
+			throw Error(sprintf('%s%i%s\n','case ', datatype,' not supported'));
 	}
 } //}}}
Index: /issm/trunk/src/m/plot/plot_unit.m
===================================================================
--- /issm/trunk/src/m/plot/plot_unit.m	(revision 22757)
+++ /issm/trunk/src/m/plot/plot_unit.m	(revision 22758)
@@ -30,6 +30,15 @@
 			patch( 'Faces',[C A D],'Vertices', [x y z],'CData',data(pos),'FaceColor','flat','EdgeColor',edgecolor);
 		else
-			A=elements(pos,1); B=elements(pos,2); C=elements(pos,3);
-			patch( 'Faces', [A B C], 'Vertices', [x y z],'CData', data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+			A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); data=data(pos);
+			patch( 'Faces', [A B C], 'Vertices', [x y z],'CData', data,'FaceColor','flat','EdgeColor',edgecolor);
+			
+			%mask value NaN, plot white faces.
+			if getfieldvalue(options,'maskwhite',0),
+				pos2=find(data==getfieldvalue(options,'maskvalue',NaN));
+				if ~isempty(pos2),
+					A=elements(pos(pos2),1); B=elements(pos(pos2),2); C=elements(pos(pos2),3); data=data(pos2);
+					patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceColor','w','EdgeColor',edgecolor);
+				end
+			end
 		end
 
Index: /issm/trunk/src/m/plot/plot_unit.py
===================================================================
--- /issm/trunk/src/m/plot/plot_unit.py	(revision 22757)
+++ /issm/trunk/src/m/plot/plot_unit.py	(revision 22758)
@@ -94,6 +94,4 @@
 			tri=ax.tripcolor(triangles,data,colorlevels,cmap=cmap,norm=norm,alpha=alpha,edgecolors=edgecolor)
 		else:
-
-
 			#first deal with colormap
 			loccmap = plt.cm.ScalarMappable(cmap=cmap)
@@ -152,5 +150,9 @@
 			else:
 				triangles=mpl.tri.Triangulation(x,y,elements)
-			tri=ax.tricontourf(triangles,data,colorlevels,cmap=cmap,norm=norm,alpha=alpha)
+				#tri=ax.tricontourf(triangles,data,colorlevels,cmap=cmap,norm=norm,alpha=alpha)
+			if options.exist('log'):
+				tri=ax.tricontourf(triangles,data,colorlevels,cmap=cmap,norm=norm,alpha=alpha)
+			else:
+				tri=ax.tricontourf(triangles,data,colorlevels,cmap=cmap,norm=norm,alpha=alpha,extend='both')
 			if edgecolor != 'None':
 				ax.triplot(x,y,elements,color=edgecolor)
Index: /issm/trunk/src/m/plot/plotdoc.js
===================================================================
--- /issm/trunk/src/m/plot/plotdoc.js	(revision 22757)
+++ /issm/trunk/src/m/plot/plotdoc.js	(revision 22758)
@@ -5,18 +5,23 @@
 	//      plotdoc()
 	
-	//TODO: Standardize image to overlay_image, heightscale to scaling, colorbarfontsize/color, clarify innermask/outermask, edgecolor implementation, check colormap, 
+	//TODO: rename innermask/outermask/maskzero and combine
 
-	console.log(' WARNING: starred methods (*) are experimental and not guarenteed to be stable');
 	console.log('   Plot usage: plotmodel(model,varargin)');
 	console.log('   Options: ');
 	console.log('       "canvasid": canvas id');
 	console.log('       "data" : what we want to plot');
-	console.log('                Available values for "data" are: ');
-	console.log('                  - any field of the model structure. ex: plot(md,"data","vel"), or plot(md,"data",md.initialization.vel)');
-	console.log('                  - "mesh": draw mesh using trisurf');
-	console.log('                  - "quiver": quiver plot');
-	console.log('       "2d": renders orthographic camera with view set to [0, 90] (default "off", ex: "on", "off")');
+	console.log('       	Available values for "data" are: ');
+	console.log('       		- any field of the model structure. ex: plot(md,"data","vel"), or plot(md,"data",md.initialization.vel)');
+	console.log('       		- "mesh": draw mesh using trisurf');
+	console.log('       		- "quiver": quiver plot');
 	console.log('       "backgroundcolor": plot background color. (default "lightcyan", ex: "green","blue")');
 	console.log('       "brush": specify brush options (default {"strength":0.075,"falloff":0.5})');
+	console.log('       	"enabled": toggle brush (default false, ex: true)');
+	console.log('       	"strength": value that brush will change data points by (ex: 0.075)');
+	console.log('       	"falloff": multiplier that brush will decrease strength by for each successive point away from brush center (ex: 0.5)');
+	console.log('       "clouds": specify brush options (default {"strength":0.075,"falloff":0.5})');
+	console.log('       	"enabled": toggle clouds (default false, ex: true)');
+	console.log('       	"height": height to spawn clouds at (ex: 7500)');
+	console.log('       	"quantity": quantity of clouds to spawn (ex: 10)');
 	console.log('       "caxis": modify  colorbar range. (array of type [a, b] where b>=a)');
 	console.log('       "colorbar": add colorbar (default "off", ex: "on", "off")');
@@ -32,16 +37,24 @@
 	console.log('       "colormap": same as standard matlab option (default "jet", ex: "hsv","cool","spring","gray","Ala","Rignot",...)');
 	console.log('       "controlsensitivity": sensitivty of view/zoom changes as a percentage of default (default 1, ex: 0.5, 2.75)');
-	console.log('       "datamarkers": toggle data marker displays (default "on", ex: "on", "off")');
-	console.log('       "datamarkers_image": toggle data marker displays (default "on", ex: "on", "off")');
-	console.log('       "datamarkerssize": specifiy the width and height of the data markers (default [32,32], ex: [24,32], [105,10])');
-	console.log('       "datamarkersoptions": specifiy options for data markers (default {"enabled":"on","image":canvas.rootPath+"textures/data_marker.svg","size":[32,32],"format":["X: %.2e<br>Y: %.2e<br>Z: %.2e]<br>Value: %0.1f","x","y","z","value"]}');
+	console.log('       "datamarkers": object cotaining data marker parameters. See webgl.js for defaults. (ex: {"enabled":true,"format":["<div id="sim-plot"></div>"],"labels":["thickness","velocity","value"],"animated":true})');
+	console.log('       	"enabled": toggle data marker displays (default true, ex: false)');
+	console.log('       	"image": image used for marking the clicked point (ex: "/canvas/data-markers/data_marker.svg")');
+	console.log('       	"labels": when displaying a sim-plot graph, display these model fields. (ex: ["thickness","velocity","value"])');
+	console.log('       	"font": font to be used for display (ex: "24px "Comic Sans MS", cursive")');
+	console.log('       	"format": an array compatible with sprintf that will be displayed as html (ex: ["X: %.2e<br>Y: %.2e<br>Z: %.2e]<br>Value: %0.1f","x","y","z","value"])');
+	console.log('      		"size": specifiy the width and height of the data markers (default [32,32], ex: [24,32], [105,10])');
 	console.log('       "displayview": print view value to console (default "off", ex: "on", "off")');
 	console.log('       "displayzoom": print zoom value to console (default "off", ex: "on", "off")');
 	console.log('       "edgecolor": same as standard matlab option EdgeColor (default "black", ex: color name: "blue" or RGB array: [0.5, 0.2, 0.8])');
 	console.log('       "heightscale": scaling factor to accentuate height. (default 1, ex: 0.5, 100)');
-	console.log('       "linewidth*": line width for mesh, quiver, and contour plots, currently limited by WebGL to 1. (default 1, ex: 2, 5)');
+	console.log('       "linewidth": line width for mesh, quiver, and contour plots, currently limited by WebGL to 1. (default 1, ex: 2, 5)');
 	console.log('       "log": value of log (default 10, ex: 2, Math.E)');
 	console.log('       "mask": list of flags of size numberofnodes or numberofelements. Only "true" values are plotted ');
-	console.log('       "movieoptions": specify movie options (default {"fps":4,"loop":true})');
+	console.log('       "movies": object cotaining transient plot animation options (ex: {"fps":4,"loop":true})');
+	console.log('       "maskzeros": object cotaining transient plot animation options (ex: "enabled":true,"color":[1.0, 1.0, 1.0, 1.0],"tolerance":1e-3,"zeroValue":0.5})');
+	console.log('       	"enabled": toggle maskzeros (default false, ex: true)');
+	console.log('       	"color": RGBA color value array with ranges 0.0 to 1.0 (ex: [1.0, 1.0, 1.0, 1.0])');
+	console.log('       	"tolerance": values within this tolerance of the zeroValue will be masked. (default: 1e-3, ex: 2.5e-2)');
+	console.log('       	"zeroValue": the percentage value with range 0.0, to 1.0 of the caxis value around which the data will be masked with the color. (default: 0.5, ex: 0, 1.0, 0.75)');
 	console.log('       "innermask*": Special mask that colors all parts of a data mesh below a height a certain color. provide innermaskheight and innermaskcolor options also (default "off", ex: "on", "off")');
 	console.log('       "outermask*": Special mask that colors all parts of a overlay mesh below a height a certain color. provide outermaskheight and outermaskcolor options also (default "off", ex: "on", "off")');
@@ -51,18 +64,49 @@
 	console.log('       "scaling": scaling factor used by quiver plots. Default is 0.4');
 	console.log('       "alpha": transparency coefficient 0.0 to 1.0, the lower, the more transparent. (default 1.0, ex: 0.5, 0.25)');
-	console.log('       "azlim": azimuth view limits (ex: [0, 180])');
-	console.log('       "ellim": elevation view limits (ex: [-90, 90])');
-	console.log('       "origin": initial camera offset from model center (default [0,0,0.0], ex: [-2, 1.5, 0.01])');
-	console.log('       "render": toggle sky, ground, and space rendering. (default [], ex: ["sky", "space"], ["ground"])');
-	console.log('       "viewPanning": enable view origin panning with two-finger touch or shift+mouse drag. (default "off", ex: "on", "off")');
-	console.log('       "view": initial azimuth and elevation angles for camera (default [0,90], ex: [90, 180]');
+	console.log('       "render": a object containing a list of default object to render. (default {}, ex: {"sky", "space"})');
+	console.log('       	"sky": render the atmosphere. (ex: {"enabled":true})');
+	console.log('       		"enabled": toggle sky (default false, ex: true)');
+	console.log('       	"space": render space. (ex: {"enabled":true})');
+	console.log('       		"enabled": toggle space (default false, ex: true)');
+	console.log('       	"coastlines": render coastlines. (ex: {"enabled":true})');
+	console.log('       		"enabled": toggle coastlines (default false, ex: true)');
+	console.log('       		"scale": scale coastlines factor (default 1.0, ex: 1.004)');
+	console.log('       		"x": x coordinate array. (ex: [0.0, 10.0, -25.0,...])');
+	console.log('       		"y": y coordinate array. (ex: [0.0, 10.0, -25.0,...])');
+	console.log('       		"z": z coordinate array. (ex: [0.0, 10.0, -25.0,...])');
+	console.log('       	"city": render city. (ex: {"enabled":true})');
+	console.log('       		"enabled": toggle city (default false, ex: true)');
+	console.log('       		"size": radius of city sphere, in meters (default 1.0, ex: 150000)');
+	console.log('       		"color": color of city sphere (ex: "magenta")');
+	console.log('       		"x": x coordinate of city. (ex: 0.0)');
+	console.log('       		"y": y coordinate of city. (ex: 0.0)');
+	console.log('       		"z": z coordinate of city. (ex: 6356700.0)');
+	console.log('       	"cities": render cities. (ex: {"enabled":true})');
+	console.log('       		"enabled": toggle cities (default false, ex: true)');
+	console.log('       		"size": radius of cities spheres, in meters (default 1.0, ex: 80000)');
+	console.log('       		"color": color of cities spheres (ex: "darkviolet")');
+	console.log('       		"x": x coordinate array of cities. (ex: [0.0, 10.0, -25.0,...])');
+	console.log('       		"y": y coordinate array of cities. (ex: [0.0, 10.0, -25.0,...])');
+	console.log('       		"z": z coordinate array of cities. (ex: [0.0, 10.0, -25.0,...])');
+	console.log('       	"graticule": render graticule. (ex: {"enabled":true})');
+	console.log('       		"enabled": toggle graticule (default false, ex: true)');
+	console.log('       		"scale": scale graticule factor (default 1.0, ex: 1.004)');
+	console.log('       		"x": x coordinate array. (ex: [0.0, 10.0, -25.0,...])');
+	console.log('       		"y": y coordinate array. (ex: [0.0, 10.0, -25.0,...])');
+	console.log('       		"z": z coordinate array. (ex: [0.0, 10.0, -25.0,...])');
+	console.log('       "view": object cotaining view parameters. See webgl.js for defaults. (ex: {"position":[0.0,0.0,0.0],"rotation":[0.0,0.0,0.0],"zoom":1.0,"zoomLimits":[0.01,100.0],"azimuthLimits":[-180,180.0],"elevationLimits":[-90,90.0],"panningEnabled":false,"twod":false})');
+	console.log('       	"position": camera position (ex: [0.0,0.0,0.0])');
+	console.log('       	"rotation": camera rotation (ex: [0.0,0.0,0.0])');
+	console.log('       	"zoom": initial camera zoom as a percentage of default (default 1, ex: 1.5, 0.01)');
+	console.log('       	"zoomLimits": zoom view limits (ex: [0.05, 10])');
+	console.log('      	 	"azimuthLimits": zoom view limits (ex: [0.05, 10])');
+	console.log('       	"elevationLimits": zoom view limits (ex: [0.05, 10])');
+	console.log('       	"panningEnabled": controls panning with shift + drag mouse or pan gestures (default: false, ex: true)');
+	console.log('       	"twod": controls twod orthographic view (default: false, ex: true)');
 	console.log('       "xlim": x coordinates to fit inside camera (ex: [0, 500])');
 	console.log('       "ylim": y coordinates to fit inside camera (ex: [0, 500])');
 	console.log('       "zlim": z coordinates to fit inside camera (ex: [0, 500])');
-	console.log('       "zoomlim": zoom view limits (ex: [0.05, 10])');
-	console.log('       "zoom": initial camera zoom as a percentage of default (default 1, ex: 1.5, 0.01)');
-	console.log('       "cloud*": plot a cloud of points, given a flat array of 3d coordinates (ex: [0.0, 0.0, 0.0, 1.0, 1.0, 1.0])');
-	console.log('       "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)');
-	console.log('       "textlabels*": plot text labels rendered in 3d space, using an array of text/coordinate pairs (ex: [{"pos":[0.0,0.0,0.0],"text":"origin"}])');
+	console.log('       "transient_field_data": array of data objects (ex: [[0.0,1.0, 2.5, 12.0...],[0.0,1.0, 2.5, 12.0...],...])');
+	console.log('       "textlabels": plot text labels rendered in 3d space, using an array of text/coordinate pairs (ex: [{"pos":[0.0,0.0,0.0],"text":"origin"}])');
 	
 	console.log('  ');
Index: /issm/trunk/src/m/plot/plotmodel.js
===================================================================
--- /issm/trunk/src/m/plot/plotmodel.js	(revision 22757)
+++ /issm/trunk/src/m/plot/plotmodel.js	(revision 22758)
@@ -36,5 +36,5 @@
 		//Reinitialize all canvases
 		for (var i=0;i<numberofplots;i++){
-			document.getElementById(options.list[i].getfieldvalue('canvasid')).initialized = false;
+			if (options.list[i].getfieldvalue('clf','on')!='off') document.getElementById(options.list[i].getfieldvalue('canvasid')).initialized = false;
 		}
 		//Go through all data plottable and close window if an error occurs
Index: /issm/trunk/src/m/plot/plotmodel.m
===================================================================
--- /issm/trunk/src/m/plot/plotmodel.m	(revision 22757)
+++ /issm/trunk/src/m/plot/plotmodel.m	(revision 22758)
@@ -48,4 +48,6 @@
 			elseif strcmpi(figposition,'mathieu'),
 				set(gcf,'Position',[300 1 1580 1150]);
+			elseif strcmpi(figposition,'byron'),
+				set(gcf,'Position',[40 1580 560*1.25 420*1.25]);  %left, bottom, width, height; W=560 H=420 is default
 			elseif strcmpi(figposition,'fullscreen'),
 				set(gcf,'Position',get(0,'ScreenSize'));
Index: /issm/trunk/src/m/plot/processdata.js
===================================================================
--- /issm/trunk/src/m/plot/processdata.js	(revision 22757)
+++ /issm/trunk/src/m/plot/processdata.js	(revision 22758)
@@ -15,7 +15,4 @@
 	//   See also: PLOTMODEL, PROCESSMESH
 
-	//variables: 
-	var datatype;
-	
 	//check format
 	if ( data.length ==0 | data === [] | typeof data === 'number' | ArrayAnyNaN(data) ){
@@ -35,4 +32,5 @@
 
 	//needed later on
+	var numberofvertices2d, numberofelements2d;
 	if ('numberofvertices2d' in md.mesh){
 		numberofvertices2d=md.mesh.numberofvertices2d; 
@@ -45,8 +43,8 @@
 
 	//initialize datatype
-	datatype=0;
+	var datatype=0;
 
 	//get datasize
-	datasize=data.length;
+	var datasize=data.length;
 
 	//transpose data if necessary
@@ -64,5 +62,5 @@
 
 	//quiver?
-	if (data[0].length>1){
+	if (Array.isArray(data[0])){
 		datatype=3;
 
@@ -115,5 +113,5 @@
 
 	//element data
-	if (datasize==md.mesh.numberofelements & data[0].length==1){
+	if (datasize==md.mesh.numberofelements & !Array.isArray(data[0])){
 
 		//Initialize datatype if non patch
@@ -158,5 +156,5 @@
 
 	//node data
-	if (datasize==md.mesh.numberofvertices){
+	if (datasize==md.mesh.numberofvertices & !Array.isArray(data[0])){
 		datatype=2;
 
Index: /issm/trunk/src/m/plot/processdata.m
===================================================================
--- /issm/trunk/src/m/plot/processdata.m	(revision 22757)
+++ /issm/trunk/src/m/plot/processdata.m	(revision 22758)
@@ -47,4 +47,11 @@
 	numberofelements2d=NaN;
 end
+numberofvertices = md.mesh.numberofvertices;
+numberofelements = md.mesh.numberofelements;
+if exist(options,'amr'),
+	step = getfieldvalue(options,'amr');
+	numberofvertices = numel(md.results.TransientSolution(step).MeshX);
+	numberofelements = numel(md.results.TransientSolution(step).MeshElements);
+end
 
 %initialize datatype
@@ -67,5 +74,5 @@
 
 %check length
-if datasize(1)~=md.mesh.numberofvertices & datasize(1)~=md.mesh.numberofelements & datasize(1)~=md.mesh.numberofvertices*6 & (strcmp(md.mesh.domaintype(),'3D') & ~(datasize(1)==numberofelements2d | datasize(1)==numberofvertices2d))
+if datasize(1)~=numberofvertices & datasize(1)~=numberofelements & datasize(1)~=numberofvertices*6 & (strcmp(md.mesh.domaintype(),'3D') & ~(datasize(1)==numberofelements2d | datasize(1)==numberofvertices2d))
 	error('plotmodel error message: data not supported yet');
 end
@@ -86,10 +93,10 @@
 
 %treat the case datasize(1)=6*nodes
-if datasize(1)==6*md.mesh.numberofvertices
+if datasize(1)==6*numberofvertices
 	%keep the only norm of data
-	data1=data(1:6:md.mesh.numberofvertices*6,:);
-	data2=data(2:6:md.mesh.numberofvertices*6,:);
+	data1=data(1:6:numberofvertices*6,:);
+	data2=data(2:6:numberofvertices*6,:);
 	data=sqrt(data1.^2+data2.^2);
-	datasize(1)=md.mesh.numberofvertices;
+	datasize(1)=numberofvertices;
 	%---> go to node data
 end
@@ -98,5 +105,5 @@
 if (dimension(md.mesh)==3 & datasize(1)==numberofvertices2d),
 	data=project3d(md,'vector',data,'type','node');
-	datasize(1)=md.mesh.numberofvertices;
+	datasize(1)=numberofvertices;
 	%---> go to node data
 end
@@ -105,5 +112,5 @@
 if (dimension(md.mesh)==3 & datasize(1)==numberofelements2d),
 	data=project3d(md,'vector',data,'type','element');
-	datasize(1)=md.mesh.numberofelements;
+	datasize(1)=numberofelements;
 	%---> go to node data
 end
@@ -112,10 +119,10 @@
 if exist(options,'smooth')
 	data=averaging(md,data,getfieldvalue(options,'smooth'));
-	datasize(1)=md.mesh.numberofvertices;
+	datasize(1)=numberofvertices;
 	%---> go to node data
 end
 
 %element data
-if (datasize(1)==md.mesh.numberofelements & datasize(2)==1),
+if (datasize(1)==numberofelements & datasize(2)==1),
 
 	%Initialize datatype if non patch
@@ -129,11 +136,11 @@
 		maskvalue=getfieldvalue(options,'maskvalue',NaN);
 		pos=find(~flags);
-		if length(flags)==md.mesh.numberofvertices,
+		if length(flags)==numberofvertices,
 			[pos2 dummy]=find(ismember(md.mesh.elements,pos));
 			data(pos2,:)=maskvalue;
-		elseif length(flags)==md.mesh.numberofelements
+		elseif length(flags)==numberofelements
 			data(pos,:)=maskvalue;
 		else
-			disp('plotmodel warning: mask length not supported yet (supported length are md.mesh.numberofvertices and md.mesh.numberofelements');
+			disp('plotmodel warning: mask length not supported yet (supported length are numberofvertices and numberofelements');
 		end
 	end
@@ -152,5 +159,5 @@
 
 %node data
-if (datasize(1)==md.mesh.numberofvertices & datasize(2)==1),
+if (datasize(1)==numberofvertices & datasize(2)==1),
 	datatype=2;
 
@@ -160,10 +167,10 @@
 		maskvalue=getfieldvalue(options,'maskvalue',NaN);
 		pos=find(~flags);
-		if length(flags)==md.mesh.numberofvertices,
+		if length(flags)==numberofvertices,
 			data(pos,:)=maskvalue;
-		elseif length(flags)==md.mesh.numberofelements
+		elseif length(flags)==numberofelements
 			data(md.mesh.elements(pos,:),:)=maskvalue;
 		else
-			disp('plotmodel warning: mask length not supported yet (supported length are md.mesh.numberofvertices and md.mesh.numberofelements');
+			disp('plotmodel warning: mask length not supported yet (supported length are numberofvertices and numberofelements');
 		end
 	end
@@ -199,10 +206,10 @@
 		flags=getfieldvalue(options,'mask');
 		pos=find(~flags);
-		if length(flags)==md.mesh.numberofvertices,
+		if length(flags)==numberofvertices,
 			data(pos,:)=NaN;
-		elseif length(flags)==md.mesh.numberofelements
+		elseif length(flags)==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');
+			disp('plotmodel warning: mask length not supported yet (supported length are numberofvertices and numberofelements');
 		end
 	end
Index: /issm/trunk/src/m/plot/processmesh.m
===================================================================
--- /issm/trunk/src/m/plot/processmesh.m	(revision 22757)
+++ /issm/trunk/src/m/plot/processmesh.m	(revision 22758)
@@ -27,12 +27,22 @@
 end
 
-if ~strcmpi(getfieldvalue(options,'coord','xy'),'latlon'),
-	x=md.mesh.x;
-	if isprop(md.mesh,'x2d'), x2d=md.mesh.x2d; end
-	y=md.mesh.y;
-	if isprop(md.mesh,'y2d'), y2d=md.mesh.y2d; end
+if isprop(md.mesh,'elements2d'), elements2d=md.mesh.elements2d; end
+
+if exist(options,'amr'),
+	step = getfieldvalue(options,'amr');
+	x = md.results.TransientSolution(step).MeshX;
+	y = md.results.TransientSolution(step).MeshY;
+	elements = md.results.TransientSolution(step).MeshElements;
 else
-	x=md.mesh.long;
-	y=md.mesh.lat;
+	elements=md.mesh.elements;
+	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
 end
 
@@ -46,7 +56,4 @@
 	z=md.(z);
 end
-
-if isprop(md.mesh,'elements2d'), elements2d=md.mesh.elements2d; end
-elements=md.mesh.elements;
 
 %is it a 2d plot?
Index: /issm/trunk/src/m/plot/webgl.js
===================================================================
--- /issm/trunk/src/m/plot/webgl.js	(revision 22757)
+++ /issm/trunk/src/m/plot/webgl.js	(revision 22758)
@@ -6,12 +6,12 @@
 	//var canvas = document.getElementById(options.getfieldvalue('canvasid'));
 	if (!canvas.initialized) {
-		typedArraySliceSupport();
-		if (!isEmptyOrUndefined(canvas.draw) && canvas.draw.handler !== 0)	{ window.cancelAnimationFrame(canvas.draw.handler); }
-		if (!isEmptyOrUndefined(canvas.animation) && canvas.animation.handler !== 0) { clearInterval(canvas.animation.handler); }
+		if (!VESL.Helpers.isEmptyOrUndefined(canvas.draw) && canvas.draw.handler !== 0)	{ window.cancelAnimationFrame(canvas.draw.handler); }
+		if (!VESL.Helpers.isEmptyOrUndefined(canvas.animation) && canvas.animation.handler !== 0) { clearInterval(canvas.animation.handler); }
 		initWebGL(canvas, options);
-		initializeMarker(canvas);
-		canvas.nodes = [];
 		draw(canvas);
 		canvas.initialized = true;
+		
+		//The onStart event triggers once per plotmodel call load after WebGL and canvas initialization are complete
+		canvas.selector.trigger('onStart', [canvas]);
 	}
 	return canvas;
@@ -19,6 +19,6 @@
 function initWebGL(canvas, options) { //{{{
 	//Initialize canvas.gl on page load, reusing gl context on additional runs
-	var gl;
-	if (!canvas.gl) {
+	var gl = canvas.gl;
+	if (VESL.Helpers.isEmptyOrUndefined(gl)) {
 		gl = GL.create({canvas: canvas});
 		gl.enable(gl.DEPTH_TEST); // Enable depth testing
@@ -27,236 +27,175 @@
 		gl.enable(gl.CULL_FACE); // Enable face culling
 		gl.cullFace(gl.FRONT);
-		gl.shaders = loadShaders(gl, options.getfieldvalue('rootpath', '../../../js/')); // Load shaders and store them in gl object
+		gl.shaders = loadShaders(gl, options.getfieldvalue('rootpath', '/canvas')); // Load shaders and store them in gl object.
 		gl.textures = {};
 		
 		// Add event listeners for canvas
-		var displayview = options.getfieldvalue('displayview', 'off') == 'on';
-		var displayzoom = options.getfieldvalue('displayzoom', 'off') == 'on';
-		var mc = new Hammer.Manager(canvas);
-		
-		mc.add( new Hammer.Tap({event: 'singletap' }) );
+		var displayview = options.getfieldvalue('displayview', 'off') === 'on';
+		var displayzoom = options.getfieldvalue('displayzoom', 'off') === 'on';
+		var mc = new Hammer(canvas);	
 		mc.add(new Hammer.Pan({threshold: 0, pointers: 0}));
 		mc.add(new Hammer.Pinch({threshold: 0})).recognizeWith(mc.get('pan'));
-		mc.on('singletap', function (ev) {onTap(ev, canvas);});
+		mc.on('tap', function (ev) {onTap(ev, canvas);});
 		mc.on('panstart panmove', function (ev) {onPan(ev, canvas, displayview);});
 		mc.on('pinchstart pinchmove', function (ev) {onPinch(ev, canvas, displayview);});
-		
 		canvas.addEventListener('mousewheel', function (ev) {onZoom(ev, canvas, displayzoom)}, false);
 		canvas.addEventListener('DOMMouseScroll', function (ev) {onZoom(ev, canvas, displayzoom)}, false);
-	}
-	else {
-		gl = canvas.gl;
-	}
-	
-	// Add context state variables
-	canvas.gl = gl;
-	canvas.textcanvas = null;
-	canvas.overlaycanvas = null;
-	canvas.unitNode = {};
-	canvas.unitData = {};
-	canvas.controlSensitivity = options.getfieldvalue('controlsensitivity', 1);
-	canvas.id = options.getfieldvalue('canvasid', '.sim-canvas');
-	canvas.rootPath = options.getfieldvalue('rootpath', '../../../js/');
-	canvas.selector = $('#' + canvas.id);
-	var backgroundcolor = new RGBColor(options.getfieldvalue('backgroundcolor', 'lightcyan'));
-	if (backgroundcolor.ok) { canvas.backgroundcolor = [backgroundcolor.r/255.0, backgroundcolor.g/255.0, backgroundcolor.b/255.0, 1.0]; }
-	else { throw Error(sprintf('s%s%s\n','initWebGL error message: cound not find out background color for curent canvas ', canvas)); }
-	
-	//Property intiialization, using values from options first, then from default values.
-	var animation = options.getfieldvalue('movies', {});
-	canvas.animation = {
-		frame: defaultFor(animation.frame, 0),
-		play: defaultFor(animation.play, true),
-		increment: defaultFor(animation.increment, true),
-		fps: defaultFor(animation.fps, 4),
-		loop: defaultFor(animation.loop, true),
-		handler: defaultFor(animation.handler, 0)
-	}
-	var brush = options.getfieldvalue('brush', {});
-	canvas.brush = {
-		enabled: defaultFor(brush.enabled, false),
-		strength: defaultFor(brush.strength, 0.075),
-		falloff: defaultFor(brush.falloff, 0.5),
-		hit: defaultFor(brush.hit, {})
-	};
-	var camera = options.getfieldvalue('camera', {});
-	canvas.camera = {
-		position: defaultFor(camera.position, vec3.create()),
-		rotation: defaultFor(camera.rotation, vec3.create()),
-		near: defaultFor(camera.near, 1e3),
-		far: defaultFor(camera.far, 1e10),
-		fov: defaultFor(camera.fov, 45),
-		vMatrix: defaultFor(camera.vMatrix, mat4.create()),
-		pMatrix: defaultFor(camera.pMatrix, mat4.create()),
-		vpMatrix: defaultFor(camera.vpMatrix, mat4.create()),
-		vInverseMatrix: defaultFor(camera.vInverseMatrix, mat4.create()),
-		pInverseMatrix: defaultFor(camera.pInverseMatrix, mat4.create()),
-		vpInverseMatrix: defaultFor(camera.vpInverseMatrix, mat4.create()),
-		ready: defaultFor(camera.ready, false)
-	};
-	var clouds = options.getfieldvalue('clouds', {});
-	canvas.clouds = {
-		enabled: defaultFor(clouds.enabled, false),
-		height: defaultFor(clouds.height, 7500),
-		quantity: defaultFor(clouds.quantity, 10)
-	};
-	var dataMarkers = options.getfieldvalue('datamarkers', {});
-	canvas.dataMarkers = {
-		enabled: defaultFor(dataMarkers.enabled, true),
-		values: defaultFor(dataMarkers.values, []),
-		image: defaultFor(dataMarkers.image, canvas.rootPath+'textures/data_marker.svg'),
-		size: defaultFor(dataMarkers.size, [32, 32]),
-		format: defaultFor(dataMarkers.format, ['X: %.2e<br>Y: %.2e<br>Z: %.2e<br>Value: %0.1f', 'x', 'y', 'z', 'value']),
-		animated: defaultFor(dataMarkers.animated, false),
-		labels: defaultFor(dataMarkers.labels, []),
-		font: defaultFor(dataMarkers.font, ''),
-		marker: defaultFor(dataMarkers.marker, document.getElementById('sim-data-marker-' + canvas.id))
-	};
-	var draw = options.getfieldvalue('draw', {});
-	canvas.draw = {
-		ready: defaultFor(draw.ready, false),
-		handler: defaultFor(draw.handler, null)
-	};
-	var view = options.getfieldvalue('view', {});
-	canvas.view = {
-		position: defaultFor(view.position, [0.0, 0.0, 0.0]),
-		rotation: defaultFor(view.rotation, [0, 90]),
-		zoom: defaultFor(view.zoom, 1.0),
-		zoomLimits: defaultFor(view.zoomLimits, [0.001, 100.0]),
-		lastZoom: defaultFor(view.lastZoom, 1.0),
-		azimuthLimits: defaultFor(view.azimuthLimits, [0, 360]),
-		elevationLimits: defaultFor(view.elevationLimits, [-180, 180]),
-		panningEnabled: defaultFor(view.panningEnabled, false),
-		twod: defaultFor(view.twod, false)
-	};
-
-	//Override with parameters from URL, if any
-	//TODO: Make permalinks more robust and less interdependent on UI
-	if (!canvas.usedparemters) {
-		function getJsonFromUrl() {
-			var query = location.search.substr(1);
-			var result = {};
-			query.split('&').forEach(function(part) {
-				var item = part.split('=');
-				result[item[0]] = decodeURIComponent(item[1]);
-			});
-			return result;
+		
+		//Add persistent state variables
+		canvas.nodes = {};
+		canvas.octrees = {};
+		canvas.unitNode = {};
+		canvas.unitData = {};
+		canvas.unitMovieData = {};
+		
+		canvas.gl = gl;
+		canvas.assetsPath = options.getfieldvalue('rootpath', '/canvas');
+		canvas.id = options.getfieldvalue('canvasid', '.sim-canvas');
+		canvas.selector = $('#' + canvas.id);
+		canvas.textcanvas = null;
+		canvas.overlaycanvas = null;
+		canvas.permalinkUsed = false;
+		
+		typedArraySliceSupport();
+	}
+	
+	if (options.getfieldvalue('clf','on')=='on') {
+		//Add context state variables
+		canvas.render = options.getfieldvalue('render', {});
+		canvas.controlSensitivity = options.getfieldvalue('controlsensitivity', 1);
+		if (options.getfieldvalue('clf','on')=='on') canvas.overlayHandlers = {};
+		var backgroundcolor = new RGBColor(options.getfieldvalue('backgroundcolor', 'lightcyan'));
+		if (backgroundcolor.ok) { canvas.backgroundcolor = [backgroundcolor.r/255.0, backgroundcolor.g/255.0, backgroundcolor.b/255.0, 1.0]; }
+		else { throw Error(sprintf('s%s%s\n','initWebGL error message: cound not find out background color for current canvas ', canvas)); }
+		
+		//Property intiialization, using values from options first, then from default values.
+		var atmosphere = options.getfieldvalue('atmosphere', {});
+		canvas.atmosphere = { 														//Default Values
+			wavelength_r: defaultFor(atmosphere.wavelength_r, 			0.65), 		//0.65		Red wavelength (micrometers)
+			wavelength_g: defaultFor(atmosphere.wavelength_g, 			0.57),		//0.57		Green wavelength (micrometers)
+			wavelength_b: defaultFor(atmosphere.wavelength_b, 			0.475),		//0.475		Green wavelength (micrometers)
+			eSun: 	defaultFor(atmosphere.eSun, 						100.0),		//20.0		Sun intensity	
+			kRayleigh: defaultFor(atmosphere.kRayleigh, 				0.0025),	//0.0025	Rayleigh scattering amount
+			kMie: defaultFor(atmosphere.kMie, 							0.000), 	//0.01		Mie scattering amount
+			g: defaultFor(atmosphere.g, 								-0.99),		//-0.99		Mie phase asymmetry/direction factor
+			hdr_exposure: defaultFor(atmosphere.hdr_exposure, 			0.8),		//0.8		High Dynamic Range Exposure
+			scaleHeight: defaultFor(atmosphere.scaleHeight, 			1.25), 		//1.025		Scale of height of atmosphere to earth radius.
+			scaleDepth: defaultFor(atmosphere.scaleDepth, 				0.25), 		//0.25		Percentage altitude at which the atmosphere's average density is found
+			a: defaultFor(atmosphere.a, 								-0.00287),	//-0.00287	Scaling constant a
+			b: defaultFor(atmosphere.b, 								0.459),		//0.459		Scaling constant b
+			c: defaultFor(atmosphere.c, 								3.83),		//3.83		Scaling constant c
+			d: defaultFor(atmosphere.d, 								-6.80),		//-6.80		Scaling constant d
+			e: defaultFor(atmosphere.e, 								3.6),		//5.25		Scaling constant e. Lower when increasing atmosphere scale.
+			attenuation: defaultFor(atmosphere.attenuation, 			0.5)		//0.5		Strength of atmospheric scattering on ground shading.
+		};
+		updateAtmosphereParameters(canvas);
+			
+		var animation = options.getfieldvalue('movies', {});
+		canvas.animation = {
+			frame: defaultFor(animation.frame, 							0),
+			play: defaultFor(animation.play, 							true),
+			increment: defaultFor(animation.increment, 					true),
+			fps: defaultFor(animation.fps, 								4),
+			interval: defaultFor(animation.interval, 					1000 / defaultFor(animation.fps, 4)),
+			loop: defaultFor(animation.loop, 							true),
+			handler: defaultFor(animation.handler, 						0)
 		}
-		parameters = getJsonFromUrl();
-		
-		if (parameters['view']) {
-			canvas.view = JSON.parse(parameters['view']);
-		}
-		if (parameters['initial']) {
-			initial = JSON.parse(parameters['initial']);
-			if (!initial) {
-				if (typeof SolveGlacier == 'function') {
-					SolveGlacier();
-				}
-				if (typeof SolveSlr == 'function') {
-					SolveSlr();
-				}
-			}
-		}
-		canvas.usedparemters = true;
-	}
-} //}}}
-function generatePermalink() { //{{{
-	var permalink = window.location.origin + window.location.pathname + '&view=' + JSON.stringify(canvas.view) + '&initial=' + JSON.stringify(initial);
-	window.prompt('Share this simulation: ', permalink);
-} //}}}
-function loadShaders(gl, rootPath) { //{{{
+		var brush = options.getfieldvalue('brush', {});
+		canvas.brush = {
+			enabled: defaultFor(brush.enabled, 							false),
+			strength: defaultFor(brush.strength, 						0.075),
+			falloff: defaultFor(brush.falloff, 							0.5),
+			hit: defaultFor(brush.hit, 									{})
+		};
+		var camera = options.getfieldvalue('camera', {});
+		canvas.camera = {
+			position: defaultFor(camera.position, 						vec3.create()),
+			rotation: defaultFor(camera.rotation, 						quat.create()),
+			relativePosition: defaultFor(camera.relativePosition, 		vec3.create()),
+			direction: defaultFor(camera.direction, 					vec3.create()),
+			near: defaultFor(camera.near, 								1e3),
+			far: defaultFor(camera.far, 								1e10),
+			fov: defaultFor(camera.fov, 								45),
+			vMatrix: defaultFor(camera.vMatrix, 						mat4.create()),
+			pMatrix: defaultFor(camera.pMatrix, 						mat4.create()),
+			vpMatrix: defaultFor(camera.vpMatrix, 						mat4.create()),
+			vInverseMatrix: defaultFor(camera.vInverseMatrix, 			mat4.create()),
+			pInverseMatrix: defaultFor(camera.pInverseMatrix, 			mat4.create()),
+			vpInverseMatrix: defaultFor(camera.vpInverseMatrix, 		mat4.create()),
+			ready: defaultFor(camera.ready, 							false)
+		};
+		var dataMarkers = options.getfieldvalue('datamarkers', {});
+		canvas.dataMarkers = {
+			enabled: defaultFor(dataMarkers.enabled, 					true),
+			values: defaultFor(dataMarkers.values, 						[]),
+			image: defaultFor(dataMarkers.image, 						canvas.assetsPath + '/data-markers/data_marker.svg'),
+			size: defaultFor(dataMarkers.size, 							[32, 32]),
+			format: defaultFor(dataMarkers.format, 						['X: %.2em<br>Y: %.2em<br>Z: %.2em<br>Value: %0.1f']),
+			animated: defaultFor(dataMarkers.animated, 					false),
+			labels: defaultFor(dataMarkers.labels, 						['x', 'y', 'z', 'value']),
+			font: defaultFor(dataMarkers.font, 							''),
+			marker: defaultFor(dataMarkers.marker, 						document.getElementById('sim-data-marker-' + canvas.id)),
+			reposition: defaultFor(dataMarkers.reposition, 				true)
+		};
+		var draw = options.getfieldvalue('draw', {});
+		canvas.draw = {
+			ready: defaultFor(draw.ready, 								false),
+			handler: defaultFor(draw.handler, 							null)
+		};
+		var view = options.getfieldvalue('view', {});
+		canvas.view = {
+			position: defaultFor(view.position, 						[0.0, 0.0, 0.0]),
+			rotation: defaultFor(view.rotation, 						[0, 90]),
+			zoom: defaultFor(view.zoom, 								1.0),
+			zoomLimits: defaultFor(view.zoomLimits, 					[0.001, 100.0]),
+			lastZoom: defaultFor(view.lastZoom, 						1.0),
+			lightingBias: defaultFor(view.lightingBias, 				0.75),
+			azimuthLimits: defaultFor(view.azimuthLimits, 				[0, 360]),
+			elevationLimits: defaultFor(view.elevationLimits, 			[-180, 180]),
+			panningEnabled: defaultFor(view.panningEnabled, 			false),
+			preventDefaultOnPan: defaultFor(view.preventDefaultOnPan, 	false),
+			twod: defaultFor(view.twod, 								false)
+		};
+
+		// Override with parameters from URL, if any
+		VESL.UI.parsePermalinkCanvas(canvas);
+	}
+} //}}}
+function loadShaders(gl, assetsPath) { //{{{
 	var shaders = {};
-	shaders.Colored = new GL.Shader.fromURL(rootPath+'shaders/Colored.vsh', rootPath+'shaders/Colored.fsh', null, gl);
-	shaders.Textured = new GL.Shader.fromURL(rootPath+'shaders/Textured.vsh', rootPath+'shaders/Textured.fsh', null, gl);
-	shaders.SkyFromSpace = new GL.Shader.fromURL(rootPath+'shaders/SkyFromSpace.vert', rootPath+'shaders/SkyFromSpace.frag', null, gl);
-	shaders.GroundFromSpace = new GL.Shader.fromURL(rootPath+'shaders/GroundFromSpace.vert', rootPath+'shaders/GroundFromSpace.frag', null, gl);
-	shaders.Clouds = new GL.Shader.fromURL(rootPath+'shaders/Clouds.vert', rootPath+'shaders/Clouds.frag', null, gl);
+	// NOTE: Consider changing fromURL() to XMLHttpRequest with responseType = 'text' to avoid XML Parsing Error (shader files are not encoded as XML).
+	shaders.Colored = new GL.Shader.fromURL(assetsPath + '/shaders/Colored.vsh', assetsPath + '/shaders/Colored.fsh', null, gl);
+	shaders.ColoredDiffuse = new GL.Shader.fromURL(assetsPath + '/shaders/ColoredDiffuse.vsh', assetsPath + '/shaders/ColoredDiffuse.fsh', null, gl);
+	shaders.Textured = new GL.Shader.fromURL(assetsPath + '/shaders/Textured.vsh', assetsPath + '/shaders/Textured.fsh', null, gl);
+	shaders.TexturedDiffuse = new GL.Shader.fromURL(assetsPath + '/shaders/TexturedDiffuse.vsh', assetsPath + '/shaders/TexturedDiffuse.fsh', null, gl);
+	shaders.SkyFromSpace = new GL.Shader.fromURL(assetsPath + '/shaders/SkyFromSpace.vert', assetsPath + '/shaders/SkyFromSpace.frag', null, gl);
+	shaders.GroundFromSpace = new GL.Shader.fromURL(assetsPath + '/shaders/GroundFromSpace.vert', assetsPath + '/shaders/GroundFromSpace.frag', null, gl);
 	return shaders;
 } //}}}
 function initTexture(gl, imageSource) { //{{{
 	//Initialize textures, or load from memory if they already exist.
-	if (isEmptyOrUndefined(gl.textures[imageSource])) {
+	if (VESL.Helpers.isEmptyOrUndefined(gl.textures[imageSource])) {
 		gl.textures[imageSource] = GL.Texture.fromURL(imageSource, {minFilter: gl.LINEAR_MIPMAP_LINEAR, magFilter: gl.LINEAR}, null, gl);
 	}
 	return gl.textures[imageSource];
 } //}}}
-function Node(gl) { //{{{
-	//Returns a Node object that contains default display states for webgl object. center represents pivot point of rotation.
-	return {
-		alpha: 1.0,
-		buffers: [],
-		cullFace: gl.BACK,
-		disableDepthTest: false, 
-		drawMode: gl.TRIANGLES,
-		drawOrder: 0,
-		enabled: true,
-		enableCullFace: true,
-		hideOcean: false,
-		lineWidth: 1.0,
-		maskEnabled: false,
-		maskHeight: 150.0,
-		maskColor: vec4.fromValues(0.0, 0.0, 1.0, 1.0),
-		mesh: null,
-		name: 'node',
-		shaderName: 'Colored',
-		shader: gl.shaders.Colored,
-		texture: null,
-		useIndexBuffer: true,
-		center: vec3.create(), 
-		scale: vec3.fromValues(1, 1, 1),
-		rotation: vec3.create(),
-		translation: vec3.create(),
-		modelMatrix: mat4.create(),
-		rotationMatrix: mat4.create(),
-		inverseModelMatrix: mat4.create(),
-		inverseRotationMatrix: mat4.create()
-	};
-} //}}}
-function debugNodes(canvasid) { //{{{
-	var canvasid = canvasid || '.sim-canvas';
-	var nodes = document.getElementById(canvasid).nodes;
-	console.log(canvasid, 'Nodes:');
-	for (var node in nodes) {
-		console.log('name: ', nodes[node].name, ' node: ', nodes[node], ' mesh: ', nodes[node].mesh, ' translation: ', nodes[node].translation, ' center:', nodes[node].center, ' rotation:', nodes[node].rotation);
-	}
-	return nodes;
-} //}}}
-function updateModelMatrix(node) { //{{{
-	var modelMatrix = mat4.create();
-
-	var translationMatrix = mat4.create();
-	mat4.translate(translationMatrix, translationMatrix, vec3.negate(vec3.create(), node.center)); //scale/rotation centering
-	mat4.multiply(modelMatrix, translationMatrix, modelMatrix);
-	
-	var scaleMatrix = mat4.create();
-	mat4.scale(scaleMatrix, scaleMatrix, node.scale);
-	mat4.multiply(modelMatrix, scaleMatrix, modelMatrix);
-	
-	var rotationMatrix = mat4.create();
-	var zRotationMatrix = mat4.create();	
-	mat4.rotate(zRotationMatrix, zRotationMatrix, DEG2RAD * node.rotation[2], [0.0, 0.0, 1.0]);
-	mat4.multiply(rotationMatrix, zRotationMatrix, rotationMatrix);
-	var yRotationMatrix = mat4.create();	
-	mat4.rotate(yRotationMatrix, yRotationMatrix, DEG2RAD * node.rotation[1], [0.0, 1.0, 0.0]);
-	mat4.multiply(rotationMatrix, yRotationMatrix, rotationMatrix);
-	var xRotationMatrix = mat4.create();	
-	mat4.rotate(xRotationMatrix, xRotationMatrix, DEG2RAD * node.rotation[0], [1.0, 0.0, 0.0]);
-	mat4.multiply(rotationMatrix, xRotationMatrix, rotationMatrix);
-	mat4.multiply(modelMatrix, rotationMatrix, modelMatrix);	
-	
-	mat4.identity(translationMatrix);
-	mat4.translate(translationMatrix, translationMatrix, node.center); //relative translation
-	mat4.multiply(modelMatrix, translationMatrix, modelMatrix);
-	
-	mat4.identity(translationMatrix);
-	mat4.translate(translationMatrix, translationMatrix, node.translation); //absolute translation
-	mat4.multiply(modelMatrix, translationMatrix, modelMatrix);
-	
-	node.modelMatrix = modelMatrix;
-	node.inverseModelMatrix = mat4.invert(mat4.create(), modelMatrix);
-	node.rotationMatrix = rotationMatrix;
-	node.inverseRotationMatrix = mat4.invert(mat4.create(), rotationMatrix);
-} //}}}
+function updateAtmosphereParameters(canvas) {
+	//Precalculate derived atmosphere shader parameters
+	//TODO: Find a better way to structure this
+	var atm = canvas.atmosphere;
+	atm.inv_wavelength4 = [1.0 / Math.pow(atm.wavelength_r, 4), 1.0 / Math.pow(atm.wavelength_g, 4), 1.0 / Math.pow(atm.wavelength_b, 4)];
+	atm.innerRadius = 6.371e6;
+	atm.innerRadius2 = atm.innerRadius * atm.innerRadius;
+	atm.outerRadius = atm.innerRadius * atm.scaleHeight;
+	atm.outerRadius2 = atm.outerRadius * atm.outerRadius;
+	atm.krESun = atm.kRayleigh * atm.eSun;
+	atm.kmESun = atm.kMie * atm.eSun;
+	atm.kr4PI = atm.kRayleigh * 4 * Math.PI;
+	atm.km4PI = atm.kMie * 4 * Math.PI;
+	atm.scale = 1.0 / (atm.outerRadius - atm.innerRadius);
+	atm.scaleOverScaleDepth = atm.scale / atm.scaleDepth;
+	atm.g2 = atm.g * atm.g;
+	canvas.atmosphere = atm;
+}
 function clamp(value, min, max) { //{{{
 	return Math.max(min, Math.min(value, max));
@@ -264,7 +203,4 @@
 function defaultFor(name, value) { //{{{
 	return typeof name !== 'undefined' ? name : value;
-} //}}}
-function isEmptyOrUndefined(object) { //{{{
-	return object === undefined || Object.getOwnPropertyNames(object).length === 0;
 } //}}}
 function recover(canvasid, name, value) { //{{{
@@ -272,417 +208,149 @@
 	var object = document.getElementById(canvasid);
 	var properties = name.split('.');
-	for (var i = 0; i < properties.length; ++i) {
+	for (var i = 0; i < properties.length; i++) {
 		object = object[properties[i]];
-		if (typeof object === 'undefined') { break; }
+		if (VESL.Helpers.isEmptyOrUndefined(object)) { break; }
     }
 	return defaultFor(object, value);
 } //}}}
-function typedArraySliceSupport() { //{{{
-	//TypedArray compatibility for Safari/IE
-	if (typeof Int8Array !== 'undefined') {
-		if (!Int8Array.prototype.fill) { Int8Array.prototype.fill = Array.prototype.fill; }
-		if (!Int8Array.prototype.slice) { Int8Array.prototype.slice = Array.prototype.slice; }
-	}
-	if (typeof Uint8Array !== 'undefined') {
-		if (!Uint8Array.prototype.fill) { Uint8Array.prototype.fill = Array.prototype.fill; }
-		if (!Uint8Array.prototype.slice) { Uint8Array.prototype.slice = Array.prototype.slice; }
-	}
-	if (typeof Uint8ClampedArray !== 'undefined') {
-		if (!Uint8ClampedArray.prototype.fill) { Uint8ClampedArray.prototype.fill = Array.prototype.fill; }
-		if (!Uint8ClampedArray.prototype.slice) { Uint8ClampedArray.prototype.slice = Array.prototype.slice; }
-	}
-	if (typeof Int16Array !== 'undefined') {
-		if (!Int16Array.prototype.fill) { Int16Array.prototype.fill = Array.prototype.fill; }
-		if (!Int16Array.prototype.slice) { Int16Array.prototype.slice = Array.prototype.slice; }
-	}
-	if (typeof Uint16Array !== 'undefined') {
-		if (!Uint16Array.prototype.fill) { Uint16Array.prototype.fill = Array.prototype.fill; }
-		if (!Uint16Array.prototype.slice) { Uint16Array.prototype.slice = Array.prototype.slice; }
-	}
-	if (typeof Int32Array !== 'undefined') {
-		if (!Int32Array.prototype.fill) { Int32Array.prototype.fill = Array.prototype.fill; }
-		if (!Int32Array.prototype.slice) { Int32Array.prototype.slice = Array.prototype.slice; }
-	}
-	if (typeof Uint32Array !== 'undefined') {
-		if (!Uint32Array.prototype.fill) { Uint32Array.prototype.fill = Array.prototype.fill; }
-		if (!Uint32Array.prototype.slice) { Uint32Array.prototype.slice = Array.prototype.slice; }
-	}
-	if (typeof Float32Array !== 'undefined') {
-		if (!Float32Array.prototype.fill) { Float32Array.prototype.fill = Array.prototype.fill; }
-		if (!Float32Array.prototype.slice) { Float32Array.prototype.slice = Array.prototype.slice; }
-	}
-	if (typeof Float64Array !== 'undefined') {
-		if (!Float64Array.prototype.fill) { Float64Array.prototype.fill = Array.prototype.fill; }
-		if (!Float64Array.prototype.slice) { Float64Array.prototype.slice = Array.prototype.slice; }
-	}
-	if (typeof TypedArray !== 'undefined') {
-		if (!TypedArray.prototype.fill) { TypedArray.prototype.fill = Array.prototype.fill; }
-		if (!TypedArray.prototype.slice) { TypedArray.prototype.slice = Array.prototype.slice; }
-	}
-} //}}}
 //}}}
-//{{{ Interface Functions
+//{{{ Interaction Functions
 function onTap(ev, canvas) { //{{{
-	//Sets up a marker on a canvas that will track a point on the mesh. Can be dismissed by closing the display or clicking the marker.
 	ev.preventDefault();
-	if (!canvas.dataMarkers.enabled) { return; }
-	var hit = raycast(canvas, ev.srcEvent.layerX, ev.srcEvent.layerY);
-	canvas.dataMarkers.marker.hit = hit;
-	canvas.brush.hit = hit;
-	updateMarker(canvas, true);
-	brushModify(canvas);
+	
+	var hit = raycastXY(canvas, ev.srcEvent.layerX, ev.srcEvent.layerY, canvas.unitNode);
+
+	//Trigger any handlers attatched to this canvas event.
+	canvas.selector.trigger('onTap', [ev, canvas, hit]);
 } //}}}
 function onPan(ev, canvas, displaylog) { //{{{
 	ev.preventDefault();
 	
-	if (canvas.dataMarkers.enabled == 'on') {
-		canvas.brush.hit = raycast(canvas, ev.srcEvent.layerX, ev.srcEvent.layerY);
-		brushModify(canvas);
-	}
-	
-	if (ev.type == 'panstart') {
+	if (ev.type === 'panstart') {
 		canvas.lastDeltaX = 0;
 		canvas.lastDeltaY = 0;
 	}
-	if (ev.srcEvent.shiftKey || ev.pointers.length == 2) {
-		if (!canvas.view.panningEnabled) return;
-		var deltaX = (canvas.lastDeltaX - ev.deltaX) / canvas.clientWidth / canvas.view.zoom * 2 * canvas.controlSensitivity * 6.371e6;
-		var deltaY = (canvas.lastDeltaY - ev.deltaY) / canvas.clientHeight / canvas.view.zoom * 2 * canvas.controlSensitivity * 6.371e6;
-		
-		if (canvas.view.twod) {
-			canvas.view.position[0] += Math.cos(DEG2RAD * canvas.view.rotation[0]) * deltaX - Math.sin(DEG2RAD * 0) * deltaY;
-			canvas.view.position[2] += Math.sin(DEG2RAD * canvas.view.rotation[0]) * deltaX + Math.cos(DEG2RAD * 0) * deltaY;
+	
+	//Trigger any handlers attatched to this canvas event.
+	canvas.selector.trigger('onPan', [ev, canvas]);
+	
+	//If any onPan handler sets preventDefaultOnPan to true, skips default onPan camera behavior
+	if (!canvas.view.preventDefaultOnPan) {
+		//If panning with two fingers or shift key, translate camera center
+		if (ev.srcEvent.shiftKey || ev.pointers.length === 2) {
+			if (canvas.view.panningEnabled) {
+				var deltaX = (canvas.lastDeltaX - ev.deltaX) / canvas.clientWidth / canvas.view.zoom * 2 * canvas.controlSensitivity * 6.371e6;
+				var deltaY = (canvas.lastDeltaY - ev.deltaY) / canvas.clientHeight / canvas.view.zoom * 2 * canvas.controlSensitivity * 6.371e6;
+				
+				//TODO: convert canvas.view.rotation from az/el euler to quaternion
+				if (canvas.view.twod) {
+					canvas.view.position[0] += Math.cos(DEG2RAD * canvas.view.rotation[0]) * deltaX - Math.sin(DEG2RAD * 0) * deltaY;
+					canvas.view.position[2] += Math.sin(DEG2RAD * canvas.view.rotation[0]) * deltaX + Math.cos(DEG2RAD * 0) * deltaY;
+				}
+				else {
+					canvas.view.position[0] += Math.cos(DEG2RAD * canvas.view.rotation[0]) * deltaX - Math.sin(DEG2RAD * canvas.view.rotation[0]) * deltaY;
+					canvas.view.position[2] += Math.sin(DEG2RAD * canvas.view.rotation[0]) * deltaX + Math.cos(DEG2RAD * canvas.view.rotation[0]) * deltaY;
+				}
+			}
 		}
+		//Else, rotate around camera center
 		else {
-			canvas.view.position[0] += Math.cos(DEG2RAD * canvas.view.rotation[0]) * deltaX - Math.sin(DEG2RAD * canvas.view.rotation[0]) * deltaY;
-			canvas.view.position[2] += Math.sin(DEG2RAD * canvas.view.rotation[0]) * deltaX + Math.cos(DEG2RAD * canvas.view.rotation[0]) * deltaY;
+			canvas.view.rotation[0] += (canvas.lastDeltaX - ev.deltaX) / canvas.clientWidth * 2 * canvas.controlSensitivity * RAD2DEG;
+			canvas.view.rotation[1] += (canvas.lastDeltaY - ev.deltaY) / canvas.clientHeight * -2 * canvas.controlSensitivity * RAD2DEG;
+			
+			if (canvas.view.rotation[0] > 360) { canvas.view.rotation[0] -= 360; };
+			if (canvas.view.rotation[0] < -360) { canvas.view.rotation[0] += 360; };
+			if (canvas.view.rotation[1] > 180) { canvas.view.rotation[1] -= 360; };
+			if (canvas.view.rotation[1] < -180) { canvas.view.rotation[1] += 360; };
+			
+			canvas.view.rotation[0] = clamp(canvas.view.rotation[0], canvas.view.azimuthLimits[0], canvas.view.azimuthLimits[1]);
+			canvas.view.rotation[1] = clamp(canvas.view.rotation[1], canvas.view.elevationLimits[0], canvas.view.elevationLimits[1]);
+			
+			if (displaylog) { console.log(canvas.view.rotation); }
 		}
-	}
-	
-	else {
-		canvas.view.rotation[0] += (canvas.lastDeltaX - ev.deltaX) / canvas.clientWidth * -2 * canvas.controlSensitivity * RAD2DEG;
-		canvas.view.rotation[1] += (canvas.lastDeltaY - ev.deltaY) / canvas.clientHeight * -2 * canvas.controlSensitivity * RAD2DEG;
-		
-		if (canvas.view.rotation[0] > 360) { canvas.view.rotation[0] -= 360; };
-		if (canvas.view.rotation[0] < -360) { canvas.view.rotation[0] += 360; };
-		if (canvas.view.rotation[1] > 180) { canvas.view.rotation[1] -= 360; };
-		if (canvas.view.rotation[1] < -180) { canvas.view.rotation[1] += 360; };
-		
-		canvas.view.rotation[0] = clamp(canvas.view.rotation[0], canvas.view.azimuthLimits[0], canvas.view.azimuthLimits[1]);
-		canvas.view.rotation[1] = clamp(canvas.view.rotation[1], canvas.view.elevationLimits[0], canvas.view.elevationLimits[1])
-	}
+	}	
+	
+	canvas.view.preventDefaultOnPan = false;
 	canvas.lastDeltaX = ev.deltaX;
 	canvas.lastDeltaY = ev.deltaY;
-	
-	repositionMarker(canvas);
-	
-	if (displaylog) { console.log(canvas.view.rotation); }
 } //}}}
 function onPinch(ev, canvas, displaylog) { //{{{
 	ev.preventDefault();
-	if (ev.type == 'pinchstart') { canvas.view.lastZoom = canvas.view.zoom; }
-	else { modifyZoom(ev.scale * canvas.view.lastZoom, canvas, displaylog); }
+	if (ev.type === 'pinchstart') { canvas.view.lastZoom = canvas.view.zoom; }
+	else { 
+		canvas.view.zoom = ev.scale * canvas.view.lastZoom;
+		if (displaylog) { console.log(canvas.view.zoom); }
+	}
 } //}}}
 function onZoom(ev, canvas, displaylog) { //{{{
 	ev.preventDefault();
-	var delta = clamp(ev.scale || ev.wheelDelta || -ev.detail, -1, 1) * canvas.controlSensitivity * canvas.view.zoom / 20;
-	modifyZoom(canvas.view.zoom + delta, canvas, displaylog);
-} //}}}
-function modifyZoom(value, canvas, displaylog) { //{{{
-	canvas.view.zoom = clamp(value, canvas.view.zoomLimits[0], canvas.view.zoomLimits[1]);
-	repositionMarker(canvas);
-	if (displaylog) { console.log(canvas.view.zoom); }
-} //}}}
-function modifyDataMarkersEnabled(value, canvas) { //{{{
-	canvas.dataMarkers.enabled = value;
+	var delta = clamp(ev.scale || ev.wheelDelta || -ev.detail, -1, 1) * canvas.controlSensitivity * canvas.view.zoom / 2;
+	modifyZoom(canvas.view.zoom + delta, canvas, displaylog, ev, 0);
+} //}}}
+function modifyZoom(value, canvas, displaylog, ev, duration) { //{{{
+	if (VESL.Helpers.isEmptyOrUndefined(duration)) duration = 200;
+	var targetZoom = clamp(value, canvas.view.zoomLimits[0], canvas.view.zoomLimits[1]);
+	var currentZoom = canvas.view.zoom;
+	animateValue(
+		0,
+		1.0,
+		duration,
+		'swing',
+		function(value, info) {
+			canvas.view.zoom = currentZoom * (1 - value) + targetZoom * value;
+			if (displaylog) { console.log(canvas.view.zoom); }
+			
+			//Trigger any handlers attatched to this canvas event.
+			canvas.selector.trigger('onZoom', [ev, canvas]);
+		}
+	);
 } //}}}
 function toggleMoviePlay(canvas) { //{{{
 	canvas.animation.play = !canvas.animation.play;
-	if (canvas.animation.play){
-		canvas.playButton.find('span').removeClass('fa-play');
-		canvas.playButton.find('span').addClass('fa-pause');
-	}
-	else{
-		canvas.playButton.find('span').removeClass('fa-pause');
-		canvas.playButton.find('span').addClass('fa-play');
-	}
-} //}}}
-function onSlideStart(canvas, progressBar) { //{{{
-	if (!isEmptyOrUndefined(canvas.animation)) {
-		canvas.animation.increment = false;	
-		canvas.animation.frame = parseInt($(progressBar).val());
-		//console.log(canvas.animation.frame);
-		//updateMarker(canvas, false);
-	}
-} //}}}
-function onSlideChange(canvas, progressBar) { //{{{
-	if (!isEmptyOrUndefined(canvas.animation)) {
-		canvas.animation.frame = parseInt($(progressBar).val());
-		//console.log("change");
-		updateMarker(canvas, false);
-	}
-} //}}}
-function onSlideStop(canvas, progressBar) { //{{{
-	if (!isEmptyOrUndefined(canvas.animation)) {
-		canvas.animation.increment = true;	
-		canvas.animation.frame = parseInt($(progressBar).val());
-		//console.log(canvas.animation.frame);
-		//updateMarker(canvas, false);
-	}
-} //}}}
-//}}}
-//{{{ Interaction Functions
-function raycast(canvas, x, y) { //{{{
-	//Performs raycast on canvas.unitNode.mesh using x/y screen coordinates. Returns hit objects with hit position, coords, and indicies of ray-triangle intersection.
+} //}}}
+function screenToWorldPoint(canvas, x, y) { //{{{
+	var viewportX = (x - canvas.width / 2) / (canvas.width / 2);
+	var viewportY = (canvas.height / 2 - y) / (canvas.height / 2);
+	var origin = vec3.transformMat4(vec3.create(), [viewportX, viewportY, 0], canvas.camera.vpInverseMatrix);
+	return origin;
+} //}}}
+function screenToModelRay(canvas, x, y, node) { //{{{
+	var inverseMVPMatrix = mat4.invert(mat4.create(), mat4.multiply(mat4.create(), canvas.camera.vpMatrix, node.modelMatrix));
+	var viewportX = (x - canvas.width / 2) / (canvas.width / 2);
+	var viewportY = (canvas.height / 2 - y) / (canvas.height / 2);
+	var origin = vec3.transformMat4(vec3.create(), [viewportX, viewportY, 0], inverseMVPMatrix);
+	var far = vec3.transformMat4(vec3.create(), [viewportX, viewportY, 1.0], inverseMVPMatrix);
+	var direction = vec3.normalize(vec3.create(), vec3.subtract(vec3.create(), far, origin));
+	return {'origin':origin, 'direction':direction};
+} //}}}
+function raycast(canvas, origin, direction, node) { //{{{
+	//Performs raycast on given node using ray origin and direction vectors.
+	//Returns hit objects with hit position, normals, barycentric coordinates, element number, and indices of ray-triangle intersection.
 	//TODO: Diagnose marker issues with orthographic views and slr-eustatic updates when switching between basins.
-	var inverseMVPMatrix = mat4.invert(mat4.create(), mat4.multiply(mat4.create(), canvas.camera.vpMatrix, canvas.unitNode.modelMatrix));
-	var origin = vec3.transformMat4(vec3.create(), [(x - canvas.width / 2) / (canvas.width / 2), (canvas.height / 2 - y) / (canvas.height / 2), 0], inverseMVPMatrix);
-	var far = far || vec3.transformMat4(vec3.create(), [(x - canvas.width / 2) / (canvas.width / 2), (canvas.height / 2 - y) / (canvas.height / 2), 1.0], inverseMVPMatrix);
-	var ray = vec3.subtract(vec3.create(), far, origin);
-
-	var mesh = canvas.unitNode.mesh;
-	if (!mesh) { return; }
-	if (!mesh.octree) { mesh.octree = new GL.Octree(mesh); }
-	
-	var hit = mesh.octree.testRay(origin, ray, 1e3, 1e10);
-	
-	if(!hit) { return; }
-	
+	if (!node.octree) { node.octree = new GL.Octree(node.mesh); }
+	
+	var hit = node.octree.testRay(origin, direction, 1e3, 1e10);
+	if (!hit) { return; }
+
 	hit.modelPos = vec3.copy(vec3.create(), hit.pos);
-	vec3.transformMat4(hit.pos, hit.pos, canvas.unitNode.modelMatrix);
-	vec3.transformMat4(hit.normal, hit.normal, canvas.unitNode.modelMatrix);
-
+	vec3.transformMat4(hit.pos, hit.pos, node.modelMatrix);
+	
 	return hit;
 } //}}}
-function brushModify(canvas) { //{{{
-	//This function takes in the canvas and x/y coordinates, performing a raycast against the mesh, and modifies the mesh using a the canvas.brush.strength and canvas.brush.falloff properties.
-	//Currently the brush extends to the raycasted element and its immediate neighbors.
-	//TODO: Allow variable brush size/additional neighbors. Allow the function to work on multiple models (currently hardcoded to md model).
-	if (!canvas.unitNode || canvas.brush.enabled != 'on') { return; }
-	
-	var hit = canvas.brush.hit;
-
-	if (hit) {
-		var bufferVertices = canvas.unitNode.mesh.getBuffer('vertices');
-		var vertices = bufferVertices.data;
-		var bufferCoords = canvas.unitNode.mesh.getBuffer('coords');
-		var coords = bufferCoords.data;
-
-		//Query nearby elements and store indicies of affected vertices using pregenerated vertexconnectivity list (from NodeConnectivity)
-		var baseIndices = new Set(hit.indices);
-		var connectedIndices = new Set(hit.indices);
-		var connectedElement;
-		var indices;
-		var lengthIndex = md.mesh.vertexconnectivity[0].length - 1;
-		var length;
-		for (var i = 0; i < 3; i++) {
-			length = md.mesh.vertexconnectivity[hit.indices[i]][lengthIndex];
-			for (var j = 0; j < length; j++) {
-				//Shift elements down by one (matlab 1-based index to 0-based index)
-				connectedElement = md.mesh.vertexconnectivity[hit.indices[i]][j] - 1;
-				indices = md.mesh.elements[connectedElement];
-				connectedIndices.add(indices[0] - 1);
-				connectedIndices.add(indices[1] - 1);
-				connectedIndices.add(indices[2] - 1);
-			}
-		}
-
-		//Apply modifications to included vertices in mesh using brush strength and falloff.
-		var strength;
-		for (var index of connectedIndices) {
-			if (!baseIndices.has(index)) {
-				strength = canvas.brush.strength * canvas.brush.falloff;
-			}
-			else {
-				strength = canvas.brush.strength;
-			}
-			vertices[index*3+2] += strength * 100;
-			md.geometry.surface[index] += strength;	
-			md.geometry.thickness[index] += strength;
-			coords[index*2+1] += strength;
-			canvas.unitData[index] += strength;
-		}
-		
-		//Update mesh on GPU
-		bufferVertices.upload(canvas.gl.DYNAMIC_DRAW);
-		bufferCoords.upload(canvas.gl.DYNAMIC_DRAW);
-		canvas.unitNode.mesh.octree = new GL.Octree(canvas.unitNode.mesh);	
-		
-		//Update clouds if rendered
-		//TODO: Steven, once you update the cloud generation in applyoptions.js, modify this code block to move the clouds as well. We'll want to move them individually later, but moving them all is ok for now.
-		for (var i = 0; i < canvas.clouds.quantity; i++) {
-			if (canvas.nodes['clouds' + i]) {
-				var v1 = vec3.fromValues(vertices[hit.indices[0] * 3], vertices[hit.indices[0] * 3 + 1], vertices[hit.indices[0] * 3 + 2]);
-				var v2 = vec3.fromValues(vertices[hit.indices[1] * 3], vertices[hit.indices[1] * 3 + 1], vertices[hit.indices[1] * 3 + 2]);
-				var v3 = vec3.fromValues(vertices[hit.indices[2] * 3], vertices[hit.indices[2] * 3 + 1], vertices[hit.indices[2] * 3 + 2]);
-				vec3.transformMat4(v1, v1, canvas.unitNode.modelMatrix);
-				vec3.transformMat4(v2, v2, canvas.unitNode.modelMatrix);
-				vec3.transformMat4(v3, v3, canvas.unitNode.modelMatrix);
-				var x  = (v1[0] + v2[0] + v3[0]) / 3 + Math.floor((Math.random() * (1 + 10000 - (-10000)) + (-10000)));
-				var y  = (v1[1] + v2[1] + v3[1]) / 3 + Math.floor((Math.random() * (1 + 10000 - (-10000)) + (-10000)));
-				var z  = (v1[2] + v2[2] + v3[2]) / 3;
-				canvas.nodes['clouds' + i].translation = [x, y + canvas.clouds.height, z];
-				updateModelMatrix(canvas.nodes['clouds' + i]);
-			}
-		}
-	}
-} //}}}
-function initializeMarker(canvas) { //{{{
-	//Initialize data marker and tooltip display once per page load
-	var marker = $('#' + canvas.dataMarkers.marker.id);
-	var size = canvas.dataMarkers.size;
-	if (!marker.hasClass('tooltipstered')) {
-		marker.css({
-			'position': 'absolute',
-			'left': -size[0] + 'px',
-			'top': -size[1] + '0px',
-			'width': size[0] + 'px',
-			'height': size[1] + 'px',
-			'pointer-events': 'all',
-			'cursor': 'pointer',
-			'display': 'none'
-		});
-		marker.tooltipster({
-			contentAsHTML: true,
-			maxWidth: 320,
-			maxHeight: 320,
-			zIndex: 1000,
-			trigger: 'custom',
-			triggerOpen: {
-				mouseenter: false,
-				originClick: true,
-				touchstart: false
-			},
-			triggerClose: {
-				mouseleave: false,
-				originClick: true,
-				touchleave: false
-			},
-		});
-		marker.on('click touch', function () {
-			marker.fadeOut(175);
-			marker.tooltipster('close');
-		});
-		canvas.dataMarkers.marker.selector = marker;
-	}
-	updateMarker(canvas, true);
-} //}}}
-function repositionMarker(canvas) { //{{{
-	//Mover marker to point to mouse position, offset in y by 1 to enable immediate clicking.
-	if (isEmptyOrUndefined(canvas.dataMarkers.marker.hit) || !canvas.camera.ready) { return; }
-	var size = canvas.dataMarkers.size;
-	var screenPoint = vec3.transformMat4(vec3.create(), canvas.dataMarkers.marker.hit.pos, canvas.camera.vpMatrix);
-	//console.log(canvas, canvas.selector, $(canvas.id)
-	var x = (screenPoint[0] + 1.0) * (canvas.width / 2) + canvas.selector.offset().left;
-	var y = (-screenPoint[1] + 1.0) * (canvas.height / 2) + canvas.selector.offset().top;
-	canvas.dataMarkers.marker.selector.css({
-		'left': (Math.round(x) - size[0] / 2) + 'px', 
-		'top': (Math.round(y) - size[1] + 1) + 'px'
+function raycastXY(canvas, x, y, node, faceWinding) { //{{{
+	//Performs raycast on given node using x and y screenspace coordinates.
+	//Returns hit objects with hit position, normals, barycentric coordinates, element number, and indices of ray-triangle intersection.
+	//TODO: Diagnose marker issues with orthographic views and slr-eustatic updates when switching between basins.
+	var ray = screenToModelRay(canvas, x, y, node);
+	return raycast(canvas, ray.origin, ray.direction, node);
+} //}}}
+function animateValue(current, target, duration, easing, stepCallback, doneCallback) { //{{{
+	//Animates scalar value for length duration, calling callback each step. Specify smooth easing as a string ('swing', 'linear').
+	$({'value':current}).animate({'value':target}, {
+		duration: duration,
+		easing: easing,
+		step: stepCallback,
+		done: doneCallback
 	});
-	
-	if (canvas.dataMarkers.marker.selector.tooltipster('status').state != 'closed') { canvas.dataMarkers.marker.selector.tooltipster('reposition'); }
-} //}}}
-function updateMarker(canvas, reset) { //{{{
-	//Retrieve data value fields and plots them on data marker popup if a hit has been registered.
-	//TODO: Automatically pick up any field of size md.mesh.numberofelements
-	//If no marker has been placed, no update is needed. If canvas is resimulating and unitNode has not been set yet, wait and try again.
-	if (isEmptyOrUndefined(canvas.dataMarkers.marker.hit)) { return; }
-	if (isEmptyOrUndefined(canvas.unitNode)) { setTimeout( function(){ updateMarker(canvas, reset); }, 750); return; }
-	
-	var hit = canvas.dataMarkers.marker.hit;
-	
-	var coords = canvas.unitNode.mesh.vertexBuffers.coords.data;
-	var latitude = md.mesh.lat;
-	var longitude = md.mesh.long;
-	var thickness;
-	var velocity;
-	if (md.results[0]) {
-		thickness = md.results[canvas.animation.frame].Thickness;
-		velocity = md.results[canvas.animation.frame].Vel;
-	}
-	else {
-		thickness = md.geometry.thickness;
-		velocity = md.initialization.vel;
-	}
-	
-	//Determine data values at hit position.
-	var hitCoords = [coords[hit.indices[0]*2], coords[hit.indices[0]*2+1], coords[hit.indices[1]*2], coords[hit.indices[1]*2+1], coords[hit.indices[2]*2], coords[hit.indices[2]*2+1]];
-	var hitLatitude = [latitude[hit.indices[0]], latitude[hit.indices[1]], latitude[hit.indices[2]]];
-	var hitLongitude = [longitude[hit.indices[0]], longitude[hit.indices[1]], longitude[hit.indices[2]]];
-	var hitThickness = [thickness[hit.indices[0]], thickness[hit.indices[1]], thickness[hit.indices[2]]];
-	var hitVelocity = [velocity[hit.indices[0]], velocity[hit.indices[1]], velocity[hit.indices[2]]];
-	var u = hitCoords[0] * hit.uvw[0] + hitCoords[2] * hit.uvw[1] + hitCoords[4] * hit.uvw[2];
-	var v = hitCoords[1] * hit.uvw[0] + hitCoords[3] * hit.uvw[1] + hitCoords[5] * hit.uvw[2];
-	var value = canvas.unitNode.caxis[0] * (1.0 - v) + canvas.unitNode.caxis[1] * v;
-	var valueLatitude = Math.abs(hitLatitude[0] * hit.uvw[0] + hitLatitude[1] * hit.uvw[1] + hitLatitude[2] * hit.uvw[2]);
-	var valueLongitude = Math.abs(hitLongitude[0] * hit.uvw[0] + hitLongitude[1] * hit.uvw[1] + hitLongitude[2] * hit.uvw[2]);
-	var valueThickness = hitThickness[0] * hit.uvw[0] + hitThickness[1] * hit.uvw[1] + hitThickness[2] * hit.uvw[2];
-	var valueVelocity = hitVelocity[0] * hit.uvw[0] + hitVelocity[1] * hit.uvw[1] + hitVelocity[2] * hit.uvw[2];	
-
-	//Construct new argument array of the data display format for sprintf using first first argument as the formatSpecifier string and the rest as the additional arguments.
-	var format = canvas.dataMarkers.format.slice();
-	for (var i = 1; i < format.length; i++) {
-		if (format[i].toLowerCase() == 'x') { format[i] = hit.modelPos[0]; }
-		else if (format[i].toLowerCase() == 'y') { format[i] = hit.modelPos[1]; }
-		else if (format[i].toLowerCase() == 'z') { format[i] = hit.modelPos[2]; }
-		else if (format[i].toLowerCase() == 'lat') { format[i] = valueLatitude; }
-		else if (format[i].toLowerCase() == 'long') { format[i] = valueLongitude; }
-		else if (format[i].toLowerCase() == 'thickness') { format[i] = valueThickness; }
-		else if (format[i].toLowerCase() == 'vel') { format[i] = valueVelocity; }
-		else if (format[i].toLowerCase() == 'value') { format[i] = value; }
-	}
-	
-	//Apply changes to tooltip
-	$('#tooltip-content-data-marker-' + canvas.id).html(sprintf.apply(null, format));
-	$('#tooltip-content-data-marker-' + canvas.id).css({'font': canvas.dataMarkers.font});				
-	
-	//If animated, setup animation loop to update plot as movie plays.
-	if (canvas.dataMarkers.animated) {
-		var isEmpty = (canvas.dataMarkers.values.length == 0);
-		var lastUpdatedIndex = (canvas.dataMarkers.values.length-1);
-		var newMovieFrame = (!isEmpty && canvas.dataMarkers.values[lastUpdatedIndex][0] != canvas.animation.frame);
-		//If new data marker has been placed, reinitialize plot. If not, push new value into plot value array.
-		if (reset) {
-			canvas.dataMarkers.values = [];
-			newMovieFrame = true;
-			for (var currentFrame = 0; currentFrame < (canvas.unitNode.movieLength); currentFrame++) {
-				coords = canvas.unitNode.texcoords[currentFrame];
-				var hitCoords = [coords[hit.indices[0]*2], coords[hit.indices[0]*2+1], coords[hit.indices[1]*2], coords[hit.indices[1]*2+1], coords[hit.indices[2]*2], coords[hit.indices[2]*2+1]];
-				var u = hitCoords[0] * hit.uvw[0] + hitCoords[2] * hit.uvw[1] + hitCoords[4] * hit.uvw[2];
-				var v = hitCoords[1] * hit.uvw[0] + hitCoords[3] * hit.uvw[1] + hitCoords[5] * hit.uvw[2];
-				var value = canvas.unitNode.caxis[0] * (1.0 - v) + canvas.unitNode.caxis[1] * v;
-				canvas.dataMarkers.values.push([currentFrame, value]);
-			}
-		}
-		else {
-			if (isEmpty || newMovieFrame) {
-				canvas.dataMarkers.values.push([canvas.animation.frame, value]);
-			}
-		}
-		
-		//Replot data marker popup using update data value array.
-		if (isEmpty || newMovieFrame) {
-			var dataLabels = {'latitude': valueLatitude, 'longitude': valueLongitude, 'thickness': valueThickness, 'velocity': valueVelocity, 'value': value};
-			var dataDisplay = canvas.dataMarkers.values.slice(0, canvas.animation.frame+1);					
-			plot(
-				'id', '#sim-plot', 
-				'type', 'bar', 
-				'width', 400, 
-				'height', 300, 
-				'nticks', 25, 
-				'xlabel', 'Time', 
-				'ylabel', 'Value', 
-				'title', 'Changes Over Time', 
-				'datalabels', canvas.dataMarkers.labels,
-				'labelvalues', dataLabels,
-				'data', dataDisplay
-			);
-		}
-	}
-	repositionMarker(canvas);
-	if (reset) {
-		canvas.dataMarkers.marker.selector.fadeIn(175);
-		canvas.dataMarkers.marker.selector.tooltipster('open');
-	}
 } //}}}
 //}}}
@@ -697,22 +365,29 @@
 	var elevationRotationMatrix = mat4.create();
 	var aspectRatio = canvas.clientWidth / canvas.clientHeight;
-	var cameraPosition = vec3.create();
-
-	if (canvas.view.twod) { mat4.ortho(pMatrix, -aspectRatio*6.371e6/canvas.view.zoom, aspectRatio*6.371e6/canvas.view.zoom, -6.371e6/canvas.view.zoom, 6.371e6/canvas.view.zoom, canvas.camera.near, canvas.camera.far); }
-	else { mat4.perspective(pMatrix, canvas.camera.fov * DEG2RAD, aspectRatio, canvas.camera.near, canvas.camera.far); }
+	var camera = canvas.camera;
+	var view = canvas.view;
+
+	if (view.twod) { mat4.ortho(pMatrix, -aspectRatio*6.371e6/view.zoom, aspectRatio*6.371e6/view.zoom, -6.371e6/view.zoom, 6.371e6/view.zoom, camera.near, camera.far); }
+	else { mat4.perspective(pMatrix, camera.fov * DEG2RAD, aspectRatio, camera.near, camera.far); }
 	
 	//Apply worldspace translation
-	mat4.translate(vMatrix, translateMatrix, vec3.negate(vec3.create(), canvas.view.position));
+	mat4.translate(vMatrix, translateMatrix, vec3.negate(vec3.create(), view.position));
 	
 	//Calculate rotation around camera focal point about worldspace origin
-	if (canvas.view.twod) {
-		mat4.rotate(azimuthRotationMatrix, azimuthRotationMatrix, DEG2RAD * 0, [0, 1, 0]);
+	if (view.twod) {
+		mat4.rotate(azimuthRotationMatrix, azimuthRotationMatrix, -DEG2RAD * 0, [0, 1, 0]);
 		mat4.rotate(elevationRotationMatrix, elevationRotationMatrix, DEG2RAD * 90, [1, 0, 0]);
 		mat4.multiply(rotationMatrix, elevationRotationMatrix, azimuthRotationMatrix);
 	}
 	else {
-		mat4.rotate(azimuthRotationMatrix, azimuthRotationMatrix, DEG2RAD * canvas.view.rotation[0], [0, 1, 0]);
-		mat4.rotate(elevationRotationMatrix, elevationRotationMatrix, DEG2RAD * canvas.view.rotation[1], [1, 0, 0]);
+		mat4.rotate(azimuthRotationMatrix, azimuthRotationMatrix, -DEG2RAD * (view.rotation[0] + 90), [0, 1, 0]);
+		mat4.rotate(elevationRotationMatrix, elevationRotationMatrix, DEG2RAD * view.rotation[1], [1, 0, 0]);
 		mat4.multiply(rotationMatrix, elevationRotationMatrix, azimuthRotationMatrix);
+		//var quaternionWorldX = Node.prototype.eulerToQuaternion(0, 0, DEG2RAD * (view.rotation[0]));
+		//var quaternionWorldY = Node.prototype.eulerToQuaternion(0, DEG2RAD * (view.rotation[1]), 0);
+		//var quaternionWorldZ = Node.prototype.eulerToQuaternion(DEG2RAD * (view.rotation[2]), 0, 0);
+		//var quaternionTemp = quat.multiply(quat.create(), quaternionWorldY, quaternionWorldX);
+		//quat.multiply(camera.rotation, quaternionWorldZ, quaternionTemp);
+		//mat4.fromQuat(rotationMatrix, camera.rotation);	
 	}
 
@@ -722,17 +397,20 @@
 	//Apply screenspace translation to emulate rotation around point
 	mat4.identity(translateMatrix);
-	mat4.translate(translateMatrix, translateMatrix, [0.0, 0.0, -6.371e6/canvas.view.zoom]);
+	mat4.translate(translateMatrix, translateMatrix, [0.0, 0.0, -6.371e6/view.zoom]);
 	mat4.multiply(vMatrix, translateMatrix, vMatrix);
 	
 	//Apply projection matrix to get camera matrix
-	mat4.copy(canvas.camera.vMatrix, vMatrix);
-	mat4.multiply(canvas.camera.vpMatrix, pMatrix, vMatrix);
+	mat4.copy(camera.vMatrix, vMatrix);
+	mat4.multiply(camera.vpMatrix, pMatrix, vMatrix);
 	
 	//Calculate inverse view matrix fields for lighting and raycasts
-	mat4.invert(canvas.camera.vInverseMatrix, canvas.camera.vMatrix);
-	mat4.invert(canvas.camera.vpInverseMatrix, canvas.camera.vpMatrix);
-	
-	vec3.transformMat4(canvas.camera.position, cameraPosition, canvas.camera.vpInverseMatrix);
-	canvas.camera.ready = true;
+	mat4.invert(camera.vInverseMatrix, camera.vMatrix);
+	mat4.invert(camera.vpInverseMatrix, camera.vpMatrix);
+	
+	vec3.transformMat4(camera.position, vec3.create(), camera.vInverseMatrix);
+	vec3.sub(camera.relativePosition, camera.position, view.position);
+	vec3.normalize(camera.direction, camera.relativePosition);
+	
+	camera.ready = true;
 }//}}}
 function drawSceneGraphNode(canvas, node) { //{{{
@@ -745,10 +423,9 @@
 	mat4.multiply(mvpMatrix, canvas.camera.vpMatrix, node.modelMatrix);
 	
-	var mvMatrix = mat4.create();
-	mat4.multiply(mvMatrix, canvas.camera.vMatrix, node.modelMatrix);
-	
-	var normalMatrix = mat4.create();
-	mat4.invert(normalMatrix, mvMatrix);
-	mat4.transpose(normalMatrix, normalMatrix);
+	var normalMatrix = mat3.create();
+	var tempMatrix = mat4.create();
+	mat4.invert(tempMatrix, node.modelMatrix);
+	mat4.transpose(tempMatrix, tempMatrix);
+	mat3.fromMat4(normalMatrix, tempMatrix);
 	
 	if (node.texture) { node.texture.bind(0); }
@@ -759,76 +436,56 @@
 	gl.lineWidth(node.lineWidth);
 	gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
-
+	
 	//Setup for light that originates from camera
-	var origin = vec3.fromValues(0, 0, 0);
-	var lightOrigin = vec3.fromValues(0, 0, 0);
-	var cameraPositionRelative = vec3.create();
-	vec3.transformMat4(origin, origin, canvas.camera.vInverseMatrix);
-	vec3.normalize(lightOrigin, lightOrigin);
-	vec3.sub(cameraPositionRelative, origin, node.translation);
-	cameraHeight = vec3.length(cameraPositionRelative);
-	
-	var atm = { 							//Default Values
-				wavelength_r: 0.65, 		//0.65		Red wavelength (micrometers)
-				wavelength_g: 0.57,			//0.57		Green wavelength (micrometers)
-				wavelength_b: 0.475,		//0.475		Green wavelength (micrometers)
-				eSun: 100.0,				//20.0		Sun intensity	
-				kRayleigh: 0.0025,			//0.0025	Rayleigh scattering amount
-				kMie: 0.000, 				//0.01		Mie scattering amount
-				g: -0.99,					//-0.99		Mie phase asymmetry/direction factor
-				hdr_exposure: 0.8,			//0.8		High Dynamic Range Exposure
-				scale: 1.25, 				//1.025		Scale of atmosphere. WARNING: Change atmosphereScale in applyoptions.js, and scaling constants.
-				scaleDepth: 0.25, 			//0.25		Percentage altitude at which the atmosphere's average density is found
-				a: -0.00287,				//-0.00287	Scaling constant a
-				b: 0.459,					//0.459		Scaling constant b
-				c: 3.83,					//3.83		Scaling constant c
-				d: -6.80,					//-6.80		Scaling constant d
-				e: 3.6,						//5.25		Scaling constant e. Lower when increasing atmosphere scale.
-				attenuation: 0.5			//0.5		Strength of atmospheric scattering on ground shading.
-	};
-			
-	var inv_wavelength4 = [1.0 / Math.pow(atm.wavelength_r, 4), 1.0 / Math.pow(atm.wavelength_g, 4), 1.0 / Math.pow(atm.wavelength_b, 4)];
-	var innerRadius = 6.371e6;
-	var outerRadius = innerRadius*atm.scale;
-	var scale = 1.0 / (outerRadius - innerRadius);
-	var scaleDepth = atm.scaleDepth;
+	var atm = canvas.atmosphere;
+	var lightOrigin = vec3.create();
 	
 	node.shader.uniforms({
-		m4MVP: mvpMatrix,
-		m4Normal: normalMatrix,
-		m4Model: node.modelMatrix,
-		//u_lightPosition: [-lightOrigin[0], -lightOrigin[1], -lightOrigin[2]],
-		u_lightPosition: [1.0, 1.0, 1.0],
-		u_diffuseColor: [1.0, 0.9, 0.9],
-		u_texture: 0,
-		u_alpha: node.alpha,
-		u_maskEnabled: node.maskEnabled,
-		u_maskHeight: node.maskHeight,
-		u_maskColor: node.maskColor,
-		v3CameraPosition: origin,
-		v3Translate: node.translation,
-		v3LightPos: lightOrigin,
-		v3InvWavelength: inv_wavelength4,
-		fOuterRadius: outerRadius,
-		fOuterRadius2: outerRadius * outerRadius,
-		fInnerRadius: innerRadius,
-		fInnerRadius2: innerRadius * innerRadius,
-		fKrESun: atm.kRayleigh * atm.eSun, 
-		fKmESun: atm.kMie * atm.eSun, 
-		fKr4PI: atm.kRayleigh * 4 * Math.PI, 
-		fKm4PI: atm.kMie * 4 * Math.PI,
-		fScale: scale, 
-		fScaleDepth: scaleDepth,
-		fScaleOverScaleDepth: scale/scaleDepth, 
-		v3LightPosFrag: lightOrigin,
-		fHdrExposure: atm.hdr_exposure,	
-		g: atm.g,			
-		g2: atm.g * atm.g,
-		a: atm.a,
-		b: atm.b,
-		c: atm.c,
-		d: atm.d,		
-		e: atm.e,
-		attenuation: atm.attenuation
+		m4MVP: 					mvpMatrix,
+		m3Normal: 				normalMatrix,
+		m4Model: 				node.modelMatrix,
+		u_alpha: 				node.alpha,
+		u_ambientColor: 		node.ambientColor,
+		u_cameraPosition: 		canvas.camera.position,
+		u_diffuseColor: 		node.diffuseColor,
+		u_lightDirection: 		canvas.camera.direction,
+		u_lightingBias: 		node.lightingBias,
+		u_maskZerosColor: 		node.maskZerosColor,
+		u_maskZerosEnabled: 	node.maskZerosEnabled,
+		u_maskZerosTolerance: 	node.maskZerosTolerance,
+		u_maskZerosZeroValue: 	node.maskZerosZeroValue,
+		u_maskEnabled: 			node.maskEnabled,
+		u_maskHeight: 			node.maskHeight,
+		u_maskColor: 			node.maskColor,
+		u_pointSize: 			node.pointSize,
+		u_specularColor: 		node.specularColor,
+		u_specularPower: 		node.specularPower,
+		u_specularStrength: 	node.specularStrength,
+		u_texture: 				0,
+		v3CameraPosition: 		canvas.camera.position,
+		v3Translate: 			node.translation,
+		v3LightPos: 			lightOrigin,
+		v3InvWavelength: 		atm.inv_wavelength4,
+		fOuterRadius: 			atm.outerRadius,
+		fOuterRadius2: 			atm.outerRadius2,
+		fInnerRadius: 			atm.innerRadius,
+		fInnerRadius2: 			atm.innerRadius2,
+		fKrESun: 				atm.krESun,
+		fKmESun: 				atm.kmESun,
+		fKr4PI: 				atm.kr4PI,
+		fKm4PI: 				atm.km4PI,
+		fScale: 				atm.scale, 
+		fScaleDepth: 			atm.scaleDepth,
+		fScaleOverScaleDepth: 	atm.scaleOverScaleDepth, 
+		v3LightPosFrag: 		lightOrigin,
+		fHdrExposure: 			atm.hdr_exposure,	
+		g: 						atm.g,			
+		g2: 					atm.g2,
+		a: 						atm.a,
+		b: 						atm.b,
+		c: 						atm.c,
+		d: 						atm.d,		
+		e: 						atm.e,
+		attenuation: 			atm.attenuation
 	}).draw(node.mesh, node.drawMode, 'triangles');
 	
@@ -836,4 +493,16 @@
 	gl.disable(gl.CULL_FACE);
 } //}}}
+function canvasResize(canvas) {
+	var rect = canvas.getBoundingClientRect();
+	canvas.width  = rect.width;
+	canvas.height = rect.height;
+	canvas.gl.viewport(0, 0, canvas.width, canvas.height);
+	
+	if (!VESL.Helpers.isEmptyOrUndefined(canvas.overlaycanvas)) {
+		rect = canvas.overlaycanvas.getBoundingClientRect();
+		canvas.overlaycanvas.width  = rect.width;
+		canvas.overlaycanvas.height = rect.height;
+	}
+}
 function draw(canvas) { //{{{
 	//Ensure all nodes are ready to render
@@ -841,8 +510,8 @@
 	var nodes = canvas.nodes;
 	if (!canvas.draw.ready) {
-		if (nodes.length !== 0) {
+		if (Object.keys(nodes).length !== 0) {
 			canvas.draw.ready = true;
 			for (var node in nodes) {
-				if (nodes[node].shader.ready == false) {
+				if (nodes[node].shader.ready === false) {
 					canvas.draw.ready = false;
 					break;
@@ -855,14 +524,9 @@
 	//Begin rendering nodes
 	if (canvas.draw.ready) {
-		if (canvas.textcanvas) { canvas.textcanvas.draw(canvas); }
-		if (canvas.overlaycanvas) { canvas.overlaycanvas.draw(canvas); }
-	
-		var rect = canvas.getBoundingClientRect();
-		canvas.width  = rect.width;
-		canvas.height = rect.height;
+		//Handle canvas resizing and viewport/screenspace coordinate synchronization
+		canvasResize(canvas);	
 		
 		var gl = canvas.gl;
 		gl.makeCurrent(); //litegl function to handle switching between multiple canvases
-		gl.viewport(0, 0, canvas.width, canvas.height);
 		gl.clearColor(canvas.backgroundcolor[0], canvas.backgroundcolor[1], canvas.backgroundcolor[2], canvas.backgroundcolor[3]);
 		gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
@@ -870,8 +534,13 @@
 		updateCameraMatrix(canvas);
 		
+		//Trigger any handlers attatched to this canvas event.
+		canvas.selector.trigger('onPreRender', [canvas]);
+		
+		for (var handler in canvas.overlayHandlers) { canvas.overlayHandlers[handler](canvas); }
+		
 		var drawPassNumber = 3;
-		for (var i = drawPassNumber - 1; i >= 0; i--) {
+		for (var i = drawPassNumber - 1; i >= 0; --i) {
 			for (var node in nodes) {
-				if (nodes[node].drawOrder == i) { drawSceneGraphNode(canvas, nodes[node]); }
+				if (nodes[node].drawOrder === i) { drawSceneGraphNode(canvas, nodes[node]); }
 			}
 		}
Index: /issm/trunk/src/m/plot/webgl_node.js
===================================================================
--- /issm/trunk/src/m/plot/webgl_node.js	(revision 22758)
+++ /issm/trunk/src/m/plot/webgl_node.js	(revision 22758)
@@ -0,0 +1,648 @@
+//NODE class definition //{{{
+//	Description:
+//		Contains all information for rendering an object in WebGL, including mesh, materials, shaders, and other attributes.	
+//	Usage:
+//		node=new Node('canvas', canvas);
+
+function Node() { //{{{
+	//properties
+	// {{{
+	var args = Array.prototype.slice.call(arguments);
+	var options = new pairoptions(args.slice(0,args.length));
+
+	this.canvas = options.getfieldvalue('canvas', 								null),
+	this.options = options.getfieldvalue('options', 							null),
+	this.gl = canvas.gl;
+	
+	this.alpha = options.getfieldvalue('alpha', 								1.0);									//Shading transparency.
+	this.ambientColor = options.getfieldvalue('ambientColor', 					[0.0, 0.0, 0.0, 1.0]);					//Ambient color used in lighting.
+	this.animation = options.getfieldvalue('animation', 						{});									//Animtation parameters.
+	this.arrays = options.getfieldvalue('arrays', 								{});									//Storage for webgl arrays.
+	this.caxis = options.getfieldvalue('caxis', 								[0.0, 1.0]);							//Color axis for texturing.
+	this.center = options.getfieldvalue('center', 								vec3.create());							//Center of rotation/scaling.
+	this.cullFace = options.getfieldvalue('cullFace', 							this.gl.BACK);							//GL enum for face culling back/front faces.
+	this.computeIndices = options.getfieldvalue('computeIndices', 				true);									//Specifies whether or not indices need to be computed during patching.
+	this.disableDepthTest = options.getfieldvalue('disableDepthTest', 			false);									//GL enum for enabling/disabling depth testing.
+	this.diffuseColor = options.getfieldvalue('diffuseColor', 					[0.0, 0.0, 0.0, 1.0]);					//Diffuse color in vec4 rgba format.
+	this.drawMode = options.getfieldvalue('drawMode', 							this.gl.TRIANGLES);						//GL enum for draw mode.
+	this.drawOrder = options.getfieldvalue('drawOrder', 						1);										//Drawing order for non-depth tested/transparent objects. Higher numbers are drawn. first.
+	this.enabled = options.getfieldvalue('enabled', 							true);									//Toggles display of this nodde.
+	this.enableCullFace = options.getfieldvalue('enableCullFace', 				true);									//Toggles use of face culling.
+	this.hideOcean = options.getfieldvalue('hideOcean', 						false);									//ISSM shader uniform controlling ocean masking
+	this.lineWidth = options.getfieldvalue('lineWidth', 						1.0);									//Controls width of gl lines. No reliable support across windows platforms.
+	this.lightingBias = options.getfieldvalue('lightingBias', 					0.0);									//Controls width of gl lines. No reliable support across windows platforms.
+	this.log = options.getfieldvalue('log', 									false);									//Controls logarithmic color axis scaling for texturing.
+	this.maskAll = options.getfieldvalue('maskAll', 							[]);									//Masking array used for marking all region elements.
+	this.maskBoundary = options.getfieldvalue('maskBoundary', 					[]);									//Masking array used for marking region boundary edges.
+	this.maskColor = options.getfieldvalue('maskColor', 						vec4.fromValues(0.0, 0.0, 1.0, 1.0));	//ISSM shader uniform controlling ocean masking color.
+	this.maskEnabled = options.getfieldvalue('maskEnabled', 					false);									//ISSM shader uniform toggling ocean masking.
+	this.maskHeight = options.getfieldvalue('maskHeight', 						150.0);									//ISSM shader uniform controlling height at which ocean masking is cut off.
+	this.maskObject = options.getfieldvalue('maskObject', 						{'enabled':false});						//Masking array options object.
+	this.maskZerosColor = options.getfieldvalue('maskZerosColor', 				[1.0, 1.0, 1.0, 1.0]);					//ISSM shader uniform controlling value masking color.
+	this.maskZerosEnabled = options.getfieldvalue('maskZerosEnabled', 			false);									//ISSM shader uniform toggling value masking.
+	this.maskZerosTolerance = options.getfieldvalue('maskZerosTolerance', 		1e-6);									//ISSM shader uniform controlling tolerance of value to zero value when masking.
+	this.maskZerosZeroValue = options.getfieldvalue('maskZerosZeroValue', 		0.5);									//ISSM shader uniform controlling zero value masking offset.
+	this.mesh = options.getfieldvalue('mesh', 									undefined);								//Litegl GL.Mesh class used for drawing.
+	this.name = options.getfieldvalue('name', 									'node');								//Name of node.
+	this.nanIndices = options.getfieldvalue('nanIndices', 						new Set());								//Set of NaN indices to mask out of mesh.
+	this.octree = options.getfieldvalue('octree', 								undefined);								//Fast raytracing octree object.
+	this.pointSize = options.getfieldvalue('pointSize', 						15.0);									//Size of points when displaying GL.POINTS.
+	this.shaderName = options.getfieldvalue('shaderName', 						'Colored');								//Name of shader to use.
+	this.shader = options.getfieldvalue('shader', 								this.gl.shaders[this.shaderName]);		//Compiled shader object.
+	this.specularColor = options.getfieldvalue('specularColor', 				[1.0, 1.0, 1.0, 1.0]);					//Specular reflection color used in lighting.
+	this.specularStrength = options.getfieldvalue('specularStrength', 			1.0);									//Specular reflection power - represents specular highlight sharpness.
+	this.specularPower = options.getfieldvalue('specularPower', 				5);										//Specular reflection power - represents specular highlight sharpness.
+	this.texture = options.getfieldvalue('texture', 							undefined);								//GL texture object.
+	this.scale = options.getfieldvalue('scale', 								vec3.fromValues(1, 1, 1));				//XYZ scaling of the node.
+	this.renderObject = options.getfieldvalue('renderObject', 					{});									//Field for additional render object state information not necessarily related to node display.
+	this.rotation = options.getfieldvalue('rotation', 							vec3.create());							//XYZ rotation of the node.
+	this.rotationQuaternion = options.getfieldvalue('rotationQuaternion',		quat.create());							//Quaternion rotation of the node. Not currently in use.
+	this.translation = options.getfieldvalue('translation', 					vec3.create());							//XYZ translation of the node.
+	this.modelMatrix = options.getfieldvalue('modelMatrix', 					mat4.create());							//Model matrix computed from updateModelMatrix function.
+	this.translationMatrix = options.getfieldvalue('translationMatrix', 		mat4.create());							//Intermediate translation matrix computed from updateModelMatrix function.
+	this.rotationMatrix = options.getfieldvalue('rotationMatrix', 				mat4.create());							//Intermediate rotation matrix computed from updateModelMatrix function.
+	this.scaleMatrix = options.getfieldvalue('scaleMatrix', 					mat4.create());							//Intermediate scale matrix computed from updateModelMatrix function.
+	this.inverseModelMatrix = options.getfieldvalue('inverseModelMatrix', 		mat4.create());							//Inverse model matrix.
+	this.inverseRotationMatrix = options.getfieldvalue('inverseRotationMatrix', mat4.create());							//Inverse rotation matrix.
+	//}}}
+	//initialize {{{
+	//if (this.name in canvas.nodes) abort?
+	this.updateModelMatrix();
+	this.updateDiffuseColor();
+	canvas.nodes[this.name] = this;
+	//}}}
+} //}}}
+Node.prototype.eulerToQuaternion = function(pitch, roll, yaw) { //{{{
+	var t0 = Math.cos(yaw * 0.5);
+	var t1 = Math.sin(yaw * 0.5);
+	var t2 = Math.cos(roll * 0.5);
+	var t3 = Math.sin(roll * 0.5);
+	var t4 = Math.cos(pitch * 0.5);
+	var t5 = Math.sin(pitch * 0.5);
+
+	var w = t0 * t2 * t4 + t1 * t3 * t5;
+	var x = t0 * t3 * t4 - t1 * t2 * t5;
+	var y = t0 * t2 * t5 + t1 * t3 * t4;
+	var z = t1 * t2 * t4 - t0 * t3 * t5;
+	return quat.fromValues(x, y, z, w);
+} //}}}
+Node.prototype.quaternionToEuler = function(q) { //{{{
+	var ysqr = q[1] * q[1];
+
+	// roll (x-axis rotation)
+	var t0 = +2.0 * (q[3] * q[0] + q[1] * q[2]);
+	var t1 = +1.0 - 2.0 * (q[0] * q[0] + ysqr);
+	var roll = Math.atan2(t0, t1);
+
+	// pitch (y-axis rotation)
+	var t2 = +2.0 * (q[3] * q[1] - q[2] * q[0]);
+	t2 = t2 > 1.0 ? 1.0 : t2;
+	t2 = t2 < -1.0 ? -1.0 : t2;
+	var pitch = Math.asin(t2);
+
+	// yaw (z-axis rotation)
+	var t3 = +2.0 * (q[3] * q[2] + q[0] * q[1]);
+	var t4 = +1.0 - 2.0 * (ysqr + q[2] * q[2]);
+	var yaw = Math.atan2(t3, t4);
+	
+	return [pitch * RAD2DEG, roll * RAD2DEG, yaw * RAD2DEG];
+} //}}}
+Node.prototype.updateModelMatrix = function() { //{{{
+	//Update the model matrix if rotation, scale, or translation have been manually modified.
+	var modelMatrix = mat4.create();
+
+	var translationMatrix = mat4.create();
+	mat4.translate(translationMatrix, translationMatrix, vec3.negate(vec3.create(), this.center)); //scale/rotation centering
+	mat4.multiply(modelMatrix, translationMatrix, modelMatrix);
+	
+	var scaleMatrix = mat4.create();
+	mat4.scale(scaleMatrix, scaleMatrix, this.scale);
+	mat4.multiply(modelMatrix, scaleMatrix, modelMatrix);
+	
+	var rotationMatrix = mat4.create();
+	var zRotationMatrix = mat4.create();	
+	mat4.rotate(zRotationMatrix, zRotationMatrix, DEG2RAD * this.rotation[2], [0.0, 0.0, 1.0]);
+	mat4.multiply(rotationMatrix, zRotationMatrix, rotationMatrix);
+	var yRotationMatrix = mat4.create();	
+	mat4.rotate(yRotationMatrix, yRotationMatrix, DEG2RAD * this.rotation[1], [0.0, 1.0, 0.0]);
+	mat4.multiply(rotationMatrix, yRotationMatrix, rotationMatrix);
+	var xRotationMatrix = mat4.create();	
+	mat4.rotate(xRotationMatrix, xRotationMatrix, DEG2RAD * this.rotation[0], [1.0, 0.0, 0.0]);
+	mat4.multiply(rotationMatrix, xRotationMatrix, rotationMatrix);
+	mat4.multiply(modelMatrix, rotationMatrix, modelMatrix);
+
+	//var rotationQuaternionX = this.eulerToQuaternion(0, -DEG2RAD * this.rotation[0], 0);
+	//var rotationQuaternionY = this.eulerToQuaternion(DEG2RAD * this.rotation[1], 0, 0);
+	//mat4.fromQuat(this.rotationMatrix, quat.multiply(quat.create(), rotationQuaternionY, rotationQuaternionX));
+
+	//mat4.multiply(this.modelMatrix, this.rotationMatrix, this.modelMatrix);	
+		
+	
+	mat4.identity(translationMatrix);
+	mat4.translate(translationMatrix, translationMatrix, this.center); //relative translation
+	mat4.multiply(modelMatrix, translationMatrix, modelMatrix);
+	
+	mat4.identity(translationMatrix);
+	mat4.translate(translationMatrix, translationMatrix, this.translation); //absolute translation
+	mat4.multiply(modelMatrix, translationMatrix, modelMatrix);
+	
+	this.modelMatrix = modelMatrix;
+	this.inverseModelMatrix = mat4.invert(mat4.create(), modelMatrix);
+	this.rotationMatrix = rotationMatrix;
+	this.inverseRotationMatrix = mat4.invert(mat4.create(), rotationMatrix);
+} //}}}
+Node.prototype.updateDiffuseColor = function() { //{{{
+	//Update the diffuse color with an RGB color name or vec4 containing r, g, b, and alpha values from 0.0 to 1.0
+	var color = this.diffuseColor;
+	if (typeof color === 'string') {
+		color = new RGBColor(color);
+		if (color.ok) color = [color.r/255.0, color.g/255.0, color.b/255.0, 1.0];
+		else throw Error(sprintf("s%s%s\n","initWebGL error message: cound not find out edgecolor color for curent canvas ", canvas));
+	}
+	this.diffuseColor = color;
+} //}}}
+Node.prototype.transform = function() { //{{{
+	//Transforms the translation, rotation, or scle fo the node and updates the model matrix.
+	var args = Array.prototype.slice.call(arguments);
+	var options = new pairoptions(args.slice(0,args.length));
+	
+	var translation = options.getfieldvalue('translation', undefined);
+	var rotation = options.getfieldvalue('rotation', undefined);
+	var scale = options.getfieldvalue('scale', undefined);
+	
+	if (!VESL.Helpers.isEmptyOrUndefined(translation)) this.translation = translation;
+	if (!VESL.Helpers.isEmptyOrUndefined(rotation)) this.rotation = rotation;
+	if (!VESL.Helpers.isEmptyOrUndefined(scale)) this.scale = scale;
+	this.updateModelMatrix();
+} //}}}
+Node.prototype.patch = function() { //{{{
+	//Emulates the behavior of MATLAB patch function by constructing a mesh from arguments.
+	//Limitations:
+	//	-Expects pair labeled arguments ('FaceColor','none',...).
+	//	-Only handles Face/Vertices/FaceVertexCData element/node plots.
+	//	-Only supports FaceColor 'interp' and 'none'.
+	
+	var args = Array.prototype.slice.call(arguments);
+	var options = new pairoptions(args.slice(0,args.length));
+
+	var faces = options.getfieldvalue('Faces', undefined);
+	var vertices = options.getfieldvalue('Vertices', undefined);
+	var faceVertexCData = options.getfieldvalue('FaceVertexCData', undefined);
+	var faceColor = options.getfieldvalue('FaceColor', 'interp');
+	var edgeColor = options.getfieldvalue('EdgeColor', this.diffuseColor);
+	var lineWidth = options.getfieldvalue('linewidth', 1);
+	
+	this.faces = faces;
+	this.vertices = vertices;
+	this.diffuseColor = edgeColor;
+	this.updateDiffuseColor();
+	this.computeMasks();
+	
+	this.patchVertices(faceVertexCData, faces, vertices);
+	this.patchCoords(faceVertexCData, faces, vertices);
+	this.patchIndices(faces, faceColor);
+
+	this.mesh = GL.Mesh.load(this.arrays, null, null, this.gl);
+	this.mesh.computeNormals();
+	this.computeOctree();
+} //}}}
+Node.prototype.patchVertices = function(faceVertexCData, faces, vertices) { //{{{
+	//Patch subfunction for processing xyz vertices.
+	var vertexArray;
+	var face;
+	
+	if (VESL.Helpers.isEmptyOrUndefined(faceVertexCData)) {
+		vertexArray = new Float32Array(vertices[0].length * 3);
+		for(var i = 0, v = 0; i < vertices[0].length; i++) {	
+			vertexArray[v++] = vertices[0][i];
+			vertexArray[v++] = vertices[1][i];
+			vertexArray[v++] = vertices[2][i];
+		}
+	}
+	else if (!Array.isArray(faceVertexCData[0])) { //indexed plot - faceVertexCData = [0, 2.32, 231.1, ...]
+		if (faceVertexCData.length === faces.length) { //element plot
+			vertexArray = new Float32Array(faces.length * 3 * 3);
+			for(var i = 0, v = 0, t = 0; i < faces.length; i++) {
+				face = [faces[i][0] - 1, faces[i][1] - 1, faces[i][2] - 1];
+				for(var j = 0; j < face.length; j++) {
+					if (isNaN(faceVertexCData[i])) {
+						this.nanIndices.add(i);
+						vertexArray[v++] = 0.0;
+						vertexArray[v++] = 0.0;
+						vertexArray[v++] = 0.0;
+					}
+					else {
+						vertexArray[v++] = vertices[0][face[j]];
+						vertexArray[v++] = vertices[1][face[j]];
+						vertexArray[v++] = vertices[2][face[j]];
+					}
+				}
+			}
+			this.computeIndices = false;
+		}
+		else if (faceVertexCData.length === vertices[0].length) { //node plot
+			vertexArray = new Float32Array(vertices[0].length * 3);
+			for(var i = 0, v = 0, t = 0; i < vertices[0].length; i++) {
+				if (isNaN(faceVertexCData[i])) {
+					this.nanIndices.add(i);
+					vertexArray[v++] = 0.0;
+					vertexArray[v++] = 0.0;
+					vertexArray[v++] = 0.0;
+				}
+				else {
+					vertexArray[v++] = vertices[0][i];
+					vertexArray[v++] = vertices[1][i];
+					vertexArray[v++] = vertices[2][i];
+				}
+			}
+		}
+	}
+	else if (Array.isArray(faceVertexCData[0])) { //JS specific: precomputed UV coord plot - faceVertexCData = [[0, 0.99, 0.4, ...],[0, 0.99, 0.4, ...]]
+		if (faceVertexCData[0].length === faces.length) { //element plot
+			vertexArray = new Float32Array(faces.length * 3 * 3);
+			for(var i = 0, v = 0, t = 0; i < faces.length; i++) {
+				face = [faces[i][0] - 1, faces[i][1] - 1, faces[i][2] - 1];
+				for(var j = 0; j < face.length; j++) {					
+					vertexArray[v++] = vertices[0][face[j]];
+					vertexArray[v++] = vertices[1][face[j]];
+					vertexArray[v++] = vertices[2][face[j]];
+				}
+			}
+			this.computeIndices = false;
+		}
+		else if (faceVertexCData[0].length === vertices[0].length) { //node plot
+			vertexArray = new Float32Array(vertices[0].length * 3);
+			for(var i = 0, v = 0, t = 0; i < vertices[0].length; i++) {
+				vertexArray[v++] = vertices[0][i];
+				vertexArray[v++] = vertices[1][i];
+				vertexArray[v++] = vertices[2][i];
+			}
+		}
+	}
+	this.arrays.vertices = vertexArray;
+} //}}}
+Node.prototype.patchCoords = function(faceVertexCData, faces, vertices) { //{{{
+	//Patch subfunction for processing texture coords/UVs.
+	var coordArray;
+	var cramge;
+	var caxis = this.caxis;
+	var face;
+	
+	if (VESL.Helpers.isEmptyOrUndefined(faceVertexCData)) { return; }
+	
+	//Use logarithmic scaling if it is valid
+	if (this.log !== false && this.log !== 'off') {	
+		caxis = [
+			Math.log10(caxis[0]) / Math.log10(this.log),
+			Math.log10(caxis[1]) / Math.log10(this.log)
+		];
+	}
+	
+	if (!Array.isArray(faceVertexCData[0])) { //indexed plot - faceVertexCData = [0, 2.32, 231.1, ...]
+		if (faceVertexCData.length === faces.length) { //element plot
+			coordArray = new Float32Array(faces.length * 3 * 2);
+			crange = caxis[1] - caxis[0];
+			for(var i = 0, v = 0, t = 0; i < faces.length; i++) {
+				face = [faces[i][0] - 1, faces[i][1] - 1, faces[i][2] - 1];
+				for(var j = 0; j < face.length; j++) {
+					if (isNaN(faceVertexCData[i])) {
+						this.nanIndices.add(i);
+						coordArray[t++] = 0.0;
+						coordArray[t++] = 0.0;
+					}
+					else {
+						coordArray[t++] = this.queryCoordMask(i); //Account for special texturing
+						coordArray[t++] = clamp((faceVertexCData[i] - caxis[0]) / crange, 0.0, 1.0);
+					}
+				}
+			}
+			this.computeIndices = false;
+		}
+		else if (faceVertexCData.length === vertices[0].length) { //node plot
+			coordArray = new Float32Array(vertices[0].length * 2);
+			crange = caxis[1] - caxis[0];
+			for(var i = 0, v = 0, t = 0; i < vertices[0].length; i++) {
+				if (isNaN(faceVertexCData[i])) {
+					this.nanIndices.add(i);
+					coordArray[t++] = 0.0;
+					coordArray[t++] = 0.0;
+				}
+				else {
+					coordArray[t++] = this.queryCoordMask(i); //Account for special texturing
+					coordArray[t++] = clamp((faceVertexCData[i] - caxis[0]) / crange, 0.0, 1.0);
+				}
+			}
+		}
+	}
+	else if (Array.isArray(faceVertexCData[0])) { //JS specific: precomputed UV coord plot - faceVertexCData = [[0, 0.99, 0.4, ...],[0, 0.99, 0.4, ...]]
+		if (faceVertexCData[0].length === faces.length) { //element plot
+			coordArray = new Float32Array(faces.length * 3 * 2);
+			for(var i = 0, v = 0, t = 0; i < faces.length; i++) {
+				face = [faces[i][0] - 1, faces[i][1] - 1, faces[i][2] - 1];
+				for(var j = 0; j < face.length; j++) {					
+					coordArray[t++] = faceVertexCData[0][i];
+					coordArray[t++] = faceVertexCData[1][i];
+				}
+			}
+			this.computeIndices = false;
+		}
+		else if (faceVertexCData[0].length === vertices[0].length) { //node plot
+			coordArray = new Float32Array(vertices[0].length * 2);
+			for(var i = 0, v = 0, t = 0; i < vertices[0].length; i++) {
+				coordArray[t++] = faceVertexCData[0][i];
+				coordArray[t++] = faceVertexCData[1][i];
+			}
+		}
+	}
+	this.arrays.coords = coordArray;
+} //}}}
+Node.prototype.patchIndices = function(faces, faceColor) { //{{{
+	//Patch subfunction for processing faces/elements/triangles/indices.
+	var indexArray;
+	var face;
+	
+	if (faceColor === 'none') { //Check for wireframe mesh rendering
+		if (this.drawMode === this.gl.TRIANGLES) { //NOTE: Stopgap to allow gl.LINE_STRIP nodes render normally. Only use case for faceColor === 'none' is for plot_mesh
+			this.drawMode = this.gl.LINES;
+		}
+	}
+	
+	if (this.computeIndices === true && !VESL.Helpers.isEmptyOrUndefined(faces)) {
+		if (!VESL.Helpers.isEmptyOrUndefined(faces[0])) { //Check for 2D format and process if needed
+			if (faceColor !== 'none') { //Check for triangle rendering
+				indexArray = new Uint16Array(faces.length * 3);
+				for(var i = 0, f = 0; i < faces.length; i++) {
+					face = [faces[i][0] - 1, faces[i][1] - 1, faces[i][2] - 1];
+					if (this.nanIndices.has(face[0]) || this.nanIndices.has(face[1]) || this.nanIndices.has(face[2])) continue; //Skip triangle if contains NaN value.
+					indexArray[f++] = faces[i][0] - 1;
+					indexArray[f++] = faces[i][1] - 1;
+					indexArray[f++] = faces[i][2] - 1;
+				}
+			}
+			else { //Check for wireframe mesh rendering
+				indexArray = new Uint16Array(faces.length * 6);
+				for(var i = 0, f = 0; i < faces.length; i++) {
+					indexArray[f++] = faces[i][0] - 1;
+					indexArray[f++] = faces[i][1] - 1;
+					indexArray[f++] = faces[i][1] - 1;
+					indexArray[f++] = faces[i][2] - 1;
+					indexArray[f++] = faces[i][2] - 1;
+					indexArray[f++] = faces[i][0] - 1;
+				}
+			}
+		}
+		else { //Else, assume face indices have already been processed
+			indexArray = faces;
+		}
+		this.arrays.triangles = indexArray;
+	}
+} //}}}
+Node.prototype.updateBuffer = function() { //{{{
+	//Updates the mesh buffers provided in place.
+	//NOTE: Only support coord buffers currently.
+	var args = Array.prototype.slice.call(arguments);
+	var options = new pairoptions(args.slice(0,args.length));
+	
+	var coords = options.getfieldvalue('Coords', undefined);
+	if (!VESL.Helpers.isEmptyOrUndefined(coords)) {
+		this.patchCoords(coords, this.faces, this.vertices);
+		var buffer = this.mesh.getBuffer("coords");
+		buffer.data = this.arrays.coords;
+		buffer.upload(this.gl.DYNAMIC_DRAW);
+	}
+} //}}}
+Node.prototype.computeOctree = function() { //{{{
+	//Computes and caches octrees for a node.
+	var octree = this.canvas.octrees[this.name];
+	if (VESL.Helpers.isEmptyOrUndefined(octree)) {
+		octree = new GL.Octree(this.mesh);
+	}
+	this.canvas.octrees[this.name] = octree;
+	this.octree = octree;
+} //}}}
+Node.prototype.geometryShader = function() { //{{{
+	//Emulates OpenGL geometry shaders by rendering each point as a mesh.
+	//Parameters:
+	//	Mesh - the geometry to duplicate for each point.
+	//	Vertices - the list of points to shade.
+	//	Indices - (optional) ordered list for non-ordered Vertices objects.
+	
+	var args = Array.prototype.slice.call(arguments);
+	var options = new pairoptions(args.slice(0,args.length));
+
+	var mesh = options.getfieldvalue('Mesh', undefined);
+	var vertices = options.getfieldvalue('Vertices', undefined);
+	var indices = options.getfieldvalue('Indices', undefined);
+	
+	//For handling key-value object arrays, like xcity
+	for (var i = 0; i < vertices.length; i++) {
+		if (!Array.isArray(vertices[i])) {
+			var array = [];
+			var coordinateObject = vertices[i];
+			var j = 0;
+			if (VESL.Helpers.isEmptyOrUndefined(indices)) {
+				for (var key in coordinateObject) {
+					console.log(key);
+					array[j++] = coordinateObject[key];
+				}
+			}
+			else {
+				for (var k = 0; k < indices.length; k++) {
+					array[j++] = coordinateObject[indices[k]];
+				}
+			}
+			vertices[i] = array;
+		}
+	}
+	
+	var x = vertices[0];
+	var y = vertices[1];
+	var z = vertices[2];
+	var meshVertices = mesh.getBuffer('vertices').data;
+	var meshIndicies = mesh.getIndexBuffer('triangles').data;
+	var indices = new Uint16Array(meshIndicies.length * x.length);
+	var size = meshVertices.length * x.length / 3;
+	newX = new Float32Array(size);
+	newY = new Float32Array(size);
+	newZ = new Float32Array(size);
+	
+	//For each vertex in vertices, instantiate mesh geomtry centered around that point.
+	for(var i = 0, v = 0, e = 0; i < x.length; i++){
+		var vector = [x[i], y[i], z[i]];
+		for (var j = 0; j < meshVertices.length;) {
+			newX[v] = meshVertices[j++] + x[i];
+			newY[v] = meshVertices[j++] + y[i];
+			newZ[v++] = meshVertices[j++] + z[i];
+		}
+		var offset = i * meshVertices.length / 3;
+		for (var j = 0; j < meshIndicies.length;) {
+			indices[e++] = meshIndicies[j++] + offset;
+		}
+	}
+	
+	this.patch('Faces', indices, 'Vertices', [newX, newY, newZ], 'FaceColor', 'interp');
+} //}}}
+Node.prototype.scaleVertices = function(md, x, y, z, elements, scale, maskObject) { //{{{
+	//Scales and returns vertices x, y, and z by factor scale. Uses md.geometry.scale for heightscaling in 3d meshes.
+	var region = maskObject.region;
+	var mask = maskObject.enabled ? maskObject.heightmask[region] : [];
+	var maskScale = maskObject.enabled ? maskObject.scale : 1;
+	
+	//The maskScaleField is the height scaling array. Use one if provided by maskObject.field, otherwise use md.geometry.surface
+	var maskScaleField = !VESL.Helpers.isEmptyOrUndefined(maskObject.scaleField) ? maskObject.scaleField : md.geometry.surface;
+	//If md.geometry.surface was empty and was used as maskScaleField, assign an empty array to both.
+	if (!maskScaleField) {
+		md.geometry.surface = NewArrayFill(md.mesh.x.length,0);
+		maskScaleField = md.geometry.surface;
+	}
+	
+	//Scale in 3D if using globe model, or in 2D otherwise.
+	if (md.mesh.classname() === 'mesh3dsurface') {
+		var element;
+		if (x.length === md.mesh.numberofelements) { //element plot
+			for (var i = 0; i < x.length; i++) {
+				if (maskObject.enabled) { //Scale the element if mask is not enabled, or if it is, only if it is also in the mask
+					element = elements[i];
+					for (var j = 0; j < 3; j++) {
+						xyz = vec3.fromValues(x[element[j] - 1], y[element[j] - 1], z[element[j] - 1]);
+						magnitude = 1 + maskScaleField[element[j] - 1] * mask[i] * scale * maskScale / vec3.length(xyz);
+						vec3.scale(xyz, xyz, magnitude);
+						x[element[j] - 1] = xyz[0];
+						y[element[j] - 1] = xyz[1];
+						z[element[j] - 1] = xyz[2];
+					}
+					
+				}
+			}
+		}
+		else if (x.length === md.mesh.numberofvertices) { //node plot
+			for (var i = 0; i < x.length; i++) {
+				if (!maskObject.enabled || mask[i] === 1) { //Scale the node if mask is not enabled, or if it is, only if it is also in the mask
+					xyz = vec3.fromValues(x[i], y[i], z[i]);
+					magnitude = 1 + maskScaleField[i] * scale * maskScale / vec3.length(xyz);
+					vec3.scale(xyz, xyz, magnitude);
+					x[i] = xyz[0];
+					y[i] = xyz[1];
+					z[i] = xyz[2];
+				}
+			}
+		}
+	} else {
+		z = z.slice();
+		var zMin = ArrayMin(maskScaleField);
+		for(var i = 0; i < z.length; i++) {
+			if (!maskObject.enabled || mask[i] === 1) { //Scale the element if mask is not enabled, or if it is, only if it is also in the mask
+				z[i] = (z[i] - zMin) * scale + zMin;
+			}
+		}
+	}
+	return [x, y, z];
+} //}}}
+Node.prototype.computeMasks = function() { //{{{
+	//NOTE: Since sets are not yet widely supported, use array with binary values to represent if object is in set.
+	//NOTE: Only support element wise masks for now.
+	var maskObject = this.maskObject;
+	if (!maskObject.enabled) { return; }
+	var region = maskObject.region;
+	var mask = maskObject.mask[region];
+	var maskRegion = []; //new Set()
+	var maskAdjacency = []; //new Set()
+	var adjacentElements;
+	var adjacentElements2;
+	var adjacentNodes;
+	var adjacentNodes2;
+	var adjacencyLength; //length of connectivity array - 3 for elements, many for nodes
+	var index;
+	//For each element in the mask elements array,
+	if (mask.length === md.mesh.numberofelements) { //element plot
+		if (md.mesh.elementconnectivity) {
+			var adjacencyLength = 3;
+			for (var i = 0; i < mask.length; i++) {
+				//Determine if element is in the mask
+				if (mask[i] === 1) {
+					//Then add each element to the adjacency set and mask region set
+					adjacentElements = md.mesh.elementconnectivity[i];
+					for (var j = 0; j < adjacencyLength; j++) {
+						index = adjacentElements[j] - 1;
+						maskAdjacency[index] = true;
+						
+						//Get second level of adjacent elemnents to form solid boundary (first layer look like this: /\/\/\/\/\; second layer looks like this \/\/\/\/\/; combined = |       |
+						adjacentElements2 = md.mesh.elementconnectivity[index];
+						for (var k = 0; k < adjacencyLength; k++) {
+							index = adjacentElements2[k] - 1;
+							maskAdjacency[index] = true;
+						}
+					}
+					maskRegion[i] = true;
+				}
+			}
+		}
+	}
+	else if (mask.length === md.mesh.numberofvertices) { //node plot
+		if (md.mesh.nodeconnectivity) {
+			var adjacencyLength = md.mesh.nodeconnectivity[0].length;
+			for (var i = 0; i < mask.length; i++) {
+				//Determine if node is in the mask
+				if (mask[i] === 1) {
+					//Then add each node to the adjacency set and mask region set
+					adjacentNodes = md.mesh.nodeconnectivity[i];
+					for (var j = 0; j < adjacencyLength; j++) {
+						index = adjacentNode[j];
+						maskAdjacency[index] = true;
+						
+						//Get second level of adjacent elemnents to form solid boundary (first layer look like this: /\/\/\/\/\; second layer looks like this \/\/\/\/\/; combined = |       |
+						adjacentNodes2 = md.mesh.nodeconnectivity[index];
+						for (var k = 0; k < adjacencyLength; k++) {
+							index = adjacentNodes2[k];
+							maskAdjacency[index] = true;
+						}
+					}
+					maskRegion[i] = true;
+				}
+			}
+		}
+	}
+	
+	//Then subtract the mask elements array from the mask adjacency array.
+	var maskBoundary = [];
+	for (var i in maskAdjacency) {
+		if (!(i in maskRegion)) {
+			maskBoundary[i] = true;
+		}
+	}
+	this.maskBoundary = maskBoundary;
+	
+	//For each element not in any mask region (default to mask[0] in slr-gfm), change color to mask color.
+	var maskAll = maskObject.mask[0];
+	this.maskAll = maskAll;
+} //}}}
+Node.prototype.queryCoordMask = function(index) { //{{{
+	//Calculate UV coordinate offsets for special color texture lookup.
+	if (!this.maskObject.enabled) {
+		return 1.0 
+	}
+	else {
+		//var sections = 3; //Object.keys(maskObject.colors).length + 1
+		//var boundaryCoord = 0.5 / sections;
+		//var maskCoord = 1.5 / sections;
+		//var textureCoord = 2.5 / sections;
+		if (index in this.maskBoundary) {
+			return 0.166666667; //boundaryCoord - edge color
+		}
+		else if (this.maskAll[index] === 0) {
+			return 0.5; //maskCoord - masked color
+		}
+		else {
+			return 0.833333333; //textureCoord - default colormap
+		}
+	}
+} //}}}
+Node.prototype.mergeVertices = function(x1, y1, z1, elements1, x2, y2, z2, elements2) { //{{{
+	//Merges and returns two sets of indexed xyz vertices.
+	elements2 = elements2.slice();
+	for (var i = 0, offset = x1.length; i < elements2.length; i++) {
+		elements2[i] = [elements2[i][0] + offset, elements2[i][1] + offset, elements2[i][2] + offset];
+	}
+	return {x:x1.concat(x2), y:y1.concat(y2), z:z1.concat(z2), elements:elements1.concat(elements2)};
+} //}}}
+//}}}
Index: /issm/trunk/src/m/print/printmodel.py
===================================================================
--- /issm/trunk/src/m/print/printmodel.py	(revision 22758)
+++ /issm/trunk/src/m/print/printmodel.py	(revision 22758)
@@ -0,0 +1,109 @@
+
+import numpy as np
+#from model import *
+#from socket import gethostname
+#from bamg import *
+#from setmask import *
+#from parameterize import *
+#from setflowequation import *
+#from solve import *
+from pairoptions import *
+
+def printmodel(filename,format,*args):
+'''	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(*args)
+
+#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 len(fig) == 1:
+	fig=gcf
+else:
+	figure(fig)
+	fig=gcf
+
+#In auto mode, MATLAB prints the figure the same size as it appears on the computer screen, centered on the page
+set(fig, 'PaperPositionMode', 'auto');
+
+#InvertHardcopy off imposes MATLAB to use the same colors
+set(fig, 'InvertHardcopy', getfieldvalue(options,'hardcopy'));
+
+#we could have several formats, as a cell array of strings.
+formats=format;
+if ~iscell(formats),
+	formats={formats};
+end
+
+#loop on formats:
+for i=1:length(formats),
+	format=formats{i};
+
+	#Use higher resolution to anti-alias and use zbuffer to have smooth colors
+	print(fig, '-zbuffer','-dtiff',['-r' num2str(get(0,'ScreenPixelsPerInch')*getfieldvalue(options,'resolution'))],filename);
+
+	#some trimming involved? 
+	if ~strcmpi(format,'pdf'),
+		if strcmpi(getfieldvalue(options,'trim'),'on'),
+			system(['convert -trim ' filename '.tif ' filename '.tif']);
+		end
+	end
+
+	#margin?
+	if ~strcmpi(format,'pdf'),
+		if strcmpi(getfieldvalue(options,'margin'),'on'),
+			marginsize=getfieldvalue(options,'marginsize');
+			system(['convert -border ' num2str(marginsize) 'x' num2str(marginsize) ' -bordercolor "white" ' filename '.tif ' filename '.tif']);
+		end
+	end
+
+	#frame?
+	if ~strcmpi(format,'pdf'),
+		if strcmpi(getfieldvalue(options,'frame'),'on'),
+			framesize=getfieldvalue(options,'framesize');
+			framecolor=getfieldvalue(options,'framecolor');
+			system(['convert -border ' num2str(framesize) 'x' num2str(framesize) ' -bordercolor "' framecolor '" ' filename '.tif ' filename '.tif']);
+		end
+	end
+
+	#convert image to correct format
+	if ~strcmpi(format,'tiff') & ~strcmpi(format,'tif'),
+		system(['convert ' filename '.tif ' filename '.' format]);
+		delete([ filename '.tif']);
+	end
+end
Index: /issm/trunk/src/m/qmu/dakota_in_write.m
===================================================================
--- /issm/trunk/src/m/qmu/dakota_in_write.m	(revision 22757)
+++ /issm/trunk/src/m/qmu/dakota_in_write.m	(revision 22758)
@@ -108,4 +108,5 @@
 
 responses_write(fidi,dmeth,dresp,params);
+
 
 fclose(fidi);
@@ -287,4 +288,6 @@
 
 fprintf(fidi,'responses,\n');
+%fprintf(fidi,'calibration_terms = 1 \n');
+
 
 %  functions, gradients, and hessians vary by method
@@ -296,5 +299,4 @@
     [rdesc]=fhresp(fidi,dresp,rdesc);
 end
-
 %  write accumulated response descriptors for all response classes
 
Index: /issm/trunk/src/m/qmu/dakota_out_parse.m
===================================================================
--- /issm/trunk/src/m/qmu/dakota_out_parse.m	(revision 22757)
+++ /issm/trunk/src/m/qmu/dakota_out_parse.m	(revision 22758)
@@ -79,13 +79,22 @@
 	%%  loop through the file to find the Dakota method name
 
-	[fline]=findline(fidi,'methodName = ');
+	[fline]=findline(fidi,'method');
 	if ~ischar(fline)
 		%do nothing
 	else
 		% display(['  ' deblank(fline)]);
-
 		[ntokens,tokens]=fltokens(fline);
-		method=tokens{1}{3};
-		display(sprintf('Dakota methodName=''%s''.',method));
+		%dakota version >6
+		if strcmp(tokens{1}{1}(7),',')
+			fline=fgetl(fidi);
+			[ntokens,tokens]=fltokens(fline);
+			method=tokens{1}{1};
+			display(sprintf('Dakota method =''%s''.',method));
+		elseif strcmp(tokens{1}{1}(7),'N')
+			[fline]=findline(fidi,'methodName = ');
+			[ntokens,tokens]=fltokens(fline);
+			method=tokens{1}{3};
+			display(sprintf('Dakota methodName=''%s''.',method));
+		end
 	end
 
@@ -141,4 +150,6 @@
 			[method]=itcomp_read(fidi,fline);
 		elseif strncmp(fline,'-----',5)
+		elseif strncmp(fline,'<<<<< Environment execution completed',37)
+			break;
 		else
 			display(['Unexpected line: ' deblank(fline)]);
Index: /issm/trunk/src/m/qmu/rlist_write.m
===================================================================
--- /issm/trunk/src/m/qmu/rlist_write.m	(revision 22757)
+++ /issm/trunk/src/m/qmu/rlist_write.m	(revision 22758)
@@ -35,9 +35,16 @@
 disp(sprintf('  Writing %d %s responses.',nresp,cstring));
 
-fprintf(fidi,'\tnum_%s = %d\n',cstring,nresp);
+if strcmp(cstring,'calibration_terms')==1
+	fprintf(fidi,'\t%s = %d\n',cstring,nresp);
+	
+else
+	fprintf(fidi,'\tnum_%s = %d\n',cstring,nresp);
+end
+
 if ~isempty(pstype)
-    fprintf(fidi,'\t  %s_scale_types =\n',cstring2);
-    vector_write(fidi,sprintf('\t    '),pstype ,6,76);
+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);
Index: /issm/trunk/src/m/shp/shp2exp.m
===================================================================
--- /issm/trunk/src/m/shp/shp2exp.m	(revision 22757)
+++ /issm/trunk/src/m/shp/shp2exp.m	(revision 22758)
@@ -37,5 +37,13 @@
 		expstruct(end).density=1;
 		expstruct(end).closed=1;
-		expstruct(end).name=num2str(shp(i).id);
+		if isfield(shp(i),'id'),
+			expstruct(end).name=num2str(shp(i).id);
+		elseif isfield(shp(i),'NAME'),
+			expstruct(end).name=num2str(shp(i).SUBREGION1);
+		elseif isfield(shp(i),'SUBREGION1'),
+			expstruct(end).name=num2str(shp(i).SUBREGION1);
+		else
+			expstruct(end).name='unknown';
+		end
 	elseif strcmpi(shp(i).Geometry,'Point'),
 		x=shp(i).X; y=shp(i).Y;
Index: /issm/trunk/src/m/solve/WriteData.js
===================================================================
--- /issm/trunk/src/m/solve/WriteData.js	(revision 22757)
+++ /issm/trunk/src/m/solve/WriteData.js	(revision 22758)
@@ -60,5 +60,5 @@
 		else{
 			if (!IsArray(data)) data=data*scale;
-			else ArrayScale(data,scale);
+			else data=ArrayScale(data,scale);
 		}
 	}
Index: /issm/trunk/src/m/solve/WriteData.py
===================================================================
--- /issm/trunk/src/m/solve/WriteData.py	(revision 22757)
+++ /issm/trunk/src/m/solve/WriteData.py	(revision 22758)
@@ -42,17 +42,16 @@
 	#Scale data if necesarry
 	if options.exist('scale'):
+		data=np.array(data)
 		scale = options.getfieldvalue('scale')
-		if np.size(data) > 1 :
-			if np.size(data,0)==timeserieslength:
-				data=np.array(data)
-				data[0:-1,:] = scale*data[0:-1,:]
-			else:
-				data  = scale*data
+		if np.size(data) > 1 and np.ndim(data) > 1 and np.size(data,0)==timeserieslength:
+			data[0:-1,:] = scale*data[0:-1,:]
 		else:
 			data  = scale*data
-	if np.size(data) > 1 :
-		if np.size(data,0)==timeserieslength:
-			yts = options.getfieldvalue('yts')
+	if np.size(data) > 1 and np.size(data,0)==timeserieslength:
+		yts = options.getfieldvalue('yts')
+		if np.ndim(data) > 1:
 			data[-1,:] = yts*data[-1,:]
+		else:
+			data[-1] = yts*data[-1]
 
 	#Step 1: write the enum to identify this record uniquely
Index: /issm/trunk/src/m/solve/marshall.py
===================================================================
--- /issm/trunk/src/m/solve/marshall.py	(revision 22757)
+++ /issm/trunk/src/m/solve/marshall.py	(revision 22758)
@@ -20,8 +20,4 @@
 		raise IOError("marshall error message: could not open '%s.bin' file for binary writing." % md.miscellaneous.name)
 
-	#Go through all model fields: check that it is a class and call checkconsistency
-	fields=vars(md)
-
-#	for field in fields.iterkeys():
 	for field in md.properties():
 
Index: /issm/trunk/src/m/solve/parseresultsfrombuffer.js
===================================================================
--- /issm/trunk/src/m/solve/parseresultsfrombuffer.js	(revision 22757)
+++ /issm/trunk/src/m/solve/parseresultsfrombuffer.js	(revision 22758)
@@ -99,4 +99,5 @@
 		else if (fieldname == 'BasalforcingsFloatingiceMeltingRate') for (var i=0;i<field.length;i++)field[i]= field[i]*yts;
 		else if (fieldname == 'TotalSmb') for (var i=0;i<field.length;i++)field[i]= field[i]/Math.pow(10,12)*yts; //(GigaTon/year)
+		else if (fieldname == 'TotalSmbScaled') for (var i=0;i<field.length;i++)field[i]= field[i]/Math.pow(10,12)*yts; //(GigaTon/year)
 		else if (fieldname == 'SmbMassBalance') for (var i=0;i<field.length;i++)field[i]= field[i]*yts;
 		else if (fieldname == 'SmbPrecipitation') for (var i=0;i<field.length;i++)field[i]= field[i]*yts;
Index: /issm/trunk/src/m/solve/parseresultsfromdisk.m
===================================================================
--- /issm/trunk/src/m/solve/parseresultsfromdisk.m	(revision 22757)
+++ /issm/trunk/src/m/solve/parseresultsfromdisk.m	(revision 22758)
@@ -48,5 +48,4 @@
 		index = counter;
 	end
-	results(index).(result.fieldname)=result.field;
 	if(result.step~=-9999),
 		results(index).step=result.step;
@@ -55,4 +54,5 @@
 		results(index).time=result.time;
 	end
+	results(index).(result.fieldname)=result.field;
 
 	%read next result
@@ -153,8 +153,8 @@
 	elseif type==3,
 		N=fread(fid,1,'int');
-		field=transpose(fread(fid,[N M],'double'));
+		field=fread(fid,[N M],'double')';
 	elseif type==4,
 		N=fread(fid,1,'int');
-		field=transpose(fread(fid,[N M],'int'));
+		field=fread(fid,[N M],'int')';
 	else
 		error(['cannot read data of type ' num2str(type) ]);
@@ -183,8 +183,14 @@
 	elseif strcmp(fieldname,'TotalFloatingBmb'),
 		field = field/10.^12*yts; %(GigaTon/year)
+	elseif strcmp(fieldname,'TotalFloatingBmbScaled'),
+		field = field/10.^12*yts; %(GigaTon/year)
 	elseif strcmp(fieldname,'TotalGroundedBmb'),
 		field = field/10.^12*yts; %(GigaTon/year)
+	elseif strcmp(fieldname,'TotalGroundedBmbScaled'),
+		field = field/10.^12*yts; %(GigaTon/year)
 	elseif strcmp(fieldname,'TotalSmb'),
 		field = field/10.^12*yts; %(GigaTon/year)
+	elseif strcmp(fieldname,'TotalSmbScaled'),
+		field = field/10.^12*yts; %(GigaTon/year)
 	elseif strcmp(fieldname,'SmbMassBalance'),
 		field = field*yts;
@@ -193,4 +199,8 @@
 	elseif strcmp(fieldname,'SmbRunoff'),
 		field = field*yts;
+	elseif strcmp(fieldname,'SmbEvaporation'),
+		field = field*yts;
+	elseif strcmp(fieldname,'SmbRefreeze'),
+		field = field*yts;
 	elseif strcmp(fieldname,'SmbEC'),
 		field = field*yts;
@@ -199,10 +209,24 @@
 	elseif strcmp(fieldname,'SmbMelt'),
 		field = field*yts;
-    elseif strcmp(fieldname,'SmbDz_add'),
-        field = field*yts;
-    elseif strcmp(fieldname,'SmbM_add'),
-        field = field*yts;
+	elseif strcmp(fieldname,'SmbMAdd'),
+		field = field*yts;
 	elseif strcmp(fieldname,'CalvingCalvingrate'),
 		field = field*yts;
+	elseif (strcmp(fieldname,'LoveKernelsReal') | strcmp(fieldname,'LoveKernelsImag')),
+		nlayer = md.materials.numlayers; 
+		degmax = md.love.sh_nmax; 
+		nfreq  = md.love.nfreq; 
+		temp_field = cell(degmax+1,nfreq,nlayer+1,6); 
+		for ii=1:degmax+1
+			for jj=1:nfreq
+				for kk=1:nlayer+1
+					ll = (ii-1)*(nlayer+1)*6 + ((kk-1)*6+1); 
+					for mm=1:6
+						temp_field{ii,jj,kk,mm} = field(ll+(mm-1),jj);  
+					end
+				end
+			end
+		end
+		field=temp_field; 
 	end
 
Index: /issm/trunk/src/m/solve/parseresultsfromdisk.py
===================================================================
--- /issm/trunk/src/m/solve/parseresultsfromdisk.py	(revision 22757)
+++ /issm/trunk/src/m/solve/parseresultsfromdisk.py	(revision 22758)
@@ -175,6 +175,4 @@
 		if fieldname=='BalancethicknessThickeningRate':
 			field = field*yts
-		elif fieldname=='Time':
-			field = field/yts
 		elif fieldname=='HydrologyWaterVx':
 			field = field*yts
@@ -191,14 +189,56 @@
 		elif fieldname=='BasalforcingsGroundediceMeltingRate':
 			field = field*yts
+		elif fieldname=='BasalforcingsFloatingiceMeltingRate':
+			field = field*yts
 		elif fieldname=='TotalFloatingBmb':
-			field = field/10.**12.*yts #(GigaTon/year)
+			field = field/10.**12*yts #(GigaTon/year)
+		elif fieldname=='TotalFloatingBmbScaled':
+			field = field/10.**12*yts #(GigaTon/year)
 		elif fieldname=='TotalGroundedBmb':
-			field = field/10.**12.*yts #(GigaTon/year)
+			field = field/10.**12*yts #(GigaTon/year)
+		elif fieldname=='TotalGroundedBmbScaled':
+			field = field/10.**12*yts #(GigaTon/year)
 		elif fieldname=='TotalSmb':
-			field = field/10.**12.*yts #(GigaTon/year)
+			field = field/10.**12*yts #(GigaTon/year)
+		elif fieldname=='TotalSmbScaled':
+			field = field/10.**12*yts #(GigaTon/year)
 		elif fieldname=='SmbMassBalance':
 			field = field*yts
+		elif fieldname=='SmbPrecipitation':
+			field = field*yts
+		elif fieldname=='SmbRunoff':
+			field = field*yts
+                elif fieldname=='SmbEvaporation':
+                        field = field*yts;
+                elif fieldname=='SmbRefreeze':
+                        field = field*yts;
+		elif fieldname=='SmbEC':
+			field = field*yts
+		elif fieldname=='SmbAccumulation':
+			field = field*yts
+		elif fieldname=='SmbMelt':
+			field = field*yts
+    		elif fieldname=='SmbMAdd':
+        		field = field*yts
 		elif fieldname=='CalvingCalvingrate':
 			field = field*yts
+		elif fieldname=='LoveKernelsReal' or fieldname=='LoveKernelsImag':
+			nlayer = md.materials.numlayers
+			degmax = md.love.sh_nmax
+			nfreq  = md.love.nfreq
+			#for numpy 1.8+ only
+			#temp_field = np.full((degmax+1,nfreq,nlayer+1,6),0.0)
+			temp_field = np.empty((degmax+1,nfreq,nlayer+1,6))
+			temp_field.fill(0.0)
+			for ii in range(degmax+1):
+				for jj in range(nfreq):
+					for kk in range(nlayer+1):
+						ll = ii*(nlayer+1)*6 + (kk*6+1)
+						for mm in range(6):
+							temp_field[ii,jj,kk,mm] = field[ll+mm-1,jj]
+			field=temp_field
+
+		if time !=-9999:
+			time = time/yts
 
 		saveres=OrderedDict()
Index: /issm/trunk/src/m/solve/solve.js
===================================================================
--- /issm/trunk/src/m/solve/solve.js	(revision 22757)
+++ /issm/trunk/src/m/solve/solve.js	(revision 22758)
@@ -165,4 +165,5 @@
 
 		/*We are running somewhere else on a computational server. Send the buffer to that server and retrieve output: */
+		console.log('running issm remotely');
 		cluster.UploadAndRun(md,callbackfunction,callbackerrorfunction,callbackid,fid,toolkitsstring,solutionstring,md.miscellaneous.name,md.priv.runtimename);
 
Index: /issm/trunk/src/m/solve/solve.m
===================================================================
--- /issm/trunk/src/m/solve/solve.m	(revision 22757)
+++ /issm/trunk/src/m/solve/solve.m	(revision 22758)
@@ -21,4 +21,5 @@
 %		 - 'Esa'                or 'esa'
 %		 - 'Sealevelrise'       or 'slr'
+%		 - 'Love'               or 'lv'
 %
 %  extra options:
@@ -50,4 +51,6 @@
 elseif strcmpi(solutionstring,'mc') || strcmpi(solutionstring,'Balancethickness')
 	solutionstring = 'BalancethicknessSolution';
+elseif strcmpi(solutionstring,'Balancethickness2')
+	solutionstring = 'Balancethickness2Solution';
 elseif strcmpi(solutionstring,'mcsoft') || strcmpi(solutionstring,'BalancethicknessSoft')
 	solutionstring = 'BalancethicknessSoftSolution';
@@ -64,4 +67,6 @@
 elseif strcmpi(solutionstring,'gia') || strcmpi(solutionstring,'Gia')
 	solutionstring = 'GiaSolution';
+elseif strcmpi(solutionstring,'lv') || strcmpi(solutionstring,'Love')
+	solutionstring = 'LoveSolution';
 elseif strcmpi(solutionstring,'esa') || strcmpi(solutionstring,'Esa')
 	solutionstring = 'EsaSolution';
@@ -121,9 +126,9 @@
 %Upload all required files
 modelname = md.miscellaneous.name;
-filelist  = {[modelname '.bin '] [modelname '.toolkits ']};
+filelist  = {[modelname '.bin'] [modelname '.toolkits']};
 if ispc,
-	filelist{end+1}=[modelname '.bat '];
+	filelist{end+1}=[modelname '.bat'];
 else
-	filelist{end+1}=[modelname '.queue '];
+	filelist{end+1}=[modelname '.queue'];
 end
 
Index: /issm/trunk/src/m/solve/solve.py
===================================================================
--- /issm/trunk/src/m/solve/solve.py	(revision 22757)
+++ /issm/trunk/src/m/solve/solve.py	(revision 22758)
@@ -29,5 +29,7 @@
 		 - 'DamageEvolution'  or 'da'
 		 - 'Gia'              or 'gia'
+		 - 'Esa'	      or 'esa'
 		 - 'Sealevelrise'     or 'slr'
+		 - 'Love'             or 'lv'
 
 	   extra options:
@@ -66,4 +68,8 @@
 	elif solutionstring.lower() == 'gia' or solutionstring.lower() == 'gia':
 		solutionstring = 'GiaSolution';
+        elif solutionstring.lower() == 'lv' or solutionstring.lower() == 'love':
+                solutionstring = 'LoveSolution';
+	elif solutionstring.lower() == 'esa':
+		solutionstring = 'EsaSolution';
 	elif solutionstring.lower() == 'slr' or solutionstring.lower() == 'sealevelrise':
 		solutionstring = 'SealevelriseSolution';
Index: /issm/trunk/src/m/solve/solveiceocean.m
===================================================================
--- /issm/trunk/src/m/solve/solveiceocean.m	(revision 22758)
+++ /issm/trunk/src/m/solve/solveiceocean.m	(revision 22758)
@@ -0,0 +1,143 @@
+function md=solveiceocean(md,solutionstring,varargin)
+%SOLVE - apply ice/ocean solution sequence for this model
+%
+%   Usage:
+%      md=solveiceocean(md,solutionstring,varargin)
+%      where varargin is a lit of paired arguments of string OR enums
+%
+%   solution types available comprise:
+%		 - 'Stressbalance'      or 'sb'
+%		 - 'Masstransport'      or 'mt'
+%		 - 'Transient'          or 'tr'
+%
+%  extra options:
+%      - loadonly    : does not solve. only load results
+%      - runtimename : true or false (default is true), makes name unique
+%      - checkconsistency : 'yes' or 'no' (default is 'yes'), ensures checks on consistency of model
+%      - restart: 'directory name (relative to the execution directory) where the restart file is located.
+%      - outbinread  : if 0, download the outbin but do not process is (md.results is not updated)
+%
+%   Examples:
+%      md=solve(md,'Transient');
+%      md=solve(md,'tr');
+
+if ~ischar(solutionstring)
+	error('ISSM''s solve function only accepts strings for solution sequences. Type help solve to get a list of supported solutions');
+end
+
+%recover and process solve options
+if strcmpi(solutionstring,'sb') || strcmpi(solutionstring,'Stressbalance')
+	solutionstring = 'StressbalanceSolution';
+elseif strcmpi(solutionstring,'mt') || strcmpi(solutionstring,'Masstransport')
+	solutionstring = 'MasstransportSolution';
+elseif strcmpi(solutionstring,'tr') || strcmpi(solutionstring,'Transient')
+	solutionstring = 'TransientSolution';
+else
+	error(['solutionstring ' solutionstring ' not supported!']);
+end
+options=pairoptions(varargin{:},'solutionstring',solutionstring);
+
+%recover some fields
+md.private.solution=solutionstring;
+cluster=md.cluster;
+if strcmpi(getfieldvalue(options,'batch','no'),'yes') batch=1; else batch=0; end
+if ~isa(cluster,'localpfe') & ~isa(cluster,'generic'),
+	error('cannot run ice/ocean simulation on any other cluster than localpfe');
+end
+
+%check model consistency
+if strcmpi(getfieldvalue(options,'checkconsistency','yes'),'yes'),
+	if md.verbose.solution,
+		disp('checking model consistency');
+	end
+	ismodelselfconsistent(md),
+end
+
+%If we are restarting, actually use the provided runtime name:
+restart=getfieldvalue(options,'restart','');
+%First, build a runtime name that is unique
+if restart==1 
+	%Leave the runtimename as is
+else
+	if ~isempty(restart),
+		md.private.runtimename=restart;
+	elseif getfieldvalue(options,'runtimename',true),
+		c=clock;
+		md.private.runtimename=sprintf('%s-%02i-%02i-%04i-%02i-%02i-%02i-%i',md.miscellaneous.name,c(2),c(3),c(1),c(4),c(5),floor(c(6)),feature('GetPid'));
+	else
+		md.private.runtimename=md.miscellaneous.name;
+	end
+end
+
+%if running qmu analysis, some preprocessing of dakota files using models
+%fields needs to be carried out. 
+if md.qmu.isdakota,
+	md=preqmu(md,options);
+end
+
+%Do we load results only?
+if getfieldvalue(options,'loadonly',false),
+	md=loadresultsfromcluster(md);
+	return;
+end
+
+%Write all input files
+marshall(md);                                          % bin file
+ToolkitsFile(md.toolkits,[md.miscellaneous.name '.toolkits']); % toolkits file
+BuildQueueScriptIceOcean(cluster,md.private.runtimename,md.miscellaneous.name,md.private.solution,md.settings.io_gather,md.debug.valgrind,md.debug.gprof,md.qmu.isdakota); % queue file
+
+%Upload all required files
+modelname = md.miscellaneous.name;
+filelist  = {[modelname '.bin'] [modelname '.toolkits']};
+if ispc,
+	filelist{end+1}=[modelname '.bat'];
+else
+	filelist{end+1}=[modelname '.queue'];
+end
+
+if md.qmu.isdakota,
+	filelist{end+1} = [modelname '.qmu.in'];
+end
+
+if isempty(restart),
+	UploadQueueJob(cluster,md.miscellaneous.name,md.private.runtimename,filelist);
+end
+
+%launch queue job: 
+LaunchQueueJobIceOcean(cluster,md.miscellaneous.name,md.private.runtimename,filelist,restart,batch);
+
+%return if batch: 
+if batch,
+	if md.verbose.solution,
+		disp('batch mode requested: not launching job interactively');
+		disp('launch solution sequence on remote cluster by hand');
+	end
+	return;
+end
+%wait on lock
+if isnan(md.settings.waitonlock),
+	%load when user enters 'y'
+	disp('solution launched on remote cluster. log in to detect job completion.');
+	choice=input('Is the job successfully completed? (y/n)','s');
+	if ~strcmp(choice,'y'), 
+		disp('Results not loaded... exiting'); 
+	else
+		md=loadresultsfromcluster(md);
+	end
+elseif md.settings.waitonlock>0,
+	%we wait for the done file
+	done=waitonlock(md);
+	if md.verbose.solution,
+		disp('loading results from cluster');
+	end
+	md=loadresultsfromcluster(md,'');
+elseif md.settings.waitonlock==0,
+	 disp('Model results must be loaded manually with md=loadresultsfromcluster(md);');
+end
+
+%post processes qmu results if necessary
+if md.qmu.isdakota,
+	if ~strncmpi(getfieldvalue(options,'keep','y'),'y',1)
+		system(['rm -rf qmu' num2str(feature('GetPid'))]);
+	end
+end
Index: /issm/trunk/src/m/solve/waitonlock.m
===================================================================
--- /issm/trunk/src/m/solve/waitonlock.m	(revision 22757)
+++ /issm/trunk/src/m/solve/waitonlock.m	(revision 22758)
@@ -20,4 +20,7 @@
 	lockfilename  = [executionpath '/Interactive' num2str(cluster.interactive) '/' md.miscellaneous.name '.lock'];
 	logfilename   = [executionpath '/Interactive' num2str(cluster.interactive) '/' md.miscellaneous.name '.outlog'];
+elseif isa(cluster,'localpfe'),
+	lockfilename  = [executionpath '/' md.miscellaneous.name '.lock'];
+	logfilename   = [executionpath '/' md.miscellaneous.name '.outlog'];
 else
 	lockfilename  = [executionpath '/' md.private.runtimename '/' md.miscellaneous.name '.lock'];
Index: /issm/trunk/src/m/solvers/asmoptions.m
===================================================================
--- /issm/trunk/src/m/solvers/asmoptions.m	(revision 22757)
+++ /issm/trunk/src/m/solvers/asmoptions.m	(revision 22758)
@@ -11,5 +11,5 @@
 %default asm options
 asm.toolkit='petsc';
-asm.mat_type=getfieldvalue(options,'mat_type','aij');
+asm.mat_type=getfieldvalue(options,'mat_type','mpiaij');
 asm.ksp_type=getfieldvalue(options,'ksp_type','gmres');
 asm.pc_type=getfieldvalue(options,'pc_type','asm');
Index: /issm/trunk/src/m/solvers/asmoptions.py
===================================================================
--- /issm/trunk/src/m/solvers/asmoptions.py	(revision 22757)
+++ /issm/trunk/src/m/solvers/asmoptions.py	(revision 22758)
@@ -10,5 +10,5 @@
 	arguments=pairoptions.pairoptions(*args) 
 	
-	options=[['toolkit','petsc'],['mat_type','aij'],['ksp_type','gmres'],['pc_type','asm'],['sub_pc_type','lu'],['pc_asm_overlap',3],['ksp_max_it',100],['ksp_rtol',1e-30]];
+	options=[['toolkit','petsc'],['mat_type','mpiaij'],['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.
Index: /issm/trunk/src/m/solvers/cgnoneoptions.m
===================================================================
--- /issm/trunk/src/m/solvers/cgnoneoptions.m	(revision 22757)
+++ /issm/trunk/src/m/solvers/cgnoneoptions.m	(revision 22758)
@@ -1,3 +1,3 @@
-function solverOptions=cgmgoptions(varargin)
+function solverOptions=cgnoneoptions(varargin)
 
 %retrieve options provided in varargin
Index: /issm/trunk/src/m/solvers/issmmumpssolver.js
===================================================================
--- /issm/trunk/src/m/solvers/issmmumpssolver.js	(revision 22758)
+++ /issm/trunk/src/m/solvers/issmmumpssolver.js	(revision 22758)
@@ -0,0 +1,21 @@
+function issmmumpssolver(){
+//ISSMMUMPSSOLVER - 
+//
+//   Usage:
+//      options=issmmumpssolver(varargin);
+
+	//Retrieve options provided in varargin. First convert arguments to array:
+	var args = Array.prototype.slice.call(arguments);
+
+	//Then process options
+	var  options = new pairoptions(args.slice(1,args.length));
+
+	//default issmoptions options
+	var issmoptions={};
+	issmoptions['toolkit']='issm';
+	issmoptions['mat_type']=options.getfieldvalue('mat_type','mpisparse');
+	issmoptions['vec_type']=options.getfieldvalue('vec_type','mpi');
+	issmoptions['solver_type']=options.getfieldvalue('solver_type','mumps');
+
+	return issmoptions;
+}
Index: /issm/trunk/src/m/solvers/jacobiasmoptions.m
===================================================================
--- /issm/trunk/src/m/solvers/jacobiasmoptions.m	(revision 22757)
+++ /issm/trunk/src/m/solvers/jacobiasmoptions.m	(revision 22758)
@@ -11,5 +11,5 @@
 %default jacobiasm options
 jacobiasm.toolkit='petsc';
-jacobiasm.mat_type=getfieldvalue(options,'mat_type','aij');
+jacobiasm.mat_type=getfieldvalue(options,'mat_type','mpiaij');
 jacobiasm.ksp_type=getfieldvalue(options,'ksp_type','gmres');
 jacobiasm.pc_type=getfieldvalue(options,'pc_type','asm');
Index: /issm/trunk/src/m/solvers/jacobiasmoptions.py
===================================================================
--- /issm/trunk/src/m/solvers/jacobiasmoptions.py	(revision 22757)
+++ /issm/trunk/src/m/solvers/jacobiasmoptions.py	(revision 22758)
@@ -10,5 +10,5 @@
 	arguments=pairoptions.pairoptions(*args) 
 	
-	options=[['toolkit','petsc'],['mat_type','aij'],['ksp_type','gmres'],['pc_type','asm'],['sub_pc_type','jacobi'],['pc_asm_overlap',3],['ksp_max_it',100],['ksp_rtol',1e-15]];
+	options=[['toolkit','petsc'],['mat_type','mpiaij'],['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.
Index: /issm/trunk/src/m/solvers/jacobicgoptions.m
===================================================================
--- /issm/trunk/src/m/solvers/jacobicgoptions.m	(revision 22757)
+++ /issm/trunk/src/m/solvers/jacobicgoptions.m	(revision 22758)
@@ -11,5 +11,5 @@
 %default jacobiasm options
 jacobicg.toolkit='petsc';
-jacobicg.mat_type=getfieldvalue(options,'mat_type','aij');
+jacobicg.mat_type=getfieldvalue(options,'mat_type','mpiaij');
 jacobicg.ksp_type=getfieldvalue(options,'ksp_type','cg');
 jacobicg.ksp_max_it=getfieldvalue(options,'ksp_max_it',100);
Index: /issm/trunk/src/m/solvers/jacobicgoptions.py
===================================================================
--- /issm/trunk/src/m/solvers/jacobicgoptions.py	(revision 22757)
+++ /issm/trunk/src/m/solvers/jacobicgoptions.py	(revision 22758)
@@ -10,5 +10,5 @@
 	arguments=pairoptions.pairoptions(*args) 
 	
-	options=[['toolkit','petsc'],['mat_type','aij'],['ksp_type','cg'],['ksp_max_it',100],['ksp_rtol',1e-15]];
+	options=[['toolkit','petsc'],['mat_type','mpiaij'],['ksp_type','cg'],['ksp_max_it',100],['ksp_rtol',1e-15]];
 
 	#now, go through our arguments, and write over default options.
Index: /issm/trunk/src/m/solvers/mumpsoptions.m
===================================================================
--- /issm/trunk/src/m/solvers/mumpsoptions.m	(revision 22757)
+++ /issm/trunk/src/m/solvers/mumpsoptions.m	(revision 22758)
@@ -30,5 +30,5 @@
 
 	%These 2 lines make raijin break (ptwgts error during solver with PETSc 3.3)
-	%mumps.mat_mumps_icntl_28=2; %1=serial, 2=parallel
-	%mumps.mat_mumps_icntl_29=2; %parallel ordering 1 = ptscotch, 2 = parmetis
+	mumps.mat_mumps_icntl_28=2; %1=serial, 2=parallel
+	mumps.mat_mumps_icntl_29=2; %parallel ordering 1 = ptscotch, 2 = parmetis
 end
Index: /issm/trunk/src/m/solvers/soroptions.m
===================================================================
--- /issm/trunk/src/m/solvers/soroptions.m	(revision 22757)
+++ /issm/trunk/src/m/solvers/soroptions.m	(revision 22758)
@@ -11,5 +11,5 @@
 %default sor options
 sor.toolkit='petsc';
-sor.mat_type=getfieldvalue(options,'mat_type','aij');
+sor.mat_type=getfieldvalue(options,'mat_type','mpiaij');
 sor.ksp_type=getfieldvalue(options,'ksp_type','cg');
 sor.pc_type=getfieldvalue(options,'pc_type','sor');
Index: /issm/trunk/src/m/solvers/soroptions.py
===================================================================
--- /issm/trunk/src/m/solvers/soroptions.py	(revision 22757)
+++ /issm/trunk/src/m/solvers/soroptions.py	(revision 22758)
@@ -10,5 +10,5 @@
 	arguments=pairoptions.pairoptions(*args) 
 	
-	options=[['toolkit','petsc'],['mat_type','aij'],['ksp_type','cg'],['pc_type','sor'],['pc_sor_omega',1.1],['pc_sor_its',2]];
+	options=[['toolkit','petsc'],['mat_type','mpiaij'],['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.
Index: /issm/trunk/src/py3/classes/stressbalance.py
===================================================================
--- /issm/trunk/src/py3/classes/stressbalance.py	(revision 22757)
+++ /issm/trunk/src/py3/classes/stressbalance.py	(revision 22758)
@@ -18,23 +18,22 @@
 
 	def __init__(self): # {{{
-		self.spcvx                    = float('NaN')
-		self.spcvy                    = float('NaN')
-		self.spcvz                    = float('NaN')
-		self.restol                   = 0
-		self.reltol                   = 0
-		self.abstol                   = 0
-		self.isnewton                 = 0
-		self.FSreconditioning     = 0
-		self.viscosity_overshoot      = 0
-		self.icefront                 = float('NaN')
-		self.maxiter                  = 0
-		self.shelf_dampening          = 0
-		self.vertex_pairing           = float('NaN')
-		self.penalty_factor           = float('NaN')
-		self.rift_penalty_lock        = float('NaN')
-		self.rift_penalty_threshold   = 0
-		self.referential              = float('NaN')
-		self.loadingforce             = float('NaN')
-		self.requested_outputs        = []
+		self.spcvx                  = float('NaN')
+		self.spcvy                  = float('NaN')
+		self.spcvz                  = float('NaN')
+		self.restol                 = 0
+		self.reltol                 = 0
+		self.abstol                 = 0
+		self.isnewton               = 0
+		self.FSreconditioning       = 0
+		self.icefront               = float('NaN')
+		self.maxiter                = 0
+		self.shelf_dampening        = 0
+		self.vertex_pairing         = float('NaN')
+		self.penalty_factor         = float('NaN')
+		self.rift_penalty_lock      = float('NaN')
+		self.rift_penalty_threshold = 0
+		self.referential            = float('NaN')
+		self.loadingforce           = float('NaN')
+		self.requested_outputs      = []
 
 		#set defaults
@@ -51,5 +50,4 @@
 		string="%s\n%s"%(string,fielddisplay(self,'isnewton',"0: Picard's fixed point, 1: Newton's method, 2: hybrid"))
 		string="%s\n%s"%(string,fielddisplay(self,'maxiter','maximum number of nonlinear iterations'))
-		string="%s\n%s"%(string,fielddisplay(self,'viscosity_overshoot','over-shooting constant new=new+C*(new-old)'))
 
 		string="%s\n%s"%(string,'\n      boundary conditions:')
@@ -100,9 +98,4 @@
 		self.penalty_factor=3
 
-		#coefficient to update the viscosity between each iteration of
-		#a stressbalance according to the following formula
-		#viscosity(n)=viscosity(n)+viscosity_overshoot(viscosity(n)-viscosity(n-1))
-		self.viscosity_overshoot=0
-
 		#Stop the iterations of rift if below a threshold
 		self.rift_penalty_threshold=0
@@ -142,5 +135,4 @@
 		md = checkfield(md,'fieldname','stressbalance.isnewton','numel',[1],'values',[0,1,2])
 		md = checkfield(md,'fieldname','stressbalance.FSreconditioning','size',[1],'NaN',1,'Inf',1)
-		md = checkfield(md,'fieldname','stressbalance.viscosity_overshoot','size',[1],'NaN',1,'Inf',1)
 		md = checkfield(md,'fieldname','stressbalance.maxiter','size',[1],'>=',1)
 		md = checkfield(md,'fieldname','stressbalance.referential','size',[md.mesh.numberofvertices,6])
@@ -186,5 +178,4 @@
 		WriteData(fid,'object',self,'class','stressbalance','fieldname','isnewton','format','Integer')
 		WriteData(fid,'object',self,'class','stressbalance','fieldname','FSreconditioning','format','Double')
-		WriteData(fid,'object',self,'class','stressbalance','fieldname','viscosity_overshoot','format','Double')
 		WriteData(fid,'object',self,'class','stressbalance','fieldname','maxiter','format','Integer')
 		WriteData(fid,'object',self,'class','stressbalance','fieldname','shelf_dampening','format','Integer')
Index: /issm/trunk/src/py3/modifier.sh
===================================================================
--- /issm/trunk/src/py3/modifier.sh	(revision 22757)
+++ /issm/trunk/src/py3/modifier.sh	(revision 22758)
@@ -260,5 +260,4 @@
 sed -i 's/(md,'fieldname','stressbalance.isnewton','numel',[1],'values',[0,1,2])/(md,fieldname='stressbalance.isnewton',numel=[1],values=[0,1,2])/g' ./classes/stressbalance.py:		
 sed -i 's/(md,'fieldname','stressbalance.FSreconditioning',size=[1],'NaN',1)/(md,fieldname='stressbalance.FSreconditioning','size',[1],NaN=1)/g' ./classes/stressbalance.py:		
-sed -i 's/(md,'fieldname','stressbalance.viscosity_overshoot',size=[1],'NaN',1)/(md,fieldname='stressbalance.viscosity_overshoot','size',[1],NaN=1)/g' ./classes/stressbalance.py:		
 sed -i 's/(md,'fieldname','stressbalance.maxiter',size=[1],'>=',1)/(md,fieldname='stressbalance.maxiter','size',[1],ge=1)/g' ./classes/stressbalance.py:		
 sed -i 's/(md,'fieldname','stressbalance.referential',size=[md.mesh.numberofvertices,6])/(md,fieldname='stressbalance.referential','size',[md.mesh.numberofvertices,6])/g' ./classes/stressbalance.py:		
Index: /issm/trunk/src/wrappers/Chaco/Chaco.cpp
===================================================================
--- /issm/trunk/src/wrappers/Chaco/Chaco.cpp	(revision 22757)
+++ /issm/trunk/src/wrappers/Chaco/Chaco.cpp	(revision 22758)
@@ -23,25 +23,15 @@
 	/*Inputs: */
 	int     nvtxs;               /* number of vertices in graph           */
-	int    *start;               /* start of edge list for each vertex    */
-	int    *adjacency;           /* edge list data                        */
+	int    *start = NULL;        /* start of edge list for each vertex    */
+	int    *adjacency = NULL;    /* edge list data                        */
 	int    *vwgts       = NULL;  /* weights for all vertices              */
-	int     nedges;
 	float  *ewgts       = NULL;  /* weights for all edges                 */
 	float  *x           = NULL;
 	float  *y           = NULL;
 	float  *z           = NULL;  /* coordinates for inertial method       */
-	double  options[10] = {1,1,0,0,1,1,50,0,.001,7654321}; /* architecture and partitioning options */
+	double  options[10] = {1,1,0,0,1,1,50,0,0.001,7654321}; /* architecture and partitioning options */
 	double *in_options  = NULL;
-	int    *nparts      = NULL;   /* number of parts options               */
 	int     npart;
 	double *goal        = NULL;   /* desired set sizes                     */
-
-	/*intermediary pointers: */
-	mwIndex *mwstart, *mwadjacency;
-	double  *doublepointer;
-
-	/*output: */
-   short  *assignment       = NULL; /* set number of each vtx (length nvtxs+1)                */
-   double *doubleassignment = NULL; /*holds assignment, in double format, to return to matlab */
 
 	#ifndef _HAVE_CHACO_ //only works if dakota library has been compiled in.
@@ -53,25 +43,8 @@
 
 	/*checks on arguments on the matlab side: */
-	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&ChacoUsage);
+	CHECKARGUMENTS(NLHS,NRHS,&ChacoUsage);
 
-	/*Fetch adjacency matrix: */
-	nvtxs = mxGetN(A_IN);
-	mwstart = mxGetJc(A_IN);
-	start=xNew<int>((nvtxs+1));
-	for (i=0; i<nvtxs+1;i++)start[i]=(int)mwstart[i];
-
-	mwadjacency = mxGetIr(A_IN);
-	adjacency = xNew<int>(mxGetNzmax(A_IN));
-	for (i=0; i<mxGetNzmax(A_IN); i++) adjacency[i]= (int)mwadjacency[i];
-
-	nedges = start[nvtxs];
-	if(!mxIsEmpty(EWGTS_IN)){
-		ewgts = xNewZeroInit<float>(nedges);
-		doublepointer=mxGetPr(A_IN);
-		for (i = 0; i < nedges; i++)ewgts[i] = (float)doublepointer[i];
-	}
-	else ewgts=NULL;
-
-	/*Fetch rest of data: */
+	/*Fetch Data*/
+	FetchChacoData(&nvtxs,&adjacency,&start,&ewgts,A_IN,EWGTS_IN);
 	FetchData(&vwgts,&nterms,VWGTS_IN); 
 	FetchData(&x,&nterms,X_IN); 
@@ -81,45 +54,20 @@
 	for (i=0;i<(nterms<10?nterms:10);i++) options[i]=in_options[i]; //copy in_options into default options
 	FetchData(&npart,NPARTS_IN); 
-	nparts=xNew<int>(1); nparts[0]=npart; //weird Chacox interface ain't it?
+	//int * nparts=xNew<int>(1); nparts[0]=npart; //weird Chacox interface ain't it?
 	FetchData(&goal,&nterms,GOAL_IN); 
 
-	/*Some debugging print: {{{*/
-	#ifdef _DEBUG_
-	_printf_("nvtxs: " << nvtxs << "\n");
-	_printf_("options: [");
-	for(i=0;i<10;i++)_printf_(options[i] << "|");
-	_printf_("]\n");
-	_printf_("start: \n");
-	for (i=0; i<nvtxs+1;i++)_printf_(start[i] << " ");
-	_printf_("\n");
-	_printf_("adjacency: \n");
-	for (i=0; i<mxGetNzmax(A_IN);i++)_printf_("" <<adjacency[i]<< " ");i++)
-	_printf_("\n");
-	_printf_("nedges: " << nedges << " " << ewgts << "\n");
-	if(ewgts) for (i = 0; i < nedges; i++)_printf_(ewgts[i] << " ");
-	_printf_("\n");
-	_printf_("vwgts:\n");
-	for (i = 0; i < nvtxs; i++)_printf_(vwgts[i] << " ");
-	_printf_("\n");
-	_printf_("nparts: " << nparts[0] << "\n");
-	_printf_("goal: " << goal << "\n");
-	#endif
-	/*}}}*/
-
 	/*Allocate output: */
-	assignment = xNewZeroInit<short>(nvtxs);
+	short* assignment = xNewZeroInit<short>(nvtxs);
 
     /*Call core: */
-	Chacox(nvtxs, start, adjacency, vwgts, ewgts, x, y, z, assignment, options, nparts, goal);
+	Chacox(nvtxs, start, adjacency, vwgts, ewgts, x, y, z, assignment, options,&npart, goal);
 
     /*Output data: */
-	doubleassignment=xNew<double>(nvtxs);
-	for(i=0;i<nvtxs;i++) doubleassignment[i]=(double)assignment[i];
-	WriteData(ASSGN_OUT,doubleassignment,nvtxs);
+	WriteData(ASSGN_OUT,assignment,nvtxs);
 
 	/*Free ressources:*/
 	xDelete<short>(assignment); 
 	xDelete<double>(goal);
-	xDelete<int>(nparts);
+	//xDelete<int>(nparts);
 	xDelete<float>(z);
 	xDelete<float>(y);
@@ -129,5 +77,4 @@
 	xDelete<int>(adjacency);
 	xDelete<int>(start);
-	xDelete<double>(doubleassignment);
 
 	/*end module: */
Index: /issm/trunk/src/wrappers/InterpFromGridToMesh/InterpFromGridToMesh.h
===================================================================
--- /issm/trunk/src/wrappers/InterpFromGridToMesh/InterpFromGridToMesh.h	(revision 22757)
+++ /issm/trunk/src/wrappers/InterpFromGridToMesh/InterpFromGridToMesh.h	(revision 22758)
@@ -51,4 +51,19 @@
 #endif
 
+#ifdef _HAVE_JAVASCRIPT_MODULES_
+/* serial input macros: */
+#define XHANDLE       xIn,dataNumColsIn,1
+#define YHANDLE       yIn,dataNumRowsIn,1
+#define DATAHANDLE    dataIn,dataNumRowsIn,dataNumColsIn
+#define XMESHHANDLE   xMeshIn,meshNumRowsIn,1
+#define YMESHHANDLE   yMeshIn,meshNumRowsIn,1
+#define DEFAULTHANDLE defaultValue
+#define INTERPENUM    interpType
+/* serial output macros: */
+#define DATAMESH pdataMesh
+#define WRAPPER(modulename) extern "C" { int InterpFromGridToMeshModule(double** pdataMesh, double* xIn, double* yIn, double* dataIn, double* xMeshIn, double* yMeshIn, double defaultValue, int nodsIn, int dataNumRowsIn, int dataNumColsIn, int meshNumRowsIn, char* interpType)
+#define nrhs 6
+#endif
+
 /* serial arg counts: */
 #undef NLHS
Index: /issm/trunk/src/wrappers/InterpFromGridToMesh/InterpFromGridToMesh.js
===================================================================
--- /issm/trunk/src/wrappers/InterpFromGridToMesh/InterpFromGridToMesh.js	(revision 22758)
+++ /issm/trunk/src/wrappers/InterpFromGridToMesh/InterpFromGridToMesh.js	(revision 22758)
@@ -0,0 +1,187 @@
+/**
+ * INTERPFROMGRIDTOMESH - interpolation from a grid onto a list of points
+ *
+ * This function interpolates a field defined on a grid to a list of points based on a bilinear interpolation.
+ *
+ * Usage:
+ *	var data_mesh=InterpFromGridToMesh(xIn,yIn,dataIn,xMeshIn,yMeshIn,defaultValue,interpType);\
+ * 
+ *	xIn,yIn						: coordinates of matrix data. (x and y must be in increasing order)
+ *	dataIn						: matrix holding the data to be interpolated onto the mesh
+ *	xMeshIn,yMeshIn				: coordinates of the points onto which we interpolate
+ *	defaultValue 				: default value if no data is found (holes)
+ *	interpType (optional) 		: interpolation type
+ * 	dataMesh					: array of mesh interpolated data
+ */
+function InterpFromGridToMesh(xIn,yIn,dataIn,dataNumColsIn,dataNumRowsIn,xMeshIn,yMeshIn,defaultValue) {
+	/*
+		Variables
+	*/
+	//{{{
+	var data 			= {};
+	var dataMesh 		= {};
+	var dataMeshPtr 	= {};
+	var ddata			= {};
+	var ddataHeap 		= {};
+	var ddataPtr 		= {};
+	var dx				= {};
+	var dxHeap 			= {};
+	var dxMesh 			= {};
+	var dxMeshHeap 		= {};
+	var dxMeshPtr 		= {};
+	var dxPtr 			= {};
+	var dy				= {};
+	var dyHeap 			= {};
+	var dyMesh			= {};
+	var dyMeshHeap 		= {};
+	var dyMeshPtr 		= {};
+	var dyPtr 			= {};
+	var interpType 		= '';
+	var meshNumRows		= 0;
+	var ndata			= {};
+	var nods 			= 0;
+	var nx 				= {};
+	var nxMesh 			= {};
+	var ny 				= {};
+	var nyMesh 			= {};
+	var pdataMesh 		= {};
+	var x 				= {};
+	var xMesh 			= {};
+	var y				= {};
+	var yMesh 			= {};
+	//}}}
+	
+
+	/*
+		Dynamic allocations
+	*/
+	//{{{
+	
+	/*
+		Input
+	*/
+	//{{{
+	dx 			= new Float64Array(xIn);
+	nx 			= dx.length * dx.BYTES_PER_ELEMENT;
+	dxPtr 		= Module._malloc(nx);
+	dxHeap 		= new Uint8Array(Module.HEAPU8.buffer, dxPtr, nx);
+	dxHeap.set(new Uint8Array(dx.buffer));
+	x 			= dxHeap.byteOffset;
+	
+	dy 			= new Float64Array(yIn);
+	ny 			= dy.length * dy.BYTES_PER_ELEMENT;
+	dyPtr 		= Module._malloc(ny);
+	dyHeap 		= new Uint8Array(Module.HEAPU8.buffer, dyPtr, ny);
+	dyHeap.set(new Uint8Array(dy.buffer));
+	y 			= dyHeap.byteOffset;
+	
+	ddata 		= new Float64Array(dataIn);
+	ndata 		= ddata.length * ddata.BYTES_PER_ELEMENT;
+	ddataPtr 	= Module._malloc(ndata);
+	ddataHeap 	= new Uint8Array(Module.HEAPU8.buffer, ddataPtr, ndata);
+	ddataHeap.set(new Uint8Array(ddata.buffer));
+	data 		= ddataHeap.byteOffset;
+	
+	dxMesh 		= new Float64Array(xMeshIn);
+	nxMesh 		= dxMesh.length * dxMesh.BYTES_PER_ELEMENT;
+	dxMeshPtr 	= Module._malloc(nxMesh);
+	dxMeshHeap 	= new Uint8Array(Module.HEAPU8.buffer, dxMeshPtr, nxMesh);
+	dxMeshHeap.set(new Uint8Array(dxMesh.buffer));
+	xMesh 		= dxMeshHeap.byteOffset;
+	
+	dyMesh 		= new Float64Array(yMeshIn);
+	nyMesh 		= dyMesh.length * dyMesh.BYTES_PER_ELEMENT;
+	dyMeshPtr 	= Module._malloc(nyMesh);
+	dyMeshHeap 	= new Uint8Array(Module.HEAPU8.buffer, dyMeshPtr, nyMesh);
+	dyMeshHeap.set(new Uint8Array(dyMesh.buffer));
+	yMesh 		= dyMeshHeap.byteOffset;
+	
+	nods 		= xMeshIn.length;
+	meshNumRows	= xMeshIn.length;
+	
+	
+	/*
+		Retrieve interpolation type
+	*/
+	//{{{
+	if (arguments.length === 7) {
+		interpType = arguments[6];
+	} else {
+		interpType = 'bilinear';
+	}
+	//}}}
+	
+	/*
+		Output
+	*/
+	pdataMesh = Module._malloc(4);
+	//}}}
+	
+	//}}}
+	
+	
+	/*
+		Declare InterpFromGridToMesh module
+	*/
+	//{{{
+	InterpFromGridToMeshModule = Module.cwrap(
+		'InterpFromGridToMeshModule', 
+		'number', 
+		[
+			'number', // output : pdataMesh
+			'number', // input	: x
+			'number', // input	: y
+			'number', // input 	: data
+			'number', // input 	: xMesh
+			'number', // input	: yMesh
+			'number', // input 	: defaultValue
+			'number', // input	: nods
+			'number', // input	: dataNumRowsIn
+			'number', // input	: dataNumColsIn
+			'number', // input	: meshNumRows
+			'string'  // input	: interpType
+		]
+	);
+	//}}}
+	
+	
+	/*
+		Call InterpFromGridToMesh module
+	*/
+	//{{{
+	InterpFromGridToMeshModule(
+		pdataMesh, 
+		x, 
+		y, 
+		data, 
+		xMesh, 
+		yMesh, 
+		defaultValue, 
+		nods,
+		dataNumRowsIn,
+		dataNumColsIn,
+		meshNumRows,
+		interpType
+	);
+	//}}}
+	
+	
+	/*
+		Dynamic copying from heap
+	*/
+	//{{{
+	dataMeshPtr	= Module.getValue(pdataMesh, 'i32');
+	dataMesh	= Module.HEAPF64.slice(dataMeshPtr / 8, dataMeshPtr / 8 + nods);
+	//}}}
+	
+	
+	/*
+		Free resources
+	*/
+	//{{{
+	Module._free(pdataMesh);
+	//}}}
+	
+	
+	return dataMesh;
+}
Index: /issm/trunk/src/wrappers/InterpFromMesh2d/InterpFromMesh2d.cpp
===================================================================
--- /issm/trunk/src/wrappers/InterpFromMesh2d/InterpFromMesh2d.cpp	(revision 22757)
+++ /issm/trunk/src/wrappers/InterpFromMesh2d/InterpFromMesh2d.cpp	(revision 22758)
@@ -23,24 +23,18 @@
 
 	/*input: */
-	double* index_data=NULL;
+	int*    index_data=NULL;
 	int     index_data_rows;
 	int     dummy;
-
 	double* x_data=NULL;
 	int     x_data_rows;
-
 	double* y_data=NULL;
 	int     y_data_rows;
-
 	double* data=NULL; 
 	int     data_rows;
 	int     data_cols;
-
 	double* x_prime=NULL;
 	double* y_prime=NULL;
-
 	int     x_prime_rows;
 	int     y_prime_rows;
-
 	double* default_values=NULL;
 	int     num_default_values=0;
@@ -139,5 +133,5 @@
 
 	/*end module: */
-	xDelete<double>(index_data);
+	xDelete<int>(index_data);
 	xDelete<double>(x_data);
 	xDelete<double>(y_data);
Index: /issm/trunk/src/wrappers/InterpFromMeshToGrid/InterpFromMeshToGrid.cpp
===================================================================
--- /issm/trunk/src/wrappers/InterpFromMeshToGrid/InterpFromMeshToGrid.cpp	(revision 22757)
+++ /issm/trunk/src/wrappers/InterpFromMeshToGrid/InterpFromMeshToGrid.cpp	(revision 22758)
@@ -12,9 +12,9 @@
 	_printf0_("\n");
 	_printf0_("   Usage:\n");
-	_printf0_("      [x_m,y_m,griddata]=InterpFromMeshToGrid(index,x,y,data,xmin,ymax,xposting,yposting,nlines,ncols,default_value)\n");
+	_printf0_("      grid=InterpFromMeshToGrid(index,x,y,data,x_grid,y_grid,default_value)\n");
 	_printf0_("\n");
 	_printf0_("      index,x,y: delaunay triangulation defining the mesh.\n");
 	_printf0_("      meshdata: vertex values of data to be interpolated.\n");
-	_printf0_("      xmin,ymax,posting,nlines,ncols: parameters that define the grid\n");
+	_printf0_("      xgrid,ygrid: parameters that define the grid\n");
 	_printf0_("      default_value: value of points located out of the mesh.\n");
 	_printf0_("\n");
@@ -22,23 +22,18 @@
 WRAPPER(InterpFromMeshToGrid_python){
 
-	/*input datasets: */
-	double* index=NULL;
-	int     nel;
+	/*inputs */
+	int*    index=NULL;
 	double* x=NULL;
-	int     nods;
 	double* y=NULL;
+	int     nel,nods;
 	double* meshdata=NULL;
 	int     meshdata_length;
-	double  xmin;
-	double  ymax;
-	double  xposting;
-	double  yposting;
-	int     nlines,ncols;
+	double* xgrid=NULL;
+	double* ygrid=NULL;
+	int     nlines,ncols,test;
 	double  default_value;
 
-	/* output datasets: */
+	/* outputs */
 	double* griddata=NULL;
-	double* x_m=NULL;
-	double* y_m=NULL;
 
 	/*Boot module: */
@@ -51,32 +46,28 @@
 
 	/*Input datasets: */
-	FetchData(&index,&nel,NULL,INDEX);
-	FetchData(&x,&nods,NULL,X);
-	FetchData(&y,NULL,NULL,Y);
-	FetchData(&meshdata,&meshdata_length,NULL,MESHDATA);
-	FetchData(&xmin,XMIN);
-	FetchData(&ymax,YMAX);
-	FetchData(&xposting,XPOSTING);
-	FetchData(&yposting,YPOSTING);
-	FetchData(&nlines,NLINES);
-	FetchData(&ncols,NCOLS);
+	FetchData(&index,&nel,&test,INDEX);
+	if(test!=3) _error_("size not supported yet");
+	FetchData(&x,&nods,X);
+	FetchData(&y,&test,Y);
+	if(test!=nods) _error_("size not supported yet");
+	FetchData(&meshdata,&meshdata_length,MESHDATA);
+	FetchData(&xgrid,&ncols,XGRID); 
+	FetchData(&ygrid,&nlines,YGRID);
 	FetchData(&default_value,DEFAULTVALUE);
 
 	/*Call core of computation: */
-	InterpFromMeshToGridx(&x_m,&y_m,&griddata,index,x,y,nods,nel,meshdata,meshdata_length,xmin,ymax,xposting,yposting,nlines,ncols,default_value);
+	InterpFromMeshToGridx(&griddata,index,x,y,nods,nel,meshdata,meshdata_length,xgrid,ygrid,nlines,ncols,default_value);
 
 	/*Write results: */
-	WriteData(XM,x_m,ncols);
-	WriteData(YM,y_m,nlines);
 	WriteData(GRIDDATA,griddata,nlines,ncols);
 
 	/*Free ressources: */
-	xDelete<double>(index);
+	xDelete<int>(index);
 	xDelete<double>(x);
 	xDelete<double>(y);
 	xDelete<double>(meshdata);
 	xDelete<double>(griddata);
-	xDelete<double>(x_m);
-	xDelete<double>(y_m);
+	xDelete<double>(xgrid);
+	xDelete<double>(ygrid);
 
 	/*end module: */
Index: /issm/trunk/src/wrappers/InterpFromMeshToGrid/InterpFromMeshToGrid.h
===================================================================
--- /issm/trunk/src/wrappers/InterpFromMeshToGrid/InterpFromMeshToGrid.h	(revision 22757)
+++ /issm/trunk/src/wrappers/InterpFromMeshToGrid/InterpFromMeshToGrid.h	(revision 22758)
@@ -33,15 +33,9 @@
 #define Y            prhs[2]
 #define MESHDATA     prhs[3]
-#define XMIN         prhs[4]
-#define YMAX         prhs[5]
-#define XPOSTING     prhs[6]
-#define YPOSTING     prhs[7]
-#define NLINES       prhs[8]
-#define NCOLS        prhs[9]
-#define DEFAULTVALUE prhs[10]
+#define XGRID        prhs[4]
+#define YGRID        prhs[5]
+#define DEFAULTVALUE prhs[6]
 /* serial output macros: */
-#define XM (mxArray**)&plhs[0]
-#define YM (mxArray**)&plhs[1]
-#define GRIDDATA (mxArray**)&plhs[2]
+#define GRIDDATA (mxArray**)&plhs[0]
 #endif
 
@@ -52,22 +46,16 @@
 #define Y            PyTuple_GetItem(args,2)
 #define MESHDATA     PyTuple_GetItem(args,3)
-#define XMIN         PyTuple_GetItem(args,4)
-#define YMAX         PyTuple_GetItem(args,5)
-#define XPOSTING     PyTuple_GetItem(args,6)
-#define YPOSTING     PyTuple_GetItem(args,7)
-#define NLINES       PyTuple_GetItem(args,8)
-#define NCOLS        PyTuple_GetItem(args,9)
+#define XGRID        PyTuple_GetItem(args,4)
+#define YGRID        PyTuple_GetItem(args,5)
 #define DEFAULTVALUE PyTuple_GetItem(args,10)
 /* serial output macros: */
-#define XM output,0
-#define YM output,1
-#define GRIDDATA output,2
+#define GRIDDATA output,0
 #endif
 
 /* serial arg counts: */
 #undef NLHS
-#define NLHS  3
+#define NLHS  1
 #undef NRHS
-#define NRHS  11
+#define NRHS  7
 
 #endif  /* _INTERPFROMMESHTOGRID_H*/
Index: /issm/trunk/src/wrappers/M1qn3/M1qn3.cpp
===================================================================
--- /issm/trunk/src/wrappers/M1qn3/M1qn3.cpp	(revision 22757)
+++ /issm/trunk/src/wrappers/M1qn3/M1qn3.cpp	(revision 22758)
@@ -38,4 +38,7 @@
 WRAPPER(M1qn3_python){
 
+	/*Boot module: */
+	MODULEBOOT();
+
 #ifdef _HAVE_M1QN3_
 	/*input: */
@@ -45,5 +48,4 @@
 	int     intn;
 	int     priorn;
-	int     maxsteps,maxiter;
 	Data    data_struct;
 
@@ -52,20 +54,11 @@
 
 	/*intermediary: */
-	double* G=NULL;
-	double* X=NULL;
 	double f;
-	double dxmin=.01;
-	double gttol=.0001;
+	double dxmin=0.01;
+	double gttol=0.0001;
 	long   omode;
 
-	/*Boot module: */
-	MODULEBOOT();
-
 	/*checks on arguments on the matlab side: */
-	if(nlhs!=NLHS){
-		M1qn3Usage();
-		_error_("M1qn3 usage error");
-	}
-	if(nrhs!=5){
+	if(nlhs!=NLHS || nrhs!=3){
 		M1qn3Usage();
 		_error_("M1qn3 usage error");
@@ -76,12 +69,4 @@
 	FetchData(&Gs,&intn,&priorn,GHANDLE);
 	FetchData(&Js,&priorn,JHANDLE);
-	FetchData(&maxsteps,MAXSTEPSHANDLE);
-	FetchData(&maxiter,MAXITERHANDLE);
-
-	/*_printf_("Xs: " << Xs[0] << "\n");
-	_printf_("Gs: " << Gs[0] << "\n");
-	_printf_("Js: " << Js[0] << "\n");
-	_printf_("maxiter: " << maxiter << "\n");
-	_printf_("maxsteps: " << maxsteps << "\n");*/
 
 	/*Initialize M1QN3 parameters*/
@@ -99,21 +84,13 @@
 
 	/*Optimization criterions*/
-	long niter = long(maxsteps); /*Maximum number of iterations*/
-	long nsim  = long(maxiter);/*Maximum number of function calls*/
+	long niter = long(intn); /*Maximum number of iterations*/
+	long nsim  = long(intn); /*Maximum number of function calls*/
 
 	/*Get problem dimension and initialize X, G and f: */
-	/*_printf_("intn: " << intn << "\n");
-	_printf_("priorn: " << priorn << "\n");*/
 	long n = long(intn);
-	IssmPDouble* G = xNew<IssmPDouble>(n); for (int i=0;i<n;i++)G[i]=Gs[i*priorn];
-	IssmPDouble* X = xNew<IssmPDouble>(n); for (int i=0;i<n;i++)X[i]=Xs[i*priorn];
+	IssmPDouble* G = xNew<IssmPDouble>(n); for (int i=0;i<n;i++)G[i]=Gs[i*priorn+0];
+	IssmPDouble* X = xNew<IssmPDouble>(n); for (int i=0;i<n;i++)X[i]=Xs[i*priorn+0];
 	f = Js[0];
 	
-	/*_printf_("X: " << X[0] << "\n");
-	_printf_("G: " << G[0] << "\n");
-	_printf_("J: " << f << "\n");
-	_printf_("n: " << n << "\n");*/
-
-
 	/*Allocate m1qn3 working arrays (see doc)*/
 	long      m   = 100;
@@ -135,5 +112,5 @@
 
 	switch(int(omode)){
-		case 0: /*_printf0_("   Stop requested (indic = 0)\n"); */ break;
+		case 0: /* _printf0_("   Stop requested\n");*/ break;
 		case 1:  _printf0_("   Convergence reached (gradient satisfies stopping criterion)\n"); break;
 		case 2:  _printf0_("   Bad initialization\n"); break;
@@ -160,8 +137,9 @@
 	xDelete<double>(G);
 	xDelete<double>(X);
-	MODULEEND();
 	#else
 	_error_("m1qn3 is not installed");
 	#endif
+	MODULEEND();
+
 }
 
@@ -181,11 +159,9 @@
 	}
 	else{
-		//_printf0_("counter: " << ds->counter << "\n");
 		ds->counter++;
 		*pf=Js[ds->counter];
-		for(int i=0;i<*n;i++)X[i]=Xs[ds->priorn*i+ds->counter];
-		for(int i=0;i<*n;i++)G[i]=Gs[ds->priorn*i+ds->counter];
+		for(int i=0;i<*n;i++) X[i]=Xs[ds->priorn*i+ds->counter];
+		for(int i=0;i<*n;i++) G[i]=Gs[ds->priorn*i+ds->counter];
 	}
-
 }
 #endif
Index: /issm/trunk/src/wrappers/M1qn3/M1qn3.h
===================================================================
--- /issm/trunk/src/wrappers/M1qn3/M1qn3.h	(revision 22757)
+++ /issm/trunk/src/wrappers/M1qn3/M1qn3.h	(revision 22758)
@@ -30,6 +30,4 @@
 #define GHANDLE       prhs[1]
 #define JHANDLE       prhs[2]
-#define MAXSTEPSHANDLE prhs[3]
-#define MAXITERHANDLE prhs[4]
 /* serial output macros: */
 #define XOUT (mxArray**)&plhs[0]
@@ -39,8 +37,6 @@
 /* serial input macros: */
 #define XHANDLE   PyTuple_GetItem(args,0)
-#define GHANDLE       PyTuple_GetItem(args,1)
-#define JHANDLE       PyTuple_GetItem(args,2)
-#define MAXSTEPSHANDLE PyTuple_GetItem(args,3)
-#define MAXITERHANDLE PyTuple_GetItem(args,4)
+#define GHANDLE   PyTuple_GetItem(args,1)
+#define JHANDLE   PyTuple_GetItem(args,2)
 /* serial output macros: */
 #define XOUT output,0
Index: /issm/trunk/src/wrappers/MeshPartition/MeshPartition.cpp
===================================================================
--- /issm/trunk/src/wrappers/MeshPartition/MeshPartition.cpp	(revision 22757)
+++ /issm/trunk/src/wrappers/MeshPartition/MeshPartition.cpp	(revision 22758)
@@ -15,18 +15,12 @@
 WRAPPER(MeshPartition_python){
 
-	/*Indexing: */
-	int i,j;
-
 	/* required input: */
-	int  meshelementtype;
 	int  numberofelements;
 	int  numberofvertices;
-	int *elements         = NULL;
+	int *elements = NULL;
 	int  elements_width;
-
-	int numberofelements2d;
-	int numberofvertices2d;
+	int numberofelements2d=0;
+	int numberofvertices2d=0;
 	int* elements2d=NULL;
-
 	int numberoflayers;
 	int numareas=1;
@@ -42,30 +36,19 @@
 
 	/*checks on arguments on the matlab side: */
-	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&MeshPartitionUsage);
+	CHECKARGUMENTS(NLHS,NRHS,&MeshPartitionUsage);
 
 	/*Fetch data: */
-	FetchData(&numberofelements,mxGetAssignedField(MESH,0,"numberofelements"));
-	FetchData(&numberofvertices,mxGetAssignedField(MESH,0,"numberofvertices"));
-	FetchData(&elements,NULL,&elements_width,mxGetAssignedField(MESH,0,"elements"));
+	FetchData(&numberofvertices,NUMBEROFVERTICES);
+	FetchData(&elements,&numberofelements,&elements_width,ELEMENTS);
+	FetchData(&numberofvertices2d,NUMBEROFVERTICES2D);
+	FetchData(&elements2d,&numberofelements2d,NULL,ELEMENTS2D);
+	FetchData(&numberoflayers,NUMBEROFLAYERS);
+	FetchData(&numareas,NUMAREAS);
 
-	if(strcmp(mxGetClassName(MESH),"mesh3dprisms")==0){
-		meshelementtype = PentaEnum;
-		FetchData(&numberofelements2d,mxGetAssignedField(MESH,0,"numberofelements2d"));
-		FetchData(&numberofvertices2d,mxGetAssignedField(MESH,0,"numberofvertices2d"));
-		FetchData(&elements2d,NULL,NULL,mxGetAssignedField(MESH,0,"elements2d"));
-		FetchData(&numberoflayers,mxGetAssignedField(MESH,0,"numberoflayers"));
-	}
-	else if(strcmp(mxGetClassName(MESH),"mesh2dhorizontal")==0){
-		meshelementtype = TriaEnum;
-		numberoflayers=1;
-	}
-	else if(strcmp(mxGetClassName(MESH),"mesh2dvertical")==0){
-		meshelementtype = TriaEnum;
-		numberoflayers=1;
-	}
-	else{
-		_error_("Mesh type "<<mxGetClassName(MESH)<<" not supported yet");
-	}
-	FetchData(&numareas,NUMAREAS);
+	/*Get mesh element type and convert to Enum*/
+	char* meshtype_str = NULL;
+	FetchData(&meshtype_str,MESHELEMENTTYPE);
+	int meshelementtype = StringToEnumx(meshtype_str); 
+	xDelete<char>(meshtype_str);
 
 	/*Run partitioning algorithm based on a "clever" use of the Metis partitioner: */
@@ -75,10 +58,10 @@
 	/*Post process node_partitioning and element_partitioning to be in double format. Metis needed them in int* format: */
 	element_partitioning=xNew<double>(numberofelements);
-	for (i=0;i<numberofelements;i++){
+	for(int i=0;i<numberofelements;i++){
 		element_partitioning[i]=(double)int_element_partitioning[i]+1; //Metis indexing from 0, matlab from 1.
 	}
 
 	node_partitioning=xNew<double>(numberofvertices);
-	for (i=0;i<numberofvertices;i++){
+	for(int i=0;i<numberofvertices;i++){
 		node_partitioning[i]=(double)int_node_partitioning[i]+1; //Metis indexing from 0, matlab from 1.
 	}
@@ -90,5 +73,5 @@
 	/*Free ressources:*/
 	xDelete<int>(elements);
-	xDelete<int>( elements2d);
+	xDelete<int>(elements2d);
 	xDelete<int>(int_element_partitioning);
 	xDelete<int>(int_node_partitioning);
Index: /issm/trunk/src/wrappers/MeshPartition/MeshPartition.h
===================================================================
--- /issm/trunk/src/wrappers/MeshPartition/MeshPartition.h	(revision 22757)
+++ /issm/trunk/src/wrappers/MeshPartition/MeshPartition.h	(revision 22758)
@@ -27,6 +27,11 @@
 #ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
-#define MESH    prhs[0]
-#define NUMAREAS prhs[1]
+#define NUMBEROFVERTICES   prhs[0]
+#define ELEMENTS           prhs[1]
+#define NUMBEROFVERTICES2D prhs[2]
+#define ELEMENTS2D         prhs[3]
+#define NUMBEROFLAYERS     prhs[4]
+#define MESHELEMENTTYPE    prhs[5]
+#define NUMAREAS           prhs[6]
 /* serial output macros: */
 #define ELEMENTPARTITIONING (mxArray**)&plhs[0]
@@ -36,6 +41,11 @@
 #ifdef _HAVE_PYTHON_MODULES_
 /* serial input macros: */
-#define MESH     PyTuple_GetItem(args,0)
-#define NUMAREAS PyTuple_GetItem(args,1)
+#define NUMBEROFVERTICES   PyTuple_GetItem(args,0)
+#define ELEMENTS           PyTuple_GetItem(args,1)
+#define NUMBEROFVERTICES2D PyTuple_GetItem(args,2)
+#define ELEMENTS2D         PyTuple_GetItem(args,3)
+#define NUMBEROFLAYERS     PyTuple_GetItem(args,4)
+#define MESHELEMENTTYPE    PyTuple_GetItem(args,5)
+#define NUMAREAS           PyTuple_GetItem(args,6)
 /* serial output macros: */
 #define ELEMENTPARTITIONING output,0
@@ -47,5 +57,5 @@
 #define NLHS  2
 #undef NRHS
-#define NRHS  2
+#define NRHS  7
 
 #endif  /* _MESHPARTITION_H */
Index: /issm/trunk/src/wrappers/ProcessRifts/ProcessRifts.cpp
===================================================================
--- /issm/trunk/src/wrappers/ProcessRifts/ProcessRifts.cpp	(revision 22758)
+++ /issm/trunk/src/wrappers/ProcessRifts/ProcessRifts.cpp	(revision 22758)
@@ -0,0 +1,59 @@
+/*!\file:  ProcessRifts.cpp
+ * \brief split a mesh where a rift (or fault) is present
+ */ 
+
+#include "./ProcessRifts.h"
+
+void ProcessRiftsUsage(void){/*{{{*/
+	_printf_("\n");
+	_printf_("   usage: [index2,x2,y2,segments2,segmentmarkers2,rifts2]=ProcessRifts(index1,x1,y1,segments1,segmentmarkers1) \n");
+	_printf_("      where: (index1,x1,y1,segments1,segmentmarkers1) is an initial triangulation.\n");
+	_printf_("      index2,x2,y2,segments2,segmentmarkers2,rifts2 is the resulting triangulation where rifts have been processed.\n");
+}/*}}}*/
+WRAPPER(ProcessRifts_python){
+
+	/* returned quantities: */
+	RiftStruct *riftstruct = NULL;
+
+	/* input: */
+	int     nel,nods;
+	int    *index          = NULL;
+	double *x              = NULL;
+	double *y              = NULL;
+	int    *segments       = NULL;
+	int    *segmentmarkers = NULL;
+	int     num_seg;
+
+	/*Boot module*/
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CHECKARGUMENTS(NLHS,NRHS,&ProcessRiftsUsage);
+
+	/*Fetch data */
+	FetchData(&index,&nel,NULL,INDEXIN);
+	FetchData(&x,&nods,XIN);
+	FetchData(&y,NULL,YIN);
+	FetchData(&segments,&num_seg,NULL,SEGMENTSIN);
+	FetchData(&segmentmarkers,NULL,SEGMENTMARKERSIN);
+
+	/*call x layer*/
+	ProcessRiftsx(&index,&nel,&x,&y,&nods,&segments,&segmentmarkers,&num_seg,&riftstruct);
+
+	/*Output : */
+	WriteData(INDEXOUT,index,nel,3);
+	WriteData(XOUT,x,nods,1);
+	WriteData(YOUT,y,nods,1);
+	WriteData(SEGMENTSOUT,segments,num_seg,3);
+	WriteData(SEGMENTMARKERSOUT,segmentmarkers,num_seg,1);
+	WriteData(RIFTSTRUCT,riftstruct);
+
+	/*end module: */
+	delete riftstruct;
+	xDelete<int>(index);
+	xDelete<double>(x);
+	xDelete<double>(y);
+	xDelete<int>(segments);
+	xDelete<int>(segmentmarkers );
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/ProcessRifts/ProcessRifts.h
===================================================================
--- /issm/trunk/src/wrappers/ProcessRifts/ProcessRifts.h	(revision 22758)
+++ /issm/trunk/src/wrappers/ProcessRifts/ProcessRifts.h	(revision 22758)
@@ -0,0 +1,65 @@
+/*
+ * ProcessRifts.h
+ */ 
+
+#ifndef _PROCESSRIFTS_H_
+#define _PROCESSRIFTS_H_
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#include "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "ProcessRifts"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#define INDEXIN          prhs[0]
+#define XIN              prhs[1]
+#define YIN              prhs[2]
+#define SEGMENTSIN       prhs[3]
+#define SEGMENTMARKERSIN prhs[4]
+/* serial output macros: */
+#define INDEXOUT          (mxArray**)&plhs[0]
+#define XOUT              (mxArray**)&plhs[1]
+#define YOUT              (mxArray**)&plhs[2]
+#define SEGMENTSOUT       (mxArray**)&plhs[3]
+#define SEGMENTMARKERSOUT (mxArray**)&plhs[4]
+#define RIFTSTRUCT        (mxArray**)&plhs[5]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define INDEXIN          PyTuple_GetItem(args,0)
+#define XIN              PyTuple_GetItem(args,1)
+#define YIN              PyTuple_GetItem(args,2)
+#define SEGMENTSIN       PyTuple_GetItem(args,3)
+#define SEGMENTMARKERSIN PyTuple_GetItem(args,4)
+/* serial output macros: */
+#define INDEXOUT          output,0
+#define XOUT              output,1
+#define YOUT              output,2
+#define SEGMENTSOUT       output,3
+#define SEGMENTMARKERSOUT output,4
+#define RIFTSTRUCT        output,5
+#endif
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  6
+#undef NRHS
+#define NRHS  5
+
+#endif
Index: /issm/trunk/src/wrappers/Triangle/Triangle.cpp
===================================================================
--- /issm/trunk/src/wrappers/Triangle/Triangle.cpp	(revision 22758)
+++ /issm/trunk/src/wrappers/Triangle/Triangle.cpp	(revision 22758)
@@ -0,0 +1,63 @@
+/*
+ * Triangle: mesh a domain using an .exp file
+ */
+
+#include "./Triangle.h"
+
+void TriangleUsage(void){/*{{{*/
+	_printf_("\n");
+	_printf_("   usage: [index,x,y,segments,segmentmarkers]=Triangle(domainoutlinefilename,rifts,area) \n");
+	_printf_("      where: index,x,y defines a triangulation, segments is an array made \n");
+	_printf_("      of exterior segments to the mesh domain outline, segmentmarkers is an array flagging each segment, \n");
+	_printf_("      outlinefilename an Argus domain outline file, \n");
+	_printf_("      area is the maximum area desired for any element of the resulting mesh, \n");
+	_printf_("\n");
+}/*}}}*/
+WRAPPER(Triangle_python){
+	
+	/*intermediary: */
+	double    area;
+	Contours *domain = NULL;
+	Contours *rifts  = NULL;
+
+	/* output: */
+	int    *index             = NULL;
+	double *x                 = NULL;
+	double *y                 = NULL;
+	int    *segments          = NULL;
+	int    *segmentmarkerlist = NULL;
+	int     nel,nods,nsegs;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments: */
+	CHECKARGUMENTS(NLHS,NRHS,&TriangleUsage);
+
+	/*Fetch data needed for meshing: */
+	FetchData(&domain,DOMAINOUTLINE);
+	FetchData(&rifts,RIFTSOUTLINE);
+	FetchData(&area,AREA);
+
+	/*call x core: */
+	Trianglex(&index,&x,&y,&segments,&segmentmarkerlist,&nel,&nods,&nsegs,domain,rifts,area);
+
+	/*write outputs: */
+	WriteData(INDEX,index,nel,3);
+	WriteData(X,x,nods);
+	WriteData(Y,y,nods);
+	WriteData(SEGMENTS,segments,nsegs,3);
+	WriteData(SEGMENTMARKERLIST,segmentmarkerlist,nsegs);
+
+	/*free ressources: */
+	delete domain;
+	delete rifts;
+	xDelete<int>(index);
+	xDelete<double>(x);
+	xDelete<double>(y);
+	xDelete<int>(segments);
+	xDelete<int>(segmentmarkerlist);
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/Triangle/Triangle.h
===================================================================
--- /issm/trunk/src/wrappers/Triangle/Triangle.h	(revision 22758)
+++ /issm/trunk/src/wrappers/Triangle/Triangle.h	(revision 22758)
@@ -0,0 +1,83 @@
+/*
+	Triangle.h
+*/
+
+#ifndef _TRIANGLE_H
+#define _TRIANGLE_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#ifdef _HAVE_JAVASCRIPT_MODULES_
+#undef _DO_NOT_LOAD_GLOBALS_ /*only module where this needs to be undefined, so as to 
+							   not include IssmComm several times in the javascript Modle construct.*/
+#endif
+
+/*Header files: */
+#include "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/toolkits/toolkits.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.h"
+#include "../../c/shared/io/io.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "Triangle"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#define DOMAINOUTLINE  prhs[0]
+#define RIFTSOUTLINE   prhs[1]
+#define AREA           prhs[2]
+/* serial output macros: */
+#define INDEX             (mxArray**)&plhs[0]
+#define X                 (mxArray**)&plhs[1]
+#define Y                 (mxArray**)&plhs[2]
+#define SEGMENTS          (mxArray**)&plhs[3]
+#define SEGMENTMARKERLIST (mxArray**)&plhs[4]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define DOMAINOUTLINE PyTuple_GetItem(args,0)
+#define RIFTSOUTLINE  PyTuple_GetItem(args,1)
+#define AREA          PyTuple_GetItem(args,2)
+/* serial output macros: */
+#define INDEX             output,0
+#define X                 output,1
+#define Y                 output,2
+#define SEGMENTS          output,3
+#define SEGMENTMARKERLIST output,4
+#endif
+
+#ifdef _HAVE_JAVASCRIPT_MODULES_
+/* serial input macros: */
+#define DOMAINOUTLINE domainx,domainy,domainnods
+#define RIFTSOUTLINE  NULL,NULL,0
+#define AREA          areain
+/* serial output macros: */
+#define INDEX             pindex,pnel
+#define X                 px,pnods
+#define Y                 py,pnods
+#define SEGMENTS          psegments,pnsegs
+#define SEGMENTMARKERLIST psegmentmarkers,pnsegs
+#define WRAPPER(modulename) extern "C" { int  TriangleModule(double** pindex, double** px, double** py, int* pnel, int* pnods, double** psegments, double** psegmentmarkers, int* pnsegs, double* domainx, double* domainy, int domainnods, double areain)
+#define _DO_NOT_LOAD_GLOBALS_//we only load globals for TriangleModule.js, not other modules!
+#endif
+
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  5
+#undef NRHS
+#define NRHS  3
+
+#endif  /* _TRIANGLE_H */
Index: /issm/trunk/src/wrappers/Triangle/Triangle.js
===================================================================
--- /issm/trunk/src/wrappers/Triangle/Triangle.js	(revision 22758)
+++ /issm/trunk/src/wrappers/Triangle/Triangle.js	(revision 22758)
@@ -0,0 +1,82 @@
+function Triangle(md,domain,rifts, area){
+/*Triangle 
+	   usage: var array = Triangle(domain,rifts,area);
+	      where: array is made of [index,x,y,segments,segmentmarkers]
+		  and index,x,y defines a triangulation, segments is an array made 
+	      of exterior segments to the mesh domain outline, segmentmarkers is an array 
+		  flagging each segment, domain a js array defining the domain outline  (sames for 
+		  rifts) and area is the maximum area desired for any element of the resulting mesh.
+
+		  Ok, for now, we are not dealing with rifts. Also, the domain is made of only one 
+		  profile, this to avoid passing a double** pointer to js. 
+*/
+
+	//Dynamic allocations: {{{
+	//Retrieve domain arrays, and allocate on Module heap: 
+	
+	//input
+	var dx=new Float64Array(domain['x']); var nx=dx.length * dx.BYTES_PER_ELEMENT;
+	var dxPtr= Module._malloc(nx); var domainxHeap = new Uint8Array(Module.HEAPU8.buffer,dxPtr,nx);
+	domainxHeap.set(new Uint8Array(dx.buffer)); var domainx=domainxHeap.byteOffset;
+
+	var dy=new Float64Array(domain['y']); var ny=dy.length * dy.BYTES_PER_ELEMENT;
+	var dyPtr = Module._malloc(ny); var domainyHeap = new Uint8Array(Module.HEAPU8.buffer,dyPtr,ny);
+	domainyHeap.set(new Uint8Array(dy.buffer)); var domainy=domainyHeap.byteOffset;
+	
+	//output
+	var nel,indexlinear,index,nods,x,y;
+	var pnel= Module._malloc(4); 
+	var pindex= Module._malloc(4); 
+	var pnods= Module._malloc(4); 
+	var px= Module._malloc(4); 
+	var py= Module._malloc(4); 
+	var psegments= Module._malloc(4); 
+	var psegmentmarkers= Module._malloc(4); 
+	var pnsegs= Module._malloc(4); 
+	//}}}
+
+	//Declare Triangle module: 
+	TriangleModule = Module.cwrap('TriangleModule','number',['number','number','number','number','number','number','number','number','number','number','number','number']);
+	
+	//Call Triangle module: 
+	TriangleModule(pindex,px,py,pnel,pnods,psegments,psegmentmarkers,pnsegs, domainx,domainy,dx.length,area);
+	
+	/*Dynamic copying from heap: {{{*/
+	//recover mesh: 
+	nel = Module.getValue(pnel, 'i32');
+	var indexptr = Module.getValue(pindex,'i32');
+	indexlinear = Module.HEAPF64.slice(indexptr /8, indexptr/8 + nel*3);
+	index = ListToMatrix(indexlinear,3);
+
+	nods = Module.getValue(pnods, 'i32');
+	var xptr = Module.getValue(px,'i32');
+	var yptr = Module.getValue(py,'i32');
+	x = Module.HEAPF64.slice(xptr /8, xptr/8 + nods);
+	y = Module.HEAPF64.slice(yptr /8, yptr/8 + nods);
+	
+	nsegs = Module.getValue(pnsegs, 'i32');
+	var segmentsptr = Module.getValue(psegments,'i32');
+	segmentslinear = Module.HEAPF64.slice(segmentsptr /8, segmentsptr/8 + nsegs*3);
+	segments = ListToMatrix(segmentslinear,3);
+	
+	var segmentmarkersptr = Module.getValue(psegmentmarkers,'i32');
+	segmentmarkers = Module.HEAPF64.slice(segmentmarkersptr /8, segmentmarkersptr/8 + nsegs);
+	/*}}}*/
+
+	var return_array=[index,x,y,segments,segmentmarkers];
+
+	/*Free ressources: */
+	Module._free(pindex); 
+	Module._free(indexlinear); 
+	Module._free(px); 
+	Module._free(x); 
+	Module._free(py); 
+	Module._free(y); 
+	Module._free(pnel); 
+	Module._free(pnods); 
+	Module._free(psegments); 
+	Module._free(psegmentmarkers); 
+	Module._free(pnsegs); 
+
+	return return_array;
+}
Index: /issm/trunk/src/wrappers/javascript/Makefile.am
===================================================================
--- /issm/trunk/src/wrappers/javascript/Makefile.am	(revision 22757)
+++ /issm/trunk/src/wrappers/javascript/Makefile.am	(revision 22758)
@@ -7,8 +7,9 @@
 AM_CPPFLAGS+=  -DISSM_PREFIX='"$(prefix)"'
 
-js_scripts = ${ISSM_DIR}/src/wrappers/TriMesh/TriMesh.js  \
+js_scripts = ${ISSM_DIR}/src/wrappers/Triangle/Triangle.js  \
 			 ${ISSM_DIR}/src/wrappers/NodeConnectivity/NodeConnectivity.js\
 			 ${ISSM_DIR}/src/wrappers/ContourToMesh/ContourToMesh.js\
 			 ${ISSM_DIR}/src/wrappers/ElementConnectivity/ElementConnectivity.js\
+			 ${ISSM_DIR}/src/wrappers/InterpFromGridToMesh/InterpFromGridToMesh.js\
 			 ${ISSM_DIR}/src/wrappers/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.js\
 			 ${ISSM_DIR}/src/wrappers/IssmConfig/IssmConfig.js\
@@ -81,13 +82,14 @@
 endif
 
-IssmModule_SOURCES = ../TriMesh/TriMesh.cpp \
+IssmModule_SOURCES = ../Triangle/Triangle.cpp \
 					 ../NodeConnectivity/NodeConnectivity.cpp\
 					 ../ContourToMesh/ContourToMesh.cpp\
 					 ../ElementConnectivity/ElementConnectivity.cpp\
+					 ../InterpFromGridToMesh/InterpFromGridToMesh.cpp\
 					 ../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp\
 					 ../IssmConfig/IssmConfig.cpp\
 					 ../Issm/issm.cpp
 
-IssmModule_CXXFLAGS= -fPIC -D_DO_NOT_LOAD_GLOBALS_  --memory-init-file 0 $(AM_CXXFLAGS) $(CXXFLAGS) $(CXXOPTFLAGS) $(COPTFLAGS) -s EXPORTED_FUNCTIONS="['_TriMeshModule','_NodeConnectivityModule','_ContourToMeshModule','_ElementConnectivityModule','_InterpFromMeshToMesh2dModule','_IssmConfigModule','_IssmModule']"  -s DISABLE_EXCEPTION_CATCHING=0 -s ALLOW_MEMORY_GROWTH=1 -s INVOKE_RUN=0
+IssmModule_CXXFLAGS= -fPIC -D_DO_NOT_LOAD_GLOBALS_  --memory-init-file 0 $(AM_CXXFLAGS) $(CXXFLAGS) $(CXXOPTFLAGS) $(COPTFLAGS) -s EXPORTED_FUNCTIONS="['_TriangleModule','_NodeConnectivityModule','_ContourToMeshModule','_ElementConnectivityModule','_InterpFromGridToMeshModule','_InterpFromMeshToMesh2dModule','_IssmConfigModule','_IssmModule']"  -s DISABLE_EXCEPTION_CATCHING=0 -s ALLOW_MEMORY_GROWTH=1 -s INVOKE_RUN=0
 IssmModule_LDADD = ${deps} $(TRIANGLELIB)  $(GSLLIB)
 #}}}
Index: /issm/trunk/src/wrappers/javascript/io/WriteJavascriptData.cpp
===================================================================
--- /issm/trunk/src/wrappers/javascript/io/WriteJavascriptData.cpp	(revision 22757)
+++ /issm/trunk/src/wrappers/javascript/io/WriteJavascriptData.cpp	(revision 22758)
@@ -78,4 +78,26 @@
 }
 /*}}}*/
+/*FUNCTION WriteData(IssmPDouble* pdouble, IssmSeqVec<double> vector){{{*/
+void WriteData(IssmPDouble** pdataref, IssmSeqVec<double>* vector){
+
+    double*  dataref=NULL;
+    double*  vector_ptr=NULL;
+    int      rows;
+
+    if(vector){
+        /*call toolkit routine: */
+        vector_ptr=vector->ToMPISerial();
+        vector->GetSize(&rows);
+
+        /*now create the js vector */
+		dataref=xNew<double>(rows); 
+        for(int i=0;i<rows;i++) dataref[i]=vector_ptr[i];
+    }
+
+    /*Clean-up and return*/
+    xDelete<double>(vector_ptr);
+    *pdataref=dataref;
+}
+/*}}}*/
 /*FUNCTION WriteData(IssmPDouble* pdouble, IssmPDouble double){{{*/
 void WriteData(IssmPDouble* pdouble, IssmPDouble doublein){
Index: /issm/trunk/src/wrappers/javascript/io/javascriptio.h
===================================================================
--- /issm/trunk/src/wrappers/javascript/io/javascriptio.h	(revision 22757)
+++ /issm/trunk/src/wrappers/javascript/io/javascriptio.h	(revision 22758)
@@ -25,4 +25,5 @@
 void WriteData(char** pstring, char* stringin);
 void WriteData(IssmPDouble* pdouble, IssmPDouble doublein);
+void WriteData(IssmPDouble** pdataref, IssmSeqVec<double>* vector);
 void WriteData(IssmPDouble** pdouble, void*);
 
Index: /issm/trunk/src/wrappers/matlab/Makefile.am
===================================================================
--- /issm/trunk/src/wrappers/matlab/Makefile.am	(revision 22757)
+++ /issm/trunk/src/wrappers/matlab/Makefile.am	(revision 22758)
@@ -58,6 +58,6 @@
 						 PointCloudFindNeighbors_matlab.la\
 						 PropagateFlagsFromConnectivity_matlab.la\
-						 TriMesh_matlab.la\
-						 TriMeshProcessRifts_matlab.la\
+						 Triangle_matlab.la\
+						 ProcessRifts_matlab.la\
 						 Scotch_matlab.la
 
@@ -151,9 +151,9 @@
 ContourToMesh_matlab_la_SOURCES = ../ContourToMesh/ContourToMesh.cpp
 ContourToMesh_matlab_la_CXXFLAGS = ${AM_CXXFLAGS}
-ContourToMesh_matlab_la_LIBADD = ${deps} $(PETSCLIB) $(MPILIB) $(NEOPZLIB) $(MULTITHREADINGLIB) $(GSLLIB) $(PROJ4LIB)
+ContourToMesh_matlab_la_LIBADD = ${deps} $(PETSCLIB) $(MPILIB) $(MULTITHREADINGLIB) $(NEOPZLIB) $(GSLLIB) $(PROJ4LIB)
 
 ExpToLevelSet_matlab_la_SOURCES = ../ExpToLevelSet/ExpToLevelSet.cpp
 ExpToLevelSet_matlab_la_CXXFLAGS = ${AM_CXXFLAGS}
-ExpToLevelSet_matlab_la_LIBADD = ${deps} $(PETSCLIB) $(MPILIB) $(NEOPZLIB) $(MULTITHREADINGLIB) $(GSLLIB) $(PROJ4LIB)
+ExpToLevelSet_matlab_la_LIBADD = ${deps} $(PETSCLIB) $(MPILIB) $(MULTITHREADINGLIB) $(NEOPZLIB) $(GSLLIB) $(PROJ4LIB)
 
 ContourToNodes_matlab_la_SOURCES = ../ContourToNodes/ContourToNodes.cpp
@@ -171,9 +171,9 @@
 InterpFromGridToMesh_matlab_la_SOURCES = ../InterpFromGridToMesh/InterpFromGridToMesh.cpp
 InterpFromGridToMesh_matlab_la_CXXFLAGS = ${AM_CXXFLAGS}
-InterpFromGridToMesh_matlab_la_LIBADD = ${deps} $(PETSCLIB) $(MPILIB) $(NEOPZLIB) $(MULTITHREADINGLIB) $(GSLLIB) $(PROJ4LIB)
+InterpFromGridToMesh_matlab_la_LIBADD = ${deps} $(PETSCLIB) $(MPILIB) $(MULTITHREADINGLIB) $(NEOPZLIB) $(GSLLIB) $(PROJ4LIB)
 
 InterpFromMeshToMesh2d_matlab_la_SOURCES = ../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp
 InterpFromMeshToMesh2d_matlab_la_CXXFLAGS = ${AM_CXXFLAGS}
-InterpFromMeshToMesh2d_matlab_la_LIBADD = ${deps} $(PETSCLIB) $(MPILIB) $(NEOPZLIB) $(MULTITHREADINGLIB) $(GSLLIB) $(PROJ4LIB)
+InterpFromMeshToMesh2d_matlab_la_LIBADD = ${deps} $(PETSCLIB) $(MPILIB) $(MULTITHREADINGLIB) $(NEOPZLIB) $(GSLLIB) $(PROJ4LIB)
 
 InterpFromMeshToMesh3d_matlab_la_SOURCES = ../InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp
@@ -187,5 +187,5 @@
 InterpFromMesh2d_matlab_la_SOURCES = ../InterpFromMesh2d/InterpFromMesh2d.cpp
 InterpFromMesh2d_matlab_la_CXXFLAGS = ${AM_CXXFLAGS}
-InterpFromMesh2d_matlab_la_LIBADD = ${deps} $(PETSCLIB) $(MPILIB) $(NEOPZLIB) $(MULTITHREADINGLIB) $(GSLLIB) $(PROJ4LIB)
+InterpFromMesh2d_matlab_la_LIBADD = ${deps} $(PETSCLIB) $(MPILIB) $(MULTITHREADINGLIB) $(NEOPZLIB) $(GSLLIB) $(PROJ4LIB)
 
 IssmConfig_matlab_la_SOURCES = ../IssmConfig/IssmConfig.cpp
@@ -195,5 +195,5 @@
 ExpSimplify_matlab_la_SOURCES = ../ExpSimplify/ExpSimplify.cpp
 ExpSimplify_matlab_la_CXXFLAGS = ${AM_CXXFLAGS}
-ExpSimplify_matlab_la_LIBADD = ${deps} $(PETSCLIB) $(MPILIB) $(NEOPZLIB) $(GSLLIB) $(PROJ4LIB)
+ExpSimplify_matlab_la_LIBADD = ${deps} $(PETSCLIB) $(MPILIB) $(NEOPZLIB) $(GSLLIB) $(PROJ4LIB) $(NEOPZLIB)
 
 Kriging_matlab_la_SOURCES = ../Kriging/Kriging.cpp
@@ -203,9 +203,9 @@
 MeshPartition_matlab_la_SOURCES = ../MeshPartition/MeshPartition.cpp
 MeshPartition_matlab_la_CXXFLAGS = ${AM_CXXFLAGS}
-MeshPartition_matlab_la_LIBADD = ${deps} $(PETSCLIB) $(MPILIB) $(NEOPZLIB) $(METISLIB) $(GSLLIB) $(PROJ4LIB)
+MeshPartition_matlab_la_LIBADD = ${deps} $(PETSCLIB) $(MPILIB) $(METISLIB) $(NEOPZLIB) $(GSLLIB) $(PROJ4LIB)
 
 M1qn3_matlab_la_SOURCES = ../M1qn3/M1qn3.cpp
 M1qn3_matlab_la_CXXFLAGS = ${AM_CXXFLAGS}
-M1qn3_matlab_la_LIBADD = ${deps} $(PETSCLIB) $(MPILIB) $(NEOPZLIB) $(METISLIB) $(M1QN3LIB) $(GSLLIB) $(PROJ4LIB)
+M1qn3_matlab_la_LIBADD = ${deps} $(PETSCLIB) $(MPILIB) $(METISLIB) $(M1QN3LIB) $(NEOPZLIB) $(GSLLIB) $(PROJ4LIB)
 
 MeshProfileIntersection_matlab_la_SOURCES = ../MeshProfileIntersection/MeshProfileIntersection.cpp
@@ -219,5 +219,5 @@
 PointCloudFindNeighbors_matlab_la_SOURCES = ../PointCloudFindNeighbors/PointCloudFindNeighbors.cpp
 PointCloudFindNeighbors_matlab_la_CXXFLAGS = ${AM_CXXFLAGS}
-PointCloudFindNeighbors_matlab_la_LIBADD = ${deps} $(PETSCLIB) $(MPILIB) $(NEOPZLIB) $(MULTITHREADINGLIB) $(GSLLIB) $(PROJ4LIB)
+PointCloudFindNeighbors_matlab_la_LIBADD = ${deps} $(PETSCLIB) $(MPILIB) $(MULTITHREADINGLIB) $(NEOPZLIB) $(GSLLIB) $(PROJ4LIB)
 
 PropagateFlagsFromConnectivity_matlab_la_SOURCES = ../PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.cpp
@@ -233,10 +233,10 @@
 ShpRead_matlab_la_LIBADD = ${deps} $(SHAPELIBLIB) $(PETSCLIB) $(MPILIB) $(NEOPZLIB) $(GSLLIB) $(PROJ4LIB)
 
-TriMesh_matlab_la_SOURCES = ../TriMesh/TriMesh.cpp
-TriMesh_matlab_la_CXXFLAGS = ${AM_CXXFLAGS}
-TriMesh_matlab_la_LIBADD = ${deps} $(PETSCLIB) $(MPILIB) $(NEOPZLIB) $(TRIANGLELIB) $(GSLLIB) $(PROJ4LIB)
-
-TriMeshProcessRifts_matlab_la_SOURCES = ../TriMeshProcessRifts/TriMeshProcessRifts.cpp
-TriMeshProcessRifts_matlab_la_CXXFLAGS = ${AM_CXXFLAGS}
-TriMeshProcessRifts_matlab_la_LIBADD = ${deps} $(PETSCLIB) $(MPILIB) $(NEOPZLIB) $(GSLLIB) $(PROJ4LIB)
-#}}}
+Triangle_matlab_la_SOURCES = ../Triangle/Triangle.cpp
+Triangle_matlab_la_CXXFLAGS = ${AM_CXXFLAGS}
+Triangle_matlab_la_LIBADD = ${deps} $(PETSCLIB) $(MPILIB) $(TRIANGLELIB) $(NEOPZLIB) $(GSLLIB) $(PROJ4LIB)
+
+ProcessRifts_matlab_la_SOURCES = ../ProcessRifts/ProcessRifts.cpp
+ProcessRifts_matlab_la_CXXFLAGS = ${AM_CXXFLAGS}
+ProcessRifts_matlab_la_LIBADD = ${deps} $(PETSCLIB) $(MPILIB) $(NEOPZLIB) $(GSLLIB) $(PROJ4LIB)
+#}}}
Index: /issm/trunk/src/wrappers/matlab/io/ApiPrintf.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/ApiPrintf.cpp	(revision 22757)
+++ /issm/trunk/src/wrappers/matlab/io/ApiPrintf.cpp	(revision 22758)
@@ -15,5 +15,6 @@
 
 	/*use mexPrintf in matlab: */
-	mexPrintf(string);
+	//mexPrintf(string); /*Messes up percentages (like "interpolation progress: 100.00%")*/
+	printf("%s",string);
 	return;
 }
Index: /issm/trunk/src/wrappers/matlab/io/FetchMatlabData.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/FetchMatlabData.cpp	(revision 22757)
+++ /issm/trunk/src/wrappers/matlab/io/FetchMatlabData.cpp	(revision 22758)
@@ -88,5 +88,6 @@
 			}
 			/*Convert matlab n-dim array to double* matrix: */
-			MatlabNArrayToNArray(&outmatrix,&outmatrix_numel,&outmatrix_ndims,&outmatrix_size,dataref);
+			_error_("not supported");
+			//MatlabNArrayToNArray(&outmatrix,&outmatrix_numel,&outmatrix_ndims,&outmatrix_size,dataref);
 		}
 	}
@@ -223,5 +224,6 @@
 
 			/*Convert matlab n-dim array to bool* matrix: */
-			MatlabNArrayToNArray(&outmatrix,&outmatrix_numel,&outmatrix_ndims,&outmatrix_size,dataref);
+			_error_("not supported");
+			//MatlabNArrayToNArray(&outmatrix,&outmatrix_numel,&outmatrix_ndims,&outmatrix_size,dataref);
 		}
 	}
@@ -238,5 +240,6 @@
 
 			/*Convert matlab n-dim array to double* matrix: */
-			MatlabNArrayToNArray(&doublematrix,&outmatrix_numel,&outmatrix_ndims,&outmatrix_size,dataref);
+			_error_("not supported");
+			//MatlabNArrayToNArray(&doublematrix,&outmatrix_numel,&outmatrix_ndims,&outmatrix_size,dataref);
 
 			/*Convert double matrix into bool matrix: */
@@ -416,5 +419,6 @@
 
 		/*Convert matlab n-dim array to char* matrix: */
-		MatlabNArrayToNArray(&outmatrix,&outmatrix_numel,&outmatrix_ndims,&outmatrix_size,dataref);
+		_error_("not supported");
+		//MatlabNArrayToNArray(&outmatrix,&outmatrix_numel,&outmatrix_ndims,&outmatrix_size,dataref);
 	}
 	else{
@@ -537,5 +541,4 @@
 	FetchData(&bamgopts->gradation,mxGetField(dataref,0,"gradation"));
 	FetchData(&bamgopts->Hessiantype,mxGetField(dataref,0,"Hessiantype"));
-	FetchData(&bamgopts->MaxCornerAngle,mxGetField(dataref,0,"MaxCornerAngle"));
 	FetchData(&bamgopts->maxnbv,mxGetField(dataref,0,"maxnbv"));
 	FetchData(&bamgopts->maxsubdiv,mxGetField(dataref,0,"maxsubdiv"));
@@ -545,9 +548,7 @@
 	FetchData(&bamgopts->omega,mxGetField(dataref,0,"omega"));
 	FetchData(&bamgopts->power,mxGetField(dataref,0,"power"));
-	FetchData(&bamgopts->random,mxGetField(dataref,0,"random"));
 	FetchData(&bamgopts->verbose,mxGetField(dataref,0,"verbose"));
 
 	FetchData(&bamgopts->Crack,mxGetField(dataref,0,"Crack"));
-	FetchData(&bamgopts->geometricalmetric,mxGetField(dataref,0,"geometricalmetric"));
 	FetchData(&bamgopts->KeepVertices,mxGetField(dataref,0,"KeepVertices"));
 	FetchData(&bamgopts->splitcorners,mxGetField(dataref,0,"splitcorners"));
@@ -641,4 +642,34 @@
 }
 /*}}}*/
+void FetchChacoData(int* pnvtxs,int** padjacency,int** pstart,float** pewgts,const mxArray* A_IN, const mxArray* EWGTS_IN){/*{{{*/
+
+	/*Fetch adjacency matrix: */
+	int      nvtxs       = mxGetN(A_IN);
+	mwIndex* mwstart     = mxGetJc(A_IN);
+	mwIndex* mwadjacency = mxGetIr(A_IN);
+	int      nzmax       = mxGetNzmax(A_IN);
+
+	int* start = xNew<int>(nvtxs+1);
+	for(int i=0;i<nvtxs+1;i++) start[i]=(int)mwstart[i];
+
+	int* adjacency = xNew<int>(nzmax);
+	for(int i=0; i<nzmax; i++) adjacency[i]= (int)mwadjacency[i];
+
+	/*Get edges weights*/
+	int nedges = start[nvtxs];
+	float* ewgts = NULL;
+	if(!mxIsEmpty(EWGTS_IN)){
+		ewgts = xNewZeroInit<float>(nedges);
+		double* doublepointer = mxGetPr(A_IN);
+		for(int i = 0; i<nedges;i++) ewgts[i] = (float)doublepointer[i];
+	}
+
+	/*Assign output pointers*/
+	*pnvtxs     = nvtxs;
+	*padjacency = adjacency;
+	*pstart     = start;
+	*pewgts     = ewgts;
+}
+/*}}}*/
 
 /*Toolkit*/
@@ -760,266 +791,34 @@
 	return 1;
 }/*}}}*/
-/*FUNCTION MatlabNArrayToNArray(double** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){{{*/
-int MatlabNArrayToNArray(double** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){
-
-	int  i,j,rows,cols;
-	int  numel,ndims;
-	int *size,*dims;
-	double* mxmatrix_ptr=NULL;
-	const mwSize* ipt=NULL;
-
-	/*output: */
-	double* matrix=NULL;
-
-	/*matlab indices: */
-	mwIndex *ir    = NULL;
-	mwIndex *jc    = NULL;
-	double  *pr    = NULL;
-	int      count;
-
-	/*get Matlab matrix information: */
-	numel=mxGetNumberOfElements(mxmatrix);
-	ndims=mxGetNumberOfDimensions(mxmatrix);
-	ipt  =mxGetDimensions(mxmatrix);
-	size =xNew<int>(ndims);
-	for (i=0;i<ndims;i++) size[i]=(int)ipt[i];
-
-	/*Ok, first check if we are dealing with a sparse or full matrix: */
-	if (mxIsSparse(mxmatrix)){
-
-		/*Dealing with sparse matrix: recover size first: */
-		rows = mxGetM(mxmatrix);
-		cols = mxGetN(mxmatrix);
-
-		matrix=xNewZeroInit<double>(rows*cols);
-
-		/*Now, get ir,jc and pr: */
-		ir = mxGetIr(mxmatrix);
-		jc = mxGetJc(mxmatrix);
-		pr = mxGetPr(mxmatrix);
-
-		/*Now, start inserting data into double* matrix: */
-		count=0;
-		for(i=0;i<cols;i++){
-			for(j=0;j<(jc[i+1]-jc[i]);j++){
-				*(matrix+rows*ir[count]+i)=pr[count];
-				count++;
-			}
-		}
-
-	}
-	else{
-
-		/*Dealing with dense matrix: recover pointer and size: */
-		mxmatrix_ptr=(double*)mxGetPr(mxmatrix);
-
-		/*Create serial matrix: */
-		matrix=xNewZeroInit<double>(numel);
-
-		dims=xNew<int>(ndims);
-		for(i=0;i<numel;i++){
-			ColumnWiseDimsFromIndex(dims,i,size,ndims);
-			j = IndexFromRowWiseDims(dims,size,ndims);
-			matrix[j]=(double)mxmatrix_ptr[i];
-		}
-		xDelete<int>(dims);
-	}
-
-	/*Assign output pointer: */
-	*pmatrix       = matrix;
-	*pmatrix_numel = numel;
-	*pmatrix_ndims = ndims;
-	*pmatrix_size  = size;
-
-	return 1;
-}
-/*}}}*/
-/*FUNCTION MatlabNArrayToNArray(bool** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){{{*/
-int MatlabNArrayToNArray(bool** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){
-
-	int  i,j,rows,cols;
-	int  numel,ndims;
-	int *size,*dims;
-	bool* mxmatrix_ptr=NULL;
-	const mwSize* ipt=NULL;
-
-	/*output: */
-	bool* matrix=NULL;
-
-	/*matlab indices: */
-	mwIndex *ir    = NULL;
-	mwIndex *jc    = NULL;
-	bool    *pm    = NULL;
-	int      count;
-
-	/*get Matlab matrix information: */
-	numel = mxGetNumberOfElements(mxmatrix);
-	ndims = mxGetNumberOfDimensions(mxmatrix);
-	ipt   = mxGetDimensions(mxmatrix);
-	size  = xNew<int>(ndims);
-	for (i=0;i<ndims;i++) size[i]=(int)ipt[i];
-
-	/*Ok, first check if we are dealing with a sparse or full matrix: */
-	if (mxIsSparse(mxmatrix)){
-
-		/*Dealing with sparse matrix: recover size first: */
-		rows=mxGetM(mxmatrix);
-		cols=mxGetN(mxmatrix);
-		matrix=xNewZeroInit<bool>(rows*cols);
-
-		/*Now, get ir,jc and pm: */
-		ir=mxGetIr(mxmatrix);
-		jc=mxGetJc(mxmatrix);
-		pm=(bool*)mxGetData(mxmatrix);
-
-		/*Now, start inserting data into bool* matrix: */
-		count=0;
-		for(i=0;i<cols;i++){
-			for(j=0;j<(jc[i+1]-jc[i]);j++){
-				matrix[rows*ir[count]+i]=pm[count];
-				count++;
-			}
-		}
-	}
-	else{
-
-		/*Dealing with dense matrix: recover pointer and size: */
-		mxmatrix_ptr=(bool*)mxGetData(mxmatrix);
-
-		/*Create serial matrix: */
-		matrix=xNew<bool>(numel);
-		dims=xNew<int>(ndims);
-		for(i=0;i<numel;i++){
-			ColumnWiseDimsFromIndex(dims,i,size,ndims);
-			j=IndexFromRowWiseDims(dims,size,ndims);
-			matrix[j]=(bool)mxmatrix_ptr[i];
-		}
-		xDelete<int>(dims);
-	}
-
-	/*Assign output pointer: */
-	*pmatrix       = matrix;
-	*pmatrix_numel = numel;
-	*pmatrix_ndims = ndims;
-	*pmatrix_size  = size;
-
-	return 1;
-}
-/*}}}*/
-/*FUNCTION MatlabNArrayToNArray(char** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){{{*/
-int MatlabNArrayToNArray(char** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){
-
-	int           i,j,rows,cols;
-	int           numel,ndims;
-	int          *size , *dims;
-	mxChar       *mxmatrix_ptr = NULL;
-	const mwSize *ipt          = NULL;
-
-	/*output: */
-	char* matrix=NULL;
-
-	/*matlab indices: */
-	mwIndex *ir    = NULL;
-	mwIndex *jc    = NULL;
-	char    *pm    = NULL;
-	int      count;
-
-	/*get Matlab matrix information: */
-	numel = mxGetNumberOfElements(mxmatrix);
-	ndims = mxGetNumberOfDimensions(mxmatrix);
-	ipt   = mxGetDimensions(mxmatrix);
-	size  = xNew<int>(ndims);
-	for (i=0;i<ndims;i++) size[i]=(int)ipt[i];
-
-	/*Ok, first check if we are dealing with a sparse or full matrix: */
-	if (mxIsSparse(mxmatrix)){
-
-		/*Dealing with sparse matrix: recover size first: */
-		rows = mxGetM(mxmatrix);
-		cols = mxGetN(mxmatrix);
-		matrix=xNew<char>(rows*cols);
-
-		/*Now, get ir,jc and pm: */
-		ir = mxGetIr(mxmatrix);
-		jc = mxGetJc(mxmatrix);
-		pm = (char*)mxGetData(mxmatrix);
-
-		/*Now, start inserting data into char* matrix: */
-		count=0;
-		for(i=0;i<cols;i++){
-			for(j=0;j<(jc[i+1]-jc[i]);j++){
-				matrix[rows*ir[count]+i]=(char)pm[count];
-				count++;
-			}
-		}
-	}
-	else{
-		/*Dealing with dense matrix: recover pointer and size: */
-		mxmatrix_ptr=mxGetChars(mxmatrix);
-
-		/*Create serial matrix: */
-		matrix=xNew<char>(numel+1);
-		matrix[numel]='\0';
-
-		/*looping code adapted from Matlab example explore.c: */
-		int elements_per_page = size[0] * size[1];
-		/* total_number_of_pages = size[2] x size[3] x ... x size[N-1] */
-		int total_number_of_pages = 1;
-		for (i=2; i<ndims; i++) {
-			total_number_of_pages *= size[i];
-		}
-
-		i=0;
-		for (int page=0; page < total_number_of_pages; page++) {
-			int row;
-			/* On each page, walk through each row. */
-			for (row=0; row<size[0]; row++)  {
-				int column;
-				j = (page * elements_per_page) + row;
-
-				/* Walk along each column in the current row. */
-				for (column=0; column<size[1]; column++) {
-					*(matrix+i++)=(char)*(mxmatrix_ptr+j);
-					j += size[0];
-				}
-			}
-		}
-	}
-
-	/*Assign output pointer: */
-	*pmatrix       = matrix;
-	*pmatrix_numel = numel;
-	*pmatrix_ndims = ndims;
-	*pmatrix_size  = size;
-
-	return 1;
-}
-/*}}}*/
 /*FUNCTION mxGetAssignedField{{{*/
 mxArray* mxGetAssignedField(const mxArray* pmxa_array,int number,const char* field){
 
-	//output
-	mxArray* mxfield=NULL;
-
-	//input
-	mxArray    *inputs[2];
-	mxArray    *pindex      = NULL;
-	const char *fnames[2];
-	mwSize      ndim        = 2;
-	mwSize      onebyone[2] = {1,1};
-
-	//We want to call the subsasgn method, and get the returned array.This ensures that if we are running 
-	//large sized problems, the data is truly loaded from disk by the model subsasgn class method.
-	inputs[0]=(mxArray*)pmxa_array; //this is the model
-
-	//create index structure used in the assignment (index.type='.' and index.subs='x' for field x for ex)
-	fnames[0] = "type";
-	fnames[1] = "subs";
-	pindex=mxCreateStructArray( ndim,onebyone,2,fnames);
-	mxSetField( pindex, 0, "type",mxCreateString("."));
-	mxSetField( pindex, 0, "subs",mxCreateString(field));
-	inputs[1]=pindex;
-
-	mexCallMATLAB( 1, &mxfield, 2, (mxArray**)inputs, "subsref");
+	/*Output*/
+	mxArray *mxfield = NULL;
+
+	if(mxIsStruct(pmxa_array)){
+		mxfield = mxGetField(pmxa_array,number,field);
+	}
+	else{
+		/*This is an object, mxGetField returns NULL in old version of matlab (we do not have access to them)*/
+
+		/*Intermediaries*/
+		mxArray    *inputs[2];
+		mwSize      ndim        = 2;
+		mwSize      onebyone[2] = {1,1};
+
+		/*create index structure used in the assignment (index.type='.' and index.subs='x' for field x*/
+		const char *fnames[2];
+		fnames[0] = "type"; fnames[1] = "subs";
+		mxArray* pindex=mxCreateStructArray( ndim,onebyone,2,fnames);
+		mxSetField( pindex, 0, "type",mxCreateString("."));
+		mxSetField( pindex, 0, "subs",mxCreateString(field));
+		inputs[0]=(mxArray*)pmxa_array; //this is the model
+		inputs[1]=pindex;
+
+		mexCallMATLAB( 1, &mxfield, 2, (mxArray**)inputs, "subsref");
+	}
+
+	if(mxfield == NULL) _error_("Could not find field "<< field <<" in structure");
 
 	return mxfield;
@@ -1077,8 +876,6 @@
 GenericOption<char*>* OptionCharParse( char* name, const mxArray* prhs[]){ /*{{{*/
 
-	GenericOption<char*>  *ochar = NULL;
-
 	/*check and parse the name  */
-	ochar=new GenericOption<char*>();
+	GenericOption<char*>* ochar=new GenericOption<char*>();
 	ochar->name =xNew<char>(strlen(name)+1);
 	memcpy(ochar->name,name,(strlen(name)+1)*sizeof(char));
@@ -1088,99 +885,13 @@
 		_error_("Value of option \"" << ochar->name  << "\" must be class \"char\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
 	}
-	FetchData(&ochar->value,&ochar->numel,&ochar->ndims,&ochar->size,prhs[0]);
+	//FetchData(&ochar->value,&ochar->numel,&ochar->ndims,&ochar->size,prhs[0]);
+	FetchData(&ochar->value,prhs[0]);
+	ochar->numel = strlen(name);
+	ochar->ndims = 2;
+	ochar->size = xNew<int>(2);
+	ochar->size[0] = ochar->numel;
+	ochar->size[1] = 1;
 
 	return(ochar);
-}/*}}}*/
-GenericOption<Options**>* OptionStructParse( char* name, const mxArray* prhs[]){ /*{{{*/
-
-	int            i;
-	char           namei[161];
-	Option*                   option      = NULL;
-	GenericOption<Options**>  *ostruct    = NULL;
-	const mwSize  *ipt        = NULL;
-	const mxArray *structi;
-	mwIndex        sindex;
-
-	/*check and parse the name  */
-	ostruct=new GenericOption<Options**>();
-	ostruct->name =xNew<char>(strlen(name)+1);
-	memcpy(ostruct->name,name,(strlen(name)+1)*sizeof(char));
-
-	/*check and parse the value  */
-	if (!mxIsClass(prhs[0],"struct")){
-		_error_("Value of option \"" << ostruct->name  << "\" must be class \"struct\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
-	}
-	ostruct->numel=mxGetNumberOfElements(prhs[0]);
-	ostruct->ndims=mxGetNumberOfDimensions(prhs[0]);
-	ipt           =mxGetDimensions(prhs[0]);
-	ostruct->size =xNew<int>(ostruct->ndims);
-	for (i=0; i<ostruct->ndims; i++) ostruct->size[i]=(int)ipt[i];
-	if (ostruct->numel) ostruct->value=xNew<Options*>(ostruct->numel);
-
-	/*loop through and process each element of the struct array  */
-	for (sindex=0; sindex<ostruct->numel; sindex++) {
-		ostruct->value[sindex]=new Options;
-
-		/*loop through and process each field for the element  */
-		for (i=0; i<mxGetNumberOfFields(prhs[0]); i++) {
-			sprintf(namei,"%s.%s",name,mxGetFieldNameByNumber(prhs[0],i));
-			structi=mxGetFieldByNumber(prhs[0],sindex,i);
-
-			option=(Option*)OptionParse(namei,&structi);
-			ostruct->value[sindex]->AddObject((Object*)option);
-			option=NULL;
-		}
-	}
-
-	return(ostruct);
-}/*}}}*/
-GenericOption<Options*>* OptionCellParse( char* name, const mxArray* prhs[]){ /*{{{*/
-
-	int            i;
-	int           *dims;
-	char           namei[161];
-	char           cstr[81];
-	GenericOption<Options*> *ocell      = NULL;
-	Option        *option     = NULL;
-	const mwSize  *ipt        = NULL;
-	const mxArray *celli;
-	mwIndex        cindex;
-
-	/*check and parse the name  */
-	ocell=new GenericOption<Options*>();
-	ocell->name =xNew<char>(strlen(name)+1);
-	memcpy(ocell->name,name,(strlen(name)+1)*sizeof(char));
-
-	/*check and parse the value  */
-	if (!mxIsClass(prhs[0],"cell")){
-		_error_("Value of option \"" << ocell->name  << "\" must be class \"cell\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
-	}
-
-	ocell->numel=mxGetNumberOfElements(prhs[0]);
-	ocell->ndims=mxGetNumberOfDimensions(prhs[0]);
-	ipt         =mxGetDimensions(prhs[0]);
-	ocell->size =xNew<int>(ocell->ndims);
-	for (i=0; i<ocell->ndims; i++) ocell->size[i]=(int)ipt[i];
-	ocell->value=new Options;
-
-	/*loop through and process each element of the cell array  */
-	dims=xNew<int>(ocell->ndims);
-	for (cindex=0; cindex<ocell->numel; cindex++) {
-		ColumnWiseDimsFromIndex(dims,(int)cindex,ocell->size,ocell->ndims);
-		StringFromDims(cstr,dims,ocell->ndims);
-		#ifdef _INTEL_WIN_
-			_snprintf(namei,161,"%s%s",name,cstr);
-		#else
-			snprintf(namei,161,"%s%s",name,cstr);
-		#endif
-		celli=mxGetCell(prhs[0],cindex);
-
-		option=(Option*)OptionParse(namei,&celli);
-		ocell->value->AddObject((Object*)option);
-		option=NULL;
-	}
-	xDelete<int>(dims);
-
-	return(ocell);
 }/*}}}*/
 Option* OptionParse(char* name, const mxArray* prhs[]){ /*{{{*/
@@ -1198,15 +909,6 @@
 	else if(mxIsClass(prhs[0],"char"))
 	 option=(Option*)OptionCharParse(name,prhs);
-	else if(mxIsClass(prhs[0],"struct"))
-	 option=(Option*)OptionStructParse(name,prhs);
-	else if(mxIsClass(prhs[0],"cell"))
-	 option=(Option*)OptionCellParse(name,prhs);
 	else {
-		_printf0_("  Converting value of option \"" << name << "\" from unrecognized class \"" << mxGetClassName(prhs[0]) << "\" to class \"" << "struct" << "\".\n");
-		if (!mexCallMATLAB(1,lhs,1,(mxArray**)prhs,"struct")) {
-			option=(Option*)OptionStructParse(name,(const mxArray**)lhs);
-			mxDestroyArray(lhs[0]);
-		}
-		else _error_("Second argument value of option \""<< name <<"\" is of unrecognized class \""<< mxGetClassName(prhs[0]) <<"\".");
+		_error_("Second argument value of option \""<< name <<"\" is of unrecognized class \""<< mxGetClassName(prhs[0]) <<"\".");
 	}
 
Index: /issm/trunk/src/wrappers/matlab/io/WriteMatlabData.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/WriteMatlabData.cpp	(revision 22757)
+++ /issm/trunk/src/wrappers/matlab/io/WriteMatlabData.cpp	(revision 22758)
@@ -88,4 +88,27 @@
 /*FUNCTION WriteData(mxArray** pdataref,int* vector, int M){{{*/
 void WriteData(mxArray** pdataref,int* vector, int M){
+
+	mxArray* dataref       = NULL;
+	double*  vector_matlab = NULL;
+
+	if(vector){
+
+		/*create the matlab vector with Matlab's memory manager */
+		vector_matlab=(double*)mxMalloc(M*sizeof(double));
+		for(int i=0;i<M;i++) vector_matlab[i]=double(vector[i]);
+		dataref = mxCreateDoubleMatrix(0,0,mxREAL);
+		mxSetM(dataref,(mwSize)M);
+		mxSetN(dataref,(mwSize)1);
+		mxSetPr(dataref,vector_matlab);
+	}
+	else{
+		dataref = mxCreateDoubleMatrix(0,0,mxREAL);
+	}
+
+	*pdataref=dataref;
+}
+/*}}}*/
+/*FUNCTION WriteData(mxArray** pdataref,short* vector, int M){{{*/
+void WriteData(mxArray** pdataref,short* vector, int M){
 
 	mxArray* dataref       = NULL;
Index: /issm/trunk/src/wrappers/matlab/io/matlabio.h
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/matlabio.h	(revision 22757)
+++ /issm/trunk/src/wrappers/matlab/io/matlabio.h	(revision 22758)
@@ -23,4 +23,5 @@
 void WriteData(mxArray** pdataref,IssmSeqVec<double>* vector);
 void WriteData(mxArray** pdataref,double* vector, int M);
+void WriteData(mxArray** pdataref,short* vector, int M);
 void WriteData(mxArray** pdataref,int* vector, int M);
 void WriteData(mxArray** pdataref,int integer);
@@ -53,4 +54,5 @@
 void FetchData(Options** poptions,int istart, int nrhs,const mxArray** pdataref);
 void FetchData(Contours** pcontours,const mxArray* dataref);
+void FetchChacoData(int* pnvtxs,int** padjacency,int** pstart,float** pewgts,const mxArray* A_IN, const mxArray* EWGTS_IN);
 
 Option* OptionParse(char* name, const mxArray* prhs[]);
@@ -59,6 +61,4 @@
 GenericOption<bool*>*     OptionLogicalParse( char* name, const mxArray* prhs[]);
 GenericOption<char*>*     OptionCharParse( char* name, const mxArray* prhs[]);
-GenericOption<Options**>* OptionStructParse( char* name, const mxArray* prhs[]);
-GenericOption<Options*>*  OptionCellParse( char* name, const mxArray* prhs[]);
 
 mxArray* mxGetAssignedField(const mxArray* pmxa_array,int number, const char* field);
@@ -73,7 +73,4 @@
 /*Matlab to double* routines: */
 int MatlabMatrixToDoubleMatrix(double** pmatrix,int* pmatrix_rows,int* pmatrix_cols,const mxArray* mxmatrix);
-int MatlabNArrayToNArray(double** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix);
-int MatlabNArrayToNArray(bool** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix);
-int MatlabNArrayToNArray(char** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix);
 
 /*Print*/
Index: /issm/trunk/src/wrappers/python/Makefile.am
===================================================================
--- /issm/trunk/src/wrappers/python/Makefile.am	(revision 22757)
+++ /issm/trunk/src/wrappers/python/Makefile.am	(revision 22758)
@@ -39,8 +39,13 @@
 						InterpFromMeshToGrid_python.la\
 						IssmConfig_python.la\
+						MeshPartition_python.la\
 						MeshProfileIntersection_python.la\
 						NodeConnectivity_python.la\
-						TriMesh_python.la\
-						TriMeshProcessRifts_python.la
+						Triangle_python.la\
+						ProcessRifts_python.la
+
+if CHACO
+lib_LTLIBRARIES += Chaco_python.la
+endif
 endif 
 #}}}
@@ -101,4 +106,10 @@
 BamgTriangulate_python_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
 
+if CHACO
+Chaco_python_la_SOURCES = ../Chaco/Chaco.cpp
+Chaco_python_la_CXXFLAGS = ${AM_CXXFLAGS}
+Chaco_python_la_LIBADD = ${deps} $(MPILIB)  $(CHACOLIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
+endif
+
 ContourToMesh_python_la_SOURCES = ../ContourToMesh/ContourToMesh.cpp
 ContourToMesh_python_la_CXXFLAGS = ${AM_CXXFLAGS}
@@ -133,4 +144,8 @@
 IssmConfig_python_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
 
+MeshPartition_python_la_SOURCES = ../MeshPartition/MeshPartition.cpp
+MeshPartition_python_la_CXXFLAGS = ${AM_CXXFLAGS}
+MeshPartition_python_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
+
 MeshProfileIntersection_python_la_SOURCES = ../MeshProfileIntersection/MeshProfileIntersection.cpp
 MeshProfileIntersection_python_la_CXXFLAGS = ${AM_CXXFLAGS}
@@ -141,10 +156,10 @@
 NodeConnectivity_python_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
 
-TriMesh_python_la_SOURCES = ../TriMesh/TriMesh.cpp
-TriMesh_python_la_CXXFLAGS = ${AM_CXXFLAGS}
-TriMesh_python_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(TRIANGLELIB) $(GSLLIB) $(PROJ4LIB)
+Triangle_python_la_SOURCES = ../Triangle/Triangle.cpp
+Triangle_python_la_CXXFLAGS = ${AM_CXXFLAGS}
+Triangle_python_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(TRIANGLELIB) $(GSLLIB) $(PROJ4LIB)
 
-TriMeshProcessRifts_python_la_SOURCES = ../TriMeshProcessRifts/TriMeshProcessRifts.cpp
-TriMeshProcessRifts_python_la_CXXFLAGS = ${AM_CXXFLAGS}
-TriMeshProcessRifts_python_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
+ProcessRifts_python_la_SOURCES = ../ProcessRifts/ProcessRifts.cpp
+ProcessRifts_python_la_CXXFLAGS = ${AM_CXXFLAGS}
+ProcessRifts_python_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
 #}}}
Index: /issm/trunk/src/wrappers/python/io/FetchPythonData.cpp
===================================================================
--- /issm/trunk/src/wrappers/python/io/FetchPythonData.cpp	(revision 22757)
+++ /issm/trunk/src/wrappers/python/io/FetchPythonData.cpp	(revision 22758)
@@ -44,4 +44,34 @@
 	/*output: */
 	*pscalar=dscalar;
+}
+/*}}}*/
+/*FUNCTION FetchData(float* pscalar,PyObject* py_float){{{*/
+void FetchData(float* pscalar,PyObject* py_float){
+
+	float fscalar;
+
+	/*return internal value: */
+	if  (PyFloat_Check(py_float))
+	 fscalar=PyFloat_AsDouble(py_float);
+	else if (PyLong_Check(py_float)){
+		#if _PYTHON_MAJOR_ == 3
+		fscalar=(float)PyLong_AsLong(py_float);
+		#else
+		fscalar=(float)PyLong_AsDouble(py_float);
+		#endif
+	}
+	else if (PyInt_Check(py_float))
+	 fscalar=(float)PyInt_AsLong(py_float);
+	else if (PyBool_Check(py_float))
+	 fscalar=(float)PyLong_AsLong(py_float);
+	else if (PyTuple_Check(py_float) && (int)PyTuple_Size(py_float)==1)
+	 FetchData(&fscalar,PyTuple_GetItem(py_float,(Py_ssize_t)0));
+	else if (PyList_Check(py_float) && (int)PyList_Size(py_float)==1)
+	 FetchData(&fscalar,PyList_GetItem(py_float,(Py_ssize_t)0));
+	else
+	 _error_("unrecognized float type in input!");
+
+	/*output: */
+	*pscalar=fscalar;
 }
 /*}}}*/
@@ -464,4 +494,89 @@
 }
 /*}}}*/
+/*FUNCTION FetchData(float** pvector,int* pM, PyObject* py_vector){{{*/
+void FetchData(float** pvector,int* pM,PyObject* py_vector){
+
+	/*output: */
+	float* vector=NULL;
+	int M;
+	int ndim;
+	npy_intp*  dims=NULL;
+
+	/*intermediary:*/
+	long*   lvector=NULL;
+	bool*   bvector=NULL;
+	double* dvector=NULL;
+	int i;
+	PyObject* py_vector2=NULL;
+
+	if     (PyArray_Check((PyArrayObject*)py_vector)) {
+		/*retrieve dimensions: */
+		ndim=PyArray_NDIM((const PyArrayObject*)py_vector);
+		if      (ndim==1) {
+			dims=PyArray_DIMS((PyArrayObject*)py_vector);
+			M=dims[0]; 
+		}
+		else if (ndim==2) {
+			dims=PyArray_DIMS((PyArrayObject*)py_vector);
+			if (dims[1]==1)
+			 M=dims[0]; 
+			else
+			 _error_("expecting an Mx1 matrix or M vector in input!");
+		}
+		else
+		 _error_("expecting an Mx1 matrix or M vector in input!");
+
+		if (M) {
+			if (!PyArray_ISCONTIGUOUS((PyArrayObject*)py_vector)) {
+				py_vector2=PyArray_ContiguousFromAny(py_vector,NPY_LONG,ndim,ndim);
+				py_vector=py_vector2;
+			}
+
+			if      (PyArray_TYPE((PyArrayObject*)py_vector) == NPY_DOUBLE) {
+				/*retrieve internal value: */
+				dvector=(double*)PyArray_DATA((PyArrayObject*)py_vector);
+
+				/*transform into int vector: */
+				vector=xNew<float>(M);
+				for(i=0;i<M;i++)vector[i]=(float)lvector[i];
+			}
+
+			else if (PyArray_TYPE((PyArrayObject*)py_vector) == NPY_LONG) {
+				/*retrieve internal value: */
+				lvector=(long*)PyArray_DATA((PyArrayObject*)py_vector);
+
+				/*transform into int vector: */
+				vector=xNew<float>(M);
+				for(i=0;i<M;i++)vector[i]=(float)lvector[i];
+			}
+
+			else if (PyArray_TYPE((PyArrayObject*)py_vector) == NPY_BOOL) {
+				/*retrieve internal value: */
+				bvector=(bool*)PyArray_DATA((PyArrayObject*)py_vector);
+
+				/*transform into int vector: */
+				vector=xNew<float>(M);
+				for(i=0;i<M;i++)vector[i]=(float)bvector[i];
+			}
+
+			else
+			 _error_("unrecognized int pyarray type in input!");
+
+			if(py_vector2) delete(py_vector2);
+		}
+		else
+		 vector=NULL;
+	}
+	else{
+		M=1;
+		vector=xNew<float>(M);
+		FetchData(&(vector[0]),py_vector);
+	}
+
+	/*output: */
+	if(pM)*pM=M;
+	if(pvector)*pvector=vector;
+}
+/*}}}*/
 /*FUNCTION FetchData(int** pvector,int* pM, PyObject* py_vector){{{*/
 void FetchData(int** pvector,int* pM,PyObject* py_vector){
@@ -692,5 +807,4 @@
 	FetchData(&bamgopts->gradation,PyDict_GetItemString(py_dict,"gradation"));
 	FetchData(&bamgopts->Hessiantype,PyDict_GetItemString(py_dict,"Hessiantype"));
-	FetchData(&bamgopts->MaxCornerAngle,PyDict_GetItemString(py_dict,"MaxCornerAngle"));
 	FetchData(&bamgopts->maxnbv,PyDict_GetItemString(py_dict,"maxnbv"));
 	FetchData(&bamgopts->maxsubdiv,PyDict_GetItemString(py_dict,"maxsubdiv"));
@@ -700,9 +814,7 @@
 	FetchData(&bamgopts->omega,PyDict_GetItemString(py_dict,"omega"));
 	FetchData(&bamgopts->power,PyDict_GetItemString(py_dict,"power"));
-	FetchData(&bamgopts->random,PyDict_GetItemString(py_dict,"random"));
 	FetchData(&bamgopts->verbose,PyDict_GetItemString(py_dict,"verbose"));
 
 	FetchData(&bamgopts->Crack,PyDict_GetItemString(py_dict,"Crack"));
-	FetchData(&bamgopts->geometricalmetric,PyDict_GetItemString(py_dict,"geometricalmetric"));
 	FetchData(&bamgopts->KeepVertices,PyDict_GetItemString(py_dict,"KeepVertices"));
 	FetchData(&bamgopts->splitcorners,PyDict_GetItemString(py_dict,"splitcorners"));
@@ -812,4 +924,7 @@
 }
 /*}}}*/
+void FetchChacoData(int* pnvtxs,int** padjacency,int** pstart,float** pewgts,PyObject* A_IN,PyObject* EWGTS_IN){
+	_error_("Nathan... I need your help here");
+}
 
 /*Python version dependent: */
Index: /issm/trunk/src/wrappers/python/io/WritePythonData.cpp
===================================================================
--- /issm/trunk/src/wrappers/python/io/WritePythonData.cpp	(revision 22757)
+++ /issm/trunk/src/wrappers/python/io/WritePythonData.cpp	(revision 22758)
@@ -93,4 +93,21 @@
 	dim=(npy_intp)M;
 	array=PyArray_SimpleNewFromData(1,&dim,NPY_DOUBLE,vector_python);
+
+	PyTuple_SetItem(py_tuple, index, array);
+
+}/*}}}*/
+/*FUNCTION WriteData(PyObject* py_tuple,int index, short* vector, int M){{{*/
+void WriteData(PyObject* py_tuple, int index,short* vector, int M){
+
+	long* lvector=NULL;
+	npy_intp dim=10;
+	PyObject* array=NULL;
+
+	/*transform into long matrix: */
+	lvector=xNew<long>(M);
+	for(int i=0;i<M;i++)lvector[i]=(long)vector[i];
+
+	dim=(npy_intp)M;
+	array=PyArray_SimpleNewFromData(1,&dim,NPY_INT64,lvector);
 
 	PyTuple_SetItem(py_tuple, index, array);
Index: /issm/trunk/src/wrappers/python/io/pythonio.h
===================================================================
--- /issm/trunk/src/wrappers/python/io/pythonio.h	(revision 22757)
+++ /issm/trunk/src/wrappers/python/io/pythonio.h	(revision 22758)
@@ -22,4 +22,5 @@
 void WriteData(PyObject* py_tuple,int index, int integer);
 void WriteData(PyObject* py_tuple,int index, double* vector, int M);
+void WriteData(PyObject* py_tuple,int index, short* vector, int M);
 void WriteData(PyObject* py_tuple,int index, int* vector, int M);
 void WriteData(PyObject* py_tuple,int index, char* string);
@@ -35,8 +36,10 @@
 void FetchData(bool** pmatrix,int* pM,int *pN,PyObject* py_matrix);
 void FetchData(double** pvector,int* pM,PyObject* py_ref);
+void FetchData(float** pvector,int* pM,PyObject* dataref);
 void FetchData(int** pvector,int* pM,PyObject* py_ref);
 void FetchData(bool** pvector,int* pM,PyObject* py_ref);
 void FetchData(char** pstring,PyObject* py_unicode);
 void FetchData(double* pscalar,PyObject* py_float);
+void FetchData(short* pscalar,PyObject* py_float);
 void FetchData(int* pscalar,PyObject* py_long);
 void FetchData(bool* pbool,PyObject* py_boolean);
@@ -46,4 +49,5 @@
 void FetchData(Options** poptions,int istart, int nrhs,PyObject* py_tuple);
 void FetchData(Contours** pcontours,PyObject* py_list);
+void FetchChacoData(int* pnvtxs,int** padjacency,int** pstart,float** pewgts,PyObject* A_IN,PyObject* EWGTS_IN);
 
 int CheckNumPythonArguments(PyObject* inputs,int NRHS, void (*function)( void ));
Index: /issm/trunk/test/Exp/Ais.exp
===================================================================
--- /issm/trunk/test/Exp/Ais.exp	(revision 22758)
+++ /issm/trunk/test/Exp/Ais.exp	(revision 22758)
@@ -0,0 +1,371 @@
+## Name:Antarctica
+## Icon:0
+# Points Count	Value
+366	25000.
+# X pos	Y pos
+-1016913.83085	878162.517102
+-1065362.784298	896183.164421
+-1121788.089839	882889.244268
+-1175850.031797	870777.005905
+-1240842.530326	864573.1765
+-1289586.904222	847734.210973
+-1347784.73245	830008.984101
+-1399778.731273	805193.666481
+-1457976.559501	786877.598714
+-1493427.013244	838280.756641
+-1542171.387141	859255.608439
+-1581757.727154	899728.209796
+-1624002.851198	937542.027121
+-1670088.441063	968856.594594
+-1722082.439886	981855.0943
+-1774962.700053	1003420.786994
+-1825479.596637	1024691.059239
+-1868906.402472	1054233.104025
+-1927399.651148	1063686.558357
+-1989437.945198	1079343.842093
+-2010412.796996	1125724.852407
+-2055612.125518	1149063.067788
+-2098448.090457	1183627.260187
+-2147192.464354	1195444.078101
+-2170826.100183	1240938.827071
+-2211889.542435	1275207.599023
+-2263016.65255	1280909.637672
+-2317350.604004	1293306.895593
+-2375534.184324	1279993.703486
+-2419418.410159	1314016.305538
+-2383423.483351	1367269.073967
+-2433224.683456	1375158.372994
+-2440620.901293	1426931.897855
+-2444072.469617	1482156.991041
+-2468233.447886	1532944.353524
+-2464781.879562	1584224.797197
+-2498804.481614	1541819.814929
+-2499790.643992	1483143.153419
+-2502256.049938	1428411.141423
+-2485984.370696	1381075.347263
+-2471191.935021	1325357.172889
+-2458864.905292	1273090.566838
+-2470205.772643	1221317.041976
+-2429773.115132	1188280.602303
+-2407625.063831	1139607.242244
+-2396364.68495	1083693.636763
+-2338897.923762	1058066.567585
+-2325307.811319	1007200.718155
+-2311717.698876	954005.135163
+-2260463.560519	964488.936191
+-2206879.6886	938861.867013
+-2152242.420374	914986.967648
+-2109443.190091	885575.174326
+-2108023.310413	827157.267588
+-2053256.522847	813972.670581
+-2101735.271841	786792.116752
+-2157921.939085	785372.237074
+-2199504.129645	750483.764995
+-2178611.614388	702410.695909
+-2125873.226361	700787.976277
+-2093621.673683	654743.30673
+-2078408.677136	605453.19792
+-2130944.225209	589631.681512
+-2134798.184334	539530.212887
+-2089767.714558	579489.683815
+-2040883.285656	566710.766716
+-2038652.046162	506061.620485
+-2008428.893024	553120.489801
+-2004980.613806	603424.798381
+-1959138.784214	567319.286578
+-1948996.786516	510118.419564
+-1893824.319042	516406.458136
+-1877191.442818	567522.126532
+-1824250.214837	562045.447775
+-1774757.266073	571376.085657
+-1776582.825659	516609.29809
+-1817962.176264	480909.466195
+-1858935.846962	446426.674024
+-1873540.323647	392674.086227
+-1841638.366983	347862.375138
+-1819355.95276	393260.191031
+-1781038.530172	360148.939989
+-1825811.605479	333909.835391
+-1805819.906737	274767.726613
+-1752925.203816	250611.090633
+-1780622.036448	206462.755911
+-1804986.91929	151069.090648
+-1851842.463216	130660.898182
+-1870376.433924	76933.207813
+-1900572.228899	28619.935854
+-1887244.429738	-22192.298448
+-1898281.513418	-81126.160364
+-1908902.103375	-139643.528557
+-1949926.735168	-186915.566207
+-1974262.594748	-234407.84861
+-1973612.520371	-288364.021891
+-1952810.140311	-336469.52578
+-1944359.173411	-393025.996568
+-1894953.520768	-425529.715412
+-1844897.793749	-420329.120397
+-1793541.917975	-423579.492281
+-1784440.876699	-368323.170247
+-1738935.670317	-400826.889091
+-1703831.653966	-346870.71581
+-1653125.852569	-364422.723985
+-1608270.720565	-329968.782011
+-1575952.847614	-401284.225807
+-1596047.631389	-452525.924435
+-1563561.064285	-502762.883873
+-1551839.107083	-553669.669438
+-1594038.153012	-582807.105913
+-1609818.336911	-637074.794991
+-1598286.506136	-694548.066946
+-1574241.707797	-738434.62511
+-1563195.194103	-792114.084796
+-1540274.279307	-848097.912086
+-1518570.404234	-916860.656475
+-1496258.0093	-974264.363443
+-1462586.576944	-1028625.471102
+-1472728.574641	-1086840.537885
+-1407819.789377	-1071424.701385
+-1355689.921212	-1064528.142951
+-1310659.451435	-1090694.49701
+-1279016.418619	-1134710.767018
+-1228306.430131	-1167976.519465
+-1175568.042104	-1200836.592005
+-1125170.672365	-1198245.774992
+-1078002.024254	-1216252.428506
+-1027089.195813	-1229234.185558
+-980030.326496	-1250938.060631
+-942099.255108	-1288666.292066
+-898082.985101	-1317875.245435
+-843316.197534	-1308341.767599
+-783478.411119	-1288057.772204
+-733985.462355	-1278321.454414
+-694228.831381	-1240593.22298
+-641287.6034	-1226800.106111
+-611470.130169	-1271627.735934
+-557311.862464	-1289274.811928
+-504979.154345	-1267165.256947
+-457311.765167	-1221729.107262
+-408427.336265	-1207935.990394
+-349198.069712	-1191505.954124
+-298285.24127	-1209153.030117
+-243721.293658	-1227002.946065
+-189157.346045	-1245461.381874
+-122828.681103	-1260268.698513
+-69481.773214	-1287043.572434
+-29522.302286	-1318483.765296
+28287.08459	-1324568.963915
+80619.792709	-1333291.081935
+133763.860644	-1348504.078481
+200701.045447	-1351546.67779
+264189.951034	-1347084.198803
+313682.899797	-1360471.635764
+308003.381087	-1310370.167138
+335792.454778	-1264528.337546
+381025.764509	-1297388.410086
+406786.43866	-1345461.479172
+436198.231983	-1395765.787751
+462364.586043	-1448301.335825
+462161.746089	-1508747.642102
+402932.479535	-1523352.118786
+451411.228529	-1541607.714642
+456685.067332	-1603879.580504
+439849.351154	-1653981.04913
+416522.75645	-1700228.558631
+408206.318338	-1750330.027256
+357902.009758	-1759863.505092
+341877.653396	-1807328.054316
+323216.377633	-1864123.241422
+345123.09266	-1917875.829219
+316725.499107	-1967774.457891
+344717.412752	-2020512.845918
+397658.640733	-2013007.767622
+441674.91074	-2041202.521221
+487313.900379	-2062095.036478
+545123.287254	-2055401.317997
+597861.675281	-2054792.798135
+654454.022434	-2061283.676662
+714900.328711	-2056212.677813
+755468.319501	-2094143.749202
+808815.22739	-2120310.103261
+861350.775463	-2112196.505103
+915103.363259	-2114427.744597
+972101.390319	-2106314.146439
+1013683.580879	-2137145.819439
+1064596.409321	-2123758.382478
+1114292.198038	-2099011.908096
+1160742.547493	-2077713.712932
+1212263.895796	-2050330.319148
+1262771.04433	-2018687.286332
+1317537.831896	-2030046.323753
+1381229.577437	-2045665.000208
+1441675.883714	-2064123.436017
+1490357.472662	-2041405.361175
+1531331.14336	-2012196.407806
+1590966.089821	-1998403.290937
+1637822.119184	-1970817.0572
+1689951.987349	-1951141.581667
+1739242.096159	-1925178.067561
+1785286.765705	-1898403.19364
+1838633.673594	-1873859.559212
+1883055.623509	-1848301.725014
+1918552.615451	-1807125.214362
+1946950.209004	-1751547.06698
+1989343.759379	-1715847.235085
+1996240.317814	-1658240.688163
+1968248.404168	-1606110.819998
+1994820.438136	-1554995.151602
+2045124.746716	-1561891.710037
+2105571.052993	-1552561.072155
+2117741.45023	-1503473.803299
+2137214.085809	-1452763.814811
+2146139.043783	-1394345.908074
+2193400.753053	-1363717.075027
+2187924.074296	-1307327.567829
+2205368.310336	-1251140.900585
+2231940.344304	-1201242.271913
+2272508.335094	-1158443.04163
+2318147.324732	-1134102.247156
+2351210.237226	-1084000.77853
+2404759.985069	-1078929.779681
+2448167.735214	-1052560.585668
+2462163.692037	-985014.881002
+2453644.413971	-927814.013989
+2413482.103089	-889071.582784
+2404557.145115	-835116.155033
+2452224.534293	-799010.64323
+2483664.727156	-746880.775065
+2516524.799696	-705501.424459
+2544719.553295	-660470.954682
+2597863.62123	-651140.316801
+2649384.969533	-620105.803846
+2599486.340861	-601241.688129
+2613482.297684	-548097.620194
+2664597.966079	-515846.067516
+2634171.972987	-469801.397969
+2652630.408796	-420916.969067
+2652021.888934	-367367.221224
+2709425.595902	-351951.384724
+2742894.188304	-309354.994395
+2714496.594751	-262904.64494
+2655064.488244	-255805.246552
+2608005.618927	-233898.531525
+2569871.707584	-199821.419262
+2574896.697294	-146121.254432
+2586855.25443	-86328.468753
+2567450.803229	-29694.547224
+2550302.683562	17688.415012
+2572189.099452	68004.608244
+2590465.384886	115161.937327
+2603326.474636	173149.657778
+2578958.094057	219404.454246
+2547369.452567	268141.215403
+2496376.359874	290027.631293
+2476746.27552	348240.984898
+2425527.549674	370804.300248
+2387846.813039	414802.765182
+2357611.970469	456319.265427
+2305039.445702	469180.355176
+2256528.317698	484072.143308
+2210724.787537	524234.844632
+2168305.754678	565074.445416
+2140101.61049	607267.845122
+2188161.472186	621257.100639
+2223585.877287	657809.671507
+2239831.464339	714669.22619
+2218170.681603	765887.952036
+2240282.730646	822973.139872
+2259010.282387	899011.512604
+2254948.885624	949102.072682
+2236898.233344	998515.733299
+2222908.977826	1063046.815202
+2203955.792932	1119003.837271
+2174849.11613	1169545.663656
+2167854.488371	1220087.490042
+2144388.640406	1268372.984892
+2139199.077876	1323653.1075
+2119343.360367	1377353.798035
+2169208.287292	1392922.485627
+2168531.387831	1451587.105538
+2179136.146046	1515215.654826
+2153413.966547	1559665.386067
+2116861.395679	1596443.590088
+2060540.583216	1638517.083388
+2005773.795649	1661843.678093
+1972305.203247	1616610.368362
+1923826.454253	1651093.160533
+1872710.785858	1633243.244586
+1825246.236634	1670971.47602
+1811655.959719	1723912.704001
+1754252.252751	1708496.867501
+1705570.663803	1733243.341883
+1651818.076006	1760221.055758
+1596848.448486	1759206.855989
+1549383.899261	1775028.372397
+1496036.991373	1783547.650463
+1458917.2798	1748659.178383
+1409627.17099	1725738.263587
+1365408.061029	1754338.697094
+1343298.506048	1778679.491568
+1346746.785265	1834257.63895
+1325854.270008	1880302.308497
+1320783.27116	1934460.576202
+1270884.642488	1962249.649893
+1215712.175014	1941357.134636
+1175347.024177	1976854.126577
+1123217.156012	1975839.926807
+1074941.246972	1947442.333254
+1017740.379958	1947036.653346
+961148.032806	1957178.651044
+916117.563029	1984967.724735
+862567.815186	1997340.961926
+806786.82785	2020667.55663
+785082.952777	2073000.264749
+731938.884842	2077259.903782
+682648.776033	2116610.854849
+630518.907867	2135880.650474
+576969.160025	2169349.242876
+522810.89232	2162047.004534
+480011.662036	2133649.410981
+431532.913042	2152919.206606
+380620.084601	2167118.003382
+327273.176712	2183142.359744
+283662.586613	2155961.805915
+228084.43923	2183142.359744
+170477.892309	2164481.083981
+114696.904972	2176854.321172
+63175.556669	2197746.836429
+13276.927997	2183750.879606
+3743.450162	2239734.706896
+-45343.818694	2226144.429982
+-76175.491695	2172797.522093
+-124654.240689	2147848.207757
+-182666.467519	2145414.12831
+-237027.575177	2127361.372408
+-282058.044954	2100383.658533
+-333376.553304	2102614.898026
+-365628.105982	2058801.467973
+-409441.536035	2019856.196815
+-426885.772075	1971377.44782
+-449401.006963	1915799.300438
+-505181.994299	1889835.786333
+-538650.586701	1852513.234806
+-577393.017906	1815596.363187
+-623640.527406	1789835.689035
+-632565.48538	1739328.540502
+-632971.165288	1679896.433994
+-648792.681696	1619855.807625
+-696865.750782	1599774.652184
+-745953.019638	1579693.496743
+-721206.545256	1528983.508255
+-696865.750782	1481924.638939
+-703762.309216	1423303.892247
+-682058.434144	1365494.505371
+-705587.868802	1319449.835825
+-726277.544105	1270768.246877
+-741287.700697	1221680.978021
+-760557.496322	1169956.789764
+-768468.254527	1118638.281414
+-757312.057059	1062654.454124
+-782261.371395	1017015.464485
+-841490.637949	989226.390794
+-880435.909107	947644.200234
+-1016913.83085	878162.517102
Index: /issm/trunk/test/MITgcm/build.sh
===================================================================
--- /issm/trunk/test/MITgcm/build.sh	(revision 22757)
+++ /issm/trunk/test/MITgcm/build.sh	(revision 22758)
@@ -13,5 +13,5 @@
 cd $modelpath
 if [ ! -d "build" ]; then mkdir build; fi
-\rm -f build/*
+rm -f build/*
 
 # Get MITgcm code, if needed
@@ -33,3 +33,3 @@
     make depend
 fi
-make -j 8
+make -j 4
Index: /issm/trunk/test/MITgcm/code/CPP_EEOPTIONS.h
===================================================================
--- /issm/trunk/test/MITgcm/code/CPP_EEOPTIONS.h	(revision 22758)
+++ /issm/trunk/test/MITgcm/code/CPP_EEOPTIONS.h	(revision 22758)
@@ -0,0 +1,167 @@
+C $Header: /u/gcmpack/MITgcm/eesupp/inc/CPP_EEOPTIONS.h,v 1.43 2017/09/14 19:47:35 jmc Exp $
+C $Name:  $
+
+CBOP
+C     !ROUTINE: CPP_EEOPTIONS.h
+C     !INTERFACE:
+C     include "CPP_EEOPTIONS.h"
+C
+C     !DESCRIPTION:
+C     *==========================================================*
+C     | CPP\_EEOPTIONS.h                                         |
+C     *==========================================================*
+C     | C preprocessor "execution environment" supporting        |
+C     | flags. Use this file to set flags controlling the        |
+C     | execution environment in which a model runs - as opposed |
+C     | to the dynamical problem the model solves.               |
+C     | Note: Many options are implemented with both compile time|
+C     |       and run-time switches. This allows options to be   |
+C     |       removed altogether, made optional at run-time or   |
+C     |       to be permanently enabled. This convention helps   |
+C     |       with the data-dependence analysis performed by the |
+C     |       adjoint model compiler. This data dependency       |
+C     |       analysis can be upset by runtime switches that it  |
+C     |       is unable to recoginise as being fixed for the     |
+C     |       duration of an integration.                        |
+C     |       A reasonable way to use these flags is to          |
+C     |       set all options as selectable at runtime but then  |
+C     |       once an experimental configuration has been        |
+C     |       identified, rebuild the code with the appropriate  |
+C     |       options set at compile time.                       |
+C     *==========================================================*
+CEOP
+
+#ifndef _CPP_EEOPTIONS_H_
+#define _CPP_EEOPTIONS_H_
+
+C     In general the following convention applies:
+C     ALLOW  - indicates an feature will be included but it may
+C     CAN      have a run-time flag to allow it to be switched
+C              on and off.
+C              If ALLOW or CAN directives are "undef'd" this generally
+C              means that the feature will not be available i.e. it
+C              will not be included in the compiled code and so no
+C              run-time option to use the feature will be available.
+C
+C     ALWAYS - indicates the choice will be fixed at compile time
+C              so no run-time option will be present
+
+C=== Macro related options ===
+C--   Control storage of floating point operands
+C     On many systems it improves performance only to use
+C     8-byte precision for time stepped variables.
+C     Constant in time terms ( geometric factors etc.. )
+C     can use 4-byte precision, reducing memory utilisation and
+C     boosting performance because of a smaller working set size.
+C     However, on vector CRAY systems this degrades performance.
+C     Enable to switch REAL4_IS_SLOW from genmake2 (with LET_RS_BE_REAL4):
+#ifdef LET_RS_BE_REAL4
+#undef REAL4_IS_SLOW
+#else /* LET_RS_BE_REAL4 */
+#define REAL4_IS_SLOW
+#endif /* LET_RS_BE_REAL4 */
+
+C--   Control use of "double" precision constants.
+C     Use D0 where it means REAL*8 but not where it means REAL*16
+#define D0 d0
+
+C--   Enable some old macro conventions for backward compatibility
+#undef USE_OLD_MACROS_R4R8toRSRL
+
+C=== IO related options ===
+C--   Flag used to indicate whether Fortran formatted write
+C     and read are threadsafe. On SGI the routines can be thread
+C     safe, on Sun it is not possible - if you are unsure then
+C     undef this option.
+#undef FMTFTN_IO_THREAD_SAFE
+
+C--   Flag used to indicate whether Binary write to Local file (i.e.,
+C     a different file for each tile) and read are thread-safe.
+#undef LOCBIN_IO_THREAD_SAFE
+
+C--   Flag to turn off the writing of error message to ioUnit zero
+#undef DISABLE_WRITE_TO_UNIT_ZERO
+
+C--   Alternative formulation of BYTESWAP, faster than
+C     compiler flag -byteswapio on the Altix.
+#undef FAST_BYTESWAP
+
+C--   Flag to turn on old default of opening scratch files with the
+C     STATUS='SCRATCH' option. This method, while perfectly FORTRAN-standard,
+C     caused filename conflicts on some multi-node/multi-processor platforms
+C     in the past and has been replace by something (hopefully) more robust.
+#undef USE_FORTRAN_SCRATCH_FILES
+
+C--   Flag defined for eeboot_minimal.F, eeset_parms.F and open_copy_data_file.F
+C     to write STDOUT, STDERR and scratch files from process 0 only.
+C WARNING: to use only when absolutely confident that the setup is working
+C     since any message (error/warning/print) from any proc <> 0 will be lost.
+#undef SINGLE_DISK_IO
+
+C=== MPI, EXCH and GLOBAL_SUM related options ===
+C--   Flag turns off MPI_SEND ready_to_receive polling in the
+C     gather_* subroutines to speed up integrations.
+#undef DISABLE_MPI_READY_TO_RECEIVE
+
+C--   Control MPI based parallel processing
+CXXX We no longer select the use of MPI via this file (CPP_EEOPTIONS.h)
+CXXX To use MPI, use an appropriate genmake2 options file or use
+CXXX genmake2 -mpi .
+CXXX #undef  ALLOW_USE_MPI
+
+C--   Control use of communication that might overlap computation.
+C     Under MPI selects/deselects "non-blocking" sends and receives.
+#define ALLOW_ASYNC_COMMUNICATION
+#undef  ALLOW_ASYNC_COMMUNICATION
+#undef  ALWAYS_USE_ASYNC_COMMUNICATION
+C--   Control use of communication that is atomic to computation.
+C     Under MPI selects/deselects "blocking" sends and receives.
+#define ALLOW_SYNC_COMMUNICATION
+#undef  ALWAYS_USE_SYNC_COMMUNICATION
+
+C--   Control XY periodicity in processor to grid mappings
+C     Note: Model code does not need to know whether a domain is
+C           periodic because it has overlap regions for every box.
+C           Model assume that these values have been
+C           filled in some way.
+#undef  ALWAYS_PREVENT_X_PERIODICITY
+#undef  ALWAYS_PREVENT_Y_PERIODICITY
+#define CAN_PREVENT_X_PERIODICITY
+#define CAN_PREVENT_Y_PERIODICITY
+
+C--   disconnect tiles (no exchange between tiles, just fill-in edges
+C     assuming locally periodic subdomain)
+#undef DISCONNECTED_TILES
+
+C--   Always cumulate tile local-sum in the same order by applying MPI allreduce
+C     to array of tiles ; can get slower with large number of tiles (big set-up)
+#define GLOBAL_SUM_ORDER_TILES
+
+C--   Alternative way of doing global sum without MPI allreduce call
+C     but instead, explicit MPI send & recv calls. Expected to be slower.
+#undef GLOBAL_SUM_SEND_RECV
+
+C--   Alternative way of doing global sum on a single CPU
+C     to eliminate tiling-dependent roundoff errors. Note: This is slow.
+#undef  CG2D_SINGLECPU_SUM
+
+C=== Other options (to add/remove pieces of code) ===
+C--   Flag to turn on checking for errors from all threads and procs
+C     (calling S/R STOP_IF_ERROR) before stopping.
+#define USE_ERROR_STOP
+
+C--   Control use of communication with other component:
+C     allow to import and export from/to Coupler interface.
+#undef COMPONENT_MODULE
+
+C--   Options used to couple MITgcm and ISSM
+C     Eventually this option can probably be merged with COMPONENT_MODULE
+#define ALLOW_CPL_ISSM
+
+C--   Activate some pieces of code for coupling to GEOS AGCM
+#undef HACK_FOR_GMAO_CPL
+
+#endif /* _CPP_EEOPTIONS_H_ */
+
+#include "CPP_EEMACROS.h"
+
Index: /issm/trunk/test/MITgcm/code/EESUPPORT.h
===================================================================
--- /issm/trunk/test/MITgcm/code/EESUPPORT.h	(revision 22758)
+++ /issm/trunk/test/MITgcm/code/EESUPPORT.h	(revision 22758)
@@ -0,0 +1,298 @@
+C $Header: /u/gcmpack/MITgcm/eesupp/inc/EESUPPORT.h,v 1.10 2009/04/21 16:00:53 jmc Exp $
+C $Name:  $
+CBOP
+C     !ROUTINE: EESUPPORT.h
+C     !INTERFACE:
+C     include "EESUPPORT.h"
+C
+C     !DESCRIPTION:
+C     *==========================================================*
+C     | EESUPPORT.h                                              |
+C     *==========================================================*
+C     | Support data structures for the MITgcm UV execution      |
+C     | environment code. This data should be private to the     |
+C     | execution environment routines. Data which needs to be   |
+C     | accessed directly by a numerical model goes in           |
+C     | EEPARAMS.h.                                              |
+C     *==========================================================*
+CEOP
+
+C     ERROR_HEADER        - String which prefixes error messages
+      CHARACTER*(*) ERROR_HEADER
+      PARAMETER ( ERROR_HEADER = ' *** ERROR ***' )
+C     PROCESS_HEADER      - String which prefixes processor number
+      CHARACTER*(*) PROCESS_HEADER
+      PARAMETER ( PROCESS_HEADER = 'PID.TID' )
+
+C     MAX_NUM_COMM_MODES - Maximum number of communication modes
+C     COMM_NONE       - No edge communication
+C     COMM_MSG        - Use messages to communicate edges
+C     COMM_PUT        - Use put to communicate edges
+C     COMM_GET        - Use get to communicate edges
+C     Note - commName holds an identifying name for each communication
+C            mode. The COMM_ parameters are used to index commName
+C            so the COMM_ parameters need to be in the range
+C            1 : MAX_NUM_COMM_MODES.
+      INTEGER MAX_NUM_COMM_MODES
+      PARAMETER ( MAX_NUM_COMM_MODES = 4 )
+      INTEGER COMM_NONE
+      PARAMETER ( COMM_NONE   =   1 )
+      INTEGER COMM_MSG
+      PARAMETER ( COMM_MSG    =   2 )
+      INTEGER COMM_PUT
+      PARAMETER ( COMM_PUT    =   3 )
+      INTEGER COMM_GET
+      PARAMETER ( COMM_GET    =   4 )
+      COMMON /EESUPP_COMMNAME/ commName
+      CHARACTER*10 commName(MAX_NUM_COMM_MODES)
+
+C     Tile identifiers
+C     Tiles have a number that is unique over the global domain.
+C     A tile that is not there has its number set to NULL_TILE
+      INTEGER NULL_TILE
+      PARAMETER ( NULL_TILE = -1 )
+
+
+C--   COMMON /EESUPP_C/ Execution environment support character variables
+C     myProcessStr - String identifying my process number
+      COMMON /EESUPP_C/ myProcessStr
+      CHARACTER*128 myProcessStr
+
+C--   COMMON /EESUPP_L/ Execution environment support logical variables
+C     initMPError - Flag indicating error during multi-processing
+C                   initialisation.
+C     finMPError  - Flag indicating error during multi-processing
+C                   termination.
+C     ThError     - Thread detected an error.
+C     usingMPI    - Flag controlling use of MPI routines. This flag
+C                   allows either MPI or threads to be used in a
+C                   shared memory environment which can be a useful
+C                   debugging/performance analysis tool.
+C     usingSyncMessages - Flag that causes blocking communication to be used
+C                         if possible. When false non-blocking EXCH routines
+C                         will be used if possible.
+C     notUsingXPeriodicity - Flag indicating no X/Y boundary wrap around
+C     notUsingYPeriodicity   This affects the communication routines but
+C                            is generally ignored in the numerical model
+C                            code.
+C     threadIsRunning, threadIsComplete - Flags used to check for correct behaviour
+C                                         of multi-threaded code.
+C                                         threadIsRunning is used to check that the
+C                                         threads we need are running. This catches the
+C                                         situation where a program eedata file has nTthreads
+C                                         greater than the setenv PARALLEL or NCPUS variable.
+C                                         threadIsComplete is used to flag that a thread has
+C                                         reached the end of the model. This is used as a check to
+C                                         trap problems that might occur if one thread "escapes"
+C                                         the main.F master loop. This should not happen
+C                                         if the multi-threading compilation tools works right.
+C                                         But (see for example KAP) this is not always the case!
+      COMMON /EESUPP_L/ thError, threadIsRunning, threadIsComplete,
+     & allMyEdgesAreSharedMemory, usingMPI, usingSyncMessages,
+     & notUsingXPeriodicity, notUsingYPeriodicity
+      LOGICAL thError(MAX_NO_THREADS)
+      LOGICAL threadIsRunning(MAX_NO_THREADS)
+      LOGICAL threadIsComplete(MAX_NO_THREADS)
+      LOGICAL allMyEdgesAreSharedMemory(MAX_NO_THREADS)
+      LOGICAL usingMPI
+      LOGICAL usingSyncMessages
+      LOGICAL notUsingXPeriodicity
+      LOGICAL notUsingYPeriodicity
+
+C--   COMMON /EESUPP_I/ Parallel support integer globals
+C     pidW   -  Process  ID of neighbor to West
+C     pidE   -           ditto             East
+C     pidN   -           ditto             North
+C     pidS   -           ditto             South
+C              Note: pid[XY] is not necessairily the UNIX
+C                    process id - it is just an identifying
+C                    number.
+C     myPid  - My own process id
+C     nProcs - Number of processes
+C     westCommunicationMode  - Mode of communication for each tile face
+C     eastCommunicationMode
+C     northCommunicationMode
+C     southCommunicationMode
+C     bi0   - Low cartesian tile index for this process
+C     bj0     Note - In a tile distribution with holes bi0 and bj0
+C                    are not useful. Neighboring tile indices must
+C                    be derived some other way.
+C     tileNo       - Tile identification number for my tile and
+C     tileNo[WENS]   my N,S,E,W neighbor tiles.
+C     tilePid[WENS] - Process identification number for
+C                     my N,S,E,W neighbor tiles.
+C     nTx, nTy    - No. threads in X and Y. This assumes a simple
+C                   cartesian gridding of the threads which is not
+C                   required elsewhere but that makes it easier.
+      COMMON /EESUPP_I/
+     & myPid, nProcs, pidW, pidE, pidN, pidS,
+     & tileCommModeW,  tileCommModeE,
+     & tileCommModeN,  tileCommModeS,
+     & tileNo, tileNoW, tileNoE, tileNoS, tileNoN,
+     &  tilePidW, tilePidE, tilePidS, tilePidN,
+     &  tileBiW, tileBiE, tileBiS, tileBiN,
+     & tileBjW, tileBjE, tileBjS, tileBjN,
+     & tileTagSendW, tileTagSendE, tileTagSendS, tileTagSendN,
+     & tileTagRecvW, tileTagRecvE, tileTagRecvS, tileTagRecvN
+      INTEGER myPid
+      INTEGER nProcs
+      INTEGER pidW
+      INTEGER pidE
+      INTEGER pidN
+      INTEGER pidS
+      INTEGER tileCommModeW ( nSx, nSy )
+      INTEGER tileCommModeE ( nSx, nSy )
+      INTEGER tileCommModeN ( nSx, nSy )
+      INTEGER tileCommModeS ( nSx, nSy )
+      INTEGER tileNo( nSx, nSy )
+      INTEGER tileNoW( nSx, nSy )
+      INTEGER tileNoE( nSx, nSy )
+      INTEGER tileNoN( nSx, nSy )
+      INTEGER tileNoS( nSx, nSy )
+      INTEGER tilePidW( nSx, nSy )
+      INTEGER tilePidE( nSx, nSy )
+      INTEGER tilePidN( nSx, nSy )
+      INTEGER tilePidS( nSx, nSy )
+      INTEGER tileBiW( nSx, nSy )
+      INTEGER tileBiE( nSx, nSy )
+      INTEGER tileBiN( nSx, nSy )
+      INTEGER tileBiS( nSx, nSy )
+      INTEGER tileBjW( nSx, nSy )
+      INTEGER tileBjE( nSx, nSy )
+      INTEGER tileBjN( nSx, nSy )
+      INTEGER tileBjS( nSx, nSy )
+      INTEGER tileTagSendW( nSx, nSy )
+      INTEGER tileTagSendE( nSx, nSy )
+      INTEGER tileTagSendN( nSx, nSy )
+      INTEGER tileTagSendS( nSx, nSy )
+      INTEGER tileTagRecvW( nSx, nSy )
+      INTEGER tileTagRecvE( nSx, nSy )
+      INTEGER tileTagRecvN( nSx, nSy )
+      INTEGER tileTagRecvS( nSx, nSy )
+
+#ifdef ALLOW_USE_MPI
+C--   Include MPI standard Fortran header file
+#include "mpif.h"
+#define _mpiTRUE_  1
+#define _mpiFALSE_ 0
+
+C--   COMMON /EESUPP_MPI_I/ MPI parallel support integer globals
+C     mpiPidW   - MPI process id for west neighbor.
+C     mpiPidE   - MPI process id for east neighbor.
+C     mpiPidN   - MPI process id for north neighbor.
+C     mpiPidS   - MPI process id for south neighbor.
+C     mpiPidNW  - MPI process id for northwest neighbor.
+C     mpiPidNE  - MPI process id for northeast neighbor.
+C     mpiPidSW  - MPI process id for southwest neighbor.
+C     mpiPidSE  - MPI process id for southeast neighbor.
+C     mpiPidIO  - MPI process to use for IO.
+C     mpiNprocs - No. of MPI processes.
+C     mpiMyId   - MPI process id of me.
+C     mpiComm   - MPI communicator to use.
+C     mpiPx     - My MPI proc. grid X coord
+C     mpiPy     - My MPI proc. grid Y coord
+C     mpiXGlobalLo - My bottom-left (south-west) x-coordinate in
+C                    global domain.
+C     mpiYGlobalLo - My bottom-left (south-west) y-coordinate in
+C                    global domain.
+C     mpiTypeXFaceBlock_xy_r4  - Primitives for communicating edge
+C     mpiTypeXFaceBlock_xy_r8    of a block.
+C     mpiTypeYFaceBlock_xy_r4    XFace is used in east-west transfer
+C     mpiTypeYFaceBlock_xy_r8    YFace is used in nrth-south transfer
+C     mpiTypeXFaceBlock_xyz_r4   xy is used in two-dimensional arrays
+C     mpiTypeXFaceBlock_xyz_r8   xyz is used with three-dimensional arrays
+C     mpiTypeYFaceBlock_xyz_r4   r4 is used for real*4 data
+C     mpiTypeYFaceBlock_xyz_r8   r8 is used for real*8 data
+C     mpiTypeXFaceThread_xy_r4  - Composites of the above primitives
+C     mpiTypeXFaceThread_xy_r8    for communicating edges of all blocks
+C     mpiTypeYFaceThread_xy_r4    owned by a thread.
+C     mpiTypeYFaceThread_xy_r8
+C     mpiTypeXFaceThread_xyz_r4
+C     mpiTypeXFaceThread_xyz_r8
+C     mpiTypeYFaceThread_xyz_r4
+C     mpiTypeYFaceBlock_xyz_r8
+C     mpiTagE       - Tags are needed to mark requests when MPI is running
+C     mpiTagW         between multithreaded processes or when the same process.
+C     mpiTagS         is a neighbor in more than one direction. The tags ensure that
+C     mpiTagN         a thread will get the message it is looking for.
+C     mpiTagSW        The scheme adopted is to tag messages according to
+C     mpiTagSE        the direction they are travelling. Thus a message
+C     mpiTagNW        travelling east is tagged mpiTagE. However, in a
+C     mpiTagNE        multi-threaded environemnt several messages could
+C                     be travelling east from the same process at the
+C                     same time. The tag is therefore modified to
+C                     be mpiTag[EWS...]*nThreads+myThid. This requires that
+C                     each thread also know the thread ids of its "neighbor"
+C                     threads.
+      COMMON /EESUPP_MPI_I/
+     & mpiPidW,  mpiPidE,  mpiPidS,  mpiPidN,
+     & mpiPidSE, mpiPidSW, mpiPidNE, mpiPidNW,
+     & mpiPidIo, mpiMyId, mpiNProcs, mpiComm,
+     & mpiPx, mpiPy, mpiXGlobalLo, mpiYGlobalLo,
+     & mpiTypeXFaceBlock_xy_r4, mpiTypeXFaceBlock_xy_r8,
+     & mpiTypeYFaceBlock_xy_r4, mpiTypeYFaceBlock_xy_r8,
+     & mpiTypeXFaceBlock_xyz_r4, mpiTypeXFaceBlock_xyz_r8,
+     & mpiTypeYFaceBlock_xyz_r4, mpiTypeYFaceBlock_xyz_r8,
+     & mpiTypeXFaceThread_xy_r4, mpiTypeXFaceThread_xy_r8,
+     & mpiTypeYFaceThread_xy_r4, mpiTypeYFaceThread_xy_r8,
+     & mpiTypeXFaceThread_xyz_r4, mpiTypeXFaceThread_xyz_r8,
+     & mpiTypeYFaceThread_xyz_r4, mpiTypeYFaceThread_xyz_r8,
+     & mpiTagE, mpiTagW, mpiTagN, mpiTagS,
+     & mpiTagSE, mpiTagSW, mpiTagNW, mpiTagNE
+
+      INTEGER mpiPidW
+      INTEGER mpiPidE
+      INTEGER mpiPidS
+      INTEGER mpiPidN
+      INTEGER mpiPidSW
+      INTEGER mpiPidSE
+      INTEGER mpiPidNW
+      INTEGER mpiPidNE
+      INTEGER mpiPidIO
+      INTEGER mpiMyId
+      INTEGER mpiNProcs
+      INTEGER mpiComm
+      INTEGER mpiPx
+      INTEGER mpiPy
+      INTEGER mpiXGlobalLo
+      INTEGER mpiYGlobalLo
+      INTEGER mpiTypeXFaceBlock_xy_r4
+      INTEGER mpiTypeXFaceBlock_xy_r8
+      INTEGER mpiTypeYFaceBlock_xy_r4
+      INTEGER mpiTypeYFaceBlock_xy_r8
+      INTEGER mpiTypeXFaceBlock_xyz_r4
+      INTEGER mpiTypeXFaceBlock_xyz_r8
+      INTEGER mpiTypeYFaceBlock_xyz_r4
+      INTEGER mpiTypeYFaceBlock_xyz_r8
+      INTEGER mpiTypeXFaceThread_xy_r4(MAX_NO_THREADS)
+      INTEGER mpiTypeXFaceThread_xy_r8(MAX_NO_THREADS)
+      INTEGER mpiTypeYFaceThread_xy_r4(MAX_NO_THREADS)
+      INTEGER mpiTypeYFaceThread_xy_r8(MAX_NO_THREADS)
+      INTEGER mpiTypeXFaceThread_xyz_r4(MAX_NO_THREADS)
+      INTEGER mpiTypeXFaceThread_xyz_r8(MAX_NO_THREADS)
+      INTEGER mpiTypeYFaceThread_xyz_r4(MAX_NO_THREADS)
+      INTEGER mpiTypeYFaceThread_xyz_r8(MAX_NO_THREADS)
+      INTEGER mpiTagNW
+      INTEGER mpiTagNE
+      INTEGER mpiTagSW
+      INTEGER mpiTagSE
+      INTEGER mpiTagW
+      INTEGER mpiTagE
+      INTEGER mpiTagN
+      INTEGER mpiTagS
+
+C--   COMMON /MPI_FULLMAP_I/ holds integer arrays of the full list of MPI process
+C     mpi_myXGlobalLo :: List of all processors bottom-left X-index in global domain
+C     mpi_myYGlobalLo :: List of all processors bottom-left Y-index in global domain
+C                        Note: needed for mpi gather/scatter routines & singleCpuIO.
+      COMMON /MPI_FULLMAP_I/
+     &        mpi_myXGlobalLo, mpi_myYGlobalLo
+      INTEGER mpi_myXGlobalLo(nPx*nPy)
+      INTEGER mpi_myYGlobalLo(nPx*nPy)
+
+C MPI communicator describing this model realization
+      COMMON /MPI_COMMS/
+     &        MPI_COMM_MODEL
+      INTEGER MPI_COMM_MODEL
+
+#endif /* ALLOW_USE_MPI */
Index: /issm/trunk/test/MITgcm/code/cpl_issm.F
===================================================================
--- /issm/trunk/test/MITgcm/code/cpl_issm.F	(revision 22758)
+++ /issm/trunk/test/MITgcm/code/cpl_issm.F	(revision 22758)
@@ -0,0 +1,198 @@
+#include "PACKAGES_CONFIG.h"
+#include "CPP_OPTIONS.h"
+
+CBOP
+C     !ROUTINE: CPL_ISSM
+C     !INTERFACE:
+      SUBROUTINE CPL_ISSM( myTime, myIter, myThid )
+
+C     !DESCRIPTION: \bv
+C     *==================================================================
+C     | SUBROUTINE cpl_issm
+C     | o Couple MITgcm ocean model with ISSM ice sheet model
+C     *==================================================================
+C     \ev
+
+C     !USES:
+      IMPLICIT NONE
+C     == Global variables ==
+#include "SIZE.h"
+#include "EEPARAMS.h"
+#include "PARAMS.h"
+#include "DYNVARS.h"
+#include "GRID.h"
+#include "FFIELDS.h"
+#include "SHELFICE_OPTIONS.h"
+#include "SHELFICE.h"
+#ifdef ALLOW_EXF
+# include "EXF_OPTIONS.h"
+# include "EXF_FIELDS.h"
+#endif
+
+      LOGICAL  DIFFERENT_MULTIPLE
+      EXTERNAL DIFFERENT_MULTIPLE
+
+C     !LOCAL VARIABLES:
+C     mytime - time counter for this thread (seconds)
+C     myiter - iteration counter for this thread
+C     mythid - thread number for this instance of the routine.
+      _RL     mytime
+      INTEGER myiter, mythid 
+CEOP
+
+#ifdef ALLOW_CPL_ISSM
+#include "EESUPPORT.h"
+      COMMON /CPL_MPI_ID/ mpiMyWid, toissmcomm
+      INTEGER mpiMyWid, toissmcomm, mpiRC
+      INTEGER mpistatus(MPI_STATUS_SIZE)
+      INTEGER i, j, bi, bj, buffsize
+      COMMON /CPL_ISSM_TIME/ CouplingTime
+      _R8 CouplingTime, IceModelTime
+      _R8 xfer_array(Nx,Ny)
+      _R8 local(1:sNx,1:sNy,nSx,nSy)
+
+C Initialization steps I1, I2, and I3:
+      IF( myTime .EQ. startTime ) THEN
+
+C   I1. ISSM sends CouplingTime, the interval at which we couple
+         IF( myProcId .EQ. 0 ) THEN
+            _BEGIN_MASTER( myThid )
+            call MPI_Recv(CouplingTime,1,MPI_DOUBLE,0,10001000,
+     &           toissmcomm,mpistatus,mpiRC)
+            _END_MASTER( myThid )
+         ENDIF
+         _BEGIN_MASTER( myThid )
+         CALL MPI_BCAST(CouplingTime,1,MPI_DOUBLE,0,
+     &        MPI_COMM_MODEL,mpiRC)
+         _END_MASTER( myThid )
+         print*, 'Ocean received CouplingTime: ', CouplingTime
+
+C   I2. MITgcm sends grid size (NX and NY)
+         IF( myProcId .EQ. 0 ) THEN
+            _BEGIN_MASTER( myThid )
+            call MPI_Send(Nx,1,MPI_INT,0,10001003,
+     &           toissmcomm,mpistatus)
+            call MPI_Send(Ny,1,MPI_INT,0,10001004,
+     &           toissmcomm,mpistatus)
+            _END_MASTER( myThid )
+         ENDIF
+
+C   I3. MITgcm sends grid coordinates of center of cells
+C       (longitude -180 <= XC < 180 and latitude YC)
+C     Send longitude East of center of cell
+         DO bj=1,nSy
+            DO bi=1,nSx
+               DO j=1,sNy
+                  DO i=1,sNx
+                     local(i,j,bi,bj) = xC(i,j,bi,bj)
+                  ENDDO
+               ENDDO
+            ENDDO
+         ENDDO
+         CALL BAR2( myThid ) 
+         CALL GATHER_2D_R8( xfer_array, local, Nx, Ny,
+     &        .FALSE., .FALSE., myThid )
+         IF( myProcId .EQ. 0 ) THEN
+            _BEGIN_MASTER( myThid )
+            buffsize = Nx*Ny
+            CALL MPI_SEND(xfer_array,buffsize,MPI_DOUBLE_PRECISION,
+     &           0,10001005,toissmcomm,mpistatus)
+            _END_MASTER( myThid )
+         ENDIF
+         CALL BAR2( myThid )
+C     Send latitude North of center of cell
+         DO bj=1,nSy
+            DO bi=1,nSx
+               DO j=1,sNy
+                  DO i=1,sNx
+                     local(i,j,bi,bj) = yC(i,j,bi,bj)
+                  ENDDO
+               ENDDO
+            ENDDO
+         ENDDO
+         CALL BAR2( myThid ) 
+         CALL GATHER_2D_R8( xfer_array, local, Nx, Ny,
+     &        .FALSE., .FALSE., myThid )
+         IF( myProcId .EQ. 0 ) THEN
+            _BEGIN_MASTER( myThid )
+            buffsize = Nx*Ny
+            CALL MPI_SEND(xfer_array,buffsize,MPI_DOUBLE_PRECISION,
+     &           0,10001006,toissmcomm,mpistatus)
+            _END_MASTER( myThid )
+         ENDIF
+         CALL BAR2( myThid )
+
+      ENDIF
+C End initialization steps I1, I2, and I3.
+
+C Recurring steps C1 and C2:
+      IF( MOD(myTime,CouplingTime) .LT. deltaT/2. ) THEN
+
+C   C1. ISSM sends ice model time IceTimeTag
+         IF( myProcId .EQ. 0 ) THEN
+            _BEGIN_MASTER( myThid )
+            call MPI_Recv(IceModelTime,1,MPI_DOUBLE,0,10001001,
+     &           toissmcomm,mpistatus,mpiRC)
+            print*, 'Ocean received IceModelTime: ', IceModelTime
+            _END_MASTER( myThid )
+         ENDIF
+
+C   C2. MITgcm sends ocean model time OceanTimeTag
+         IF( myProcId .EQ. 0 ) THEN
+            _BEGIN_MASTER( myThid )
+            call MPI_Send(myTime,1,MPI_DOUBLE,0,10001002,
+     &           toissmcomm,mpistatus)
+            _END_MASTER( myThid )
+         ENDIF
+
+      ENDIF
+C End recurring steps C1 and C2.
+
+C Recurring step C3 except during Initialization:
+C  C3. MITgcm sends
+C      (N-1)*CouplingTime <= OceanModelTime < N*CouplingTime
+C      time-mean melt rate to ISSM
+      IF( myTime .NE. startTime .AND.
+     &     MOD(myTime,CouplingTime) .LT. deltaT/2. ) THEN
+         DO bj=1,nSy
+            DO bi=1,nSx
+               DO j=1,sNy
+                  DO i=1,sNx
+                     local(i,j,bi,bj) = shelficeHeatFlux(i,j,bi,bj)
+                  ENDDO
+               ENDDO
+            ENDDO
+         ENDDO
+         CALL BAR2( myThid ) 
+         CALL GATHER_2D_R8( xfer_array, local, Nx, Ny,
+     &        .FALSE., .FALSE., myThid )
+         IF( myProcId .EQ. 0 ) THEN
+            _BEGIN_MASTER( myThid )
+            buffsize = Nx*Ny
+            CALL MPI_SEND(xfer_array,buffsize,MPI_DOUBLE_PRECISION,
+     &           0,10001007,toissmcomm,mpistatus)
+            _END_MASTER( myThid )
+         ENDIF
+         CALL BAR2( myThid )
+         print*,'Done Sending shelficeHeatFlux array.'
+         
+      ENDIF
+C End recurring step C3.
+
+C Recurring step C4 except during Termination:
+C  C4. ISSM sends IceModelTime=(N-1)*CouplingTime base to MITgcm
+      IF( myTime .NE. endtime .AND.
+     &     MOD(myTime,CouplingTime) .LT. deltaT/2. ) THEN         
+         IF( myProcId .EQ. 0 ) THEN
+            _BEGIN_MASTER( myThid )         
+            call MPI_Recv(xfer_array,buffsize,MPI_DOUBLE_PRECISION,
+     &           0,10001008,toissmcomm,mpistatus,mpiRC)
+            _END_MASTER( myThid )
+         ENDIF
+      ENDIF
+C End recurring step C4.
+
+#endif /* ALLOW_CPL_ISSM */
+
+      RETURN
+      END
Index: /issm/trunk/test/MITgcm/code/do_oceanic_phys.F
===================================================================
--- /issm/trunk/test/MITgcm/code/do_oceanic_phys.F	(revision 22758)
+++ /issm/trunk/test/MITgcm/code/do_oceanic_phys.F	(revision 22758)
@@ -0,0 +1,1195 @@
+C $Header: /u/gcmpack/MITgcm/model/src/do_oceanic_phys.F,v 1.149 2017/02/12 20:18:24 gforget Exp $
+C $Name:  $
+
+#include "PACKAGES_CONFIG.h"
+#include "CPP_OPTIONS.h"
+#ifdef ALLOW_AUTODIFF
+# include "AUTODIFF_OPTIONS.h"
+#endif
+#ifdef ALLOW_CTRL
+# include "CTRL_OPTIONS.h"
+#endif
+#ifdef ALLOW_SALT_PLUME
+# include "SALT_PLUME_OPTIONS.h"
+#endif
+#ifdef ALLOW_ECCO
+# include "ECCO_OPTIONS.h"
+#endif
+
+#ifdef ALLOW_AUTODIFF
+# ifdef ALLOW_GGL90
+#  include "GGL90_OPTIONS.h"
+# endif
+# ifdef ALLOW_GMREDI
+#  include "GMREDI_OPTIONS.h"
+# endif
+# ifdef ALLOW_KPP
+#  include "KPP_OPTIONS.h"
+# endif
+# ifdef ALLOW_SEAICE
+#  include "SEAICE_OPTIONS.h"
+# endif
+# ifdef ALLOW_EXF
+#  include "EXF_OPTIONS.h"
+# endif
+#endif /* ALLOW_AUTODIFF */
+
+CBOP
+C     !ROUTINE: DO_OCEANIC_PHYS
+C     !INTERFACE:
+      SUBROUTINE DO_OCEANIC_PHYS(myTime, myIter, myThid)
+C     !DESCRIPTION: \bv
+C     *==========================================================*
+C     | SUBROUTINE DO_OCEANIC_PHYS
+C     | o Controlling routine for oceanic physics and
+C     |   parameterization
+C     *==========================================================*
+C     | o originally, part of S/R thermodynamics
+C     *==========================================================*
+C     \ev
+
+C     !CALLING SEQUENCE:
+C     DO_OCEANIC_PHYS
+C       |
+C       |-- OBCS_CALC
+C       |
+C       |-- OCN_APPLY_IMPORT
+C       |
+C       |-- FRAZIL_CALC_RHS
+C       |
+C       |-- THSICE_MAIN
+C       |
+C       |-- SEAICE_FAKE
+C       |-- SEAICE_MODEL
+C       |-- SEAICE_COST_SENSI
+C       |
+C       |-- OCN_EXPORT_DATA
+C       |
+C       |-- SHELFICE_THERMODYNAMICS
+C       |
+C       |-- ICEFRONT_THERMODYNAMICS
+C       |
+C       |-- SALT_PLUME_DO_EXCH
+C       |
+C       |-- FREEZE_SURFACE
+C       |
+C       |-- EXTERNAL_FORCING_SURF
+C       |
+C       |- k loop (Nr:1):
+C       | - DWNSLP_CALC_RHO
+C       | - BBL_CALC_RHO
+C       | - FIND_RHO_2D @ p(k)
+C       | - FIND_RHO_2D @ p(k-1)
+C       | - GRAD_SIGMA
+C       | - CALC_IVDC
+C       | - DIAGS_RHO_L
+C       |- end k loop.
+C       |
+C       |-- CALC_OCE_MXLAYER
+C       |
+C       |-- SALT_PLUME_CALC_DEPTH
+C       |-- SALT_PLUME_VOLFRAC
+C       |-- SALT_PLUME_APPLY
+C       |-- SALT_PLUME_APPLY
+C       |-- SALT_PLUME_FORCING_SURF
+C       |
+C       |-- KPP_CALC
+C       |-- KPP_CALC_DUMMY
+C       |
+C       |-- PP81_CALC
+C       |
+C       |-- KL10_CALC
+C       |
+C       |-- MY82_CALC
+C       |
+C       |-- GGL90_CALC
+C       |
+C       |-- TIMEAVE_SURF_FLUX
+C       |
+C       |-- GMREDI_CALC_TENSOR
+C       |-- GMREDI_CALC_TENSOR_DUMMY
+C       |
+C       |-- DWNSLP_CALC_FLOW
+C       |-- DWNSLP_CALC_FLOW
+C       |
+C       |-- OFFLINE_GET_DIFFUS
+C       |
+C       |-- BBL_CALC_RHS
+C       |
+C       |-- MYPACKAGE_CALC_RHS
+C       |
+C       |-- GMREDI_DO_EXCH
+C       |
+C       |-- KPP_DO_EXCH
+C       |
+C       |-- DIAGS_RHO_G
+C       |-- DIAGS_OCEANIC_SURF_FLUX
+C       |-- SALT_PLUME_DIAGNOSTICS_FILL
+C       |
+C       |-- ECCO_PHYS
+
+C     !USES:
+      IMPLICIT NONE
+C     == Global variables ===
+#include "SIZE.h"
+#include "EEPARAMS.h"
+#include "PARAMS.h"
+#include "GRID.h"
+#include "DYNVARS.h"
+#ifdef ALLOW_TIMEAVE
+# include "TIMEAVE_STATV.h"
+#endif
+#ifdef ALLOW_OFFLINE
+# include "OFFLINE_SWITCH.h"
+#endif
+
+#ifdef ALLOW_AUTODIFF
+# include "AUTODIFF_MYFIELDS.h"
+# include "tamc.h"
+# include "tamc_keys.h"
+# include "FFIELDS.h"
+# include "SURFACE.h"
+# include "EOS.h"
+# ifdef ALLOW_GMREDI
+#  include "GMREDI.h"
+# endif
+# ifdef ALLOW_KPP
+#  include "KPP.h"
+# endif
+# ifdef ALLOW_GGL90
+#  include "GGL90.h"
+# endif
+# ifdef ALLOW_EBM
+#  include "EBM.h"
+# endif
+# ifdef ALLOW_EXF
+#  include "ctrl.h"
+#  include "EXF_FIELDS.h"
+#  ifdef ALLOW_BULKFORMULAE
+#   include "EXF_CONSTANTS.h"
+#  endif
+# endif
+# ifdef ALLOW_SEAICE
+#  include "SEAICE_SIZE.h"
+#  include "SEAICE.h"
+#  include "SEAICE_PARAMS.h"
+# endif
+# ifdef ALLOW_THSICE
+#  include "THSICE_VARS.h"
+# endif
+# ifdef ALLOW_SALT_PLUME
+#  include "SALT_PLUME.h"
+# endif
+# ifdef ALLOW_ECCO
+#  ifdef ALLOW_SIGMAR_COST_CONTRIBUTION
+#   include "ecco_cost.h"
+#  endif
+# endif
+#endif /* ALLOW_AUTODIFF */
+
+C     !INPUT/OUTPUT PARAMETERS:
+C     == Routine arguments ==
+C     myTime :: Current time in simulation
+C     myIter :: Current iteration number in simulation
+C     myThid :: Thread number for this instance of the routine.
+      _RL myTime
+      INTEGER myIter
+      INTEGER myThid
+
+C     !LOCAL VARIABLES:
+C     == Local variables
+C     rhoK, rhoKm1  :: Density at current level, and level above
+C     iMin, iMax    :: Ranges and sub-block indices on which calculations
+C     jMin, jMax       are applied.
+C     bi, bj        :: tile indices
+C     msgBuf        :: Temp. for building output string
+C     i,j,k         :: loop indices
+      _RL rhoKp1  (1-OLx:sNx+OLx,1-OLy:sNy+OLy)
+      _RL rhoKm1  (1-OLx:sNx+OLx,1-OLy:sNy+OLy)
+      _RL sigmaX  (1-OLx:sNx+OLx,1-OLy:sNy+OLy,Nr)
+      _RL sigmaY  (1-OLx:sNx+OLx,1-OLy:sNy+OLy,Nr)
+      _RL sigmaR  (1-OLx:sNx+OLx,1-OLy:sNy+OLy,Nr)
+      INTEGER iMin, iMax
+      INTEGER jMin, jMax
+      INTEGER bi, bj
+      INTEGER i, j, k
+      CHARACTER*(MAX_LEN_MBUF) msgBuf
+      INTEGER doDiagsRho
+      LOGICAL calcGMRedi, calcKPP, calcConvect
+#ifdef ALLOW_DIAGNOSTICS
+      LOGICAL  DIAGNOSTICS_IS_ON
+      EXTERNAL DIAGNOSTICS_IS_ON
+#endif /* ALLOW_DIAGNOSTICS */
+#ifdef ALLOW_AUTODIFF
+      _RL thetaRef
+#endif /* ALLOW_AUTODIFF */
+CEOP
+
+#ifdef ALLOW_AUTODIFF_TAMC
+C--   dummy statement to end declaration part
+      itdkey = 1
+#endif /* ALLOW_AUTODIFF_TAMC */
+
+#ifdef ALLOW_DEBUG
+      IF (debugMode) CALL DEBUG_ENTER('DO_OCEANIC_PHYS',myThid)
+#endif
+
+      doDiagsRho = 0
+#ifdef ALLOW_DIAGNOSTICS
+      IF ( useDiagnostics .AND. fluidIsWater ) THEN
+        IF ( DIAGNOSTICS_IS_ON('MXLDEPTH',myThid) )
+     &       doDiagsRho = doDiagsRho + 1
+        IF ( DIAGNOSTICS_IS_ON('DRHODR  ',myThid) )
+     &       doDiagsRho = doDiagsRho + 2
+        IF ( DIAGNOSTICS_IS_ON('WdRHO_P ',myThid) )
+     &       doDiagsRho = doDiagsRho + 4
+        IF ( DIAGNOSTICS_IS_ON('WdRHOdP ',myThid) )
+     &       doDiagsRho = doDiagsRho + 8
+      ENDIF
+#endif /* ALLOW_DIAGNOSTICS */
+
+      calcGMRedi  = useGMRedi
+      calcKPP     = useKPP
+      calcConvect = ivdc_kappa.NE.0.
+#ifdef ALLOW_OFFLINE
+      IF ( useOffLine ) THEN
+        calcGMRedi = useGMRedi .AND. .NOT.offlineLoadGMRedi
+        calcKPP    = useKPP    .AND. .NOT.offlineLoadKPP
+        calcConvect=calcConvect.AND. .NOT.offlineLoadConvec
+      ENDIF
+#endif /* ALLOW_OFFLINE */
+
+#ifdef  ALLOW_OBCS
+      IF (useOBCS) THEN
+C--   Calculate future values on open boundaries
+C--   moved before SEAICE_MODEL call since SEAICE_MODEL needs seaice-obcs fields
+# ifdef ALLOW_AUTODIFF_TAMC
+CADJ STORE theta = comlev1, key=ikey_dynamics, kind=isbyte
+CADJ STORE salt  = comlev1, key=ikey_dynamics, kind=isbyte
+# endif
+# ifdef ALLOW_DEBUG
+       IF (debugMode) CALL DEBUG_CALL('OBCS_CALC',myThid)
+# endif
+       CALL OBCS_CALC( myTime+deltaTClock, myIter+1,
+     I                 uVel, vVel, wVel, theta, salt, myThid )
+      ENDIF
+#endif  /* ALLOW_OBCS */
+
+#ifdef ALLOW_OCN_COMPON_INTERF
+C--    Apply imported data (from coupled interface) to forcing fields
+C jmc: moved here before any freezing/seaice pkg adjustment of surf-fluxes
+      IF ( useCoupler ) THEN
+         CALL OCN_APPLY_IMPORT( .TRUE., myTime, myIter, myThid )
+      ENDIF
+#endif /* ALLOW_OCN_COMPON_INTERF */
+
+#ifdef ALLOW_AUTODIFF
+# ifdef ALLOW_SALT_PLUME
+      DO bj=myByLo(myThid),myByHi(myThid)
+       DO bi=myBxLo(myThid),myBxHi(myThid)
+        DO j=1-OLy,sNy+OLy
+         DO i=1-OLx,sNx+OLx
+          saltPlumeDepth(i,j,bi,bj) = 0. _d 0
+          saltPlumeFlux(i,j,bi,bj)  = 0. _d 0
+         ENDDO
+        ENDDO
+       ENDDO
+      ENDDO
+# endif
+# ifdef ALLOW_ECCO
+#  ifdef ALLOW_SIGMAR_COST_CONTRIBUTION
+      DO bj=myByLo(myThid),myByHi(myThid)
+       DO bi=myBxLo(myThid),myBxHi(myThid)
+        DO k=1,Nr
+         DO j=1-OLy,sNy+OLy
+          DO i=1-OLx,sNx+OLx
+           sigmaRfield(i,j,k,bi,bj) = 0. _d 0
+          ENDDO
+         ENDDO
+        ENDDO
+       ENDDO
+      ENDDO
+#  endif
+# endif
+#endif /* ALLOW_AUTODIFF */
+
+#ifdef ALLOW_FRAZIL
+      IF ( useFRAZIL ) THEN
+C--   Freeze water in the ocean interior and let it rise to the surface
+CADJ STORE theta = comlev1, key=ikey_dynamics, kind=isbyte
+CADJ STORE salt  = comlev1, key=ikey_dynamics, kind=isbyte
+       CALL FRAZIL_CALC_RHS( myTime, myIter, myThid )
+      ENDIF
+#endif /* ALLOW_FRAZIL */
+
+#ifndef OLD_THSICE_CALL_SEQUENCE
+#if (defined ALLOW_THSICE) && !(defined ALLOW_ATM2D)
+      IF ( useThSIce .AND. fluidIsWater ) THEN
+# ifdef ALLOW_AUTODIFF_TAMC
+CADJ STORE uice,vice         = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+CADJ STORE iceMask,iceHeight = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+CADJ STORE snowHeight, Tsrf  = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+CADJ STORE Qice1, Qice2      = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+CADJ STORE sHeating, snowAge = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+CADJ STORE hocemxl = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+CADJ STORE icflxsw = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+CADJ STORE salt,theta        = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+CADJ STORE uvel,vvel         = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+CADJ STORE qnet,qsw, empmr   = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+CADJ STORE atemp,aqh,precip  = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+CADJ STORE swdown,lwdown     = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+#  ifdef NONLIN_FRSURF
+CADJ STORE hFac_surfC       = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+#  endif
+# endif /* ALLOW_AUTODIFF_TAMC */
+# ifdef ALLOW_DEBUG
+        IF (debugMode) CALL DEBUG_CALL('THSICE_MAIN',myThid)
+# endif
+C--     Step forward Therm.Sea-Ice variables
+C       and modify forcing terms including effects from ice
+        CALL TIMER_START('THSICE_MAIN     [DO_OCEANIC_PHYS]', myThid)
+        CALL THSICE_MAIN( myTime, myIter, myThid )
+        CALL TIMER_STOP( 'THSICE_MAIN     [DO_OCEANIC_PHYS]', myThid)
+      ENDIF
+#endif /* ALLOW_THSICE */
+#endif /* ndef OLD_THSICE_CALL_SEQUENCE */
+
+#ifdef ALLOW_SEAICE
+# ifdef ALLOW_AUTODIFF
+CADJ STORE area   = comlev1, key=ikey_dynamics, kind=isbyte
+CADJ STORE fu,fv  = comlev1, key=ikey_dynamics, kind=isbyte
+CADJ STORE qnet   = comlev1, key=ikey_dynamics, kind=isbyte
+CADJ STORE qsw    = comlev1, key=ikey_dynamics, kind=isbyte
+CADJ STORE theta  = comlev1, key=ikey_dynamics, kind=isbyte
+CADJ STORE salt   = comlev1, key=ikey_dynamics, kind=isbyte
+#if (defined ALLOW_EXF) && (defined ALLOW_ATM_TEMP)
+CADJ STORE evap   = comlev1, key=ikey_dynamics, kind=isbyte
+#endif
+      IF ( .NOT.useSEAICE .AND. SEAICEadjMODE .EQ. -1 ) THEN
+        CALL SEAICE_FAKE( myTime, myIter, myThid )
+      ENDIF
+CADJ STORE area   = comlev1, key=ikey_dynamics, kind=isbyte
+CADJ STORE fu,fv  = comlev1, key=ikey_dynamics, kind=isbyte
+CADJ STORE qnet   = comlev1, key=ikey_dynamics, kind=isbyte
+CADJ STORE qsw    = comlev1, key=ikey_dynamics, kind=isbyte
+CADJ STORE theta  = comlev1, key=ikey_dynamics, kind=isbyte
+CADJ STORE salt   = comlev1, key=ikey_dynamics, kind=isbyte
+#if (defined ALLOW_EXF) && (defined ALLOW_ATM_TEMP)
+CADJ STORE evap   = comlev1, key=ikey_dynamics, kind=isbyte
+#endif
+# endif /* ALLOW_AUTODIFF */
+#endif /* ALLOW_SEAICE */
+
+#ifdef ALLOW_SEAICE
+      IF ( useSEAICE ) THEN
+# ifdef ALLOW_AUTODIFF_TAMC
+cph-adj-test(
+CADJ STORE area   = comlev1, key=ikey_dynamics, kind=isbyte
+CADJ STORE hsnow  = comlev1, key=ikey_dynamics, kind=isbyte
+CADJ STORE heff   = comlev1, key=ikey_dynamics, kind=isbyte
+CADJ STORE tices  = comlev1, key=ikey_dynamics, kind=isbyte
+CADJ STORE empmr, qnet  = comlev1, key=ikey_dynamics, kind=isbyte
+CADJ STORE qsw,saltflux = comlev1, key=ikey_dynamics, kind=isbyte
+CADJ STORE fu, fv = comlev1, key=ikey_dynamics, kind=isbyte
+cCADJ STORE theta  = comlev1, key=ikey_dynamics, kind=isbyte
+cCADJ STORE salt   = comlev1, key=ikey_dynamics, kind=isbyte
+cph-adj-test)
+c#ifdef ALLOW_EXF
+CADJ STORE atemp,aqh,precip    = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+CADJ STORE swdown,lwdown       = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+CADJ STORE evap                = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+CADJ STORE uwind,vwind         = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+c#endif
+CADJ STORE uvel,vvel           = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+#  ifdef SEAICE_CGRID
+CADJ STORE stressdivergencex   = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+CADJ STORE stressdivergencey   = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+#  endif
+#  ifdef SEAICE_ALLOW_DYNAMICS
+CADJ STORE uice                = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+CADJ STORE vice                = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+CADJ STORE dwatn               = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+#   ifdef SEAICE_ALLOW_EVP
+CADJ STORE seaice_sigma1       = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+CADJ STORE seaice_sigma2       = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+CADJ STORE seaice_sigma12      = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+#   endif
+#  endif
+#  ifdef SEAICE_VARIABLE_SALINITY
+CADJ STORE hsalt               = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+#  endif
+#  ifdef ATMOSPHERIC_LOADING
+CADJ STORE pload               = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+CADJ STORE siceload            = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+#  endif
+#  ifdef NONLIN_FRSURF
+CADJ STORE recip_hfacc         = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+#  endif
+#  ifdef ANNUAL_BALANCE
+CADJ STORE balance_itcount     = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+#  endif /* ANNUAL_BALANCE */
+#  ifdef ALLOW_THSICE
+C-- store thSIce vars before advection (called from SEAICE_MODEL) update them:
+CADJ STORE iceMask,iceHeight = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+CADJ STORE snowHeight, hOceMxL = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+CADJ STORE Qice1, Qice2  = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+#  endif /* ALLOW_THSICE */
+# endif /* ALLOW_AUTODIFF_TAMC */
+# ifdef ALLOW_DEBUG
+        IF (debugMode) CALL DEBUG_CALL('SEAICE_MODEL',myThid)
+# endif
+        CALL TIMER_START('SEAICE_MODEL    [DO_OCEANIC_PHYS]', myThid)
+        CALL SEAICE_MODEL( myTime, myIter, myThid )
+        CALL TIMER_STOP ('SEAICE_MODEL    [DO_OCEANIC_PHYS]', myThid)
+# ifdef ALLOW_COST
+        CALL SEAICE_COST_SENSI ( myTime, myIter, myThid )
+# endif
+      ENDIF
+#endif /* ALLOW_SEAICE */
+
+#if (defined ALLOW_OCN_COMPON_INTERF) && (defined ALLOW_THSICE)
+C--   After seaice-dyn and advection of pkg/thsice fields,
+C     Export ocean coupling fields to coupled interface (only with pkg/thsice)
+      IF ( useCoupler ) THEN
+# ifdef ALLOW_DEBUG
+        IF (debugMode) CALL DEBUG_CALL('OCN_EXPORT_DATA',myThid)
+# endif
+         CALL TIMER_START('OCN_EXPORT_DATA [DO_OCEANIC_PHYS]', myThid)
+         CALL OCN_EXPORT_DATA( myTime, myIter, myThid )
+         CALL TIMER_STOP ('OCN_EXPORT_DATA [DO_OCEANIC_PHYS]', myThid)
+      ENDIF
+#endif /* ALLOW_OCN_COMPON_INTERF & ALLOW_THSICE */
+
+#ifdef ALLOW_AUTODIFF_TAMC
+CADJ STORE sst, sss           = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+CADJ STORE qsw                = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+# ifdef ALLOW_SEAICE
+CADJ STORE area               = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+# endif
+#endif
+
+#ifdef OLD_THSICE_CALL_SEQUENCE
+#if (defined ALLOW_THSICE) && !(defined ALLOW_ATM2D)
+      IF ( useThSIce .AND. fluidIsWater ) THEN
+# ifdef ALLOW_AUTODIFF_TAMC
+cph(
+#  ifdef NONLIN_FRSURF
+CADJ STORE uice,vice        = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+CADJ STORE salt,theta       = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+CADJ STORE qnet,qsw, empmr  = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+CADJ STORE hFac_surfC       = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+#  endif
+# endif
+# ifdef ALLOW_DEBUG
+        IF (debugMode) CALL DEBUG_CALL('THSICE_MAIN',myThid)
+# endif
+C--     Step forward Therm.Sea-Ice variables
+C       and modify forcing terms including effects from ice
+        CALL TIMER_START('THSICE_MAIN     [DO_OCEANIC_PHYS]', myThid)
+        CALL THSICE_MAIN( myTime, myIter, myThid )
+        CALL TIMER_STOP( 'THSICE_MAIN     [DO_OCEANIC_PHYS]', myThid)
+      ENDIF
+#endif /* ALLOW_THSICE */
+#endif /* OLD_THSICE_CALL_SEQUENCE */
+
+#ifdef ALLOW_CPL_ISSM
+      IF ( useCoupler) CALL CPL_ISSM( myTime, myIter, myThid )
+#endif
+
+#ifdef ALLOW_SHELFICE
+      IF ( useShelfIce .AND. fluidIsWater ) THEN
+#ifdef ALLOW_DEBUG
+       IF (debugMode) CALL DEBUG_CALL('SHELFICE_THERMODYNAMICS',myThid)
+#endif
+#ifdef ALLOW_AUTODIFF_TAMC
+CADJ STORE salt, theta = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+CADJ STORE uvel, vvel = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+#endif
+C     compute temperature and (virtual) salt flux at the
+C     shelf-ice ocean interface
+       CALL TIMER_START('SHELFICE_THERMODYNAMICS [DO_OCEANIC_PHYS]',
+     &       myThid)
+       CALL SHELFICE_THERMODYNAMICS( myTime, myIter, myThid )
+       CALL TIMER_STOP( 'SHELFICE_THERMODYNAMICS [DO_OCEANIC_PHYS]',
+     &      myThid)
+      ENDIF
+#endif /* ALLOW_SHELFICE */
+
+#ifdef ALLOW_ICEFRONT
+      IF ( useICEFRONT .AND. fluidIsWater ) THEN
+#ifdef ALLOW_DEBUG
+       IF (debugMode) CALL DEBUG_CALL('ICEFRONT_THERMODYNAMICS',myThid)
+#endif
+C     compute temperature and (virtual) salt flux at the
+C     ice-front ocean interface
+       CALL TIMER_START('ICEFRONT_THERMODYNAMICS [DO_OCEANIC_PHYS]',
+     &       myThid)
+       CALL ICEFRONT_THERMODYNAMICS( myTime, myIter, myThid )
+       CALL TIMER_STOP( 'ICEFRONT_THERMODYNAMICS [DO_OCEANIC_PHYS]',
+     &      myThid)
+      ENDIF
+#endif /* ALLOW_ICEFRONT */
+
+#ifdef ALLOW_SALT_PLUME
+      IF ( useSALT_PLUME ) THEN
+Catn: exchanging saltPlumeFlux:
+          CALL SALT_PLUME_DO_EXCH( myTime, myIter, myThid )
+      ENDIF
+#endif /* ALLOW_SALT_PLUME */
+
+C--   Freeze water at the surface
+      IF ( allowFreezing ) THEN
+#ifdef ALLOW_AUTODIFF_TAMC
+CADJ STORE theta = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+#endif
+        CALL FREEZE_SURFACE( myTime, myIter, myThid )
+      ENDIF
+
+      iMin = 1-OLx
+      iMax = sNx+OLx
+      jMin = 1-OLy
+      jMax = sNy+OLy
+
+C---  Determines forcing terms based on external fields
+C     relaxation terms, etc.
+#ifdef ALLOW_AUTODIFF
+CADJ STORE salt, theta = comlev1, key = ikey_dynamics,
+CADJ &     kind = isbyte
+#else  /* ALLOW_AUTODIFF */
+C--   if fluid is not water, by-pass surfaceForcing, find_rho, gmredi
+C     and all vertical mixing schemes, but keep OBCS_CALC
+      IF ( fluidIsWater ) THEN
+#endif /* ALLOW_AUTODIFF */
+#ifdef ALLOW_DEBUG
+      IF (debugMode) CALL DEBUG_CALL('EXTERNAL_FORCING_SURF',myThid)
+#endif
+        CALL EXTERNAL_FORCING_SURF(
+     I             iMin, iMax, jMin, jMax,
+     I             myTime, myIter, myThid )
+
+#ifdef ALLOW_AUTODIFF_TAMC
+C--   HPF directive to help TAMC
+CHPF$ INDEPENDENT
+#endif /* ALLOW_AUTODIFF_TAMC */
+      DO bj=myByLo(myThid),myByHi(myThid)
+#ifdef ALLOW_AUTODIFF_TAMC
+C--   HPF directive to help TAMC
+CHPF$ INDEPENDENT
+#endif /* ALLOW_AUTODIFF_TAMC */
+       DO bi=myBxLo(myThid),myBxHi(myThid)
+
+#ifdef ALLOW_AUTODIFF_TAMC
+          act1 = bi - myBxLo(myThid)
+          max1 = myBxHi(myThid) - myBxLo(myThid) + 1
+          act2 = bj - myByLo(myThid)
+          max2 = myByHi(myThid) - myByLo(myThid) + 1
+          act3 = myThid - 1
+          max3 = nTx*nTy
+          act4 = ikey_dynamics - 1
+          itdkey = (act1 + 1) + act2*max1
+     &                      + act3*max1*max2
+     &                      + act4*max1*max2*max3
+#endif /* ALLOW_AUTODIFF_TAMC */
+
+C--   Set up work arrays with valid (i.e. not NaN) values
+C     These inital values do not alter the numerical results. They
+C     just ensure that all memory references are to valid floating
+C     point numbers. This prevents spurious hardware signals due to
+C     uninitialised but inert locations.
+        DO k=1,Nr
+         DO j=1-OLy,sNy+OLy
+          DO i=1-OLx,sNx+OLx
+C This is currently used by GMRedi, IVDC, MXL-depth  and Diagnostics
+           sigmaX(i,j,k) = 0. _d 0
+           sigmaY(i,j,k) = 0. _d 0
+           sigmaR(i,j,k) = 0. _d 0
+          ENDDO
+         ENDDO
+        ENDDO
+
+#ifdef ALLOW_AUTODIFF
+        DO j=1-OLy,sNy+OLy
+         DO i=1-OLx,sNx+OLx
+          rhoKm1 (i,j)   = 0. _d 0
+          rhoKp1 (i,j)   = 0. _d 0
+         ENDDO
+        ENDDO
+cph all the following init. are necessary for TAF
+cph although some of these are re-initialised later.
+        DO k=1,Nr
+         DO j=1-OLy,sNy+OLy
+          DO i=1-OLx,sNx+OLx
+           rhoInSitu(i,j,k,bi,bj) = 0.
+# ifdef ALLOW_GGL90
+           GGL90viscArU(i,j,k,bi,bj)  = 0. _d 0
+           GGL90viscArV(i,j,k,bi,bj)  = 0. _d 0
+           GGL90diffKr(i,j,k,bi,bj)  = 0. _d 0
+# endif /* ALLOW_GGL90 */
+# ifdef ALLOW_SALT_PLUME
+#  ifdef SALT_PLUME_VOLUME
+           SPforcingS(i,j,k,bi,bj) = 0. _d 0
+           SPforcingT(i,j,k,bi,bj) = 0. _d 0
+#  endif
+# endif /* ALLOW_SALT_PLUME */
+          ENDDO
+         ENDDO
+        ENDDO
+#ifdef ALLOW_OFFLINE
+       IF ( calcConvect ) THEN
+#endif
+        DO k=1,Nr
+         DO j=1-OLy,sNy+OLy
+          DO i=1-OLx,sNx+OLx
+           IVDConvCount(i,j,k,bi,bj) = 0.
+          ENDDO
+         ENDDO
+        ENDDO
+#ifdef ALLOW_OFFLINE
+       ENDIF
+       IF ( calcGMRedi ) THEN
+#endif
+# ifdef ALLOW_GMREDI
+        DO k=1,Nr
+         DO j=1-OLy,sNy+OLy
+          DO i=1-OLx,sNx+OLx
+           Kwx(i,j,k,bi,bj)  = 0. _d 0
+           Kwy(i,j,k,bi,bj)  = 0. _d 0
+           Kwz(i,j,k,bi,bj)  = 0. _d 0
+#  ifdef GM_NON_UNITY_DIAGONAL
+           Kux(i,j,k,bi,bj)  = 0. _d 0
+           Kvy(i,j,k,bi,bj)  = 0. _d 0
+#  endif
+#  ifdef GM_EXTRA_DIAGONAL
+           Kuz(i,j,k,bi,bj)  = 0. _d 0
+           Kvz(i,j,k,bi,bj)  = 0. _d 0
+#  endif
+#  ifdef GM_BOLUS_ADVEC
+           GM_PsiX(i,j,k,bi,bj)  = 0. _d 0
+           GM_PsiY(i,j,k,bi,bj)  = 0. _d 0
+#  endif
+#  ifdef GM_VISBECK_VARIABLE_K
+           VisbeckK(i,j,bi,bj)   = 0. _d 0
+#  endif
+          ENDDO
+         ENDDO
+        ENDDO
+# endif /* ALLOW_GMREDI */
+#ifdef ALLOW_OFFLINE
+       ENDIF
+       IF ( calcKPP ) THEN
+#endif
+# ifdef ALLOW_KPP
+        DO k=1,Nr
+         DO j=1-OLy,sNy+OLy
+          DO i=1-OLx,sNx+OLx
+           KPPdiffKzS(i,j,k,bi,bj)  = 0. _d 0
+           KPPdiffKzT(i,j,k,bi,bj)  = 0. _d 0
+          ENDDO
+         ENDDO
+        ENDDO
+# endif /* ALLOW_KPP */
+#ifdef ALLOW_OFFLINE
+       ENDIF
+#endif
+#endif /* ALLOW_AUTODIFF */
+
+#ifdef ALLOW_AUTODIFF_TAMC
+CADJ STORE theta(:,:,:,bi,bj) = comlev1_bibj, key=itdkey,
+CADJ &     kind = isbyte
+CADJ STORE salt (:,:,:,bi,bj) = comlev1_bibj, key=itdkey,
+CADJ &     kind = isbyte
+CADJ STORE totphihyd(:,:,:,bi,bj)
+CADJ &     = comlev1_bibj, key=itdkey,
+CADJ &     kind = isbyte
+# ifdef ALLOW_KPP
+CADJ STORE uvel (:,:,:,bi,bj) = comlev1_bibj, key=itdkey,
+CADJ &     kind = isbyte
+CADJ STORE vvel (:,:,:,bi,bj) = comlev1_bibj, key=itdkey,
+CADJ &     kind = isbyte
+# endif
+# ifdef ALLOW_SALT_PLUME
+CADJ STORE saltplumedepth(:,:,bi,bj) = comlev1_bibj, key=itdkey,
+CADJ &     kind = isbyte
+CADJ STORE saltplumeflux(:,:,bi,bj) = comlev1_bibj, key=itdkey,
+CADJ &     kind = isbyte
+# endif
+#endif /* ALLOW_AUTODIFF_TAMC */
+
+C--   Always compute density (stored in common block) here; even when it is not
+C     needed here, will be used anyway in calc_phi_hyd (data flow easier this way)
+#ifdef ALLOW_DEBUG
+        IF (debugMode) CALL DEBUG_CALL('FIND_RHO_2D (xNr)',myThid)
+#endif
+#ifdef ALLOW_AUTODIFF
+        IF ( fluidIsWater ) THEN
+#endif /* ALLOW_AUTODIFF */
+#ifdef ALLOW_DOWN_SLOPE
+         IF ( useDOWN_SLOPE ) THEN
+           DO k=1,Nr
+            CALL DWNSLP_CALC_RHO(
+     I                  theta, salt,
+     O                  rhoInSitu(1-OLx,1-OLy,k,bi,bj),
+     I                  k, bi, bj, myTime, myIter, myThid )
+           ENDDO
+         ENDIF
+#endif /* ALLOW_DOWN_SLOPE */
+#ifdef ALLOW_BBL
+         IF ( useBBL ) THEN
+C     pkg/bbl requires in-situ bbl density for depths equal to and deeper than the bbl.
+C     To reduce computation and storage requirement, these densities are stored in the
+C     dry grid boxes of rhoInSitu.  See BBL_CALC_RHO for details.
+           DO k=Nr,1,-1
+            CALL BBL_CALC_RHO(
+     I                  theta, salt,
+     O                  rhoInSitu,
+     I                  k, bi, bj, myTime, myIter, myThid )
+
+           ENDDO
+         ENDIF
+#endif /* ALLOW_BBL */
+         IF ( .NOT. ( useDOWN_SLOPE .OR. useBBL ) ) THEN
+           DO k=1,Nr
+            CALL FIND_RHO_2D(
+     I                iMin, iMax, jMin, jMax, k,
+     I                theta(1-OLx,1-OLy,k,bi,bj),
+     I                salt (1-OLx,1-OLy,k,bi,bj),
+     O                rhoInSitu(1-OLx,1-OLy,k,bi,bj),
+     I                k, bi, bj, myThid )
+           ENDDO
+         ENDIF
+#ifdef ALLOW_AUTODIFF
+        ELSE
+C-        fluid is not water:
+          DO k=1,Nr
+           IF ( select_rStar.GE.1 .OR. selectSigmaCoord.GE.1 ) THEN
+C-    isothermal (theta=const) reference state
+             thetaRef = thetaConst
+           ELSE
+C-    horizontally uniform (tRef) reference state
+             thetaRef = tRef(k)
+           ENDIF
+           DO j=1-OLy,sNy+OLy
+            DO i=1-OLx,sNx+OLx
+             rhoInSitu(i,j,k,bi,bj) =
+     &         ( theta(i,j,k,bi,bj)
+     &              *( salt(i,j,k,bi,bj)*atm_Rq + oneRL )
+     &         - thetaRef )*maskC(i,j,k,bi,bj)
+            ENDDO
+           ENDDO
+          ENDDO
+        ENDIF
+#endif /* ALLOW_AUTODIFF */
+
+#ifdef ALLOW_DEBUG
+        IF (debugMode) THEN
+          WRITE(msgBuf,'(A,2(I4,A))')
+     &         'ENTERING UPWARD K LOOP (bi=', bi, ', bj=', bj,')'
+          CALL DEBUG_MSG(msgBuf(1:43),myThid)
+        ENDIF
+#endif
+
+C--     Start of diagnostic loop
+        DO k=Nr,1,-1
+
+#ifdef ALLOW_AUTODIFF_TAMC
+C? Patrick, is this formula correct now that we change the loop range?
+C? Do we still need this?
+cph kkey formula corrected.
+cph Needed for rhoK, rhoKm1, in the case useGMREDI.
+          kkey = (itdkey-1)*Nr + k
+#endif /* ALLOW_AUTODIFF_TAMC */
+
+c#ifdef ALLOW_AUTODIFF_TAMC
+cCADJ STORE theta(:,:,k,bi,bj) = comlev1_bibj_k, key=kkey,
+cCADJ &     kind = isbyte
+cCADJ STORE salt(:,:,k,bi,bj)  = comlev1_bibj_k, key=kkey,
+cCADJ &     kind = isbyte
+c#endif /* ALLOW_AUTODIFF_TAMC */
+
+C--       Calculate gradients of potential density for isoneutral
+C         slope terms (e.g. GM/Redi tensor or IVDC diffusivity)
+          IF ( calcGMRedi .OR. (k.GT.1 .AND. calcConvect)
+     &         .OR. usePP81 .OR. useKL10
+     &         .OR. useMY82 .OR. useGGL90
+     &         .OR. useSALT_PLUME .OR. doDiagsRho.GE.1 ) THEN
+            IF (k.GT.1) THEN
+#ifdef ALLOW_AUTODIFF_TAMC
+CADJ STORE theta(:,:,k-1,bi,bj) = comlev1_bibj_k, key=kkey,
+CADJ &     kind = isbyte
+CADJ STORE salt (:,:,k-1,bi,bj) = comlev1_bibj_k, key=kkey,
+CADJ &     kind = isbyte
+CADJ STORE rhokm1 (bi,bj)       = comlev1_bibj_k, key=kkey,
+CADJ &     kind = isbyte
+#endif /* ALLOW_AUTODIFF_TAMC */
+             CALL FIND_RHO_2D(
+     I                 iMin, iMax, jMin, jMax, k,
+     I                 theta(1-OLx,1-OLy,k-1,bi,bj),
+     I                 salt (1-OLx,1-OLy,k-1,bi,bj),
+     O                 rhoKm1,
+     I                 k-1, bi, bj, myThid )
+            ENDIF
+#ifdef ALLOW_DEBUG
+            IF (debugMode) CALL DEBUG_CALL('GRAD_SIGMA',myThid)
+#endif
+cph Avoid variable aliasing for adjoint !!!
+            DO j=jMin,jMax
+             DO i=iMin,iMax
+              rhoKp1(i,j) = rhoInSitu(i,j,k,bi,bj)
+             ENDDO
+            ENDDO
+            CALL GRAD_SIGMA(
+     I             bi, bj, iMin, iMax, jMin, jMax, k,
+     I             rhoInSitu(1-OLx,1-OLy,k,bi,bj), rhoKm1, rhoKp1,
+     O             sigmaX, sigmaY, sigmaR,
+     I             myThid )
+#ifdef ALLOW_ECCO
+# ifdef ALLOW_SIGMAR_COST_CONTRIBUTION
+            DO j=jMin,jMax
+             DO i=iMin,iMax
+              sigmaRfield(i,j,k,bi,bj)=sigmaR(i,j,k)
+             ENDDO
+            ENDDO
+# endif
+#endif /* ALLOW_ECCO */
+#ifdef ALLOW_AUTODIFF
+#ifdef GMREDI_WITH_STABLE_ADJOINT
+cgf zero out adjoint fields to stabilize pkg/gmredi adjoint
+cgf -> cuts adjoint dependency from slope to state
+            CALL ZERO_ADJ_LOC( Nr, sigmaX, myThid)
+            CALL ZERO_ADJ_LOC( Nr, sigmaY, myThid)
+            CALL ZERO_ADJ_LOC( Nr, sigmaR, myThid)
+#endif
+#endif /* ALLOW_AUTODIFF */
+          ENDIF
+
+C--       Implicit Vertical Diffusion for Convection
+          IF (k.GT.1 .AND. calcConvect) THEN
+#ifdef ALLOW_DEBUG
+            IF (debugMode) CALL DEBUG_CALL('CALC_IVDC',myThid)
+#endif
+            CALL CALC_IVDC(
+     I        bi, bj, iMin, iMax, jMin, jMax, k,
+     I        sigmaR,
+     I        myTime, myIter, myThid)
+          ENDIF
+
+#ifdef ALLOW_DIAGNOSTICS
+          IF ( doDiagsRho.GE.4 ) THEN
+            CALL DIAGS_RHO_L( doDiagsRho, k, bi, bj,
+     I                        rhoInSitu(1-OLx,1-OLy,1,bi,bj),
+     I                        rhoKm1, wVel,
+     I                        myTime, myIter, myThid )
+          ENDIF
+#endif
+
+C--     end of diagnostic k loop (Nr:1)
+        ENDDO
+
+#ifdef ALLOW_AUTODIFF_TAMC
+CADJ STORE IVDConvCount(:,:,:,bi,bj)
+CADJ &     = comlev1_bibj, key=itdkey,
+CADJ &     kind = isbyte
+#endif
+
+C--     Diagnose Mixed Layer Depth:
+        IF ( calcGMRedi .OR. MOD(doDiagsRho,2).EQ.1 ) THEN
+          CALL CALC_OCE_MXLAYER(
+     I              rhoInSitu(1-OLx,1-OLy,1,bi,bj), sigmaR,
+     I              bi, bj, myTime, myIter, myThid )
+        ENDIF
+
+#ifdef ALLOW_SALT_PLUME
+        IF ( useSALT_PLUME ) THEN
+          CALL SALT_PLUME_CALC_DEPTH(
+     I              rhoInSitu(1-OLx,1-OLy,1,bi,bj), sigmaR,
+     I              bi, bj, myTime, myIter, myThid )
+#ifdef SALT_PLUME_VOLUME
+          CALL SALT_PLUME_VOLFRAC(
+     I              bi, bj, myTime, myIter, myThid )
+C-- get forcings for kpp
+          CALL SALT_PLUME_APPLY(
+     I              1, bi, bj, recip_hFacC(1-OLx,1-OLy,1,bi,bj),
+     I              theta, 0,
+     I              myTime, myIter, myThid )
+          CALL SALT_PLUME_APPLY(
+     I              2, bi, bj, recip_hFacC(1-OLx,1-OLy,1,bi,bj),
+     I              salt, 0,
+     I              myTime, myIter, myThid )
+C-- need to call this S/R from here to apply just before kpp
+          CALL SALT_PLUME_FORCING_SURF(
+     I              bi, bj, iMin, iMax, jMin, jMax,
+     I              myTime, myIter, myThid )
+#endif /* SALT_PLUME_VOLUME */
+        ENDIF
+#endif /* ALLOW_SALT_PLUME */
+
+#ifdef ALLOW_DIAGNOSTICS
+        IF ( MOD(doDiagsRho,4).GE.2 ) THEN
+          CALL DIAGNOSTICS_FILL (sigmaR, 'DRHODR  ', 0, Nr,
+     &         2, bi, bj, myThid)
+        ENDIF
+#endif /* ALLOW_DIAGNOSTICS */
+
+C--    This is where EXTERNAL_FORCING_SURF(bi,bj) used to be called;
+C      now called earlier, before bi,bj loop.
+
+#ifdef ALLOW_AUTODIFF_TAMC
+cph needed for KPP
+CADJ STORE surfaceForcingU(:,:,bi,bj)
+CADJ &     = comlev1_bibj, key=itdkey,
+CADJ &     kind = isbyte
+CADJ STORE surfaceForcingV(:,:,bi,bj)
+CADJ &     = comlev1_bibj, key=itdkey,
+CADJ &     kind = isbyte
+CADJ STORE surfaceForcingS(:,:,bi,bj)
+CADJ &     = comlev1_bibj, key=itdkey,
+CADJ &     kind = isbyte
+CADJ STORE surfaceForcingT(:,:,bi,bj)
+CADJ &     = comlev1_bibj, key=itdkey,
+CADJ &     kind = isbyte
+CADJ STORE surfaceForcingTice(:,:,bi,bj)
+CADJ &     = comlev1_bibj, key=itdkey,
+CADJ &     kind = isbyte
+#endif /* ALLOW_AUTODIFF_TAMC */
+
+#ifdef  ALLOW_KPP
+C--     Compute KPP mixing coefficients
+        IF ( calcKPP ) THEN
+#ifdef ALLOW_DEBUG
+          IF (debugMode) CALL DEBUG_CALL('KPP_CALC',myThid)
+#endif
+          CALL TIMER_START('KPP_CALC [DO_OCEANIC_PHYS]', myThid)
+          CALL KPP_CALC(
+     I                  bi, bj, myTime, myIter, myThid )
+          CALL TIMER_STOP ('KPP_CALC [DO_OCEANIC_PHYS]', myThid)
+#if (defined ALLOW_AUTODIFF) && !(defined ALLOW_OFFLINE)
+        ELSE
+          CALL KPP_CALC_DUMMY(
+     I                  bi, bj, myTime, myIter, myThid )
+#endif /* ALLOW_AUTODIFF and not ALLOW_OFFLINE */
+        ENDIF
+#endif  /* ALLOW_KPP */
+
+#ifdef  ALLOW_PP81
+C--     Compute PP81 mixing coefficients
+        IF (usePP81) THEN
+#ifdef ALLOW_DEBUG
+          IF (debugMode) CALL DEBUG_CALL('PP81_CALC',myThid)
+#endif
+          CALL PP81_CALC(
+     I                     bi, bj, sigmaR, myTime, myIter, myThid )
+        ENDIF
+#endif /* ALLOW_PP81 */
+
+#ifdef  ALLOW_KL10
+C--     Compute KL10 mixing coefficients
+        IF (useKL10) THEN
+#ifdef ALLOW_DEBUG
+          IF (debugMode) CALL DEBUG_CALL('KL10_CALC',myThid)
+#endif
+          CALL KL10_CALC(
+     I                     bi, bj, sigmaR, myTime, myIter, myThid )
+        ENDIF
+#endif /* ALLOW_KL10 */
+
+#ifdef  ALLOW_MY82
+C--     Compute MY82 mixing coefficients
+        IF (useMY82) THEN
+#ifdef ALLOW_DEBUG
+          IF (debugMode) CALL DEBUG_CALL('MY82_CALC',myThid)
+#endif
+          CALL MY82_CALC(
+     I                     bi, bj, sigmaR, myTime, myIter, myThid )
+        ENDIF
+#endif /* ALLOW_MY82 */
+
+#ifdef  ALLOW_GGL90
+#ifdef ALLOW_AUTODIFF_TAMC
+CADJ STORE GGL90TKE (:,:,:,bi,bj) = comlev1_bibj, key=itdkey,
+CADJ &     kind = isbyte
+#endif /* ALLOW_AUTODIFF_TAMC */
+C--     Compute GGL90 mixing coefficients
+        IF (useGGL90) THEN
+#ifdef ALLOW_DEBUG
+          IF (debugMode) CALL DEBUG_CALL('GGL90_CALC',myThid)
+#endif
+          CALL TIMER_START('GGL90_CALC [DO_OCEANIC_PHYS]', myThid)
+          CALL GGL90_CALC(
+     I                     bi, bj, sigmaR, myTime, myIter, myThid )
+          CALL TIMER_STOP ('GGL90_CALC [DO_OCEANIC_PHYS]', myThid)
+        ENDIF
+#endif /* ALLOW_GGL90 */
+
+#ifdef ALLOW_TIMEAVE
+        IF ( taveFreq.GT. 0. _d 0 ) THEN
+          CALL TIMEAVE_SURF_FLUX( bi, bj, myTime, myIter, myThid)
+        ENDIF
+        IF ( taveFreq.GT.0. .AND. calcConvect ) THEN
+          CALL TIMEAVE_CUMULATE(ConvectCountTave, IVDConvCount,
+     I                           Nr, deltaTClock, bi, bj, myThid)
+        ENDIF
+#endif /* ALLOW_TIMEAVE */
+
+#ifdef ALLOW_GMREDI
+#ifdef ALLOW_AUTODIFF_TAMC
+# ifndef GM_EXCLUDE_CLIPPING
+cph storing here is needed only for one GMREDI_OPTIONS:
+cph define GM_BOLUS_ADVEC
+cph keep it although TAF says you dont need to.
+cph but I have avoided the #ifdef for now, in case more things change
+CADJ STORE sigmaX(:,:,:)        = comlev1_bibj, key=itdkey,
+CADJ &     kind = isbyte
+CADJ STORE sigmaY(:,:,:)        = comlev1_bibj, key=itdkey,
+CADJ &     kind = isbyte
+CADJ STORE sigmaR(:,:,:)        = comlev1_bibj, key=itdkey,
+CADJ &     kind = isbyte
+# endif
+#endif /* ALLOW_AUTODIFF_TAMC */
+
+C--     Calculate iso-neutral slopes for the GM/Redi parameterisation
+        IF ( calcGMRedi ) THEN
+#ifdef ALLOW_DEBUG
+          IF (debugMode) CALL DEBUG_CALL('GMREDI_CALC_TENSOR',myThid)
+#endif
+          CALL GMREDI_CALC_TENSOR(
+     I             iMin, iMax, jMin, jMax,
+     I             sigmaX, sigmaY, sigmaR,
+     I             bi, bj, myTime, myIter, myThid )
+#if (defined ALLOW_AUTODIFF) && !(defined ALLOW_OFFLINE)
+        ELSE
+          CALL GMREDI_CALC_TENSOR_DUMMY(
+     I             iMin, iMax, jMin, jMax,
+     I             sigmaX, sigmaY, sigmaR,
+     I             bi, bj, myTime, myIter, myThid )
+#endif /* ALLOW_AUTODIFF and not ALLOW_OFFLINE */
+        ENDIF
+#endif /* ALLOW_GMREDI */
+
+#ifdef ALLOW_DOWN_SLOPE
+        IF ( useDOWN_SLOPE ) THEN
+C--     Calculate Downsloping Flow for Down_Slope parameterization
+         IF ( usingPCoords ) THEN
+          CALL DWNSLP_CALC_FLOW(
+     I                bi, bj, kSurfC, rhoInSitu,
+     I                myTime, myIter, myThid )
+         ELSE
+          CALL DWNSLP_CALC_FLOW(
+     I                bi, bj, kLowC, rhoInSitu,
+     I                myTime, myIter, myThid )
+         ENDIF
+        ENDIF
+#endif /* ALLOW_DOWN_SLOPE */
+
+C--   end bi,bj loops.
+       ENDDO
+      ENDDO
+
+#ifndef ALLOW_AUTODIFF
+C---  if fluid Is Water: end
+      ENDIF
+#endif
+
+#ifdef ALLOW_OFFLINE
+      IF ( useOffLine ) THEN
+#ifdef ALLOW_DEBUG
+        IF (debugMode) CALL DEBUG_CALL('OFFLINE_GET_DIFFUS',myThid)
+#endif /* ALLOW_DEBUG */
+        CALL OFFLINE_GET_DIFFUS( myTime, myIter, myThid )
+      ENDIF
+#endif /* ALLOW_OFFLINE */
+
+#ifdef ALLOW_BBL
+      IF ( useBBL ) THEN
+       CALL BBL_CALC_RHS(
+     I                          myTime, myIter, myThid )
+      ENDIF
+#endif /* ALLOW_BBL */
+
+#ifdef ALLOW_MYPACKAGE
+      IF ( useMYPACKAGE ) THEN
+       CALL MYPACKAGE_CALC_RHS(
+     I                          myTime, myIter, myThid )
+      ENDIF
+#endif /* ALLOW_MYPACKAGE */
+
+#ifdef ALLOW_GMREDI
+      IF ( calcGMRedi ) THEN
+        CALL GMREDI_DO_EXCH( myTime, myIter, myThid )
+      ENDIF
+#endif /* ALLOW_GMREDI */
+
+#ifdef ALLOW_KPP
+      IF ( calcKPP ) THEN
+        CALL KPP_DO_EXCH( myThid )
+      ENDIF
+#endif /* ALLOW_KPP */
+
+#ifdef ALLOW_DIAGNOSTICS
+      IF ( fluidIsWater .AND. useDiagnostics ) THEN
+        CALL DIAGS_RHO_G(
+     I                    rhoInSitu, uVel, vVel, wVel,
+     I                    myTime, myIter, myThid )
+      ENDIF
+      IF ( useDiagnostics ) THEN
+        CALL DIAGS_OCEANIC_SURF_FLUX( myTime, myIter, myThid )
+      ENDIF
+      IF ( calcConvect .AND. useDiagnostics ) THEN
+        CALL DIAGNOSTICS_FILL( IVDConvCount, 'CONVADJ ',
+     &                               0, Nr, 0, 1, 1, myThid )
+      ENDIF
+#ifdef ALLOW_SALT_PLUME
+      IF ( useDiagnostics )
+     &      CALL SALT_PLUME_DIAGNOSTICS_FILL(bi,bj,myThid)
+#endif
+#endif
+
+#ifdef ALLOW_DEBUG
+      IF (debugMode) CALL DEBUG_LEAVE('DO_OCEANIC_PHYS',myThid)
+#endif
+
+      RETURN
+      END
Index: /issm/trunk/test/MITgcm/code/eeboot_minimal.F
===================================================================
--- /issm/trunk/test/MITgcm/code/eeboot_minimal.F	(revision 22758)
+++ /issm/trunk/test/MITgcm/code/eeboot_minimal.F	(revision 22758)
@@ -0,0 +1,309 @@
+C $Header: /u/gcmpack/MITgcm/eesupp/src/eeboot_minimal.F,v 1.31 2017/07/26 21:23:07 jmc Exp $
+C $Name:  $
+
+#include "PACKAGES_CONFIG.h"
+#include "CPP_EEOPTIONS.h"
+
+CBOP
+C     !ROUTINE: EEBOOT_MINIMAL
+
+C     !INTERFACE:
+      SUBROUTINE EEBOOT_MINIMAL( myComm )
+
+C     !DESCRIPTION:
+C     *==========================================================*
+C     | SUBROUTINE EEBOOT\_MINIMAL
+C     | o Set an initial environment that is predictable i.e.
+C     | behaves in a similar way on all machines and stable.
+C     *==========================================================*
+C     | Under MPI this routine calls MPI\_INIT to setup the
+C     | mpi environment ( on some systems the code is running as
+C     | a single process prior to MPI\_INIT, on others the mpirun
+C     | script has already created multiple processes). Until
+C     | MPI\_Init is called it is unclear what state the
+C     | application is in. Once this routine has been run it is
+C     | "safe" to do things like I/O to report erros and to get
+C     | run parameters.
+C     | Note: This routine can also be compiled with CPP
+C     | directives set so that no multi-processing is initialise.
+C     | This is OK and will work fine.
+C     *==========================================================*
+
+C     !USES:
+      IMPLICIT NONE
+C     == Global data ==
+#include "SIZE.h"
+#include "EEPARAMS.h"
+#include "EESUPPORT.h"
+
+C     !ROUTINE ARGUMENTS
+C     == Routine arguments ==
+C     myComm     :: Communicator that is passed down from
+C                   upper level driver (if there is one).
+      INTEGER myComm
+
+C     !LOCAL VARIABLES:
+C     == Local variables ==
+C     myThid     :: Temp. dummy thread number.
+C     fNam       :: Used to build file name for standard and error output.
+C     msgBuf     :: Used to build messages for printing.
+      INTEGER myThid
+#ifdef USE_PDAF
+      CHARACTER*18 fNam
+#else
+      CHARACTER*13 fNam
+#endif /* USE_PDAF */
+      CHARACTER*(MAX_LEN_MBUF) msgBuf
+#ifdef ALLOW_USE_MPI
+C     mpiRC      :: Error code reporting variable used with MPI.
+      INTEGER mpiRC
+      INTEGER mpiIsInitialized
+      LOGICAL doReport
+#if defined(ALLOW_OASIS) || defined(COMPONENT_MODULE)
+      INTEGER mpiMyWid
+#endif
+#ifdef ALLOW_CPL_ISSM
+      COMMON /CPL_MPI_ID/ mpiMyWid, toissmcomm
+      INTEGER             mpiMyWid, toissmcomm
+      INTEGER my_local_rank,my_local_size, numprocsworld
+      INTEGER status(MPI_STATUS_SIZE)
+#endif /* ALLOW_CPL_ISSM */
+#if defined(ALLOW_NEST_PARENT) || defined(ALLOW_NEST_CHILD)
+      INTEGER mpiMyWid, color
+#endif
+#ifdef USE_PDAF
+      INTEGER mpi_task_id
+#endif /* USE_PDAF */
+#endif /* ALLOW_USE_MPI */
+CEOP
+
+C--   Default values set to single processor case
+      numberOfProcs = 1
+      myProcId      = 0
+      pidIO         = myProcId
+      myProcessStr  = '------'
+C     Set a dummy value for myThid because we are not multi-threading yet.
+      myThid        = 1
+
+C     Annoyingly there is no universal way to have the usingMPI
+C     parameter work as one might expect. This is because, on some
+C     systems I/O does not work until MPI_Init has been called.
+C     The solution for now is that the parameter below may need to
+C     be changed manually!
+#ifdef ALLOW_USE_MPI
+      usingMPI = .TRUE.
+#else
+      usingMPI = .FALSE.
+#endif
+
+      IF ( .NOT.usingMPI ) THEN
+
+        WRITE(myProcessStr,'(I4.4)') myProcId
+        WRITE(fNam,'(A,A)') 'STDERR.', myProcessStr(1:4)
+        OPEN(errorMessageUnit,FILE=fNam,STATUS='unknown')
+c       WRITE(fNam,'(A,A)') 'STDOUT.', myProcessStr(1:4)
+c       OPEN(standardMessageUnit,FILE=fNam,STATUS='unknown')
+
+#ifdef ALLOW_USE_MPI
+      ELSE
+C--   MPI style multiple-process initialisation
+C--   =========================================
+
+       CALL MPI_Initialized( mpiIsInitialized, mpiRC )
+
+       IF ( mpiIsInitialized .EQ. 0 ) THEN
+C--     Initialise MPI multi-process parallel environment.
+C       On some systems program forks at this point. Others have already
+C       forked within mpirun - now thats an open standard!
+        CALL MPI_INIT( mpiRC )
+        IF ( mpiRC .NE. MPI_SUCCESS ) THEN
+         eeBootError = .TRUE.
+         WRITE(msgBuf,'(A,I5)')
+     &        'EEBOOT_MINIMAL: MPI_INIT return code', mpiRC
+         CALL PRINT_ERROR( msgBuf, myThid )
+         GOTO 999
+        ENDIF
+
+C--     MPI has now been initialized ; now we need to either
+C       ask for a communicator or pretend that we have:
+C       Pretend that we have asked for a communicator
+        MPI_COMM_MODEL = MPI_COMM_WORLD
+
+       ELSE
+C--     MPI was already initialized and communicator has been passed
+C       down from upper level driver
+        MPI_COMM_MODEL = myComm
+
+       ENDIF
+
+       doReport = .FALSE.
+#ifdef USE_PDAF
+C     initialize PDAF
+C     for more output increase second parameter from 1 to 2
+       CALL INIT_PARALLEL_PDAF(0, 1, MPI_COMM_MODEL, MPI_COMM_MODEL,
+     &      mpi_task_id)
+#endif /* USE_PDAF */
+
+#ifdef ALLOW_OASIS
+C      add a 1rst preliminary call EESET_PARAMS to set useOASIS
+C      (needed to decide either to call OASIS_INIT or not)
+       CALL MPI_COMM_RANK( MPI_COMM_WORLD, mpiMyWId, mpiRC )
+       CALL EESET_PARMS ( mpiMyWId, doReport )
+       IF ( useOASIS ) CALL OASIS_INIT(MPI_COMM_MODEL)
+#endif /* ALLOW_OASIS */
+
+#ifdef COMPONENT_MODULE
+C--    Set the running directory
+       CALL MPI_COMM_RANK( MPI_COMM_WORLD, mpiMyWId, mpiRC )
+       CALL SETDIR( mpiMyWId )
+
+C- jmc: test:
+C      add a 1rst preliminary call EESET_PARAMS to set useCoupler
+C      (needed to decide either to call CPL_INIT or not)
+       CALL EESET_PARMS ( mpiMyWId, doReport )
+C- jmc: test end ; otherwise, uncomment next line:
+c      useCoupler = .TRUE.
+
+C--    Ask coupler interface for a communicator
+       IF ( useCoupler) CALL CPL_INIT
+#endif /* COMPONENT_MODULE */
+
+C--    Case with Nest(ing)
+#if defined(ALLOW_NEST_PARENT) || defined(ALLOW_NEST_CHILD)
+C--    Set the running directory
+       CALL MPI_COMM_RANK( MPI_COMM_WORLD, mpiMyWId, mpiRC )
+       CALL SETDIR( mpiMyWId )
+
+C--    Setup Nesting Execution Environment
+       CALL NEST_EEINIT( mpiMyWId, color )
+#endif /* ALLOW_NEST_PARENT | ALLOW_NEST_CHILD */
+
+#ifdef ALLOW_CPL_ISSM
+C     add a 1rst preliminary call EESET_PARAMS to set useCoupler
+       CALL MPI_COMM_RANK(MPI_COMM_WORLD, mpiMyWid, mpiRC)
+       CALL EESET_PARMS ( mpiMyWId, doReport )
+
+       IF ( useCoupler ) THEN
+          CALL MPI_COMM_SIZE(MPI_COMM_WORLD, numprocsworld, mpiRC)
+
+c     Split world into sub-communicators for each and every model:*/
+          CALL MPI_COMM_SPLIT(MPI_COMM_WORLD,1,MPIMYWID,
+     &         MPI_COMM_MODEL,mpiRC)
+
+          print*,'Oc My global rank',mpiMyWid
+          print*,'Oc My world size:',numprocsworld
+
+          CALL MPI_INTERCOMM_CREATE(MPI_COMM_MODEL,0,MPI_COMM_WORLD,
+     &         0,0,toissmcomm,mpiRC)
+
+          CALL MPI_COMM_RANK(MPI_COMM_MODEL, my_local_rank, mpiRC)
+          CALL MPI_COMM_SIZE(MPI_COMM_MODEL, my_local_size, mpiRC)
+
+          print*,'Oc My global rank',mpiMyWid,'MyLocal rank: ',
+     &         my_local_rank
+          print*,'Oc My world size:',numprocsworld,'My local size: ',
+     &         my_local_size
+       ENDIF
+#endif /* ALLOW_CPL_ISSM */
+
+C---+----1----+----2----+----3----+----4----+----5----+----6----+----7-|--+----|
+
+C--    Get my process number
+       CALL MPI_COMM_RANK( MPI_COMM_MODEL, mpiMyId, mpiRC )
+       IF ( mpiRC .NE. MPI_SUCCESS ) THEN
+        eeBootError = .TRUE.
+        WRITE(msgBuf,'(A,I5)')
+     &        'EEBOOT_MINIMAL: MPI_COMM_RANK return code', mpiRC
+        CALL PRINT_ERROR( msgBuf, myThid )
+        GOTO 999
+       ENDIF
+       myProcId = mpiMyId
+#ifdef USE_PDAF
+       WRITE(myProcessStr,'(I4.4,A1,I4.4)') mpi_task_id,'.',myProcId
+#else
+       WRITE(myProcessStr,'(I4.4)') myProcId
+#endif /* USE_PDAF */
+       mpiPidIo = myProcId
+       pidIO    = mpiPidIo
+       IF ( mpiPidIo .EQ. myProcId ) THEN
+#ifdef SINGLE_DISK_IO
+        IF( myProcId .EQ. 0 ) THEN
+#endif
+         WRITE(fNam,'(A,A)') 'STDERR.', myProcessStr(1:4)
+#ifdef USE_PDAF
+         WRITE(fNam,'(A,A)') 'STDERR.', myProcessStr(1:9)
+#endif
+         OPEN(errorMessageUnit,FILE=fNam,STATUS='unknown')
+         WRITE(fNam,'(A,A)') 'STDOUT.', myProcessStr(1:4)
+#ifdef USE_PDAF
+         WRITE(fNam,'(A,A)') 'STDOUT.', myProcessStr(1:9)
+#endif
+         OPEN(standardMessageUnit,FILE=fNam,STATUS='unknown')
+#ifdef SINGLE_DISK_IO
+        ELSE
+         OPEN(errorMessageUnit,FILE='/dev/null',STATUS='unknown')
+         standardMessageUnit=errorMessageUnit
+        ENDIF
+        IF( myProcId .EQ. 0 ) THEN
+          WRITE(msgBuf,'(2A)') '** WARNING ** EEBOOT_MINIMAL: ',
+     &     'defined SINGLE_DISK_IO will result in losing'
+          CALL PRINT_MESSAGE( msgBuf, errorMessageUnit,
+     &                        SQUEEZE_RIGHT, myThid )
+          WRITE(msgBuf,'(2A)') '** WARNING ** EEBOOT_MINIMAL: ',
+     &     'any message (error/warning) from any proc <> 0'
+          CALL PRINT_MESSAGE( msgBuf, errorMessageUnit,
+     &                        SQUEEZE_RIGHT, myThid )
+        ENDIF
+#endif
+       ENDIF
+
+#if defined(ALLOW_NEST_PARENT) || defined(ALLOW_NEST_CHILD)
+       WRITE(standardMessageUnit,'(2(A,I6))')
+     &           ' mpiMyWId =', mpiMyWId, ' , color =',color
+#endif /* ALLOW_NEST_PARENT | ALLOW_NEST_CHILD */
+
+C--    Synchronise all processes
+C      Strictly this is superfluous, but by using it we can guarantee to
+C      find out about processes that did not start up.
+       CALL MPI_BARRIER( MPI_COMM_MODEL, mpiRC )
+       IF ( mpiRC .NE. MPI_SUCCESS ) THEN
+        eeBootError = .TRUE.
+        WRITE(msgBuf,'(A,I6)')
+     &        'EEBOOT_MINIMAL: MPI_BARRIER return code', mpiRC
+        CALL PRINT_ERROR( msgBuf, myThid )
+        GOTO 999
+       ENDIF
+
+C--    Get number of MPI processes
+       CALL MPI_COMM_SIZE ( MPI_COMM_MODEL, mpiNProcs, mpiRC )
+       IF ( mpiRC .NE. MPI_SUCCESS ) THEN
+        eeBootError = .TRUE.
+        WRITE(msgBuf,'(A,I6)')
+     &        'EEBOOT_MINIMAL: MPI_COMM_SIZE return code', mpiRC
+        CALL PRINT_ERROR( msgBuf, myThid )
+        GOTO 999
+       ENDIF
+       numberOfProcs = mpiNProcs
+
+#endif /* ALLOW_USE_MPI */
+      ENDIF
+
+C--    Under MPI only allow same number of processes as proc grid size.
+C      Strictly we are allowed more procs but knowing there
+C      is an exact match makes things easier.
+       IF ( numberOfProcs .NE. nPx*nPy ) THEN
+        eeBootError = .TRUE.
+        WRITE(msgBuf,'(2(A,I6))')
+     &  'EEBOOT_MINIMAL: No. of procs=', numberOfProcs,
+     &  ' not equal to nPx*nPy=', nPx*nPy
+        CALL PRINT_ERROR( msgBuf, myThid )
+        GOTO 999
+       ENDIF
+
+#ifdef USE_LIBHPM
+       CALL F_HPMINIT(myProcId, "mitgcmuv")
+#endif
+
+ 999  CONTINUE
+      RETURN
+      END
Index: /issm/trunk/test/MITgcm/code/eedie.F
===================================================================
--- /issm/trunk/test/MITgcm/code/eedie.F	(revision 22758)
+++ /issm/trunk/test/MITgcm/code/eedie.F	(revision 22758)
@@ -0,0 +1,110 @@
+C $Header: /u/gcmpack/MITgcm/eesupp/src/eedie.F,v 1.13 2012/10/11 19:15:18 jmc Exp $
+C $Name:  $
+
+#include "CPP_EEOPTIONS.h"
+#ifdef USE_LIBHPM
+# include "f_hpm.h"
+#endif
+
+CBOP
+      SUBROUTINE EEDIE
+C     *==========================================================*
+C     | SUBROUTINE EEDIE                                         |
+C     | o Close execution "environment", particularly perform    |
+C     |   steps to terminate parallel processing.                |
+C     *==========================================================*
+C     | Note: This routine can also be compiled with CPP         |
+C     | directives set so that no multi-processing is initialised|
+C     | This is OK and should work fine.                         |
+C     *==========================================================*
+      IMPLICIT NONE
+
+C     == Global variables ==
+#include "SIZE.h"
+#include "EEPARAMS.h"
+#include "EESUPPORT.h"
+CEOP
+
+C     == Local variables ==
+C     msgBuf       :: I/O Buffer
+C     nThreadsDone :: Used to count number of completed threads.
+C     I            :: Loop counter.
+      CHARACTER*(MAX_LEN_MBUF) msgBuf
+      INTEGER nThreadsDone
+      INTEGER I
+#ifdef ALLOW_USE_MPI
+C     mpiRC        :: Error code reporting variable used with MPI.
+      INTEGER mpiRC
+#endif /* ALLOW_USE_MPI */
+
+      IF ( eeBootError ) THEN
+C--   Skip ended threads counting if earlier error was found
+        WRITE(msgBuf,'(2A)')
+     &   'EEDIE: earlier error in multi-proc/thread setting'
+        CALL PRINT_ERROR( msgBuf, 1 )
+        fatalError = .TRUE.
+
+      ELSE
+C--   Check that all the threads have ended
+C     No thread should reach this loop before all threads have set
+C     threadIsComplete to TRUE. If they do then either there is a bug
+C     in the code or the behaviour of the parallel compiler directives
+C     are not right for this code. In the latter case different
+C     directives may be available or the compiler itself may have a
+C     bug or you may need a different parallel compiler for main.F
+        nThreadsDone = 0
+        DO I = 1, nThreads
+         IF ( threadIsComplete(I) ) nThreadsDone = nThreadsDone+1
+        ENDDO
+        IF ( nThreadsDone .LT. nThreads ) THEN
+         WRITE(msgBuf,'(A,I5,A)')
+     &    'S/R EEDIE: Only',nThreadsDone,' threads have completed,'
+         CALL PRINT_ERROR( msgBuf, 1 )
+         WRITE(msgBuf,'(A,I5,A)')
+     &    'S/R EEDIE:',nThreads,' are expected for this config !'
+         CALL PRINT_ERROR( msgBuf, 1 )
+         eeEndError = .TRUE.
+         fatalError = .TRUE.
+        ENDIF
+
+C--   end if/else eebootError
+      ENDIF
+
+#ifdef USE_LIBHPM
+      CALL F_HPMTERMINATE(myProcId)
+#endif
+
+C--   Flush IO-unit before MPI termination
+      CALL MDS_FLUSH( errorMessageUnit, 1 )
+c#ifdef ALLOW_USE_MPI
+      CALL MDS_FLUSH( standardMessageUnit, 1 )
+c#endif /* ALLOW_USE_MPI */
+
+#ifdef ALLOW_USE_MPI
+C- Note: since MPI_INIT is always called, better to also always terminate MPI
+C        (even if usingMPI=F) --> comment out test on usingMPI
+c     IF ( usingMPI ) THEN
+
+C--   MPI style multiple-process termination
+C--   ======================================
+#if (defined COMPONENT_MODULE) || (defined ALLOW_CPL_ISSM)
+       IF ( useCoupler) CALL MPI_BARRIER( MPI_COMM_WORLD, mpiRC )
+#endif
+#ifdef ALLOW_OASIS
+       IF ( useOASIS ) CALL OASIS_FINALIZE
+#endif
+       CALL MPI_FINALIZE  ( mpiRC )
+       IF ( mpiRC .NE. MPI_SUCCESS ) THEN
+        eeEndError = .TRUE.
+        fatalError = .TRUE.
+        WRITE(msgBuf,'(A,I5)')
+     &       'S/R FIN_PROCS: MPI_FINALIZE return code',
+     &       mpiRC
+        CALL PRINT_ERROR( msgBuf, 1 )
+       ENDIF
+
+c     ENDIF
+#endif /* ALLOW_USE_MPI */
+
+      RETURN
+      END
Index: /issm/trunk/test/MITgcm/code/packages.conf
===================================================================
--- /issm/trunk/test/MITgcm/code/packages.conf	(revision 22758)
+++ /issm/trunk/test/MITgcm/code/packages.conf	(revision 22758)
@@ -0,0 +1,8 @@
+# $Header: /u/gcmpack/MITgcm/verification/isomip/code/packages.conf,v 1.2 2010/02/11 22:24:12 dimitri Exp $
+# $Name:  $
+
+gfd
+timeave
+shelfice
+obcs
+diagnostics
Index: /issm/trunk/test/MITgcm/coupling_rules.txt
===================================================================
--- /issm/trunk/test/MITgcm/coupling_rules.txt	(revision 22758)
+++ /issm/trunk/test/MITgcm/coupling_rules.txt	(revision 22758)
@@ -0,0 +1,123 @@
+Rules for coupling ISSM and MITgcm:
+
+* 
+>>>> CREATE A FILE WITH ALL THE NAMES AND TAGS FOR THE INFORMATION EXCHANGE INCLUDING:
+CouplingTime           1           Real*8  10001000
+IceModelTime           1           Real*8  10001001
+OceanModelTime         1           Real*8  10001002
+Nx                     1           Integer 10001003
+Ny                     1           Integer 10001004
+xC                     Nx*Ny       Real*8  10001005
+yC                     Nx*Ny       Real*8  10001006
+IceBase                Nx*Ny       Real*8  10001007
+OceanMelt              Nx*Ny       Real*8  10001008
+
+>>>> INITIALIZATION FROM SCRATCH
+IceModelTime   = 0
+OceanModelTime = 0
+
+Initialization:
+  I1. ISSM sends CouplingTime, the interval at which we couple
+  I2. MITgcm sends grid size (NX and NY)
+  I3. MITgcm sends grid coordinates of center of cells
+      (longitude -180 <= XC < 180 and latitude YC)
+  C1. ISSM sends ice model time IceTimeTag
+  C2. MITgcm sends ocean model time OceanTimeTag
+  C4. ISSM sends IceModelTime=0 base to MITgcm
+      (base should be 9999 in areas not covered by ice grid)
+  C5o. MITgcm integrates from OceanModelTime=0
+                           to OceanModelTime=CouplingTime
+
+First Recurrent Coupling Exchange:
+IceModelTime   = 0
+OceanModelTime = CouplingTime
+  C1. ISSM sends ice model time IceTimeTag
+  C2. MITgcm sends ocean model time OceanTimeTag
+  C3. MITgcm sends
+      0 <= OceanModelTime < CouplingTime
+      time-mean melt rate to ISSM
+  C4. ISSM sends IceModelTime=0 base to MITgcm
+      (this is duplicate of Initialization)
+  C5i. ISSM integrates from IceModelTime=0
+                         to IceModelTime=CouplingTime
+  C5o. MITgcm integrates from OceanModelTime=CouplingTime
+                           to OceanModelTime=2*CouplingTime
+
+...
+
+Coupling Exchange N:
+IceModelTime   = (N-1) * CouplingTime
+OceanModelTime =   N   * CouplingTime
+  C1. ISSM sends ice model time IceTimeTag
+  C2. MITgcm sends ocean model time OceanTimeTag
+  C3. MITgcm sends
+      (N-1)*CouplingTime <= OceanModelTime < N*CouplingTime
+      time-mean melt rate to ISSM
+  C4. ISSM sends IceModelTime=(N-1)*CouplingTime base to MITgcm
+  C5i. ISSM integrates from IceModelTime=(N-1)*CouplingTime
+                         to IceModelTime=N*CouplingTime
+  C5o. MITgcm integrates from OceanModelTime=N*CouplingTime
+                           to OceanModelTime=(N+1)*CouplingTime
+
+Termination:
+IceModelTime   =   N   * CouplingTime
+OceanModelTime = (N+1) * CouplingTime
+  C1. ISSM sends ice model time IceTimeTag
+  C2. MITgcm sends ocean model time OceanTimeTag
+  C3. MITgcm sends
+      N*CouplingTime <= OceanModelTime < (N+1)*CouplingTime
+      time-mean melt rate to ISSM
+  Ti. ISSM saves to restart files the IceModelTime=N state and
+       the N*CouplingTime to (N+1)*CouplingTime mean melt rate
+  To. MITgcm saves to restart files
+       the OceanModelTime=(N+1)*CouplingTime state
+
+
+>>>> RESTART FROM SAVED STATE
+IceModelTime   =   N   * CouplingTime
+OceanModelTime = (N+1) * CouplingTime
+
+  - ISSM reads from restart files the IceModelTime=N state and
+      the N*CouplingTime to (N+1)*CouplingTime mean melt rate
+      
+  - MITgcm reads from restart files
+      the OceanModelTime=(N+1)*CouplingTime state
+
+Initialization:
+  I1. ISSM sends CouplingTime
+  I2. MITgcm sends grid size (NX and NY)
+  I3. MITgcm sends grid coordinates (XC and YC)
+  C1. ISSM sends ice model time IceTimeTag
+  C2. MITgcm sends ocean model time OceanTimeTag
+  C4. ISSM sends IceModelTime=N base to MITgcm
+  C5i. ISSM integrates from IceModelTime=N*CouplingTime
+                         to IceModelTime=(N+1)*CouplingTime
+  C5o. MITgcm integrates from OceanModelTime=(N+1)*CouplingTime
+                          to OceanModelTime=(N+2)*CouplingTime
+
+First Recurrent Coupling Exchange:
+IceModelTime   = (N+1)   * CouplingTime
+OceanModelTime = (N+2) * CouplingTime
+  C1. ISSM sends ice model time IceTimeTag
+  C2. MITgcm sends ocean model time OceanTimeTag
+  C3. MITgcm sends
+      (N+1)*CouplingTime <= OceanModelTime < (N+2)*CouplingTime
+      time-mean melt rate to ISSM
+  C4. ISSM sends IceModelTime=(N+1)*CouplingTime base to MITgcm
+  C5i. ISSM integrates from IceModelTime=(N+1)*CouplingTime
+                         to IceModelTime=(N+2)*CouplingTime
+  C5o. MITgcm integrates from OceanModelTime=(N+2)*CouplingTime
+                           to OceanModelTime=(N+3)*CouplingTime
+
+...
+
+
+TODO/WISH LIST
+* finish initialization 
+   - MITgcm runs 1 time step with ocean ice base, not from ISSM
+* do other time steps (coupling time = N)
+* ISSM works on interpolation
+* 1 + 1 = 2 (so pickup working)
+* change MITgcm to include new base and changes in ocean
+* make sure that RunCoupledMITgcmISSM and RunCoupledMITgcmISSM2
+  can produce the same results!
Index: /issm/trunk/test/MITgcm/input/data
===================================================================
--- /issm/trunk/test/MITgcm/input/data	(revision 22757)
+++ /issm/trunk/test/MITgcm/input/data	(revision 22758)
@@ -50,5 +50,5 @@
  dumpFreq=0.,
  taveFreq=2592000.,
- monitorFreq=86400.,
+ monitorFreq=1200.,
  monitorSelect=2,
  &
Index: /issm/trunk/test/MITgcm/input/eedata
===================================================================
--- /issm/trunk/test/MITgcm/input/eedata	(revision 22757)
+++ /issm/trunk/test/MITgcm/input/eedata	(revision 22758)
@@ -4,4 +4,5 @@
 # nTy - No. threads per process in Y
  &EEPARMS
+ useCoupler=.TRUE.,
  &
 # Note: Some systems use & as the
Index: /issm/trunk/test/MITgcm/input/eedata_uncoupled
===================================================================
--- /issm/trunk/test/MITgcm/input/eedata_uncoupled	(revision 22758)
+++ /issm/trunk/test/MITgcm/input/eedata_uncoupled	(revision 22758)
@@ -0,0 +1,10 @@
+# Example "eedata" file
+# Lines beginning "#" are comments
+# nTx - No. threads per process in X
+# nTy - No. threads per process in Y
+ &EEPARMS
+ useCoupler=.FALSE.,
+ &
+# Note: Some systems use & as the
+# namelist terminator. Other systems
+# use a / character (as shown here).
Index: /issm/trunk/test/MITgcm/install.sh
===================================================================
--- /issm/trunk/test/MITgcm/install.sh	(revision 22757)
+++ /issm/trunk/test/MITgcm/install.sh	(revision 22758)
@@ -2,5 +2,5 @@
 
 #Some cleanup
-\rm -rf install
+rm -rf install
 
 #Add cvs repository
Index: /issm/trunk/test/NightlyRun/IdFromString.m
===================================================================
--- /issm/trunk/test/NightlyRun/IdFromString.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/IdFromString.m	(revision 22758)
@@ -34,7 +34,5 @@
 ids_raw=strsplit_strict(ids_raw,char(10));
 ids_raw=ids_raw(1:end-1);
-for i=1:length(ids_raw),
-	eval(['ids=[ids ' ids_raw{i} '];']); 
-end
+ids=cellfun(@str2num,ids_raw);
 ids=sort(ids);
 
Index: /issm/trunk/test/NightlyRun/README
===================================================================
--- /issm/trunk/test/NightlyRun/README	(revision 22757)
+++ /issm/trunk/test/NightlyRun/README	(revision 22758)
@@ -1,36 +1,1 @@
-
-# running a test
------------------
-
-To run a test, just type: testxxx in matlab
-To check that the results of a test are similar to the Archive, type: runme('id',xxx)
-Several tests can be run at the same time.
-If no id if specified, all the tests will be done.
-All the archives are contained in ../Archives
-To update a test archive, use runme('procedure','update','id',xxx)
-Once again, if no id is specified, all the archives will be updated.
-
-
-# How to create a new test
---------------------------
-
-This directory contains all the tests that run every night to check the code.
-The file IdToName associate a test id to its name.
-All the files necessary to run the tests can be found in:
-../Exp/ for the exp files (domains, contours, ...)
-../Par/ for the parameter files (to parameterize a model)
-../Data/ for the datasets needed to initialize a model
-To add a test, create a new testxxx.m and a testxxx_nightly.m
-
-The first number of the id correspond to the type of test:
-1: SquareShelfConstrained (no icefront)
-2: SquareShelf (with an icefront)
-3: SquareSheetConstrained (no icefront)
-4: SquareSheetShelf (Marine ice sheet with an ice shelf at the end)
-5: Pine Island Glacier
-6: 79North
-Add the id and testname in IdToName.m (incresing order)
-We try not to create too many .par and .exp files, so try to use the existing ones as much as possible.
-To modify some characteristics, do it in the testxxx.m file.
-Specify the field_names the field_values and the tolerance at the end of the test file.
-Don't forget to commit the archive (Archivexxx.arch in ../Archives)
+For more info: https://issm.ess.uci.edu/trac/issm/wiki/addnewNR
Index: /issm/trunk/test/NightlyRun/runme.m
===================================================================
--- /issm/trunk/test/NightlyRun/runme.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/runme.m	(revision 22758)
@@ -34,4 +34,6 @@
 %      runme('exclude',101);
 %      runme('id',102,'procedure','update');
+
+%      runme('procedure','valgrind','stoponerror',1,'exclude','IdFromString('Dak'));
 
 %Check inputs
@@ -132,8 +134,8 @@
 	try,
 		%Execute test
-		eval(['cd ' root ]);
+		cd(root);
 		id_string='N/A';
 		id_string=IdToName(id);
-		eval(['test' num2str(id)]);
+		run(['test' num2str(id)]);
 
 		%UPDATE ARCHIVE?
Index: /issm/trunk/test/NightlyRun/runme.py
===================================================================
--- /issm/trunk/test/NightlyRun/runme.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/runme.py	(revision 22758)
@@ -180,7 +180,9 @@
 						# Matlab uses base 1, so use base 1 in labels
 						archive=np.array(archread(archive_file,archive_name+'_field'+str(k+1)))
-						if archive == None:
+						#Because np.array is weird (str(np.array(None)) becomes 'None' but np.array(None) is never equal to None, it basically becomes a type of string in an array):
+						if str(archive) == 'None':
 							raise NameError("Field name '"+archive_name+'_field'+str(k+1)+"' does not exist in archive file.")
 						error_diff=np.amax(np.abs(archive-field),axis=0)/(np.amax(np.abs(archive),axis=0)+float_info.epsilon)
+                                                if not np.isscalar(error_diff): error_diff=error_diff[0]
 
 						#disp test result
Index: /issm/trunk/test/NightlyRun/test101.html
===================================================================
--- /issm/trunk/test/NightlyRun/test101.html	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test101.html	(revision 22758)
@@ -4,7 +4,7 @@
 <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
 <!-- Includes {{{-->
-<script type="text/javascript" src="../../build-js/bin/issm-bin.js"> </script>
-<script type="text/javascript" src="../../build-js/bin/issm-prebin.js"> </script>
-<script type="text/javascript" src="../../build-js/bin/IssmModule.js"></script>
+<script type="text/javascript" src="../../bin/issm-bin.js"> </script>
+<script type="text/javascript" src="../../bin/issm-prebin.js"> </script>
+<script type="text/javascript" src="../../bin/IssmModule.js"></script>
 <script type="text/javascript" src="../Exp/Square.js"></script>
 <script type="text/javascript" src="../Par/SquareShelfConstrained.js"></script>
@@ -32,4 +32,9 @@
 	
 	console.log(md.results['StressbalanceSolution'][0]['Vel']);
+	
+	plotmodel(md,
+		'colorbar','on',
+		'data',md.results['StressbalanceSolution'][0]['Vel'],
+		'data','mesh');
 
 </script>
Index: /issm/trunk/test/NightlyRun/test101.m
===================================================================
--- /issm/trunk/test/NightlyRun/test101.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test101.m	(revision 22758)
@@ -22,6 +22,6 @@
 field_names     ={'Vx','Vy','Vel','Pressure',...
 	'DeviatoricStressxx','DeviatoricStressyy','DeviatoricStressxy','MassFlux1','MassFlux2','MassFlux3','MassFlux4','MassFlux5','MassFlux6'};
-field_tolerances={2e-13,1e-13,1e-13,1e-13,...
-	1e-13,1e-13,1e-13,...
+field_tolerances={3e-13,1e-13,1e-13,1e-13,...
+	2e-13,1e-13,1e-13,...
 	1e-13, 1e-13, 1e-13, 1e-13, 1e-13, 1e-13 };
 field_values={...
Index: /issm/trunk/test/NightlyRun/test101.py
===================================================================
--- /issm/trunk/test/NightlyRun/test101.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test101.py	(revision 22758)
@@ -31,6 +31,6 @@
 									'DeviatoricStressxx','DeviatoricStressyy','DeviatoricStressxy',
 									'MassFlux1','MassFlux2','MassFlux3','MassFlux4','MassFlux5','MassFlux6']
-field_tolerances=[1e-13, 1e-13, 1e-13, 1e-13,
-									1e-13, 1e-13, 1e-13,
+field_tolerances=[3e-13, 1e-13, 1e-13, 1e-13,
+									2e-13, 1e-13, 1e-13,
 									1e-13, 1e-13, 1e-13, 
 									1e-13, 1e-13, 1e-13 ]
Index: /issm/trunk/test/NightlyRun/test1108.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1108.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test1108.py	(revision 22758)
@@ -8,4 +8,5 @@
 from setflowequation import *
 from solve import *
+from squaremesh import *
 
 from PythonFuncs import *
@@ -16,4 +17,5 @@
 """
 
+#L_list=[5000.,10000.,20000.,40000.,80000.,160000.]
 L_list=[80000.]
 results=[]
@@ -35,5 +37,11 @@
 	md.stressbalance.spcvz=np.nan*np.ones((md.mesh.numberofvertices))
 	
-	pos=np.nonzero(logical_and.reduce_n(md.mesh.vertexonbase,np.logical_or.reduce(md.mesh.x==0.,md.mesh.x==np.max(md.mesh.x)),np.logical_or.reduce(md.mesh.y==0.,md.mesh.y==np.max(md.mesh.y))))
+	maxx = max(md.mesh.x)
+	maxy = max(md.mesh.y)
+	posA = np.where(md.mesh.vertexonbase)
+	posB = np.unique(np.concatenate((np.where(md.mesh.x==0.), np.where(md.mesh.x==maxx))))
+	posC = np.unique(np.concatenate((np.where(md.mesh.y==0.), np.where(md.mesh.y==maxy))))
+	pos = np.intersect1d(np.intersect1d(posA,posB),posC)
+
 	md.stressbalance.spcvx[pos]=0.
 	md.stressbalance.spcvy[pos]=0.
@@ -44,6 +52,6 @@
 	posx2=np.nonzero(md.mesh.x==np.max(md.mesh.x))[0]
 
-	posy=np.nonzero(logical_and.reduce_n(md.mesh.y==0.,md.mesh.x!=0.,md.mesh.x!=np.max(md.mesh.x)))[0]    #Don't take the same nodes two times
-	posy2=np.nonzero(logical_and.reduce_n(md.mesh.y==np.max(md.mesh.y),md.mesh.x!=0.,md.mesh.x!=np.max(md.mesh.x)))[0]
+	posy=np.intersect1d(np.intersect1d(np.where(md.mesh.y==0.),np.where(md.mesh.x!=0.)),np.where(md.mesh.x!=np.max(md.mesh.x)))[0]    #Don't take the same nodes two times
+	posy2=np.intersect1d(np.intersect1d(np.where(md.mesh.y==np.max(md.mesh.y)),np.where(md.mesh.x!=0.)),np.where(md.mesh.x!=np.max(md.mesh.x)))[0]
 
 	md.stressbalance.vertex_pairing=np.vstack((np.hstack((posx.reshape(-1,1)+1,posx2.reshape(-1,1)+1)),np.hstack((posy.reshape(-1,1)+1,posy2.reshape(-1,1)+1))))
Index: /issm/trunk/test/NightlyRun/test1109.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1109.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test1109.py	(revision 22758)
@@ -0,0 +1,86 @@
+#Test Name: ISMIPE
+import numpy as np
+import sys
+from model import *
+from socket import gethostname
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+from squaremesh import *
+
+#This test is a test from the ISMP-HOM Intercomparison project.
+#TestE 
+#Four tests to run: - Pattyn frozen
+#                   - Stokes frozen
+#                   - Pattyn with some sliding
+#                   - Stokes with some sliding
+printingflag = False
+results = []
+
+for i in range(4):
+	Lx=10. #in m
+	Ly=5000. #in m
+	nx=3 #number of nodes in x direction
+	ny=51
+	md = model()
+	md = squaremesh(md,Lx,Ly,nx,ny)
+	md = setmask(md,'','') #ice sheet test
+	md = parameterize(md,'../Par/ISMIPE.py')
+	md = md.extrude(10,1.)
+
+	if i==0 or i==2:
+		md = setflowequation(md,'HO','all')
+	elif i==1 or i==3:
+		md = setflowequation(md,'FS','all')
+
+	#Create MPCs to have periodic boundary conditions
+	posx = np.where(md.mesh.x == 0.)[0]
+	posx2 = np.where(md.mesh.x == max(md.mesh.x))[0]
+	md.stressbalance.vertex_pairing = np.column_stack((posx,posx2))
+
+	#Create spcs on the bed 
+	pos = np.where(md.mesh.vertexonbase)[0]
+	md.stressbalance.spcvx = float('NaN') * np.ones((md.mesh.numberofvertices,))
+	md.stressbalance.spcvy = float('NaN') * np.ones((md.mesh.numberofvertices,))
+	md.stressbalance.spcvz = float('NaN') * np.ones((md.mesh.numberofvertices,))
+	md.stressbalance.spcvx[pos] = 0.
+	md.stressbalance.spcvy[pos] = 0.
+	md.stressbalance.spcvz[pos] = 0.
+
+	#Remove the spc where there is some sliding (case 3 and 4):
+	if i==2 or i==3:
+		pos = np.intersect1d(np.where((md.mesh.y / max(md.mesh.y)) >= 0.44), np.where((md.mesh.y / max(md.mesh.y)) <= 0.5))[0]
+		md.stressbalance.spcvx[pos] = float('NaN')
+		md.stressbalance.spcvy[pos] = float('NaN')
+		md.stressbalance.spcvz[pos] = float('NaN')
+
+	#Compute the stressbalance
+	md.cluster = generic('name',gethostname(),'np',8)
+	md = solve(md,'Stressbalance')
+
+	vx = md.results.StressbalanceSolution.Vx
+	vy = md.results.StressbalanceSolution.Vy
+	vz = md.results.StressbalanceSolution.Vz
+	results[i] = md.results.StressbalanceSolution
+
+
+#Fields and tolerances to track changes
+field_names = [
+	'VyPattynSliding','VzPattynSliding',
+	'VxStokesSliding','VyStokesSliding','VzStokesSliding',
+	'VyPattynFrozen','VzPattynFrozen',
+	'VxStokesFrozen','VyStokesFrozen','VzStokesFrozen'
+	]
+field_tolerances = [
+	1e-05,1e-05,
+	1e-05,1e-06,1e-06,
+	1e-05,1e-04,
+	1e-05,1e-05,1e-06
+	]
+
+field_values = []
+for i in range(4):
+	result = results[i]
+	field_values += [result.Vx,result.Vy,result.Vz]
Index: /issm/trunk/test/NightlyRun/test1110.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1110.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test1110.py	(revision 22758)
@@ -0,0 +1,141 @@
+#Test Name: ISMIPF
+import numpy as np
+from model import *
+from socket import gethostname
+from bamg import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+from squaremesh import *
+
+#This test is a test from the ISMP-HOM Intercomparison project.
+#TestF 
+printingflag = False
+results = []
+
+for i in range(4):
+	L = 100000. #in m
+	nx = 30 #numberof nodes in x direction
+	ny = 30
+	md = model()
+	md = squaremesh(md,L,L,nx,ny)
+#	md = triangle(md,'../Exp/SquareISMIP.exp',5500.)
+	md = setmask(md,'','') #ice sheet test
+	md = parameterize(md,'../Par/ISMIPF.py')
+	md = md.extrude(4,1.)
+
+	if (i == 0 or i == 1):
+		md = setflowequation(md,'HO','all')
+	else:
+		md = setflowequation(md,'FS','all')
+
+	md.stressbalance.spcvx = float('NaN') * np.ones((md.mesh.numberofvertices,))
+	md.stressbalance.spcvy = float('NaN') * np.ones((md.mesh.numberofvertices,))
+	md.stressbalance.spcvz = float('NaN') * np.ones((md.mesh.numberofvertices,))
+	if (i == 0 or i == 2):
+		#Create dirichlet on the bed if no slip
+		pos = np.where(md.mesh.vertexonbase)
+		md.stressbalance.spcvx[pos] = 0.
+		md.stressbalance.spcvy[pos] = 0.
+		md.stressbalance.spcvz[pos] = 0.
+	else:
+		posA = np.where(md.mesh.vertexonbase)
+		posB = np.unique(np.concatenate(np.where(md.mesh.x == 0.),np.where(md.mesh.x == max(md.mesh.x))))
+		posC = np.unique(np.concatenate(np.where(md.mesh.y == 0.),np.where(md.mesh.y == max(md.mesh.y))))
+		pos = np.intersect1d(np.intersect1d(posA,posB),posC)
+		md.stressbalance.spcvx[pos] = 100. #because we need a dirichlet somewhere
+		md.stressbalance.spcvy[pos] = 0.
+		md.stressbalance.spcvz[pos] = 0.
+	
+	pos = np.where(np.logical_not(md.mesh.vertexonbase))
+	md.thermal.spctemperature[pos] = 255.
+
+	#Create MPCs to have periodic boundary conditions
+	posx = np.where(md.mesh.x == 0.)
+	posx2 = np.where(md.mesh.x == max(md.mesh.x))
+
+	posy = np.where(md.mesh.y == 0.)
+	posy2 = np.where(md.mesh.y == max(md.mesh.y))
+
+	md.stressbalance.vertex_pairing = np.column_stack((posx,posx2,posy,posy2))
+	md.masstransport.vertex_pairing = np.column_stack((posx,posx2,posy,posy2))
+
+	md.timestepping.time_step = 3.
+	md.timestepping.final_time = 300.
+	md.settings.output_frequency = 50
+	md.masstransport.stabilization = 1
+	md.stressbalance.maxiter = 1
+	
+	#Compute the stressbalance
+	md.cluster = generic('name',gethostname(),'np',8)
+	md.verbose = verbose('convergence',True,'solution',True)
+	md = solve(md,'Transient')
+
+	#save the results
+	results[i] = md.results.TransientSolution()
+	
+	#Now plot vx and delta surface 
+	if (i == 0 or i == 2):
+		plotmodel(md,'data',(md.results.TransientSolution().Vx),'layer',md.mesh.numberoflayers,'sectionvalue','../Exp/ISMIP100000.exp','title','','xlabel','','ylabel','Velocity (m/yr)','linewidth',3,'grid','on','unit','km','ylim',[91,100])
+	elif (i == 1 or i == 3):
+		plotmodel(md,'data',(md.results.TransientSolution().Vx),'layer',md.mesh.numberoflayers,'sectionvalue','../Exp/ISMIP100000.exp','title','','xlabel','','ylabel','Velocity (m/yr)','linewidth',3,'grid','on','unit','km','ylim',[185,200])
+	
+	if printingflag:
+		#set(gcf,'Color','w')
+		if i == 0:
+			printmodel('ismipfHOvxfrozen','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off')
+			#system(['mv ismipfHOvxfrozen.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF'])
+		elif i == 1:
+			printmodel('ismipfHOvxsliding','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off')
+			#system(['mv ismipfHOvxsliding.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF'])
+		elif i == 2:
+			printmodel('ismipfFSvxfrozen','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off')
+			#system(['mv ismipfFSvxfrozen.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF'])
+		elif i == 3:
+			printmodel('ismipfFSvxsliding','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off')
+			#system(['mv ismipfFSvxsliding.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF'])
+		
+	
+
+	plotmodel(md,'data',(md.results.TransientSolution().Surface)-md.geometry.surface,'layer',md.mesh.numberoflayers,'sectionvalue','../Exp/ISMIP100000.exp','title','','xlabel','','ylabel','Surface (m)','linewidth',3,'grid','on','unit','km','ylim',[-30,50])
+	if printingflag:
+		#set(gcf,'Color','w')
+		if i == 0:
+			printmodel('ismipfHOdeltasurfacefrozen','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off')
+			#system(['mv ismipfHOdeltasurfacefrozen.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF'])
+		elif i == 1:
+			printmodel('ismipfHOdeltasurfacesliding','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off')
+			#system(['mv ismipfHOdeltasurfacesliding.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF'])
+		elif i == 2:
+			printmodel('ismipfFSdeltasurfacefrozen','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off')
+			#system(['mv ismipfFSdeltasurfacefrozen.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF'])
+		elif i == 3:
+			printmodel('ismipfFSdeltasurfacesliding','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off')
+			#system(['mv ismipfFSdeltasurfacesliding.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF'])
+		
+	
+
+
+#Fields and tolerances to track changes
+field_names = [
+	'VxPattynFrozen','VyPattynFrozen','VzPattynFrozen','SurfacePattynFrozen',
+	'VxPattynSliding','VyPattynSliding','VzPattynSliding','SurfacePattynSliding',
+	'VxStokesFrozen','VyStokesFrozen','VzStokesFrozen','SurfaceStokesFrozen',
+	'VxStokesSliding','VyStokesSliding','VzStokesSliding','SurfaceStokesSliding'
+]
+field_tolerances = [
+	1e-10,1e-09,1e-09,1e-10,
+	1e-10,1e-09,1e-09,1e-10,
+	1e-08,1e-09,1e-08,1e-09,
+	1e-08,2e-09,1e-08,1e-09
+]
+field_values = []
+for i in range(4):
+	result = results[i]
+	field_values += ([
+		result.Vx,
+		result.Vy,
+		result.Vz,
+		result.Surface] - md.geometry.surface)
+
Index: /issm/trunk/test/NightlyRun/test119.m
===================================================================
--- /issm/trunk/test/NightlyRun/test119.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test119.m	(revision 22758)
@@ -2,10 +2,10 @@
 
 %Simple mesh
-md=bamg(model(),'domain','../Exp/Square.exp','hmax',100000.,'rand',false);
+md=bamg(model(),'domain','../Exp/Square.exp','hmax',100000.);
 x1=md.mesh.x;
 y1=md.mesh.y;
 
 %hVertices
-md=bamg(model(),'domain','../Exp/Square.exp','hmax',300000.,'hVertices',[10000. 100000. 400000. 100000.]','rand',false);
+md=bamg(model(),'domain','../Exp/Square.exp','hmax',300000.,'hVertices',[10000. 100000. 400000. 100000.]');
 x2=md.mesh.x;
 y2=md.mesh.y;
@@ -13,5 +13,5 @@
 %big mesh
 t0=clock;
-md=bamg(model(),'domain','../Exp/Square.exp','hmax',3000.,'rand',false);
+md=bamg(model(),'domain','../Exp/Square.exp','hmax',3000.);
 nbelements=md.mesh.numberofelements;
 if nbelements>267895-50 & nbelements<267895+50
Index: /issm/trunk/test/NightlyRun/test119.py
===================================================================
--- /issm/trunk/test/NightlyRun/test119.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test119.py	(revision 22758)
@@ -8,10 +8,10 @@
 
 #Simple mesh
-md=bamg(model(),'domain','../Exp/Square.exp','hmax',100000.,'rand',False)
+md=bamg(model(),'domain','../Exp/Square.exp','hmax',100000.)
 x1=md.mesh.x
 y1=md.mesh.y
 
 #hVertices
-md=bamg(model(),'domain','../Exp/Square.exp','hmax',300000.,'hVertices',np.array([10000.,100000.,400000.,100000.]).reshape(-1,1),'rand',False)
+md=bamg(model(),'domain','../Exp/Square.exp','hmax',300000.,'hVertices',np.array([10000.,100000.,400000.,100000.]).reshape(-1,1))
 x2=md.mesh.x
 y2=md.mesh.y
@@ -19,5 +19,5 @@
 #big mesh
 t0=time.time()
-md=bamg(model(),'domain','../Exp/Square.exp','hmax',3000.,'rand',False)
+md=bamg(model(),'domain','../Exp/Square.exp','hmax',3000.)
 nbelements=md.mesh.numberofelements
 elapsedtime=time.time()-t0
Index: /issm/trunk/test/NightlyRun/test123.py
===================================================================
--- /issm/trunk/test/NightlyRun/test123.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test123.py	(revision 22758)
@@ -0,0 +1,43 @@
+#Test Name: SquareShelfConstrainedTranMisfitSurface
+from model import *
+from socket import gethostname
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+from misfit import *
+
+
+md=triangle(model(),'../Exp/Square.exp',180000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',gethostname(),'np',3)
+
+fake_surface = np.vstack((np.append(np.array(md.geometry.surface)+100,1.1),
+		np.append(np.array(md.geometry.surface)+200,2.1),
+		np.append(np.array(md.geometry.surface)+300,2.5))).T
+
+md.transient.requested_outputs = ['default','SurfaceMisfit']
+md.outputdefinition.definitions = [misfit(
+		name='SurfaceMisfit',
+		definitionstring='Outputdefinition1',
+		model_string='Surface',
+		observation=fake_surface,
+		observation_string='SurfaceObservation',
+		timeinterpolation='nearestneighbor',
+		weights=np.ones((md.mesh.numberofvertices,1)),
+		weights_string='WeightsSurfaceObservation'
+		)]
+
+md=solve(md,'Transient')
+
+#Fields and tolerances to track changes
+field_names = ['SurfaceMisfitFirstStep','SurfaceMisfitSecondStep','SurfaceMisfitThirdStep']
+field_tolerances = [1e-13,1e-13,1e-13]
+field_values = [
+	md.results.TransientSolution[0].SurfaceMisfit,
+	md.results.TransientSolution[1].SurfaceMisfit,
+	md.results.TransientSolution[2].SurfaceMisfit
+	]
Index: /issm/trunk/test/NightlyRun/test124.py
===================================================================
--- /issm/trunk/test/NightlyRun/test124.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test124.py	(revision 22758)
@@ -0,0 +1,56 @@
+#Test Name: SquareShelfConstrainedTranFSFreeSurface
+from model import *
+from socket import gethostname
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(3,1)
+md=setflowequation(md,'FS','all')
+
+#Free surface
+md.masstransport.isfreesurface = 1
+md.timestepping.time_step = 0.00001
+md.timestepping.final_time = 0.00005
+
+#Go solve
+md.cluster=generic('name',gethostname(),'np',3)
+md=solve(md,'Transient')
+
+#Fields and tolerances to track changes
+field_names      = [
+	'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1',
+	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2',
+	'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3']
+field_tolerances = [
+	2e-09,3e-9,3e-9,3e-9,1e-13,1e-12,1e-12,
+	2e-09,3e-9,3e-9,3e-9,1e-10,1e-10,1e-10,
+	2e-09,3e-9,3e-9,3e-9,1e-10,1e-10,1e-10]
+field_values = [
+	md.results.TransientSolution[0].Vx,
+	md.results.TransientSolution[0].Vy,
+	md.results.TransientSolution[0].Vel,
+	md.results.TransientSolution[0].Pressure,
+	md.results.TransientSolution[0].Base,
+	md.results.TransientSolution[0].Surface,
+	md.results.TransientSolution[0].Thickness,
+	md.results.TransientSolution[1].Vx,
+	md.results.TransientSolution[1].Vy,
+	md.results.TransientSolution[1].Vel,
+	md.results.TransientSolution[1].Pressure,
+	md.results.TransientSolution[1].Base,
+	md.results.TransientSolution[1].Surface,
+	md.results.TransientSolution[1].Thickness,
+	md.results.TransientSolution[2].Vx,
+	md.results.TransientSolution[2].Vy,
+	md.results.TransientSolution[2].Vel,
+	md.results.TransientSolution[2].Pressure,
+	md.results.TransientSolution[2].Base,
+	md.results.TransientSolution[2].Surface,
+	md.results.TransientSolution[2].Thickness,
+	]
Index: /issm/trunk/test/NightlyRun/test2002.m
===================================================================
--- /issm/trunk/test/NightlyRun/test2002.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test2002.m	(revision 22758)
@@ -9,4 +9,5 @@
 md.slr.deltathickness=zeros(md.mesh.numberofelements,1);
 md.slr.sealevel=zeros(md.mesh.numberofvertices,1);
+md.slr.steric_rate=zeros(md.mesh.numberofvertices,1);
 %antarctica
 late=sum(md.mesh.lat(md.mesh.elements),2)/3;
@@ -65,4 +66,7 @@
 md.slr.abstol=1e-3;
 
+% max number of iteration reverted back to 10 (i.e., the original default value)
+md.slr.maxiter=10; 
+
 %eustatic run: 
 md.slr.rigid=0; md.slr.elastic=0;
Index: /issm/trunk/test/NightlyRun/test2002.py
===================================================================
--- /issm/trunk/test/NightlyRun/test2002.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test2002.py	(revision 22758)
@@ -19,4 +19,6 @@
 md.slr.deltathickness=np.zeros((md.mesh.numberofelements))
 md.slr.sealevel=np.zeros((md.mesh.numberofvertices))
+md.slr.steric_rate=np.zeros((md.mesh.numberofvertices))
+
 #antarctica
 late=np.sum(md.mesh.lat[md.mesh.elements-1],axis=1)/3
@@ -77,4 +79,7 @@
 md.slr.abstol=1e-3
 
+#max number of iteration reverted back to 10 (i.e., the original default value)
+md.slr.maxiter=10 
+
 #eustatic run: 
 md.slr.rigid=0
Index: /issm/trunk/test/NightlyRun/test2003.m
===================================================================
--- /issm/trunk/test/NightlyRun/test2003.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test2003.m	(revision 22758)
@@ -9,4 +9,5 @@
 md.slr.deltathickness=zeros(md.mesh.numberofelements,1);
 md.slr.sealevel=zeros(md.mesh.numberofvertices,1);
+md.slr.steric_rate=zeros(md.mesh.numberofvertices,1);
 %antarctica
 late=sum(md.mesh.lat(md.mesh.elements),2)/3;
Index: /issm/trunk/test/NightlyRun/test2003.py
===================================================================
--- /issm/trunk/test/NightlyRun/test2003.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test2003.py	(revision 22758)
@@ -0,0 +1,113 @@
+#Test Name: EarthSlr_rotationalFeedback
+import numpy as np
+from model import *
+from socket import gethostname
+from solve import *
+from gmshplanet import *
+from love_numbers import *
+from paterson import *
+from maskpsl import *
+from gmtmask import *
+
+#mesh earth:
+md = model()
+md.mesh = gmshplanet('radius',6.371012*1e3,'resolution',1000) #500 km resolution mesh
+
+#parameterize slr solution:
+#slr loading:  {{{
+md.slr.deltathickness = np.zeros((md.mesh.numberofelements,))
+md.slr.sealevel = np.zeros((md.mesh.numberofvertices,))
+md.slr.steric_rate = np.zeros((md.mesh.numberofvertices,))
+
+#antarctica
+#Access every element in lat using the indices in elements
+#-1 to convert to base 0 indexing, 1 (not 2, in matlab) to sum over rows
+late = sum(md.mesh.lat[md.mesh.elements - 1],1) / 3
+longe = sum(md.mesh.long[md.mesh.elements - 1],1) / 3
+pos = np.intersect1d(np.array(np.where(late < -75)), np.array(np.where(longe < 0)))
+md.slr.deltathickness[pos] = -1
+
+#elastic loading from love numbers: 
+nlov = 1000
+md.slr.love_h = np.array(love_numbers('h'))
+md.slr.love_h = np.resize(md.slr.love_h, nlov + 1)
+md.slr.love_k = np.array(love_numbers('k'))
+md.slr.love_k = np.resize(md.slr.love_k, nlov + 1)
+md.slr.love_l = np.array(love_numbers('l'))
+md.slr.love_l = np.resize(md.slr.love_l, nlov + 1)
+#}}}
+
+#mask:  {{{
+md.mask = maskpsl() # use maskpsl class (instead of mask) to store the ocean function as a ocean_levelset 
+mask = gmtmask(md.mesh.lat,md.mesh.long) 
+
+icemask = np.ones((md.mesh.numberofvertices,))
+pos = np.where(mask == 0)
+#pos[0] because np.where(mask==0) returns a 2d array, the latter parts of which are all array/s of 0s
+icemask[pos[0]] = -1
+pos = np.where(sum(mask[md.mesh.elements - 1],1) < 3)
+icemask[md.mesh.elements[pos,:] - 1] = -1
+md.mask.ice_levelset = icemask
+md.mask.ocean_levelset = np.zeros((md.mesh.numberofvertices,))
+pos = np.where(md.mask.ice_levelset == 1)
+md.mask.ocean_levelset[pos] = 1
+
+#make sure that the ice level set is all inclusive:
+md.mask.land_levelset = np.zeros((md.mesh.numberofvertices,))
+md.mask.groundedice_levelset = -np.ones((md.mesh.numberofvertices,))
+
+#make sure wherever there is an ice load, that the mask is set to ice: 
+pos = np.where(md.slr.deltathickness)
+md.mask.ice_levelset[md.mesh.elements[pos,:]] = -1
+# }}}
+
+# use model representation of ocea area (not the ture area) 
+md.slr.ocean_area_scaling = 0
+
+#geometry
+di = md.materials.rho_ice / md.materials.rho_water
+md.geometry.thickness = np.ones((md.mesh.numberofvertices,))
+md.geometry.surface = (1 - di) * np.zeros((md.mesh.numberofvertices,))
+md.geometry.base = md.geometry.surface - md.geometry.thickness
+md.geometry.bed = md.geometry.base
+
+#materials
+md.initialization.temperature = 273.25 * np.ones((md.mesh.numberofvertices,))
+md.materials.rheology_B = paterson(md.initialization.temperature)
+md.materials.rheology_n = 3 * np.ones((md.mesh.numberofelements,))
+
+#Miscellaneous
+md.miscellaneous.name = 'test2003'
+
+#Solution parameters
+md.slr.reltol = float('NaN')
+md.slr.abstol = 1e-3
+
+#eustatic + rigid + elastic run: 
+md.slr.rigid = 1
+md.slr.elastic = 1
+md.slr.rotation = 0
+md.cluster = generic('name',gethostname(),'np',3)
+#md.verbose = verbose('111111111')
+#print md.calving
+#print md.gia
+#print md.love
+#print md.esa
+#print md.autodiff
+md = solve(md,'Sealevelrise')
+SnoRotation = md.results.SealevelriseSolution.Sealevel
+
+#eustatic + rigid + elastic + rotation run: 
+md.slr.rigid = 1
+md.slr.elastic = 1
+md.slr.rotation = 1
+md.cluster = generic('name',gethostname(),'np',3)
+#md.verbose = verbose('111111111')
+md = solve(md,'Sealevelrise')
+SRotation = md.results.SealevelriseSolution.Sealevel
+
+#Fields and tolerances to track changes
+field_names = ['noRotation', 'Rotation']
+field_tolerances = [1e-13, 1e-13]
+field_values = [SnoRotation, SRotation]
+
Index: /issm/trunk/test/NightlyRun/test2010.m
===================================================================
--- /issm/trunk/test/NightlyRun/test2010.m	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test2010.m	(revision 22758)
@@ -0,0 +1,93 @@
+%Test Name: MomentOfIntertia
+
+%mesh earth: 
+md=model; 
+rad_e = 6.371012*10^3; % mean radius of Earth, km
+md.mesh=gmshplanet('radius',rad_e,'resolution',1000.0);  % km resolution 
+
+%parameterize slr solution:
+%slr loading:  {{{
+late=sum(md.mesh.lat(md.mesh.elements),2)/3;
+longe=sum(md.mesh.long(md.mesh.elements),2)/3;
+
+md.slr.deltathickness=zeros(md.mesh.numberofelements,1);
+pos=find(late <-75 & longe >0);
+md.slr.deltathickness(pos(6:7))=-1;
+
+md.slr.sealevel=zeros(md.mesh.numberofvertices,1);
+md.slr.steric_rate=zeros(md.mesh.numberofvertices,1);
+md.slr.ocean_area_scaling = 1; 
+
+%elastic loading from love numbers: 
+nlov=1001;
+md.slr.love_h = love_numbers('h'); md.slr.love_h(nlov+1:end)=[];
+md.slr.love_k = love_numbers('k'); md.slr.love_k(nlov+1:end)=[];
+md.slr.love_l = love_numbers('l'); md.slr.love_l(nlov+1:end)=[];
+
+%}}}
+%mask:  {{{
+md.mask=maskpsl(); % use maskpsl class (instead of mask) to store the ocean function as a ocean_levelset 
+mask=gmtmask(md.mesh.lat,md.mesh.long); 
+
+icemask=ones(md.mesh.numberofvertices,1);
+pos=find(mask==0);  icemask(pos)=-1;
+pos=find(sum(mask(md.mesh.elements),2)<3);   icemask(md.mesh.elements(pos,:))=-1;
+md.mask.ice_levelset=icemask;
+md.mask.ocean_levelset=zeros(md.mesh.numberofvertices,1);
+pos=find(md.mask.ice_levelset==1); md.mask.ocean_levelset(pos)=1;
+
+%make sure that the ice level set is all inclusive:
+md.mask.land_levelset=zeros(md.mesh.numberofvertices,1);
+md.mask.groundedice_levelset=-ones(md.mesh.numberofvertices,1); 
+
+%make sure wherever there is an ice load, that the mask is set to ice: 
+md.mask.ice_levelset=ones(md.mesh.numberofvertices,1);
+pos=find(md.slr.deltathickness); 
+md.mask.ice_levelset(md.mesh.elements(pos,:))=-1;
+% }}}
+%geometry {{{
+di=md.materials.rho_ice/md.materials.rho_water;
+md.geometry.thickness=ones(md.mesh.numberofvertices,1);
+md.geometry.surface=(1-di)*zeros(md.mesh.numberofvertices,1);
+md.geometry.base=md.geometry.surface-md.geometry.thickness;
+md.geometry.bed=md.geometry.base;
+% }}}
+%materials {{{
+md.initialization.temperature=273.25*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_B=paterson(md.initialization.temperature);
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+% }}}
+%Miscellaneous {{{
+md.miscellaneous.name='test2010';
+% }}}
+%Solution parameters {{{
+md.slr.reltol=NaN;
+md.slr.abstol=1e-3;
+% }}}
+
+%eustatic + rigid + elastic run: 
+md.slr.rigid=1; md.slr.elastic=1; md.slr.rotation=1; 
+md.cluster=generic('name',oshostname(),'np',3);
+
+% uncomment following 2 lines for 
+md=solve(md,'Sealevelrise');
+eus=md.results.SealevelriseSolution.SealevelEustatic;
+slr=md.results.SealevelriseSolution.Sealevel;
+moixz=md.results.SealevelriseSolution.SealevelInertiaTensorXZ; 
+moiyz=md.results.SealevelriseSolution.SealevelInertiaTensorYZ; 
+moizz=md.results.SealevelriseSolution.SealevelInertiaTensorZZ; 
+
+% analytical moi => just checking FOR ICE only!!! {{{
+% ...have to mute ** slr induced MOI in Tria.cpp ** prior to the comparison 
+%rad_e = rad_e*1e3; % now in meters 
+%areas=GetAreasSphericalTria(md.mesh.elements,md.mesh.lat,md.mesh.long,rad_e);
+%lat=late*pi/180; lon=longe*pi/180; 
+%moi_xz = sum(-md.materials.rho_freshwater.*md.slr.deltathickness.*areas.*rad_e^2.*sin(lat).*cos(lat).*cos(lon));
+%moi_yz = sum(-md.materials.rho_freshwater.*md.slr.deltathickness.*areas.*rad_e^2.*sin(lat).*cos(lat).*sin(lon));
+% }}}
+
+%Fields and tolerances to track changes
+field_names     ={'eus','slr','moixz','moiyz','moizz'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={eus,slr,moixz,moiyz,moizz};
+
Index: /issm/trunk/test/NightlyRun/test2010.py
===================================================================
--- /issm/trunk/test/NightlyRun/test2010.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test2010.py	(revision 22758)
@@ -0,0 +1,110 @@
+#Test Name: MomentOfIntertia
+import numpy as np
+from model import *
+from socket import gethostname
+from solve import *
+from gmshplanet import *
+from love_numbers import *
+from paterson import *
+from maskpsl import *
+from gmtmask import *
+
+#mesh earth: 
+md = model()
+rad_e = 6.371012*1e3 # mean radius of Earth, km
+md.mesh = gmshplanet('radius',rad_e,'resolution',1000.0)  # km resolution 
+
+#parameterize slr solution:
+#slr loading:  {{{
+late = sum(md.mesh.lat[md.mesh.elements - 1],1) / 3
+longe = sum(md.mesh.long[md.mesh.elements - 1],1) / 3
+
+md.slr.deltathickness = np.zeros((md.mesh.numberofelements,))
+pos = np.intersect1d(np.array(np.where(late < -75)), np.array(np.where(longe > 0)))
+#python does not include last element in array slices, (6:7) -> [5:7]
+md.slr.deltathickness[pos[5:7]] = -1
+
+md.slr.sealevel = np.zeros((md.mesh.numberofvertices,))
+md.slr.steric_rate = np.zeros((md.mesh.numberofvertices,))
+md.slr.ocean_area_scaling = 1
+
+#elastic loading from love numbers: 
+nlov = 1000
+md.slr.love_h = np.array(love_numbers('h'))
+md.slr.love_h = np.resize(md.slr.love_h, nlov + 1)
+md.slr.love_k = np.array(love_numbers('k'))
+md.slr.love_k = np.resize(md.slr.love_k, nlov + 1)
+md.slr.love_l = np.array(love_numbers('l'))
+md.slr.love_l = np.resize(md.slr.love_l, nlov + 1)
+
+#}}}
+#mask:  {{{
+md.mask = maskpsl() # use maskpsl class (instead of mask) to store the ocean function as a ocean_levelset 
+mask = gmtmask(md.mesh.lat,md.mesh.long)
+
+icemask = np.ones((md.mesh.numberofvertices,))
+pos = np.where(mask == 0)
+icemask[pos[0]] = -1
+pos = np.where(sum(mask[md.mesh.elements - 1],1) < 3)
+icemask[md.mesh.elements[pos,:] - 1] = -1
+md.mask.ice_levelset = icemask
+md.mask.ocean_levelset = np.zeros((md.mesh.numberofvertices,))
+pos = np.where(md.mask.ice_levelset == 1)
+md.mask.ocean_levelset[pos] = 1
+
+#make sure that the ice level set is all inclusive:
+md.mask.land_levelset = np.zeros((md.mesh.numberofvertices,))
+md.mask.groundedice_levelset = -np.ones((md.mesh.numberofvertices,))
+
+#make sure wherever there is an ice load, that the mask is set to ice: 
+#md.mask.ice_levelset = np.ones((md.mesh.numberofvertices,))
+pos = np.where(md.slr.deltathickness)
+md.mask.ice_levelset[md.mesh.elements[pos,:]] = -1
+# }}}
+#geometry {{{
+di = md.materials.rho_ice / md.materials.rho_water
+md.geometry.thickness = np.ones((md.mesh.numberofvertices,))
+md.geometry.surface = (1 - di) * np.zeros((md.mesh.numberofvertices,))
+md.geometry.base = md.geometry.surface - md.geometry.thickness
+md.geometry.bed = md.geometry.base
+# }}}
+#materials {{{
+md.initialization.temperature = 273.25 * np.ones((md.mesh.numberofvertices,))
+md.materials.rheology_B = paterson(md.initialization.temperature)
+md.materials.rheology_n = 3 * np.ones((md.mesh.numberofelements,))
+# }}}
+#Miscellaneous {{{
+md.miscellaneous.name = 'test2010'
+# }}}
+#Solution parameters {{{
+md.slr.reltol = float('NaN')
+md.slr.abstol = 1e-3
+# }}}
+
+#eustatic + rigid + elastic run: 
+md.slr.rigid = 1
+md.slr.elastic = 1
+md.slr.rotation = 1
+md.cluster = generic('name',gethostname(),'np',3)
+
+# uncomment following 2 lines for 
+md = solve(md,'Sealevelrise')
+eus = md.results.SealevelriseSolution.SealevelEustatic
+slr = md.results.SealevelriseSolution.Sealevel
+moixz = md.results.SealevelriseSolution.SealevelInertiaTensorXZ
+moiyz = md.results.SealevelriseSolution.SealevelInertiaTensorYZ
+moizz = md.results.SealevelriseSolution.SealevelInertiaTensorZZ 
+
+# analytical moi => just checking FOR ICE only!!! {{{
+# ...have to mute ** slr induced MOI in Tria.cpp ** prior to the comparison 
+#rad_e = rad_e*1e3 # now in meters 
+#areas=GetAreasSphericalTria(md.mesh.elements,md.mesh.lat,md.mesh.long,rad_e)
+#lat=late*pi/180 lon=longe*pi/180
+#moi_xz = sum(-md.materials.rho_freshwater.*md.slr.deltathickness.*areas.*rad_e^2.*sin(lat).*cos(lat).*cos(lon))
+#moi_yz = sum(-md.materials.rho_freshwater.*md.slr.deltathickness.*areas.*rad_e^2.*sin(lat).*cos(lat).*sin(lon))
+# }}}
+
+#Fields and tolerances to track changes
+field_names     = ['eus','slr','moixz','moiyz','moizz']
+field_tolerances= [1e-13,1e-13,1e-13,1e-13,1e-13]
+field_values = [eus,slr,moixz,moiyz,moizz]
Index: /issm/trunk/test/NightlyRun/test204.m
===================================================================
--- /issm/trunk/test/NightlyRun/test204.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test204.m	(revision 22758)
@@ -14,5 +14,5 @@
 %Fields and tolerances to track changes
 field_names     ={'Vx','Vy','Vz','Vel','Pressure','Vx_damp','Vy_damp','Vz_damp','Vel_damp','Pressure_damp'};
-field_tolerances={1e-08,1e-08,2e-06,1e-08,1e-08,1e-08,1e-08,2e-07,1e-08,1e-08};
+field_tolerances={1e-08,1e-08,4e-06,1e-08,1e-08,1e-08,1e-08,2e-07,1e-08,1e-08};
 field_values={...
 	(md.results.StressbalanceSolution.Vx),...
Index: /issm/trunk/test/NightlyRun/test204.py
===================================================================
--- /issm/trunk/test/NightlyRun/test204.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test204.py	(revision 22758)
@@ -27,5 +27,5 @@
 
 field_names     =['Vx','Vy','Vz','Vel','Pressure']
-field_tolerances=[1e-08,1e-08,2e-06,1e-08,1e-08]
+field_tolerances=[1e-08,1e-08,4e-06,1e-08,1e-08]
 field_values=[\
 	md.results.StressbalanceSolution.Vx,\
Index: /issm/trunk/test/NightlyRun/test2051.py
===================================================================
--- /issm/trunk/test/NightlyRun/test2051.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test2051.py	(revision 22758)
@@ -0,0 +1,37 @@
+#Test Name: GiaIvinsBenchmarksAB2dA1
+import numpy as np
+from model import *
+from socket import gethostname
+from solve import *
+from triangle import *
+from setmask import *
+from parameterize import *
+
+# Benchmark experiments (Figure A2a Ivins and James, 1999, Geophys. J. Int.) 
+md = triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000.)
+md = setmask(md,'','')
+md = parameterize(md,'../Par/GiaIvinsBenchmarksAB.py')
+
+# indicate what you want to compute 
+md.gia.cross_section_shape = 1 # for square-edged x-section 
+
+# define loading history 
+md.timestepping.start_time = 2002100 # after 2 kyr of deglaciation 
+md.timestepping.final_time = 2500000 # 2,500 kyr
+md.geometry.thickness = np.array([
+	np.append(md.geometry.thickness * 0.0 ,0.0),
+	np.append(md.geometry.thickness, 1000),
+	np.append(md.geometry.thickness, 2000000),
+	np.append(md.geometry.thickness * 0.0, 2000100),
+	np.append(md.geometry.thickness * 0.0, md.timestepping.start_time)
+	]).T
+
+# solve for GIA deflection 
+md.cluster=generic('name',gethostname(),'np',3)
+md.verbose = verbose('1111111')
+md = solve(md,'Gia')
+
+#Fields and tolerances to track changes
+field_names      = ['GiaW','GiadWdt']
+field_tolerances = [1e-13,1e-13]
+field_values = [md.results.GiaSolution.GiaW, md.results.GiaSolution.GiadWdt]
Index: /issm/trunk/test/NightlyRun/test2052.py
===================================================================
--- /issm/trunk/test/NightlyRun/test2052.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test2052.py	(revision 22758)
@@ -0,0 +1,37 @@
+#Test Name: GiaIvinsBenchmarksAB2dA2
+import numpy as np
+from model import *
+from socket import gethostname
+from solve import *
+from triangle import *
+from setmask import *
+from parameterize import *
+
+#Benchmark experiments (Figure A2a Ivins and James, 1999, Geophys. J. Int.) 
+md = triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000)
+md = setmask(md,'','')
+md = parameterize(md,'../Par/GiaIvinsBenchmarksAB.py')
+
+#indicate what you want to compute 
+md.gia.cross_section_shape = 1    # for square-edged x-section 
+
+#define loading history 
+md.timestepping.start_time = 2005100 # after 5 kyr of deglaciation 
+md.timestepping.final_time = 2500000 # 2,500 kyr
+md.geometry.thickness = np.array([
+	np.append(md.geometry.thickness * 0.0 ,0.0),
+	np.append(md.geometry.thickness, 1000),
+	np.append(md.geometry.thickness, 2000000),
+	np.append(md.geometry.thickness * 0.0, 2000100),
+	np.append(md.geometry.thickness * 0.0, md.timestepping.start_time)
+	]).T
+
+#solve for GIA deflection 
+md.cluster = generic('name',gethostname(),'np',3)
+md.verbose = verbose('1111111')
+md = solve(md,'Gia')
+
+#Fields and tolerances to track changes
+field_names      = ['GiaW','GiadWdt']
+field_tolerances = [1e-13,1e-13]
+field_values = [md.results.GiaSolution.GiaW,md.results.GiaSolution.GiadWdt]
Index: /issm/trunk/test/NightlyRun/test2053.py
===================================================================
--- /issm/trunk/test/NightlyRun/test2053.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test2053.py	(revision 22758)
@@ -0,0 +1,37 @@
+#Test Name: GiaIvinsBenchmarksAB2dA3
+import numpy as np
+from model import *
+from socket import gethostname
+from solve import *
+from triangle import *
+from setmask import *
+from parameterize import *
+
+#Benchmark experiments (Figure A2a Ivins and James, 1999, Geophys. J. Int.) 
+md = triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000)
+md = setmask(md,'','')
+md = parameterize(md,'../Par/GiaIvinsBenchmarksAB.py')
+
+#indicate what you want to compute 
+md.gia.cross_section_shape = 1    # for square-edged x-section 
+
+#define loading history 
+md.timestepping.start_time = 2010100 # after 10 kyr of deglaciation 
+md.timestepping.final_time = 2500000 # 2,500 kyr
+md.geometry.thickness = np.array([
+	np.append(md.geometry.thickness * 0.0 ,0.0),
+	np.append(md.geometry.thickness, 1000),
+	np.append(md.geometry.thickness, 2000000),
+	np.append(md.geometry.thickness * 0.0, 2000100),
+	np.append(md.geometry.thickness * 0.0, md.timestepping.start_time)
+	]).T
+
+#solve for GIA deflection 
+md.cluster = generic('name',gethostname(),'np',3)
+md.verbose = verbose('1111111')
+md = solve(md,'Gia')
+
+#Fields and tolerances to track changes
+field_names      = ['GiaW','GiadWdt']
+field_tolerances = [1e-13,1e-13]
+field_values = [md.results.GiaSolution.GiaW,md.results.GiaSolution.GiadWdt]
Index: /issm/trunk/test/NightlyRun/test2071.py
===================================================================
--- /issm/trunk/test/NightlyRun/test2071.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test2071.py	(revision 22758)
@@ -0,0 +1,36 @@
+#Test Name: GiaIvinsBenchmarksAB2dC1
+import numpy as np
+from model import *
+from socket import gethostname
+from solve import *
+from triangle import *
+from setmask import *
+from parameterize import *
+
+#Benchmark experiments (Figure A2c Ivins and James, 1999, Geophys. J. Int.) 
+md = triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000)
+md = setmask(md,'','')
+md = parameterize(md,'../Par/GiaIvinsBenchmarksCD.py')
+
+#indicate what you want to compute 
+md.gia.cross_section_shape = 1 # for square-edged x-section 
+
+#define loading history 
+md.timestepping.start_time = 0.3 # for t \approx 0 kyr : to get eleastic response!   
+md.timestepping.final_time = 2500000 # 2,500 kyr
+md.geometry.thickness = np.array([
+	np.append(md.geometry.thickness * 0.0, 0.0),
+	np.append(md.geometry.thickness / 2.0, 0.1),
+	np.append(md.geometry.thickness, 0.2),
+	np.append(md.geometry.thickness, md.timestepping.start_time)
+	]).T
+
+#solve for GIA deflection 
+md.cluster = generic('name',gethostname(),'np',3)
+md.verbose = verbose('1111111')
+md = solve(md,'Gia')
+
+#Fields and tolerances to track changes
+field_names      = ['GiaW','GiadWdt']
+field_tolerances = [1e-13,1e-13]
+field_values = [md.results.GiaSolution.GiaW, md.results.GiaSolution.GiadWdt]
Index: /issm/trunk/test/NightlyRun/test2072.py
===================================================================
--- /issm/trunk/test/NightlyRun/test2072.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test2072.py	(revision 22758)
@@ -0,0 +1,36 @@
+#Test Name: GiaIvinsBenchmarksAB2dC2
+import numpy as np
+from model import *
+from socket import gethostname
+from solve import *
+from triangle import *
+from setmask import *
+from parameterize import *
+
+#Benchmark experiments (Figure A2c Ivins and James, 1999, Geophys. J. Int.) 
+md = triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000)
+md = setmask(md,'','')
+md = parameterize(md,'../Par/GiaIvinsBenchmarksCD.py')
+
+#indicate what you want to compute 
+md.gia.cross_section_shape = 1 # for square-edged x-section 
+
+#define loading history 
+md.timestepping.start_time = 1000.3 # for t \approx 1 kyr   
+md.timestepping.final_time = 2500000 # 2,500 kyr
+md.geometry.thickness = np.array([
+	np.append(md.geometry.thickness * 0.0, 0.0),
+	np.append(md.geometry.thickness / 2.0, 0.1),
+	np.append(md.geometry.thickness, 0.2),
+	np.append(md.geometry.thickness, md.timestepping.start_time)
+	]).T
+
+#solve for GIA deflection 
+md.cluster = generic('name',gethostname(),'np',3)
+md.verbose = verbose('1111111')
+md = solve(md,'Gia')
+
+#Fields and tolerances to track changes
+field_names      = ['GiaW','GiadWdt']
+field_tolerances = [1e-13,1e-13]
+field_values = [md.results.GiaSolution.GiaW, md.results.GiaSolution.GiadWdt]
Index: /issm/trunk/test/NightlyRun/test2073.py
===================================================================
--- /issm/trunk/test/NightlyRun/test2073.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test2073.py	(revision 22758)
@@ -0,0 +1,36 @@
+#Test Name: GiaIvinsBenchmarksAB2dC3
+import numpy as np
+from model import *
+from socket import gethostname
+from solve import *
+from triangle import *
+from setmask import *
+from parameterize import *
+
+#Benchmark experiments (Figure A2c Ivins and James, 1999, Geophys. J. Int.) 
+md = triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000)
+md = setmask(md,'','')
+md = parameterize(md,'../Par/GiaIvinsBenchmarksCD.py')
+
+#indicate what you want to compute 
+md.gia.cross_section_shape = 1 # for square-edged x-section 
+
+#define loading history 
+md.timestepping.start_time = 2400000 # for t \approx \infty  
+md.timestepping.final_time = 2500000 # 2,500 kyr
+md.geometry.thickness = np.array([
+	np.append(md.geometry.thickness * 0.0, 0.0),
+	np.append(md.geometry.thickness / 2.0, 0.1),
+	np.append(md.geometry.thickness, 0.2),
+	np.append(md.geometry.thickness, md.timestepping.start_time)
+	]).T
+
+#solve for GIA deflection 
+md.cluster = generic('name',gethostname(),'np',3)
+md.verbose = verbose('1111111')
+md = solve(md,'Gia')
+
+#Fields and tolerances to track changes
+field_names      = ['GiaW','GiadWdt']
+field_tolerances = [1e-13,1e-13]
+field_values = [md.results.GiaSolution.GiaW, md.results.GiaSolution.GiadWdt]
Index: /issm/trunk/test/NightlyRun/test2081.py
===================================================================
--- /issm/trunk/test/NightlyRun/test2081.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test2081.py	(revision 22758)
@@ -0,0 +1,36 @@
+#Test Name: GiaIvinsBenchmarksAB2dD1
+import numpy as np
+from model import *
+from socket import gethostname
+from solve import *
+from triangle import *
+from setmask import *
+from parameterize import *
+
+#Benchmark experiments (Figure A2c Ivins and James, 1999, Geophys. J. Int.) 
+md = triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000)
+md = setmask(md,'','')
+md = parameterize(md,'../Par/GiaIvinsBenchmarksCD.py')
+
+#indicate what you want to compute 
+md.gia.cross_section_shape = 2 # for square-edged x-section 
+
+#define loading history 
+md.timestepping.start_time = 0.3 # for t \approx 0 kyr : to get eleastic response!  
+md.timestepping.final_time = 2500000 # 2,500 kyr
+md.geometry.thickness = np.array([
+	np.append(md.geometry.thickness * 0.0, 0.0),
+	np.append(md.geometry.thickness / 2.0, 0.1),
+	np.append(md.geometry.thickness, 0.2),
+	np.append(md.geometry.thickness, md.timestepping.start_time)
+	]).T
+
+#solve for GIA deflection 
+md.cluster = generic('name',gethostname(),'np',3)
+md.verbose = verbose('1111111')
+md = solve(md,'Gia')
+
+#Fields and tolerances to track changes
+field_names      = ['GiaW','GiadWdt']
+field_tolerances = [1e-13,1e-13]
+field_values = [md.results.GiaSolution.GiaW, md.results.GiaSolution.GiadWdt]
Index: /issm/trunk/test/NightlyRun/test2082.py
===================================================================
--- /issm/trunk/test/NightlyRun/test2082.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test2082.py	(revision 22758)
@@ -0,0 +1,36 @@
+#Test Name: GiaIvinsBenchmarksAB2dD2
+import numpy as np
+from model import *
+from socket import gethostname
+from solve import *
+from triangle import *
+from setmask import *
+from parameterize import *
+
+#Benchmark experiments (Figure A2c Ivins and James, 1999, Geophys. J. Int.) 
+md = triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000)
+md = setmask(md,'','')
+md = parameterize(md,'../Par/GiaIvinsBenchmarksCD.py')
+
+#indicate what you want to compute 
+md.gia.cross_section_shape = 2 # for square-edged x-section 
+
+#define loading history 
+md.timestepping.start_time = 1000.3 # for t \approx 1 kyr  
+md.timestepping.final_time = 2500000 # 2,500 kyr
+md.geometry.thickness = np.array([
+	np.append(md.geometry.thickness * 0.0, 0.0),
+	np.append(md.geometry.thickness / 2.0, 0.1),
+	np.append(md.geometry.thickness, 0.2),
+	np.append(md.geometry.thickness, md.timestepping.start_time)
+	]).T
+
+#solve for GIA deflection 
+md.cluster = generic('name',gethostname(),'np',3)
+md.verbose = verbose('1111111')
+md = solve(md,'Gia')
+
+#Fields and tolerances to track changes
+field_names      = ['GiaW','GiadWdt']
+field_tolerances = [1e-13,1e-13]
+field_values = [md.results.GiaSolution.GiaW, md.results.GiaSolution.GiadWdt]
Index: /issm/trunk/test/NightlyRun/test2083.py
===================================================================
--- /issm/trunk/test/NightlyRun/test2083.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test2083.py	(revision 22758)
@@ -0,0 +1,36 @@
+#Test Name: GiaIvinsBenchmarksAB2dD3
+import numpy as np
+from model import *
+from socket import gethostname
+from solve import *
+from triangle import *
+from setmask import *
+from parameterize import *
+
+#Benchmark experiments (Figure A2c Ivins and James, 1999, Geophys. J. Int.) 
+md = triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000)
+md = setmask(md,'','')
+md = parameterize(md,'../Par/GiaIvinsBenchmarksCD.py')
+
+#indicate what you want to compute 
+md.gia.cross_section_shape = 2 # for square-edged x-section 
+
+#define loading history 
+md.timestepping.start_time = 2400000 # for t \approx \infty  
+md.timestepping.final_time = 2500000 # 2,500 kyr
+md.geometry.thickness = np.array([
+	np.append(md.geometry.thickness * 0.0, 0.0),
+	np.append(md.geometry.thickness / 2.0, 0.1),
+	np.append(md.geometry.thickness, 0.2),
+	np.append(md.geometry.thickness, md.timestepping.start_time)
+	]).T
+
+#solve for GIA deflection 
+md.cluster = generic('name',gethostname(),'np',3)
+md.verbose = verbose('1111111')
+md = solve(md,'Gia')
+
+#Fields and tolerances to track changes
+field_names      = ['GiaW','GiadWdt']
+field_tolerances = [1e-13,1e-13]
+field_values = [md.results.GiaSolution.GiaW, md.results.GiaSolution.GiadWdt]
Index: /issm/trunk/test/NightlyRun/test2084.m
===================================================================
--- /issm/trunk/test/NightlyRun/test2084.m	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test2084.m	(revision 22758)
@@ -0,0 +1,159 @@
+
+%Test Name: GiaCaron. 
+%Forward Love number solution for a viscoelastic earth, model M3-L70-V01 from
+%Spada, G., Barletta, V. R., Klemann, V., Riva, R. E. M., Martinec, Z.,
+%Gasperini, P., Lund, B., Wolf, D., Vermeersen, L. L. A. and King, M. A.
+%(2011), A benchmark study for glacial isostatic adjustment codes. Geophysical
+%Journal International, 185: 106--132. doi:10.1111/j.1365-246X.2011.04952.x
+
+md=model();
+md.cluster=generic('name',oshostname(),'np',1);
+
+md.materials=materials('litho');
+md.miscellaneous.name='FourierLoveTest';
+
+md.verbose=verbose('all');
+cst=365.25*24*3600*1000;
+
+md.materials.numlayers=6;
+md.materials.radius =  [10 1222.5 3.4800e+03   5.7010e+03   5.9510e+03   6.3010e+03   6.3710e+03]'*1e3;
+md.materials.density=  [1.0750e4 1.0750e+04   4.9780e+03   3.8710e+03   3.4380e+03   3.0370e+03]';
+md.materials.lame_mu=  [1e-5         0   2.2834e+00   1.0549e+00   7.0363e-01   5.0605e-01]'*1e11;
+md.materials.viscosity=[0            0   2.0000e+00   1.0000e+00   1.0000e+00   1.0000e+25]'*1e21;
+md.materials.lame_lambda=md.materials.lame_mu*0+5e14;
+md.materials.issolid=[1 0 1 1 1 1]';
+md.materials.isburgers=zeros(md.materials.numlayers,1);
+
+md.love.allow_layer_deletion=1;
+md.love.frequencies=([0]*2*pi)'/cst;
+md.love.nfreq=length(md.love.frequencies);
+md.love.sh_nmax=256;
+
+md.materials.burgers_mu=md.materials.lame_mu;
+md.materials.burgers_viscosity=md.materials.viscosity;
+
+md=solve(md,'lv');
+
+%Fields and tolerances to track changes
+%loading love numbers
+field_names     ={'LoveH_loading_elastic','LoveK_loading_elastic','LoveL_loading_elastic'};
+field_tolerances={7.0e-10,7.0e-10,7.0e-10};
+field_values={...
+	(md.results.LoveSolution.LoveHr(:,1)),...
+	(md.results.LoveSolution.LoveKr(:,1)),...
+	(md.results.LoveSolution.LoveLr(:,1)),...
+	};
+
+
+md.love.frequencies=([1e-3 1e-2 1e-1 1 -1e-3 -1e-2 -1e-1 -1]*2*pi)'/cst;
+md.love.nfreq=length(md.love.frequencies);
+md.love.sh_nmax=256;
+md.materials.burgers_mu=md.materials.lame_mu;
+md.materials.burgers_viscosity=md.materials.viscosity;
+
+md=solve(md,'lv');
+
+%Fields and tolerances to track changes
+field_names     ={field_names{:},'LoveH_loading_realpart','LoveK_loading_realpart','LoveL_loading_realpart','LoveH_loading_imagpart','LoveK_loading_imagpart','LoveL_loading_imagpart'};
+field_tolerances={field_tolerances{:},7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10};
+field_values={field_values{:},...
+	(md.results.LoveSolution.LoveHr(:,:)),...
+	(md.results.LoveSolution.LoveKr(:,:)),...
+	(md.results.LoveSolution.LoveLr(:,:)),...
+	(md.results.LoveSolution.LoveHi(:,:)),...
+	(md.results.LoveSolution.LoveKi(:,:)),...
+	(md.results.LoveSolution.LoveLi(:,:)),...
+	};
+
+md.love.forcing_type=9;
+md.love.sh_nmin=2;
+md.love.frequencies=([0 1e-3 1e-2 1e-1 1 -1e-3 -1e-2 -1e-1 -1]*2*pi)'/cst;
+md.love.nfreq=length(md.love.frequencies);
+md=solve(md,'lv');
+
+%tidal love numbers
+field_names     ={field_names{:},'LoveH_tidal_elastic','LoveK_tidal_elastic','LoveL_tidal_elastic','LoveH_tidal_realpart','LoveK_tidal_realpart','LoveL_tidal_realpart','LoveH_tidal_imagpart','LoveK_tidal_imagpart','LoveL_tidal_imagpart'};
+field_tolerances={field_tolerances{:},7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10};
+field_values={field_values{:},...
+	(md.results.LoveSolution.LoveHr(:,1)),...
+	(md.results.LoveSolution.LoveKr(:,1)),...
+	(md.results.LoveSolution.LoveLr(:,1)),...
+	(md.results.LoveSolution.LoveHr(:,2:end)),...
+	(md.results.LoveSolution.LoveKr(:,2:end)),...
+	(md.results.LoveSolution.LoveLr(:,2:end)),...
+	(md.results.LoveSolution.LoveHi(:,2:end)),...
+	(md.results.LoveSolution.LoveKi(:,2:end)),...
+	(md.results.LoveSolution.LoveLi(:,2:end)),...
+	};
+
+%Many layers PREM-based model
+%data=load('../Data/PREM_500layers');
+%md.love.sh_nmin=1;
+%md.materials.radius=data(2:end-2,1);
+%md.materials.density=data(3:end-2,2);
+%md.materials.lame_lambda=data(3:end-2,3);
+%md.materials.lame_mu=data(3:end-2,4);
+%md.materials.issolid=data(3:end-2,4)>0;
+%ind=find(md.materials.issolid==0);
+%md.materials.density(ind(1))=sum((md.materials.radius(ind+1).^3-md.materials.radius(ind).^3).*md.materials.density(ind))/(md.materials.radius(ind(end)+1).^3-md.materials.radius(ind(1)+1).^3);
+%md.materials.lame_lambda(ind(1))=sum((md.materials.radius(ind+1).^3-md.materials.radius(ind).^3).*md.materials.lame_lambda(ind))/(md.materials.radius(ind(end)+1).^3-md.materials.radius(ind(1)+1).^3);
+%md.materials.lame_mu(ind(1))=sum((md.materials.radius(ind+1).^3-md.materials.radius(ind).^3).*md.materials.lame_mu(ind))/(md.materials.radius(ind(end)+1).^3-md.materials.radius(ind(1)).^3);
+%md.materials.radius(ind(2:end)+1)=[];
+%md.materials.density(ind(2:end))=[];
+%md.materials.lame_lambda(ind(2:end))=[];
+%md.materials.lame_mu(ind(2:end))=[];
+%md.materials.issolid(ind(2:end))=[];
+%md.materials.viscosity=10.^interp1([0 3479e3 3480e3 3680e3 5720e3 5800e3 6270e3 6371e3], log10([1e8 1e8 5e21 1e23 1e22 1e20 1e21 1e40]), md.materials.radius(2:end),'PCHIP');
+%md.materials.viscosity=md.materials.viscosity.*md.materials.issolid;
+%md.materials.burgers_mu=md.materials.lame_mu;
+%md.materials.burgers_viscosity=md.materials.viscosity;
+%md.materials.isburgers=md.materials.issolid*0;
+%md.love.forcing_type=11;
+%md.materials.numlayers=length(md.materials.viscosity);
+%md=solve(md,'lv');
+%
+%field_names     ={field_names{:},'LoveH_loadingVSS96_elastic','LoveK_loadingVSS96_elastic','LoveL_loadingVSS96_elastic','LoveH_loadingVSS96_realpart','LoveK_loadingVSS96_realpart','LoveL_loadingVSS96_realpart','LoveH_loadingVSS96_imagpart','LoveK_loadingVSS96_imagpart','LoveL_loadingVSS96_imagpart'};
+%field_tolerances={field_tolerances{:},7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10};
+%field_values={field_values{:},...
+%	(md.results.LoveSolution.LoveHr(:,1)),...
+%	(md.results.LoveSolution.LoveKr(:,1)),...
+%	(md.results.LoveSolution.LoveLr(:,1)),...
+%	(md.results.LoveSolution.LoveHr(:,2:end)),...
+%	(md.results.LoveSolution.LoveKr(:,2:end)),...
+%	(md.results.LoveSolution.LoveLr(:,2:end)),...
+%	(md.results.LoveSolution.LoveHi(:,2:end)),...
+%	(md.results.LoveSolution.LoveKi(:,2:end)),...
+%	(md.results.LoveSolution.LoveLi(:,2:end)),...
+%	};
+
+%Model VSS96 from Vermeersen, L.L.A., Sabadini, R. & Spada, G., 1996a. Analytical visco-elastic relaxation models, Geophys. Res. Lett., 23, 697–700.
+md.materials.radius=[10, 1222.5, 3480., 3600., 3630.5, 3700., 3900., 4000., 4200., 4300., 4500., 4600., 4800., 4900., 5100., 5200., 5400., 5500., 5600.5, 5650., 5701., 5736., 5771.5, 5821., 5951., 5970.5, 6016., 6061., 6150.5, 6151.5, 6251., 6371.]'*1e3;
+md.materials.lame_mu=[1e-5, 0., 2.933, 2.8990002, 2.8550003, 2.7340002, 2.675, 2.559, 2.502, 2.388, 2.331, 2.215, 2.157, 2.039, 1.979, 1.8560001, 1.794, 1.73, 1.639, 1.2390001, 1.224, 1.21, 1.128, 0.97700006, 0.906, 0.79, 0.773, 0.741, 0.656, 0.665, 0.602]'*1e11;
+md.materials.density=[10925., 10925., 5506.42, 5491.45, 5456.57, 5357.06, 5307.24, 5207.13, 5156.69, 5054.69, 5002.99, 4897.83, 4844.22, 4734.6, 4678.44, 4563.07, 4503.72, 4443.16, 4412.41, 3992.14, 3983.99, 3975.84, 3912.82, 3786.78, 3723.78, 3516.39, 3489.51, 3435.78, 3359.5, 3367.1, 3184.3]';
+md.materials.viscosity=[0., 0., 7.999999999999999E+21, 8.5E+21, 8.999999999999999E+21, 3.E+22, 4.E+22, 5.0000000000000004E+22, 6.E+22, 5.0000000000000004E+22, 4.5E+22, 3.E+22, 2.5000000000000002E+22, 1.7999999999999998E+22, 1.3E+22, 7.999999999999999E+21, 6.999999999999999E+21, 6.5E+21, 6.E+21, 5.5E+21, 5.E+21, 4.4999999999999995E+21, 3.9999999999999995E+21, 2.5E+21, 1.9999999999999997E+21, 1.5E+21, 9.999999999999999E+20, 6.E+20, 5.5000000000000007E+20, 2.E+20, 1.E40]';
+md.materials.lame_lambda=md.materials.lame_mu*0+5e14;
+md.materials.issolid=md.materials.lame_mu>0;
+md.materials.numlayers=length(md.materials.lame_mu);
+md.materials.burgers_mu=md.materials.lame_mu;
+md.materials.burgers_viscosity=md.materials.viscosity;
+md.materials.isburgers=md.materials.issolid*0;
+md.love.forcing_type=11;
+md.love.sh_nmin=1;
+md.love.sh_nmax=100;
+md=solve(md,'lv');
+md.love.frequencies=([0 1e-3 1e-2 1 -1e-3 -1e-2 -1]*2*pi)'/cst;
+md.love.nfreq=length(md.love.frequencies);
+
+field_names     ={field_names{:},'LoveH_loadingVSS96_elastic','LoveK_loadingVSS96_elastic','LoveL_loadingVSS96_elastic','LoveH_loadingVSS96_realpart','LoveK_loadingVSS96_realpart','LoveL_loadingVSS96_realpart','LoveH_loadingVSS96_imagpart','LoveK_loadingVSS96_imagpart','LoveL_loadingVSS96_imagpart'};
+field_tolerances={field_tolerances{:},7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10};
+field_values={field_values{:},...
+	(md.results.LoveSolution.LoveHr(:,1)),...
+	(md.results.LoveSolution.LoveKr(:,1)),...
+	(md.results.LoveSolution.LoveLr(:,1)),...
+	(md.results.LoveSolution.LoveHr(:,2:end)),...
+	(md.results.LoveSolution.LoveKr(:,2:end)),...
+	(md.results.LoveSolution.LoveLr(:,2:end)),...
+	(md.results.LoveSolution.LoveHi(:,2:end)),...
+	(md.results.LoveSolution.LoveKi(:,2:end)),...
+	(md.results.LoveSolution.LoveLi(:,2:end)),...
+	};
Index: /issm/trunk/test/NightlyRun/test2084.py
===================================================================
--- /issm/trunk/test/NightlyRun/test2084.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test2084.py	(revision 22758)
@@ -0,0 +1,199 @@
+#Test Name: GiaCaron. Forward Love number solution for a viscoelastic earth,
+#	model M3-L70-V01 from Spada, G., Barletta, V. R., Klemann, V., Riva, R. E. M.,
+#	Martinec, Z., Gasperini, P., Lund, B., Wolf, D., Vermeersen, L. L. A.
+#	and King, M. A. (2011), A benchmark study for glacial isostatic
+#	adjustment codes. Geophysical Journal International,
+#	185: 106-132. doi:10.1111/j.1365-246X.2011.04952.x
+
+from model import *
+from socket import gethostname
+from solve import *
+from numpy import *
+from generic import generic
+from materials import *
+
+md=model()
+md.cluster=generic('name',gethostname(),'np',1)
+
+md.materials=materials('litho')
+md.miscellaneous.name='FourierLoveTest'
+
+md.verbose=verbose('all')
+cst=365.25*24*3600*1000
+
+md.materials.numlayers=6
+md.materials.radius=np.array([10,1222.5,3.4800e+03,5.7010e+03,5.9510e+03,
+				6.3010e+03,6.3710e+03]).reshape(-1,1)*1e3
+md.materials.density=np.array([1.0750e4,1.0750e+04,4.9780e+03,3.8710e+03,
+				3.4380e+03,3.0370e+03]).reshape(-1,1)
+md.materials.lame_mu=np.array([1e-5,0,2.2834e+00,1.0549e+00,7.0363e-01,
+				5.0605e-01]).reshape(-1,1)*1e11
+md.materials.viscosity=np.array([0,0,2.0000e+00,1.0000e+00,1.0000e+00,
+				1.0000e+25]).reshape(-1,1)*1e21
+md.materials.lame_lambda=np.array(md.materials.lame_mu)*0+5e14
+md.materials.issolid=np.array([1,0,1,1,1,1]).reshape(-1,1)
+md.materials.isburgers=np.zeros((md.materials.numlayers,1))
+
+md.love.allow_layer_deletion=1
+md.love.frequencies=(np.array([0])*2*pi).reshape(-1,1)/cst
+md.love.nfreq=len(md.love.frequencies)
+md.love.sh_nmax=256
+
+md.materials.burgers_mu=md.materials.lame_mu
+md.materials.burgers_viscosity=md.materials.viscosity
+
+md=solve(md,'lv')
+
+#Fields and tolerances to track changes
+#loading love numbers
+field_names=['LoveHe','LoveKe','LoveLe']
+field_tolerances=[3.7e-9,3.7e-9,3.7e-9]
+field_values=[
+np.array(md.results.LoveSolution.LoveHr)[:,0],
+np.array(md.results.LoveSolution.LoveKr)[:,0],
+np.array(md.results.LoveSolution.LoveLr)[:,0]
+]
+
+md.love.frequencies=(np.array([1e-3,1e-2,1e-1,1,-1e-3,-1e-2,-1e-1,
+				-1])*2*pi).reshape(-1,1)/cst
+md.love.nfreq=len(md.love.frequencies)
+md.love.sh_nmax=256
+md.materials.burgers_mu=md.materials.lame_mu
+md.materials.burgers_viscosity=md.materials.viscosity
+
+md=solve(md,'lv')
+
+#Fields and tolerances to track changes
+#loading love numbers
+field_names+=['LoveHlr','LoveKlr','LoveLlr','LoveHli','LoveKli','LoveLli']
+field_tolerances+=[3.7e-9,3.7e-9,3.7e-9,3.7e-9,3.7e-9,3.7e-9]
+field_values+=[
+np.array(md.results.LoveSolution.LoveHr),
+np.array(md.results.LoveSolution.LoveKr),
+np.array(md.results.LoveSolution.LoveLr),
+np.array(md.results.LoveSolution.LoveHi),
+np.array(md.results.LoveSolution.LoveKi),
+np.array(md.results.LoveSolution.LoveLi)
+]
+
+md.love.forcing_type=9
+md.love.sh_nmin=2
+md.love.frequencies=((np.array([0,1e-3,1e-2,1e-1,1,-1e-3,
+				-1e-2,-1e-1,-1])*2*pi).reshape(-1,1)/cst)
+md.love.nfreq=len(md.love.frequencies)
+
+md=solve(md,'lv')
+
+#tidal love numbers, check
+field_names+=['LoveHtr','LoveKtr','LoveLtr','LoveHti','LoveKti','LoveLti']
+field_tolerances+=[3.7e-9,3.7e-9,3.7e-9,3.7e-9,3.7e-9,3.7e-9,3.7e-9,3.7e-9,3.7e-9]
+field_values+=[
+np.array(md.results.LoveSolution.LoveHr)[:,0],
+np.array(md.results.LoveSolution.LoveKr)[:,0],
+np.array(md.results.LoveSolution.LoveLr)[:,0],
+np.array(md.results.LoveSolution.LoveHr)[:,1:],
+np.array(md.results.LoveSolution.LoveKr)[:,1:],
+np.array(md.results.LoveSolution.LoveLr)[:,1:],
+np.array(md.results.LoveSolution.LoveHi)[:,1:],
+np.array(md.results.LoveSolution.LoveKi)[:,1:],
+np.array(md.results.LoveSolution.LoveLi)[:,1:]
+]
+
+#Many layers PREM-based model
+#data=load('../Data/PREM_500layers')
+#md.love.sh_nmin=1
+#md.materials.radius=data(2:end-2,1)
+#md.materials.density=data(3:end-2,2)
+#md.materials.lame_lambda=data(3:end-2,3)
+#md.materials.lame_mu=data(3:end-2,4)
+#md.materials.issolid=data(3:end-2,4)>0
+#ind=find(md.materials.issolid==0)
+#md.materials.density(ind(1))=sum((md.materials.radius(ind+1).^3-md.materials.radius(ind).^3).*md.materials.density(ind))/(md.materials.radius(ind(end)+1).^3-md.materials.radius(ind(1)+1).^3)
+#md.materials.lame_lambda(ind(1))=sum((md.materials.radius(ind+1).^3-md.materials.radius(ind).^3).*md.materials.lame_lambda(ind))/(md.materials.radius(ind(end)+1).^3-md.materials.radius(ind(1)+1).^3)
+#md.materials.lame_mu(ind(1))=sum((md.materials.radius(ind+1).^3-md.materials.radius(ind).^3).*md.materials.lame_mu(ind))/(md.materials.radius(ind(end)+1).^3-md.materials.radius(ind(1)).^3)
+#md.materials.radius(ind(2:end)+1)=[]
+#md.materials.density(ind(2:end))=[]
+#md.materials.lame_lambda(ind(2:end))=[]
+#md.materials.lame_mu(ind(2:end))=[]
+#md.materials.issolid(ind(2:end))=[]
+#md.materials.viscosity=10.^interp1([0 3479e3 3480e3 3680e3 5720e3 5800e3 6270e3 6371e3], log10([1e8 1e8 5e21 1e23 1e22 1e20 1e21 1e40]), md.materials.radius(2:end),'PCHIP')
+#md.materials.viscosity=md.materials.viscosity.*md.materials.issolid
+#md.materials.burgers_mu=md.materials.lame_mu
+#md.materials.burgers_viscosity=md.materials.viscosity
+#md.materials.isburgers=md.materials.issolid*0
+#md.love.forcing_type=11
+#md.materials.numlayers=len(md.materials.viscosity)
+#md=solve(md,'lv')
+#
+#field_names=[field_names,'LoveHmr','LoveKmr','LoveLmr','LoveHmi','LoveKmi','LoveLmi']
+#field_tolerances=[field_tolerances,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13]
+#field_values=[field_values,\
+#	(md.results.LoveSolution.LoveHr[:][0]),\
+#	(md.results.LoveSolution.LoveKr[:][0]),\
+#	(md.results.LoveSolution.LoveLr[:][0]),\
+#	(md.results.LoveSolution.LoveHr[:][1:]),\
+#	(md.results.LoveSolution.LoveKr[:][1:]),\
+#	(md.results.LoveSolution.LoveLr[:][1:]),\
+#	(md.results.LoveSolution.LoveHi[:][1:]),\
+#	(md.results.LoveSolution.LoveKi[:][1:]),\
+#	(md.results.LoveSolution.LoveLi[:][1:]),\
+#	]
+#Model VSS96 from Vermeersen, L.L.A., Sabadini, R. & Spada, G., 1996a. Analytical visco-elastic relaxation models, Geophys. Res. Lett., 23, 697-700.
+
+md.materials.radius=np.array([10,1222.5,3480.,3600.,3630.5,3700.,3900.,4000.,
+				4200.,4300.,4500.,4600.,4800.,4900.,5100.,5200.,
+				5400.,5500.,5600.5,5650.,5701.,5736.,5771.5,
+				5821.,5951.,5970.5,6016.,6061.,6150.5,6151.5,
+				6251.,6371.]).reshape(-1,1)*1e3
+md.materials.lame_mu=np.array([1e-5,0.,2.933,2.8990002,2.8550003,2.7340002,2.675,
+				2.559,2.502,2.388,2.331,2.215,2.157,2.039,1.979,
+				1.8560001,1.794,1.73,1.639,1.2390001,1.224,1.21,
+				1.128,0.97700006,0.906,0.79,0.773,0.741,0.656,0.665,
+				0.602]).reshape(-1,1)*1e11
+md.materials.density=np.array([10925.,10925.,5506.42,5491.45,5456.57,5357.06,
+				5307.24,5207.13,5156.69,5054.69,5002.99,4897.83,
+				4844.22,4734.6,4678.44,4563.07,4503.72,4443.16,
+				4412.41,3992.14,3983.99,3975.84,3912.82,3786.78,
+				3723.78,3516.39,3489.51,3435.78,3359.5,3367.1,
+				3184.3]).reshape(-1,1)
+md.materials.viscosity=np.array([0.,0.,7.999999999999999E+21,8.5E+21,
+				8.999999999999999E+21,3.E+22,4.E+22,
+				5.0000000000000004E+22,6.E+22,
+				5.0000000000000004E+22,4.5E+22,3.E+22,
+				2.5000000000000002E+22,1.7999999999999998E+22,
+				1.3E+22,7.999999999999999E+21,6.999999999999999E+21,
+				6.5E+21,6.E+21,5.5E+21,5.E+21,4.4999999999999995E+21,
+				3.9999999999999995E+21,2.5E+21,
+				1.9999999999999997E+21,1.5E+21,9.999999999999999E+20,
+				6.E+20,5.5000000000000007E+20,2.E+20,
+				1.E40]).reshape(-1,1)
+md.materials.lame_lambda=np.array(md.materials.lame_mu)*0+5e14
+md.materials.issolid=np.ones(len(md.materials.lame_mu)).reshape(-1,1)
+md.materials.issolid[1]=0
+md.materials.numlayers=len(md.materials.lame_mu)
+md.materials.burgers_mu=md.materials.lame_mu
+md.materials.burgers_viscosity=md.materials.viscosity
+md.materials.isburgers=md.materials.issolid*0
+md.love.forcing_type=11
+md.love.sh_nmin=1
+md.love.sh_nmax=100
+
+md=solve(md,'lv')
+
+md.love.frequencies=(np.array([0,1e-3,1e-2,1,-1e-3,-1e-2,
+				-1])*2*pi).reshape(-1,1)/cst
+md.love.nfreq=len(md.love.frequencies)
+
+field_names+=['LoveHmr','LoveKmr','LoveLmr','LoveHmi','LoveKmi','LoveLmi']
+field_tolerances+=[3.7e-9,3.7e-9,3.7e-9,3.7e-9,3.7e-9,3.7e-9,3.7e-9,3.7e-9,3.7e-9]
+field_values+=[
+np.array(md.results.LoveSolution.LoveHr)[:,0],
+np.array(md.results.LoveSolution.LoveKr)[:,0],
+np.array(md.results.LoveSolution.LoveLr)[:,0],
+np.array(md.results.LoveSolution.LoveHr)[:,1:],
+np.array(md.results.LoveSolution.LoveKr)[:,1:],
+np.array(md.results.LoveSolution.LoveLr)[:,1:],
+np.array(md.results.LoveSolution.LoveHi)[:,1:],
+np.array(md.results.LoveSolution.LoveKi)[:,1:],
+np.array(md.results.LoveSolution.LoveLi)[:,1:]
+]
Index: /issm/trunk/test/NightlyRun/test2085.m
===================================================================
--- /issm/trunk/test/NightlyRun/test2085.m	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test2085.m	(revision 22758)
@@ -0,0 +1,44 @@
+
+%Test Name: LovenumberstAtDepth. 
+%Same as test #1 of test2084.m 
+
+md=model();
+md.cluster=generic('name',oshostname(),'np',1);
+
+md.materials=materials('litho');
+md.miscellaneous.name='FourierLoveTest';
+
+md.verbose=verbose('111111101');
+cst=365.25*24*3600*1000;
+
+	md.materials.numlayers=6;
+        md.materials.radius =  [10 1222.5 3.4800e+03   5.7010e+03   5.9510e+03   6.3010e+03   6.3710e+03]'*1e3;
+	md.materials.density=  [1.0750e4 1.0750e+04   4.9780e+03   3.8710e+03   3.4380e+03   3.0370e+03]';
+	md.materials.lame_mu=  [1e-5         0   2.2834e+00   1.0549e+00   7.0363e-01   5.0605e-01]'*1e11;
+	md.materials.viscosity=[0             0   2.0000e+00   1.0000e+00   1.0000e+00   1.0000e+25]'*1e21;
+	md.materials.lame_lambda=md.materials.lame_mu*0+5e14;
+	md.materials.issolid=[1 0 1 1 1 1]';
+	md.materials.isburgers=zeros(md.materials.numlayers,1);
+
+md.love.love_kernels=1; 
+md.love.allow_layer_deletion=1;
+md.love.frequencies=([0]*2*pi)'/cst;
+md.love.nfreq=length(md.love.frequencies);
+md.love.sh_nmax=2;
+
+md.materials.burgers_mu=md.materials.lame_mu;
+md.materials.burgers_viscosity=md.materials.viscosity;
+
+md=solve(md,'lv');
+
+%Fields and tolerances to track changes
+%loading love numbers
+field_names = {'LoveH_loading_elastic','LoveK_loading_elastic','LoveL_loading_elastic','LoveKernels_degree1','LoveKernels_degree2'};
+field_tolerances={1e-10,1e-10,1e-10,1e-10,1e-10}; 
+field_values={...
+	(md.results.LoveSolution.LoveHr(:,1)),...
+	(md.results.LoveSolution.LoveKr(:,1)),...
+	(md.results.LoveSolution.LoveLr(:,1)),...
+	squeeze(cell2mat(md.results.LoveSolution.LoveKernelsReal(2,1,:,:))),...
+	squeeze(cell2mat(md.results.LoveSolution.LoveKernelsReal(3,1,:,:))),...
+	};
Index: /issm/trunk/test/NightlyRun/test2085.py
===================================================================
--- /issm/trunk/test/NightlyRun/test2085.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test2085.py	(revision 22758)
@@ -0,0 +1,49 @@
+#Test Name: LovenumberstAtDepth.
+#Same as test #1 of test2084.m 
+
+from model import *
+from socket import gethostname
+from solve import *
+from numpy import *
+from generic import generic
+from materials import *
+
+md = model()
+md.cluster = generic('name',gethostname(),'np',1)
+
+md.materials = materials('litho')
+md.miscellaneous.name = 'FourierLoveTest'
+
+md.verbose = verbose('111111101')
+cst = 365.25*24*3600*1000
+
+md.materials.numlayers = 6
+md.materials.radius = np.array([10,1222.5,3.4800e+03,5.7010e+03,5.9510e+03,6.3010e+03,6.3710e+03]).reshape(-1,1)*1e3
+md.materials.density = np.array([1.0750e4,1.0750e+04,4.9780e+03,3.8710e+03,3.4380e+03,3.0370e+03]).reshape(-1,1)
+md.materials.lame_mu = np.array([1e-5,0,2.2834e+00,1.0549e+00,7.0363e-01,5.0605e-01]).reshape(-1,1)*1e11
+md.materials.viscosity = np.array([0,0,2.0000e+00,1.0000e+00,1.0000e+00,1.0000e+25]).reshape(-1,1)*1e21
+md.materials.lame_lambda = np.array(md.materials.lame_mu)*0+5e14
+md.materials.issolid = np.array([1,0,1,1,1,1]).reshape(-1,1)
+md.materials.isburgers = np.zeros((md.materials.numlayers,))
+
+md.love.love_kernels = 1 
+md.love.allow_layer_deletion = 1
+md.love.frequencies = (np.array([0])*2*pi).reshape(-1,1) / cst
+md.love.nfreq = len(md.love.frequencies)
+md.love.sh_nmax = 2
+
+md.materials.burgers_mu = md.materials.lame_mu
+md.materials.burgers_viscosity = md.materials.viscosity
+
+md = solve(md,'lv')
+
+#Fields and tolerances to track changes
+#loading love numbers
+field_names =  ['LoveH_loading_elastic','LoveK_loading_elastic','LoveL_loading_elastic','LoveKernels_degree1','LoveKernels_degree2']
+field_tolerances = [1e-10,1e-10,1e-10,1e-10,1e-10] 
+field_values = [
+	md.results.LoveSolution.LoveHr[:,0],
+	md.results.LoveSolution.LoveKr[:,0],
+	md.results.LoveSolution.LoveLr[:,0],
+	md.results.LoveSolution.LoveKernelsReal[1,0,:,:],
+	md.results.LoveSolution.LoveKernelsReal[2,0,:,:]]
Index: /issm/trunk/test/NightlyRun/test210.js
===================================================================
--- /issm/trunk/test/NightlyRun/test210.js	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test210.js	(revision 22758)
@@ -15,7 +15,7 @@
 					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'];
 field_tolerances=[
-	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,
-	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,
-	1e-09,1e-09,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05];
+	1e-08,1e-08,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,
+	1e-08,1e-08,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,
+	1e-08,1e-08,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05];
 field_values=[
 	(md.results.TransientSolution[0](1).Vx),
Index: /issm/trunk/test/NightlyRun/test210.m
===================================================================
--- /issm/trunk/test/NightlyRun/test210.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test210.m	(revision 22758)
@@ -14,7 +14,7 @@
 					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'};
 field_tolerances={...
-	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,...
-	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,...
-	1e-09,1e-09,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05};
+	1e-08,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,...
+	1e-08,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,...
+	1e-08,1e-08,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05};
 field_values={...
 	(md.results.TransientSolution(1).Vx),...
Index: /issm/trunk/test/NightlyRun/test210.py
===================================================================
--- /issm/trunk/test/NightlyRun/test210.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test210.py	(revision 22758)
@@ -23,10 +23,10 @@
 
 field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', \
-				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', \
-					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3']
+        'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', \
+        'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3']
 field_tolerances=[\
-	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,\
-	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,\
-	1e-09,1e-09,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05]
+	1e-08,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,\
+	1e-08,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,\
+	1e-08,1e-08,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05]
 field_values=[\
 	md.results.TransientSolution[0].Vx,\
Index: /issm/trunk/test/NightlyRun/test2101.py
===================================================================
--- /issm/trunk/test/NightlyRun/test2101.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test2101.py	(revision 22758)
@@ -0,0 +1,82 @@
+#Test Name: EarthEsa
+#Elastostatic adjustment for an elemental ice unloading
+
+import numpy as np
+from model import *
+from socket import gethostname
+from solve import *
+from gmshplanet import *
+from love_numbers import *
+from paterson import *
+from maskpsl import *
+from gmtmask import *
+
+#mesh earth: 
+md = model()
+md.mesh = gmshplanet('radius',6.371012*1e3,'resolution',1000)
+
+#define load 
+md.esa.deltathickness = np.zeros((md.mesh.numberofelements,))
+pos = 449
+md.esa.deltathickness[pos] = -100   # this is the only "icy" element
+
+#love numbers:
+nlov = 10000
+md.esa.love_h = np.array(love_numbers('h'))	#Originally had CM arg
+md.esa.love_h = np.resize(md.esa.love_h, nlov + 1)
+md.esa.love_l = np.array(love_numbers('l'))	#Originally had CM arg
+md.esa.love_l = np.resize(md.esa.love_l, nlov + 1)
+
+#mask:  {{{
+md.mask = maskpsl() # use maskpsl class (instead of mask) to store the ocean function as a ocean_levelset 
+md.mask.ocean_levelset = gmtmask(md.mesh.lat,md.mesh.long) 
+
+#make sure wherever there is an ice load, that the mask is set to ice: 
+md.mask.ice_levelset = np.ones((md.mesh.numberofvertices,))
+pos = np.where(md.esa.deltathickness)
+md.mask.ice_levelset[md.mesh.elements[pos,:]] = -1
+
+#is ice grounded? 
+md.mask.groundedice_levelset = -np.ones((md.mesh.numberofvertices,))
+pos = np.where(md.mask.ice_levelset <= 0)
+md.mask.groundedice_levelset[pos] = 1
+
+#make sure ice domain is on the continent: 
+#pos = np.where(md.mask.ice_levelset <= 0)
+#md.mask.ocean_levelset[pos] = 0
+
+#land mask 
+md.mask.land_levelset = 1 - md.mask.ocean_levelset
+
+# }}}
+#geometry:  {{{
+di = md.materials.rho_ice / md.materials.rho_water
+md.geometry.thickness = np.ones((md.mesh.numberofvertices,))
+md.geometry.surface = (1 - di) * np.zeros((md.mesh.numberofvertices,))
+md.geometry.base = md.geometry.surface - md.geometry.thickness
+md.geometry.bed = md.geometry.base
+# }}}
+#materials:  {{{
+md.initialization.temperature = 273.25 * np.ones((md.mesh.numberofvertices,))
+md.materials.rheology_B = paterson(md.initialization.temperature)
+md.materials.rheology_n = 3 * np.ones((md.mesh.numberofelements,))
+# }}}
+#Miscellaneous: {{{
+md.miscellaneous.name = 'test2101'
+# }}}
+
+#solve esa 
+md.esa.requested_outputs = ['EsaUmotion','EsaNmotion','EsaEmotion']
+md.cluster = generic('name',gethostname(),'np',3)
+md.verbose = verbose('111111111')
+md = solve(md,'Esa')
+
+#Fields and tolerances to track changes
+field_names     = ['EsaUmotion','EsaNmotion','EsaEmotion']
+field_tolerances= [1e-13,1e-13,1e-13]
+field_values = [
+	md.results.EsaSolution.EsaUmotion,
+	md.results.EsaSolution.EsaNmotion,
+	md.results.EsaSolution.EsaEmotion,
+	]
+
Index: /issm/trunk/test/NightlyRun/test2110.m
===================================================================
--- /issm/trunk/test/NightlyRun/test2110.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test2110.m	(revision 22758)
@@ -49,5 +49,5 @@
 
 % solve esa 
-md.esa.requested_outputs = {'EsaUmotion','EsaNmotion','EsaEmotion',...
+md.esa.requested_outputs = {'EsaUmotion','EsaXmotion','EsaYmotion',...
 	'EsaStrainratexx','EsaStrainratexy','EsaStrainrateyy','EsaRotationrate'};
 md.cluster=generic('name',oshostname(),'np',3); 
@@ -56,11 +56,11 @@
 
 %Fields and tolerances to track changes
-field_names     ={'EsaUmotion','EsaNmotion','EsaEmotion',...
+field_names     ={'EsaUmotion','EsaXmotion','EsaYmotion',...
 	'EsaStrainratexx','EsaStrainratexy','EsaStrainrateyy','EsaRotationrate'};
 field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
 	(md.results.EsaSolution.EsaUmotion),...
-	(md.results.EsaSolution.EsaNmotion),...
-	(md.results.EsaSolution.EsaEmotion),...
+	(md.results.EsaSolution.EsaXmotion),...
+	(md.results.EsaSolution.EsaYmotion),...
 	(md.results.EsaSolution.EsaStrainratexx),...
 	(md.results.EsaSolution.EsaStrainratexy),...
Index: /issm/trunk/test/NightlyRun/test2110.py
===================================================================
--- /issm/trunk/test/NightlyRun/test2110.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test2110.py	(revision 22758)
@@ -0,0 +1,82 @@
+#Test Name: Esa2Dsurface
+#Elastostatic adjustment for an elemental ice unloading
+
+import numpy as np
+from model import *
+from socket import gethostname
+from solve import *
+from roundmesh import *
+from love_numbers import *
+from paterson import *
+
+#mesh earth: 
+md = model()
+md = roundmesh(md,50000,2000)     # radius and element size (meters)
+
+#define load 
+md.esa.deltathickness = np.zeros((md.mesh.numberofelements,))
+disc_radius = 20 # km
+index = md.mesh.elements
+x_element = np.mean(md.mesh.x[index - 1], 1)
+y_element = np.mean(md.mesh.y[index - 1], 1)
+rad_dist = np.sqrt(x_element**2 + y_element**2) / 1000  # radial distance in km
+md.esa.deltathickness[np.where(rad_dist <= disc_radius)] = -1   # 1 m water withdrawl
+
+#love numbers:
+nlov = 10000	# horizontal displacements do not work for low degree truncation, e.g., 101
+md.esa.love_h = np.array(love_numbers('h'))
+md.esa.love_h = np.resize(md.esa.love_h, nlov + 1)
+md.esa.love_l = np.array(love_numbers('l'))
+md.esa.love_l = np.resize(md.esa.love_l, nlov + 1)
+
+#mask:  {{{
+#make sure wherever there is an ice load, that the mask is set to ice: 
+md.mask.ice_levelset = np.ones((md.mesh.numberofvertices,))
+pos = np.where(md.esa.deltathickness)
+md.mask.ice_levelset[md.mesh.elements[pos,:]-1] = -1
+
+#is ice grounded? 
+md.mask.groundedice_levelset = -np.ones((md.mesh.numberofvertices,))
+pos = np.where(md.mask.ice_levelset <= 0)
+md.mask.groundedice_levelset[pos] = 1
+
+# }}}
+#geometry:  {{{
+di = md.materials.rho_ice / md.materials.rho_water
+md.geometry.thickness = np.ones((md.mesh.numberofvertices,))
+md.geometry.surface = (1 - di) * np.zeros((md.mesh.numberofvertices,))
+md.geometry.base = md.geometry.surface - md.geometry.thickness
+md.geometry.bed = md.geometry.base
+# }}}
+#materials:  {{{
+md.initialization.temperature = 273.25 * np.ones((md.mesh.numberofvertices,))
+md.materials.rheology_B = paterson(md.initialization.temperature)
+md.materials.rheology_n = 3 * np.ones((md.mesh.numberofelements,))
+# }}}
+#Miscellaneous: {{{
+md.miscellaneous.name = 'test2110'
+# }}}
+
+md.esa.degacc = 0.01
+
+#solve esa 
+md.esa.requested_outputs = ['EsaUmotion','EsaXmotion','EsaYmotion',
+	'EsaStrainratexx','EsaStrainratexy','EsaStrainrateyy','EsaRotationrate']
+md.cluster = generic('name',gethostname(),'np',3)
+md.verbose = verbose('111111111')
+md = solve(md,'Esa')
+
+#Fields and tolerances to track changes
+field_names     = ['EsaUmotion','EsaXmotion','EsaYmotion',
+	'EsaStrainratexx','EsaStrainratexy','EsaStrainrateyy','EsaRotationrate']
+field_tolerances = [1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13]
+field_values = [
+	md.results.EsaSolution.EsaUmotion,
+	md.results.EsaSolution.EsaXmotion,
+	md.results.EsaSolution.EsaYmotion,
+	md.results.EsaSolution.EsaStrainratexx,
+	md.results.EsaSolution.EsaStrainratexy,
+	md.results.EsaSolution.EsaStrainrateyy,
+	md.results.EsaSolution.EsaRotationrate,
+	]
+
Index: /issm/trunk/test/NightlyRun/test2111.m
===================================================================
--- /issm/trunk/test/NightlyRun/test2111.m	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test2111.m	(revision 22758)
@@ -0,0 +1,66 @@
+%Test Name: Esa2Dsurface
+%AIS -- southern hemisphere example for north-south, east-west components of horiz motion 
+
+%mesh ais: {{{
+	md=model();
+	md=triangle(md,'../Exp/Ais.exp',200000); % max element size
+% }}}
+%define load: {{{
+	md.esa.deltathickness=zeros(md.mesh.numberofelements,1);
+	disc_radius=500; % km
+	index=md.mesh.elements;
+	x_element=mean(md.mesh.x(index),2)-1.0e6;
+	y_element=mean(md.mesh.y(index),2)-1.0e6;
+	rad_dist=sqrt(x_element.^2+y_element.^2)/1000;  % radial distance in km
+	md.esa.deltathickness(rad_dist<=disc_radius)=-1;   % 1 m water withdrawl
+% }}}
+%read in love numbers:{{{
+	nlov=10001;	% horizontal displacements do not work for low degree truncation, e.g., 101
+	md.esa.love_h = love_numbers('h','CF'); md.esa.love_h(nlov+1:end)=[];
+	md.esa.love_l = love_numbers('l','CF'); md.esa.love_l(nlov+1:end)=[];
+% }}}
+%mask:  {{{
+	%make sure wherever there is an ice load, that the mask is set to ice: 
+	md.mask.ice_levelset=ones(md.mesh.numberofvertices,1);
+	pos=find(md.esa.deltathickness); md.mask.ice_levelset(md.mesh.elements(pos,:))=-1;
+
+	%is ice grounded? 
+	md.mask.groundedice_levelset=-ones(md.mesh.numberofvertices,1);
+	pos=find(md.mask.ice_levelset<=0); md.mask.groundedice_levelset(pos)=1; 
+% }}}
+%geometry:  {{{
+	di=md.materials.rho_ice/md.materials.rho_water;
+	md.geometry.thickness=ones(md.mesh.numberofvertices,1);
+	md.geometry.surface=(1-di)*zeros(md.mesh.numberofvertices,1);
+	md.geometry.base=md.geometry.surface-md.geometry.thickness;
+	md.geometry.bed=md.geometry.base;
+% }}}
+%materials:  {{{
+	md.initialization.temperature=273.25*ones(md.mesh.numberofvertices,1);
+	md.materials.rheology_B=paterson(md.initialization.temperature);
+	md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+% }}}
+%additional parameters, miscellaneous: {{{
+	md.miscellaneous.name='test2111';
+	md.esa.degacc=0.01;
+	md.esa.hemisphere = -1; 
+% }}}
+
+%solve esa: {{{
+md.esa.requested_outputs = {'EsaUmotion','EsaNmotion','EsaEmotion','EsaXmotion','EsaYmotion'}; 
+md.cluster=generic('name',oshostname(),'np',3); 
+md.verbose=verbose('111111111');
+md=solve(md,'Esa');
+% }}}
+%fields and tolerances to track changes {{{
+field_names     ={'EsaUmotion','EsaNmotion','EsaEmotion','EsaXmotion','EsaYmotion'}; 
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.EsaSolution.EsaUmotion),...
+	(md.results.EsaSolution.EsaNmotion),...
+	(md.results.EsaSolution.EsaEmotion),...
+	(md.results.EsaSolution.EsaXmotion),...
+	(md.results.EsaSolution.EsaYmotion),...
+	};
+% }}} 
+
Index: /issm/trunk/test/NightlyRun/test2111.py
===================================================================
--- /issm/trunk/test/NightlyRun/test2111.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test2111.py	(revision 22758)
@@ -0,0 +1,78 @@
+#Test Name: Esa2Dsurface
+#AIS -- southern hemisphere example for north-south, east-west components of horiz motion 
+
+import numpy as np
+from model import *
+from socket import gethostname
+from solve import *
+from roundmesh import *
+from love_numbers import *
+from paterson import *
+
+#mesh ais: {{{
+md = model()
+md = triangle(md,'../Exp/Ais.exp',200000); # max element size
+# }}}
+#define load: {{{
+md.esa.deltathickness = np.zeros((md.mesh.numberofelements,))
+disc_radius = 500 # km
+index = md.mesh.elements
+x_element = np.mean(md.mesh.x[index - 1], 1) - 1.0e6
+y_element = np.mean(md.mesh.y[index - 1], 1) - 1.0e6
+rad_dist = np.sqrt(x_element**2 + y_element**2) / 1000  # radial distance in km
+md.esa.deltathickness[np.where(rad_dist <= disc_radius)] = -1   # 1 m water withdrawl
+# }}}
+#love numbers: {{{
+nlov = 10000	# horizontal displacements do not work for low degree truncation, e.g., 101
+md.esa.love_h = np.array(love_numbers('h','CF'))
+md.esa.love_h = np.resize(md.esa.love_h, nlov + 1)
+md.esa.love_l = np.array(love_numbers('l','CF'))
+md.esa.love_l = np.resize(md.esa.love_l, nlov + 1)
+# }}}
+#mask:  {{{
+#make sure wherever there is an ice load, that the mask is set to ice: 
+md.mask.ice_levelset = np.ones((md.mesh.numberofvertices,))
+pos = np.where(md.esa.deltathickness)
+md.mask.ice_levelset[md.mesh.elements[pos,:]] = -1
+
+#is ice grounded? 
+md.mask.groundedice_levelset = -np.ones((md.mesh.numberofvertices,))
+pos = np.where(md.mask.ice_levelset <= 0)
+md.mask.groundedice_levelset[pos] = 1
+# }}}
+#geometry:  {{{
+di = md.materials.rho_ice / md.materials.rho_water
+md.geometry.thickness = np.ones((md.mesh.numberofvertices,))
+md.geometry.surface = (1 - di) * np.zeros((md.mesh.numberofvertices,))
+md.geometry.base = md.geometry.surface - md.geometry.thickness
+md.geometry.bed = md.geometry.base
+# }}}
+#materials:  {{{
+md.initialization.temperature = 273.25 * np.ones((md.mesh.numberofvertices,))
+md.materials.rheology_B = paterson(md.initialization.temperature)
+md.materials.rheology_n = 3 * np.ones((md.mesh.numberofelements,))
+# }}}
+#additional parameters, miscellaneous: {{{
+md.miscellaneous.name='test2111';
+md.esa.degacc=0.01;
+md.esa.hemisphere = -1; 
+# }}}
+
+#solve esa: {{{
+md.esa.requested_outputs = ['EsaUmotion','EsaNmotion','EsaEmotion','EsaXmotion','EsaYmotion'] 
+md.cluster = generic('name',gethostname(),'np',3)
+md.verbose = verbose('111111111')
+md = solve(md,'Esa')
+# }}}
+#Fields and tolerances to track changes: {{{
+field_names     = ['EsaUmotion','EsaNmotion','EsaEmotion','EsaXmotion','EsaYmotion']
+field_tolerances = [1e-13,1e-13,1e-13,1e-13,1e-13]
+field_values = [
+	md.results.EsaSolution.EsaUmotion,
+	md.results.EsaSolution.EsaNmotion,
+	md.results.EsaSolution.EsaEmotion,
+	md.results.EsaSolution.EsaXmotion,
+	md.results.EsaSolution.EsaYmotion,
+	]
+# }}}
+
Index: /issm/trunk/test/NightlyRun/test2112.m
===================================================================
--- /issm/trunk/test/NightlyRun/test2112.m	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test2112.m	(revision 22758)
@@ -0,0 +1,66 @@
+%Test Name: Esa2Dsurface
+%AIS 2 -- load centered at the south pole! 
+
+%mesh ais: {{{
+	md=model();
+	md=triangle(md,'../Exp/Ais.exp',100000); % max element size
+% }}}
+%define load: {{{
+	md.esa.deltathickness=zeros(md.mesh.numberofelements,1);
+	disc_radius=500; % km
+	index=md.mesh.elements;
+	x_element=mean(md.mesh.x(index),2); 
+	y_element=mean(md.mesh.y(index),2); 
+	rad_dist=sqrt(x_element.^2+y_element.^2)/1000;  % radial distance in km
+	md.esa.deltathickness(rad_dist<=disc_radius)=-1;   % 1 m water withdrawl
+% }}}
+%read in love numbers:{{{
+	nlov=10001;	% horizontal displacements do not work for low degree truncation, e.g., 101
+	md.esa.love_h = love_numbers('h','CF'); md.esa.love_h(nlov+1:end)=[];
+	md.esa.love_l = love_numbers('l','CF'); md.esa.love_l(nlov+1:end)=[];
+% }}}
+%mask:  {{{
+	%make sure wherever there is an ice load, that the mask is set to ice: 
+	md.mask.ice_levelset=ones(md.mesh.numberofvertices,1);
+	pos=find(md.esa.deltathickness); md.mask.ice_levelset(md.mesh.elements(pos,:))=-1;
+
+	%is ice grounded? 
+	md.mask.groundedice_levelset=-ones(md.mesh.numberofvertices,1);
+	pos=find(md.mask.ice_levelset<=0); md.mask.groundedice_levelset(pos)=1; 
+% }}}
+%geometry:  {{{
+	di=md.materials.rho_ice/md.materials.rho_water;
+	md.geometry.thickness=ones(md.mesh.numberofvertices,1);
+	md.geometry.surface=(1-di)*zeros(md.mesh.numberofvertices,1);
+	md.geometry.base=md.geometry.surface-md.geometry.thickness;
+	md.geometry.bed=md.geometry.base;
+% }}}
+%materials:  {{{
+	md.initialization.temperature=273.25*ones(md.mesh.numberofvertices,1);
+	md.materials.rheology_B=paterson(md.initialization.temperature);
+	md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+% }}}
+%additional parameters, miscellaneous: {{{
+	md.miscellaneous.name='test2112';
+	md.esa.degacc=0.01;
+	md.esa.hemisphere = -1; 
+% }}}
+
+%solve esa: {{{
+md.esa.requested_outputs = {'EsaUmotion','EsaNmotion','EsaEmotion','EsaXmotion','EsaYmotion'}; 
+md.cluster=generic('name',oshostname(),'np',3); 
+md.verbose=verbose('111111111');
+md=solve(md,'Esa');
+% }}}
+%fields and tolerances to track changes {{{
+field_names     ={'EsaUmotion','EsaNmotion','EsaEmotion','EsaXmotion','EsaYmotion'}; 
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.EsaSolution.EsaUmotion),...
+	(md.results.EsaSolution.EsaNmotion),...
+	(md.results.EsaSolution.EsaEmotion),...
+	(md.results.EsaSolution.EsaXmotion),...
+	(md.results.EsaSolution.EsaYmotion),...
+	};
+% }}} 
+
Index: /issm/trunk/test/NightlyRun/test2112.py
===================================================================
--- /issm/trunk/test/NightlyRun/test2112.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test2112.py	(revision 22758)
@@ -0,0 +1,78 @@
+#Test Name: Esa2Dsurface
+#AIS 2 -- load centered at the south pole! 
+
+import numpy as np
+from model import *
+from socket import gethostname
+from solve import *
+from roundmesh import *
+from love_numbers import *
+from paterson import *
+
+#mesh ais: {{{
+md = model()
+md = triangle(md,'../Exp/Ais.exp',100000); # max element size
+# }}}
+#define load: {{{
+md.esa.deltathickness = np.zeros((md.mesh.numberofelements,))
+disc_radius = 500 # km
+index = md.mesh.elements
+x_element = np.mean(md.mesh.x[index - 1], 1)
+y_element = np.mean(md.mesh.y[index - 1], 1)
+rad_dist = np.sqrt(x_element**2 + y_element**2) / 1000  # radial distance in km
+md.esa.deltathickness[np.where(rad_dist <= disc_radius)] = -1   # 1 m water withdrawl
+# }}}
+#love numbers: {{{
+nlov = 10000	# horizontal displacements do not work for low degree truncation, e.g., 101
+md.esa.love_h = np.array(love_numbers('h','CF'))
+md.esa.love_h = np.resize(md.esa.love_h, nlov + 1)
+md.esa.love_l = np.array(love_numbers('l','CF'))
+md.esa.love_l = np.resize(md.esa.love_l, nlov + 1)
+# }}}
+#mask:  {{{
+#make sure wherever there is an ice load, that the mask is set to ice: 
+md.mask.ice_levelset = np.ones((md.mesh.numberofvertices,))
+pos = np.where(md.esa.deltathickness)
+md.mask.ice_levelset[md.mesh.elements[pos,:]] = -1
+
+#is ice grounded? 
+md.mask.groundedice_levelset = -np.ones((md.mesh.numberofvertices,))
+pos = np.where(md.mask.ice_levelset <= 0)
+md.mask.groundedice_levelset[pos] = 1
+# }}}
+#geometry:  {{{
+di = md.materials.rho_ice / md.materials.rho_water
+md.geometry.thickness = np.ones((md.mesh.numberofvertices,))
+md.geometry.surface = (1 - di) * np.zeros((md.mesh.numberofvertices,))
+md.geometry.base = md.geometry.surface - md.geometry.thickness
+md.geometry.bed = md.geometry.base
+# }}}
+#materials:  {{{
+md.initialization.temperature = 273.25 * np.ones((md.mesh.numberofvertices,))
+md.materials.rheology_B = paterson(md.initialization.temperature)
+md.materials.rheology_n = 3 * np.ones((md.mesh.numberofelements,))
+# }}}
+#additional parameters, miscellaneous: {{{
+md.miscellaneous.name='test2112';
+md.esa.degacc=0.01;
+md.esa.hemisphere = -1; 
+# }}}
+
+#solve esa: {{{
+md.esa.requested_outputs = ['EsaUmotion','EsaNmotion','EsaEmotion','EsaXmotion','EsaYmotion'] 
+md.cluster = generic('name',gethostname(),'np',3)
+md.verbose = verbose('111111111')
+md = solve(md,'Esa')
+# }}}
+#Fields and tolerances to track changes: {{{
+field_names     = ['EsaUmotion','EsaNmotion','EsaEmotion','EsaXmotion','EsaYmotion']
+field_tolerances = [1e-13,1e-13,1e-13,1e-13,1e-13]
+field_values = [
+	md.results.EsaSolution.EsaUmotion,
+	md.results.EsaSolution.EsaNmotion,
+	md.results.EsaSolution.EsaEmotion,
+	md.results.EsaSolution.EsaXmotion,
+	md.results.EsaSolution.EsaYmotion,
+	]
+# }}}
+
Index: /issm/trunk/test/NightlyRun/test2113.m
===================================================================
--- /issm/trunk/test/NightlyRun/test2113.m	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test2113.m	(revision 22758)
@@ -0,0 +1,65 @@
+%Test Name: Esa2Dsurface
+%Northern hemisphere example for north-south, east-west components of horiz motion 
+%Same as test2111.m except that AIS is assumed to have located in Northern Hemisphere 
+
+%mesh ais: {{{
+	md=model();
+	md=triangle(md,'../Exp/Ais.exp',200000); % max element size
+% }}}
+%define load: {{{
+	md.esa.deltathickness=zeros(md.mesh.numberofelements,1);
+	disc_radius=500; % km
+	index=md.mesh.elements;
+	x_element=mean(md.mesh.x(index),2)-1.0e6;
+	y_element=mean(md.mesh.y(index),2)+1.0e6;
+	rad_dist=sqrt(x_element.^2+y_element.^2)/1000;  % radial distance in km
+	md.esa.deltathickness(rad_dist<=disc_radius)=-1;   % 1 m water withdrawl
+% }}}
+%read in love numbers:{{{
+	nlov=10001;	% horizontal displacements do not work for low degree truncation, e.g., 101
+	md.esa.love_h = love_numbers('h','CF'); md.esa.love_h(nlov+1:end)=[];
+	md.esa.love_l = love_numbers('l','CF'); md.esa.love_l(nlov+1:end)=[];
+% }}}
+%mask:  {{{
+	%make sure wherever there is an ice load, that the mask is set to ice: 
+	md.mask.ice_levelset=ones(md.mesh.numberofvertices,1);
+	pos=find(md.esa.deltathickness); md.mask.ice_levelset(md.mesh.elements(pos,:))=-1;
+
+	%is ice grounded? 
+	md.mask.groundedice_levelset=-ones(md.mesh.numberofvertices,1);
+	pos=find(md.mask.ice_levelset<=0); md.mask.groundedice_levelset(pos)=1; 
+% }}}
+%geometry:  {{{
+	di=md.materials.rho_ice/md.materials.rho_water;
+	md.geometry.thickness=ones(md.mesh.numberofvertices,1);
+	md.geometry.surface=(1-di)*zeros(md.mesh.numberofvertices,1);
+	md.geometry.base=md.geometry.surface-md.geometry.thickness;
+	md.geometry.bed=md.geometry.base;
+% }}}
+%materials:  {{{
+	md.initialization.temperature=273.25*ones(md.mesh.numberofvertices,1);
+	md.materials.rheology_B=paterson(md.initialization.temperature);
+	md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+% }}}
+%additional parameters, miscellaneous: {{{
+	md.miscellaneous.name='test2113';
+	md.esa.degacc=0.01;
+	md.esa.hemisphere = 1; % AIS is placed in Northern Hemisphere 
+% }}}
+
+%solve esa: {{{
+md.esa.requested_outputs = {'EsaUmotion','EsaNmotion','EsaEmotion'}; 
+md.cluster=generic('name',oshostname(),'np',3); 
+md.verbose=verbose('111111111');
+md=solve(md,'Esa');
+% }}}
+%fields and tolerances to track changes {{{
+field_names     ={'EsaUmotion','EsaNmotion','EsaEmotion'}; 
+field_tolerances={1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.EsaSolution.EsaUmotion),...
+	(md.results.EsaSolution.EsaNmotion),...
+	(md.results.EsaSolution.EsaEmotion),...
+	};
+% }}} 
+
Index: /issm/trunk/test/NightlyRun/test2113.py
===================================================================
--- /issm/trunk/test/NightlyRun/test2113.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test2113.py	(revision 22758)
@@ -0,0 +1,77 @@
+#Test Name: Esa2Dsurface
+#Northern hemisphere example for north-south, east-west components of horiz motion 
+#Same as test2111.m except that AIS is assumed to have located in Northern Hemisphere 
+
+import numpy as np
+from model import *
+from socket import gethostname
+from solve import *
+from roundmesh import *
+from love_numbers import *
+from paterson import *
+
+#mesh ais: {{{
+md = model()
+md = triangle(md,'../Exp/Ais.exp',200000); # max element size
+# }}}
+#define load: {{{
+md.esa.deltathickness = np.zeros((md.mesh.numberofelements,))
+disc_radius = 500 # km
+index = md.mesh.elements
+x_element = np.mean(md.mesh.x[index - 1], 1) - 1.0e6
+y_element = np.mean(md.mesh.y[index - 1], 1) + 1.0e6
+rad_dist = np.sqrt(x_element**2 + y_element**2) / 1000  # radial distance in km
+md.esa.deltathickness[np.where(rad_dist <= disc_radius)] = -1   # 1 m water withdrawl
+# }}}
+#love numbers: {{{
+nlov = 10000	# horizontal displacements do not work for low degree truncation, e.g., 101
+md.esa.love_h = np.array(love_numbers('h','CF'))
+md.esa.love_h = np.resize(md.esa.love_h, nlov + 1)
+md.esa.love_l = np.array(love_numbers('l','CF'))
+md.esa.love_l = np.resize(md.esa.love_l, nlov + 1)
+# }}}
+#mask:  {{{
+#make sure wherever there is an ice load, that the mask is set to ice: 
+md.mask.ice_levelset = np.ones((md.mesh.numberofvertices,))
+pos = np.where(md.esa.deltathickness)
+md.mask.ice_levelset[md.mesh.elements[pos,:]] = -1
+
+#is ice grounded? 
+md.mask.groundedice_levelset = -np.ones((md.mesh.numberofvertices,))
+pos = np.where(md.mask.ice_levelset <= 0)
+md.mask.groundedice_levelset[pos] = 1
+# }}}
+#geometry:  {{{
+di = md.materials.rho_ice / md.materials.rho_water
+md.geometry.thickness = np.ones((md.mesh.numberofvertices,))
+md.geometry.surface = (1 - di) * np.zeros((md.mesh.numberofvertices,))
+md.geometry.base = md.geometry.surface - md.geometry.thickness
+md.geometry.bed = md.geometry.base
+# }}}
+#materials:  {{{
+md.initialization.temperature = 273.25 * np.ones((md.mesh.numberofvertices,))
+md.materials.rheology_B = paterson(md.initialization.temperature)
+md.materials.rheology_n = 3 * np.ones((md.mesh.numberofelements,))
+# }}}
+#additional parameters, miscellaneous: {{{
+md.miscellaneous.name='test2113';
+md.esa.degacc=0.01;
+md.esa.hemisphere = 1; # AIS is placed in Northern Hemisphere 
+# }}}
+
+#solve esa: {{{
+md.esa.requested_outputs = ['EsaUmotion','EsaNmotion','EsaEmotion']
+md.cluster = generic('name',gethostname(),'np',3)
+md.verbose = verbose('111111111')
+md = solve(md,'Esa')
+# }}}
+#Fields and tolerances to track changes: {{{
+field_names     = ['EsaUmotion','EsaNmotion','EsaEmotion']
+field_tolerances = [1e-13,1e-13,1e-13]
+field_values = [
+	md.results.EsaSolution.EsaUmotion,
+	md.results.EsaSolution.EsaNmotion,
+	md.results.EsaSolution.EsaEmotion,
+	]
+# }}}
+
Index: /issm/trunk/test/NightlyRun/test215.js
===================================================================
--- /issm/trunk/test/NightlyRun/test215.js	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test215.js	(revision 22758)
@@ -25,5 +25,5 @@
 //Fields and tolerances to track changes
 field_names     =['Gradient','Misfits','MaterialsRheologyBbar','Pressure','Vel','Vx','Vy'];
-field_tolerances=[4.6e-08,1e-08,2e-08,1e-09,2e-09,5e-09,2e-09];
+field_tolerances=[4.6e-08,1e-08,2e-08,1e-09,2e-09,1e-08,1e-08];
 field_values=[
 	(md.results.StressbalanceSolution[0].Gradient1),
Index: /issm/trunk/test/NightlyRun/test215.m
===================================================================
--- /issm/trunk/test/NightlyRun/test215.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test215.m	(revision 22758)
@@ -24,5 +24,5 @@
 %Fields and tolerances to track changes
 field_names     ={'Gradient','Misfits','MaterialsRheologyBbar','Pressure','Vel','Vx','Vy'};
-field_tolerances={4.6e-08,1e-08,2e-08,1e-09,2e-09,5e-09,2e-09};
+field_tolerances={4.6e-08,1e-08,2e-08,1e-09,2e-09,1e-08,1e-08};
 field_values={...
 	(md.results.StressbalanceSolution.Gradient1),...
Index: /issm/trunk/test/NightlyRun/test215.py
===================================================================
--- /issm/trunk/test/NightlyRun/test215.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test215.py	(revision 22758)
@@ -1,4 +1,3 @@
 #Test Name: SquareShelfCMBFS
-
 from model import *
 from socket import gethostname
@@ -19,5 +18,4 @@
 
 # control parameters
-
 md.inversion.iscontrol=1
 md.inversion.control_parameters=['MaterialsRheologyBbar']
@@ -33,5 +31,4 @@
 md.inversion.vy_obs=md.initialization.vy
 
-
 md.cluster=generic('name',gethostname(),'np',3)
 md=solve(md,'Stressbalance')
@@ -39,12 +36,11 @@
 
 # Fields and tolerances to track changes
-
 field_names     =['Gradient','Misfits','MaterialsRheologyBbar','Pressure','Vel','Vx','Vy']
-field_tolerances=[4.6e-08,1e-08,2e-09,1e-08,2e-09,5e-09,2e-09]
+field_tolerances=[4.6e-08,1e-08,2e-09,1e-08,2e-09,1e-08,1e-08]
 field_values=[md.results.StressbalanceSolution.Gradient1,
-							md.results.StressbalanceSolution.J,
-							md.results.StressbalanceSolution.MaterialsRheologyBbar,
-							md.results.StressbalanceSolution.Pressure,
-							md.results.StressbalanceSolution.Vel,
-							md.results.StressbalanceSolution.Vx,
-							md.results.StressbalanceSolution.Vy]
+        md.results.StressbalanceSolution.J,
+        md.results.StressbalanceSolution.MaterialsRheologyBbar,
+        md.results.StressbalanceSolution.Pressure,
+        md.results.StressbalanceSolution.Vel,
+        md.results.StressbalanceSolution.Vx,
+        md.results.StressbalanceSolution.Vy]
Index: /issm/trunk/test/NightlyRun/test216.js
===================================================================
--- /issm/trunk/test/NightlyRun/test216.js	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test216.js	(revision 22758)
@@ -18,5 +18,5 @@
 //Fields and tolerances to track changes
 field_names     =['Vx','Vy','Vel','Pressure'];
-field_tolerances=[8e-7,5e-8,7e-8,2e-11];
+field_tolerances=[9e-7,7e-8,9e-8,2e-11];
 field_values=[
 	(md.results.StressbalanceSolution[0].Vx),
Index: /issm/trunk/test/NightlyRun/test216.m
===================================================================
--- /issm/trunk/test/NightlyRun/test216.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test216.m	(revision 22758)
@@ -17,5 +17,5 @@
 %Fields and tolerances to track changes
 field_names     ={'Vx','Vy','Vel','Pressure'};
-field_tolerances={8e-7,5e-8,7e-8,2e-11};
+field_tolerances={9e-7,7e-8,9e-8,2e-11};
 field_values={...
 	(md.results.StressbalanceSolution.Vx),...
Index: /issm/trunk/test/NightlyRun/test216.py
===================================================================
--- /issm/trunk/test/NightlyRun/test216.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test216.py	(revision 22758)
@@ -31,5 +31,5 @@
 
 field_names     =['Vx','Vy','Vel','Pressure']
-field_tolerances=[4e-11,2e-11,4e-11,2e-11]
+field_tolerances=[9e-7,7e-8,9e-8,2e-11]
 field_values=[\
 	md.results.StressbalanceSolution.Vx,\
Index: /issm/trunk/test/NightlyRun/test219.js
===================================================================
--- /issm/trunk/test/NightlyRun/test219.js	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test219.js	(revision 22758)
@@ -11,5 +11,5 @@
 //Fields and tolerances to track changes
 field_names     =['Vx','Vy','Vz','Vel','Pressure'];
-field_tolerances=[1e-09,1e-09,1e-09,1e-09,1e-13];
+field_tolerances=[5e-09,5e-09,5e-09,5e-09,1e-13];
 field_values=[
 	(md.results.StressbalanceSolution[0].Vx),
Index: /issm/trunk/test/NightlyRun/test219.m
===================================================================
--- /issm/trunk/test/NightlyRun/test219.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test219.m	(revision 22758)
@@ -10,5 +10,5 @@
 %Fields and tolerances to track changes
 field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-13};
+field_tolerances={5e-09,5e-09,5e-09,5e-09,1e-13};
 field_values={...
 	(md.results.StressbalanceSolution.Vx),...
Index: /issm/trunk/test/NightlyRun/test219.py
===================================================================
--- /issm/trunk/test/NightlyRun/test219.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test219.py	(revision 22758)
@@ -22,5 +22,5 @@
 
 field_names     =['Vx','Vy','Vz','Vel','Pressure']
-field_tolerances=[1e-09,1e-09,1e-09,1e-09,1e-13]
+field_tolerances=[5e-09,5e-09,5e-09,5e-09,1e-13]
 field_values=[\
 	md.results.StressbalanceSolution.Vx,\
Index: /issm/trunk/test/NightlyRun/test220.js
===================================================================
--- /issm/trunk/test/NightlyRun/test220.js	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test220.js	(revision 22758)
@@ -7,5 +7,5 @@
 setflowequation(md,'FS','../Exp/SquareHalfRight.exp','fill','HO');
 //md.cluster=generic('name',oshostname(),'np',3);
-md.verbose=verbose('all');
+//md.verbose=verbose('all');
 md=solve(md,'Stressbalance');
 
Index: /issm/trunk/test/NightlyRun/test220.m
===================================================================
--- /issm/trunk/test/NightlyRun/test220.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test220.m	(revision 22758)
@@ -6,5 +6,5 @@
 md=setflowequation(md,'FS','../Exp/SquareHalfRight.exp','fill','HO');
 md.cluster=generic('name',oshostname(),'np',3);
-md.verbose=verbose('all');
+%md.verbose=verbose('all');
 md=solve(md,'Stressbalance');
 
Index: /issm/trunk/test/NightlyRun/test221.js
===================================================================
--- /issm/trunk/test/NightlyRun/test221.js	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test221.js	(revision 22758)
@@ -7,5 +7,4 @@
 setflowequation(md,'FS','../Exp/SquareHalfRight.exp','fill','SSA');
 //md.cluster=generic('name',oshostname(),'np',3);
-md.stressbalance.viscosity_overshoot=0;
 md=solve(md,'Stressbalance');
 
Index: /issm/trunk/test/NightlyRun/test221.m
===================================================================
--- /issm/trunk/test/NightlyRun/test221.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test221.m	(revision 22758)
@@ -6,5 +6,4 @@
 md=setflowequation(md,'FS','../Exp/SquareHalfRight.exp','fill','SSA');
 md.cluster=generic('name',oshostname(),'np',3);
-md.stressbalance.viscosity_overshoot=0;
 md=solve(md,'Stressbalance');
 
Index: /issm/trunk/test/NightlyRun/test221.py
===================================================================
--- /issm/trunk/test/NightlyRun/test221.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test221.py	(revision 22758)
@@ -15,5 +15,4 @@
 md=setflowequation(md,'FS','../Exp/SquareHalfRight.exp','fill','SSA')
 md.cluster=generic('name',gethostname(),'np',3)
-md.stressbalance.viscosity_overshoot=0
 md=solve(md,'Stressbalance')
 
Index: /issm/trunk/test/NightlyRun/test224.js
===================================================================
--- /issm/trunk/test/NightlyRun/test224.js	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test224.js	(revision 22758)
@@ -15,7 +15,7 @@
 	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'];
 field_tolerances=[
-	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,
-	1e-09,5e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,
-	1e-09,5e-09,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05];
+	2e-09,2e-09,2e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,
+	2e-09,5e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,
+	2e-09,5e-09,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05];
 field_values=[
 	(md.results.TransientSolution[0](1).Vx),
Index: /issm/trunk/test/NightlyRun/test224.m
===================================================================
--- /issm/trunk/test/NightlyRun/test224.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test224.m	(revision 22758)
@@ -14,7 +14,7 @@
 	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'};
 field_tolerances={...
-	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,...
-	1e-09,5e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,...
-	1e-09,5e-09,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05};
+	2e-09,2e-09,2e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,...
+	2e-09,5e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,...
+	2e-09,5e-09,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05};
 field_values={...
 	(md.results.TransientSolution(1).Vx),...
Index: /issm/trunk/test/NightlyRun/test224.py
===================================================================
--- /issm/trunk/test/NightlyRun/test224.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test224.py	(revision 22758)
@@ -23,7 +23,7 @@
 	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3']
 field_tolerances=[\
-	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,\
-	1e-09,5e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,\
-	1e-09,5e-09,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05]
+	2e-09,2e-09,2e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,\
+	2e-09,5e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,\
+	2e-09,5e-09,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05]
 field_values=[\
 	md.results.TransientSolution[0].Vx,\
Index: /issm/trunk/test/NightlyRun/test226.js
===================================================================
--- /issm/trunk/test/NightlyRun/test226.js	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test226.js	(revision 22758)
@@ -6,5 +6,5 @@
 setflowequation(md,'SSA','all');
 //md.cluster=generic('name',oshostname(),'np',3);
-md.timestepping.time_adapt=1.;
+md.timestepping = timesteppingadaptive(md.timestepping);
 md.timestepping.final_time=15.;
 md=solve(md,'Transient');
Index: /issm/trunk/test/NightlyRun/test226.m
===================================================================
--- /issm/trunk/test/NightlyRun/test226.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test226.m	(revision 22758)
@@ -5,5 +5,5 @@
 md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.timestepping.time_adapt=1.;
+md.timestepping = timesteppingadaptive(md.timestepping);
 md.timestepping.final_time=15.;
 md=solve(md,'Transient');
Index: /issm/trunk/test/NightlyRun/test226.py
===================================================================
--- /issm/trunk/test/NightlyRun/test226.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test226.py	(revision 22758)
@@ -14,5 +14,5 @@
 md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',gethostname(),'np',3)
-md.timestepping.time_adapt=1.
+md.timestepping = timesteppingadaptive(md.timestepping);
 md.timestepping.final_time=15.
 md=solve(md,'Transient')
Index: /issm/trunk/test/NightlyRun/test227.js
===================================================================
--- /issm/trunk/test/NightlyRun/test227.js	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test227.js	(revision 22758)
@@ -7,5 +7,5 @@
 setflowequation(md,'HO','all');
 //md.cluster=generic('name',oshostname(),'np',3);
-md.timestepping.time_adapt=1.;
+md.timestepping = timesteppingadaptive(md.timestepping);
 md.timestepping.final_time=20.;
 md=solve(md,'Transient');
@@ -16,6 +16,6 @@
 	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'];
 field_tolerances=[
-	1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,
-	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,
+	1e-08,5e-09,1e-09,5e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,
+	1e-09,5e-09,1e-08,5e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,
 	1e-08,1e-08,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05];
 field_values=[
Index: /issm/trunk/test/NightlyRun/test227.m
===================================================================
--- /issm/trunk/test/NightlyRun/test227.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test227.m	(revision 22758)
@@ -6,5 +6,5 @@
 md=setflowequation(md,'HO','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.timestepping.time_adapt=1.;
+md.timestepping = timesteppingadaptive(md.timestepping);
 md.timestepping.final_time=20.;
 md=solve(md,'Transient');
@@ -15,6 +15,6 @@
 	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'};
 field_tolerances={...
-	1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,...
-	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,...
+	1e-08,5e-09,1e-09,5e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,...
+	1e-09,5e-09,1e-08,5e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,...
 	1e-08,1e-08,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05};
 field_values={...
Index: /issm/trunk/test/NightlyRun/test227.py
===================================================================
--- /issm/trunk/test/NightlyRun/test227.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test227.py	(revision 22758)
@@ -15,5 +15,5 @@
 md=setflowequation(md,'HO','all')
 md.cluster=generic('name',gethostname(),'np',3)
-md.timestepping.time_adapt=1.
+md.timestepping = timesteppingadaptive(md.timestepping)
 md.timestepping.final_time=20.
 md=solve(md,'Transient')
@@ -24,6 +24,6 @@
 	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3']
 field_tolerances=[\
-	1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,\
-	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,\
+	1e-08,5e-09,1e-09,5e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,\
+	1e-09,5e-09,1e-08,5e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,\
 	1e-08,1e-08,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05]
 field_values=[\
Index: /issm/trunk/test/NightlyRun/test233.js
===================================================================
--- /issm/trunk/test/NightlyRun/test233.js	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test233.js	(revision 22758)
@@ -20,5 +20,5 @@
 	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06, 
 	1e-08,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06, 
-	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06];
+	1e-08,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06];
 field_values=[
 	(md.results.TransientSolution[0](1).Vx),
Index: /issm/trunk/test/NightlyRun/test233.m
===================================================================
--- /issm/trunk/test/NightlyRun/test233.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test233.m	(revision 22758)
@@ -19,5 +19,5 @@
 	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06, ...
 	1e-08,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06, ...
-	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06};
+	1e-08,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06};
 field_values={...
 	(md.results.TransientSolution(1).Vx),...
Index: /issm/trunk/test/NightlyRun/test233.py
===================================================================
--- /issm/trunk/test/NightlyRun/test233.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test233.py	(revision 22758)
@@ -23,49 +23,49 @@
 #Fields and tolerances to track changes
 field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1',
-									'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2',
-									'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3',
-									'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','Temperature4','BasalforcingsGroundediceMeltingRate4']
+        'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2',
+        'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3',
+        'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','Temperature4','BasalforcingsGroundediceMeltingRate4']
 field_tolerances=[1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,
-									1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,
-									1e-08,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,
-									1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06]
+        1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,
+        1e-08,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,
+        1e-08,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06]
 field_values=[md.results.TransientSolution[0].Vx,
-							md.results.TransientSolution[0].Vy,
-							md.results.TransientSolution[0].Vz,
-							md.results.TransientSolution[0].Vel,
-							md.results.TransientSolution[0].Pressure,
-							md.results.TransientSolution[0].Base,
-							md.results.TransientSolution[0].Surface,
-							md.results.TransientSolution[0].Thickness,
-							md.results.TransientSolution[0].Temperature,
-							md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,
-							md.results.TransientSolution[1].Vx,
-							md.results.TransientSolution[1].Vy,
-							md.results.TransientSolution[1].Vz,
-							md.results.TransientSolution[1].Vel,
-							md.results.TransientSolution[1].Pressure,
-							md.results.TransientSolution[1].Base,
-							md.results.TransientSolution[1].Surface,
-							md.results.TransientSolution[1].Thickness,
-							md.results.TransientSolution[1].Temperature,
-							md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,
-							md.results.TransientSolution[2].Vx,
-							md.results.TransientSolution[2].Vy,
-							md.results.TransientSolution[2].Vz,
-							md.results.TransientSolution[2].Vel,
-							md.results.TransientSolution[2].Pressure,
-							md.results.TransientSolution[2].Base,
-							md.results.TransientSolution[2].Surface,
-							md.results.TransientSolution[2].Thickness,
-							md.results.TransientSolution[2].Temperature,
-							md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,
-							md.results.TransientSolution[3].Vx,
-							md.results.TransientSolution[3].Vy,
-							md.results.TransientSolution[3].Vz,
-							md.results.TransientSolution[3].Vel,
-							md.results.TransientSolution[3].Pressure,
-							md.results.TransientSolution[3].Base,
-							md.results.TransientSolution[3].Surface,
-							md.results.TransientSolution[3].Thickness,
-							md.results.TransientSolution[3].Temperature,
-							md.results.TransientSolution[3].BasalforcingsGroundediceMeltingRate]
+        md.results.TransientSolution[0].Vy,
+        md.results.TransientSolution[0].Vz,
+        md.results.TransientSolution[0].Vel,
+        md.results.TransientSolution[0].Pressure,
+        md.results.TransientSolution[0].Base,
+        md.results.TransientSolution[0].Surface,
+        md.results.TransientSolution[0].Thickness,
+        md.results.TransientSolution[0].Temperature,
+        md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,
+        md.results.TransientSolution[1].Vx,
+        md.results.TransientSolution[1].Vy,
+        md.results.TransientSolution[1].Vz,
+        md.results.TransientSolution[1].Vel,
+        md.results.TransientSolution[1].Pressure,
+        md.results.TransientSolution[1].Base,
+        md.results.TransientSolution[1].Surface,
+        md.results.TransientSolution[1].Thickness,
+        md.results.TransientSolution[1].Temperature,
+        md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,
+        md.results.TransientSolution[2].Vx,
+        md.results.TransientSolution[2].Vy,
+        md.results.TransientSolution[2].Vz,
+        md.results.TransientSolution[2].Vel,
+        md.results.TransientSolution[2].Pressure,
+        md.results.TransientSolution[2].Base,
+        md.results.TransientSolution[2].Surface,
+        md.results.TransientSolution[2].Thickness,
+        md.results.TransientSolution[2].Temperature,
+        md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,
+        md.results.TransientSolution[3].Vx,
+        md.results.TransientSolution[3].Vy,
+        md.results.TransientSolution[3].Vz,
+        md.results.TransientSolution[3].Vel,
+        md.results.TransientSolution[3].Pressure,
+        md.results.TransientSolution[3].Base,
+        md.results.TransientSolution[3].Surface,
+        md.results.TransientSolution[3].Thickness,
+        md.results.TransientSolution[3].Temperature,
+        md.results.TransientSolution[3].BasalforcingsGroundediceMeltingRate]
Index: /issm/trunk/test/NightlyRun/test2424.py
===================================================================
--- /issm/trunk/test/NightlyRun/test2424.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test2424.py	(revision 22758)
@@ -0,0 +1,51 @@
+#Test Name: SquareSheetShelfGroundingLine2dAggressive. From test424, with sea level increasing.
+import numpy as np
+from model import *
+from socket import gethostname
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+from newforcing import *
+
+md = triangle(model(),'../Exp/Square.exp',150000.)
+md = setmask(md,'../Exp/SquareShelf.exp','')
+md = parameterize(md,'../Par/SquareSheetShelf.py')
+md = setflowequation(md,'SSA','all')
+md.initialization.vx[:] = 0.
+md.initialization.vy[:] = 0.
+md.smb.mass_balance[:] = 0.
+
+md.geometry.base = -700. - np.abs(md.mesh.y-500000.) / 1000.
+md.geometry.bed = -700. - np.abs(md.mesh.y-500000.) / 1000.
+md.geometry.thickness[:] = 1000.
+md.geometry.surface = md.geometry.base + md.geometry.thickness
+
+md.transient.isstressbalance = 0
+md.transient.isgroundingline = 1
+md.transient.isthermal = 0
+md.groundingline.migration = 'AggressiveMigration'
+md.transient.requested_outputs = ['IceVolume','IceVolumeAboveFloatation','Sealevel']
+
+md.timestepping.time_step = .1
+md.slr.sealevel = newforcing(md.timestepping.start_time, md.timestepping.final_time,
+			     md.timestepping.time_step, -200., 200., md.mesh.numberofvertices)
+
+md.cluster = generic('name',gethostname(),'np',3)
+md = solve(md,'Transient')
+
+#we are checking that the grounding line position is near the theorical one, which is the 0 contour level 
+#of surface - sealevel - (1-di)* thickness 
+
+nsteps = len(md.results.TransientSolution)
+field_names = []
+field_tolerances = []
+field_values = []
+#time is off by the year constant
+for i in range(nsteps):
+	field_names.append('Time-' + str(md.results.TransientSolution[i].time) + 
+		'-yr-ice_levelset-S-sl-(1-di)*H')
+	field_tolerances.append(1e-12)
+	field_values.append(md.results.TransientSolution[i].MaskGroundediceLevelset.reshape(-1,) - (md.geometry.surface - md.results.TransientSolution[i].Sealevel.reshape(-1,) - (1 - md.materials.rho_ice / md.materials.rho_water) * md.geometry.thickness))
+
Index: /issm/trunk/test/NightlyRun/test2425.py
===================================================================
--- /issm/trunk/test/NightlyRun/test2425.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test2425.py	(revision 22758)
@@ -0,0 +1,50 @@
+#Test Name: SquareSheetShelfGroundingLine2dSoft
+import numpy as np
+from model import *
+from socket import gethostname
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md = triangle(model(),'../Exp/Square.exp',150000.)
+md = setmask(md,'../Exp/SquareShelf.exp','')
+md = parameterize(md,'../Par/SquareSheetShelf.py')
+md = setflowequation(md,'SSA','all')
+md.initialization.vx[:] = 0.
+md.initialization.vy[:] = 0.
+md.geometry.base = -700. - (md.mesh.y - 500000.) / 1000.
+md.geometry.bed = -700. - (md.mesh.y - 500000.) / 1000.
+md.geometry.thickness[:] = 1300.
+md.geometry.surface = md.geometry.base + md.geometry.thickness
+md.transient.isstressbalance = 1
+md.transient.isgroundingline = 1
+md.groundingline.migration = 'AggressiveMigration'
+
+md.timestepping.time_step = .1
+md.timestepping.final_time = 1
+
+md.cluster = generic('name',gethostname(),'np',3)
+md = solve(md,'Transient')
+vel1 = md.results.TransientSolution[-1].Vel
+
+#get same results with offset in bed and sea level: 
+md.geometry.base = -700. - (md.mesh.y - 500000.) / 1000.
+md.geometry.bed  = -700. - (md.mesh.y - 500000.) / 1000.
+md.geometry.thickness[:] = 1300.
+md.geometry.surface = md.geometry.base + md.geometry.thickness
+
+md.geometry.base = md.geometry.base + 1000
+md.geometry.bed = md.geometry.bed + 1000
+md.geometry.surface = md.geometry.surface + 1000
+md.slr.sealevel = 1000 * np.ones((md.mesh.numberofvertices,))
+
+md = solve(md,'Transient','checkconsistency','no')
+vel2 = md.results.TransientSolution[-1].Vel
+
+#Fields and tolerances to track changes
+field_names = ['Vel','Veloffset']
+field_tolerances = [1e-13,1e-13]
+field_values = [vel1,vel2]
+
Index: /issm/trunk/test/NightlyRun/test243.m
===================================================================
--- /issm/trunk/test/NightlyRun/test243.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test243.m	(revision 22758)
@@ -27,5 +27,5 @@
 
 %smb settings
-md.smb.requested_outputs={'SmbDz','SmbT','SmbD','SmbRe','SmbGdn','SmbGsp','SmbEC','SmbA','SmbMassBalance'};
+md.smb.requested_outputs={'SmbDz','SmbT','SmbD','SmbRe','SmbGdn','SmbGsp','SmbEC','SmbA','SmbMassBalance','SmbMAdd','SmbDzAdd','SmbFAC'};
 
 %only run smb core: 
@@ -44,6 +44,6 @@
 
 %Fields and tolerances to track changes
-field_names      ={'SmbDz','SmbT' ,'SmbD' ,'SmbRe','SmbGdn','SmbGsp','SmbA' ,'SmbEC','SmbMassBalance'};
-field_tolerances ={5e-4,5e-5,0.0006,0.0002,1e-5,0.0003,2e-5,2e-7,1e-7};
+field_names      ={'SmbDz','SmbT' ,'SmbD' ,'SmbRe','SmbGdn','SmbGsp','SmbA' ,'SmbEC','SmbMassBalance','SmbMAdd','SmbDzAdd','SmbFAC'};
+field_tolerances ={1e-11,1e-12,1e-11,2e-11,1e-11,1e-11,1e-12,2e-12,1e-12,1e-12,1e-12,1e-11};
 
 field_values={...
@@ -57,3 +57,6 @@
 	(md.results.TransientSolution(end).SmbEC(1)),...
 	(md.results.TransientSolution(end).SmbMassBalance(1)),...
+	(md.results.TransientSolution(end).SmbMAdd(1)),...
+	(md.results.TransientSolution(end).SmbDzAdd(1)),...
+	(md.results.TransientSolution(end).SmbFAC(1))
 	};
Index: /issm/trunk/test/NightlyRun/test243.py
===================================================================
--- /issm/trunk/test/NightlyRun/test243.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test243.py	(revision 22758)
@@ -0,0 +1,75 @@
+#Test Name: SquareShelfSMBGemb
+import numpy as np
+import scipy.io as spio
+from model import *
+from socket import gethostname
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+from SMBgemb import *
+
+md = triangle(model(),'../Exp/Square.exp',200000.)
+md = setmask(md,'all','')
+md = parameterize(md,'../Par/SquareShelf.py')
+md = setflowequation(md,'SSA','all')
+md.materials.rho_ice = 910
+md.cluster = generic('name',gethostname(),'np',3)
+
+#Use of Gemb method for SMB computation
+md.smb = SMBgemb()
+md.smb.setdefaultparameters(md.mesh,md.geometry)
+
+#load hourly surface forcing date from 1979 to 2009:
+inputs = spio.loadmat('../Data/gemb_input.mat',squeeze_me=True)
+
+#setup the inputs: 
+md.smb.Ta = np.append(np.tile(np.conjugate(inputs['Ta0']),(md.mesh.numberofelements,1)),np.conjugate([inputs['dateN']]),axis=0)
+md.smb.V = np.append(np.tile(np.conjugate(inputs['V0']),(md.mesh.numberofelements,1)),np.conjugate([inputs['dateN']]),axis=0)
+md.smb.dswrf = np.append(np.tile(np.conjugate(inputs['dsw0']),(md.mesh.numberofelements,1)),np.conjugate([inputs['dateN']]),axis=0)
+md.smb.dlwrf = np.append(np.tile(np.conjugate(inputs['dlw0']),(md.mesh.numberofelements,1)),np.conjugate([inputs['dateN']]),axis=0)
+md.smb.P = np.append(np.tile(np.conjugate(inputs['P0']),(md.mesh.numberofelements,1)),np.conjugate([inputs['dateN']]),axis=0)
+md.smb.eAir = np.append(np.tile(np.conjugate(inputs['eAir0']),(md.mesh.numberofelements,1)),np.conjugate([inputs['dateN']]),axis=0)
+md.smb.pAir = np.append(np.tile(np.conjugate(inputs['pAir0']),(md.mesh.numberofelements,1)),np.conjugate([inputs['dateN']]),axis=0)
+md.smb.pAir = np.append(np.tile(np.conjugate(inputs['pAir0']),(md.mesh.numberofelements,1)),np.conjugate([inputs['dateN']]),axis=0)
+md.smb.Vz = np.tile(np.conjugate(inputs['LP']['Vz']),(md.mesh.numberofelements,1)).flatten()
+md.smb.Tz = np.tile(np.conjugate(inputs['LP']['Tz']),(md.mesh.numberofelements,1)).flatten()
+md.smb.Tmean = np.tile(np.conjugate(inputs['LP']['Tmean']),(md.mesh.numberofelements,1)).flatten()
+md.smb.C = np.tile(np.conjugate(inputs['LP']['C']),(md.mesh.numberofelements,1)).flatten()
+
+#smb settings
+md.smb.requested_outputs = ['SmbDz','SmbT','SmbD','SmbRe','SmbGdn','SmbGsp','SmbEC','SmbA','SmbMassBalance','SmbMAdd','SmbDzAdd','SmbFAC']
+
+#only run smb core: 
+md.transient.isstressbalance = 0
+md.transient.ismasstransport = 0
+md.transient.isthermal = 0
+
+#time stepping: 
+md.timestepping.start_time = 1965.
+md.timestepping.final_time = 1966.
+md.timestepping.time_step = 1. / 365.0
+md.timestepping.interp_forcings = 0.
+
+#Run transient
+md = solve(md,'Transient')
+
+#Fields and tolerances to track changes
+field_names      = ['SmbDz','SmbT' ,'SmbD' ,'SmbRe','SmbGdn','SmbGsp','SmbA' ,'SmbEC','SmbMassBalance','SmbMAdd','SmbDzAdd','SmbFAC']
+field_tolerances = [1e-11,1e-12,1e-11,2e-11,1e-11,1e-11,1e-12,2e-12,1e-12,1e-12,1e-12,1e-11]
+#shape is different in python solution (fixed using reshape) which can cause test failure:
+field_values = [
+	md.results.TransientSolution[-1].SmbDz[0,0:240].reshape(1,-1),
+	md.results.TransientSolution[-1].SmbT[0,0:240].reshape(1,-1),
+	md.results.TransientSolution[-1].SmbD[0,0:240].reshape(1,-1),
+	md.results.TransientSolution[-1].SmbRe[0,0:240].reshape(1,-1),
+	md.results.TransientSolution[-1].SmbGdn[0,0:240].reshape(1,-1),
+	md.results.TransientSolution[-1].SmbGsp[0,0:240].reshape(1,-1),
+	md.results.TransientSolution[-1].SmbA[0,0:240].reshape(1,-1),
+	md.results.TransientSolution[-1].SmbEC[0],
+	md.results.TransientSolution[-1].SmbMassBalance[0],
+	md.results.TransientSolution[-1].SmbMAdd[0],
+	md.results.TransientSolution[-1].SmbDzAdd[0],
+	md.results.TransientSolution[-1].SmbFAC[0],
+	]
Index: /issm/trunk/test/NightlyRun/test244.m
===================================================================
--- /issm/trunk/test/NightlyRun/test244.m	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test244.m	(revision 22758)
@@ -0,0 +1,117 @@
+%Test Name: SquareShelfSMBGembDakota
+md=triangle(model(),'../Exp/Square.exp',200000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'SSA','all');
+md.materials.rho_ice=910;
+md.cluster=generic('name',oshostname(),'np',3);
+md.geometry.bed=md.geometry.base;
+
+% Use of Gemb method for SMB computation
+md.smb = SMBgemb(md.mesh,md.geometry);
+
+%load hourly surface forcing date from 1979 to 2009:
+inputs=load('../Data/gemb_input.mat');
+
+%setup the inputs: 
+md.smb.Ta=[repmat(inputs.Ta0',md.mesh.numberofelements,1);inputs.dateN'];
+md.smb.V=[repmat(inputs.V0',md.mesh.numberofelements,1);inputs.dateN'];
+md.smb.dswrf=[repmat(inputs.dsw0',md.mesh.numberofelements,1);inputs.dateN'];
+md.smb.dlwrf=[repmat(inputs.dlw0',md.mesh.numberofelements,1);inputs.dateN'];
+md.smb.P=[repmat(inputs.P0',md.mesh.numberofelements,1);inputs.dateN'];
+md.smb.eAir=[repmat(inputs.eAir0',md.mesh.numberofelements,1);inputs.dateN'];
+md.smb.pAir=[repmat(inputs.pAir0',md.mesh.numberofelements,1);inputs.dateN'];
+md.smb.Vz=repmat(inputs.LP.Vz,md.mesh.numberofelements,1);
+md.smb.Tz=repmat(inputs.LP.Tz,md.mesh.numberofelements,1);
+md.smb.Tmean=repmat(inputs.LP.Tmean,md.mesh.numberofelements,1);
+md.smb.C=repmat(inputs.LP.C,md.mesh.numberofelements,1);
+
+%smb settings
+md.smb.requested_outputs={'SmbDz','SmbT','SmbD','SmbRe','SmbGdn','SmbGsp','SmbEC','SmbA','SmbMassBalance'};
+
+%only run smb core: 
+md.transient.isstressbalance=0;
+md.transient.ismasstransport=1;
+md.transient.isthermal=0;
+
+%time stepping: 
+md.timestepping.start_time=1965;
+md.timestepping.final_time=1965.75;
+md.timestepping.time_step=1/365.0;
+md.timestepping.interp_forcings=0;
+
+%dakota version
+version=IssmConfig('_DAKOTA_VERSION_'); version=version(1:3); version=str2num(version);
+
+%partitioning
+md.qmu.numberofpartitions=md.mesh.numberofelements;
+md=partitioner(md,'package','linear');
+md.qmu.partition=md.qmu.partition-1;
+
+%variables
+md.qmu.variables.surface_mass_balanceC=normal_uncertain('scaled_SmbC',1,0.5);
+Tmin=273;
+telms=min(md.smb.Ta(1:end-1,:),[],2);
+mint_on_partition=telms;
+for pa=1:length(mint_on_partition)
+	vi=find(md.qmu.partition+1 == pa);
+	mint=telms(vi).*1.05;
+	pos=find(mint < Tmin);
+	mint(pos)=Tmin;
+	mint_on_partition(pa)=max(mint./telms(vi));
+end
+mint_on_partition(isnan(mint_on_partition)) = 10^-10;
+md.qmu.variables.surface_mass_balanceTa=uniform_uncertain('scaled_SmbTa',1,0.05); 
+md.qmu.variables.surface_mass_balanceTa.lower=0.95;
+md.qmu.variables.surface_mass_balanceTa.upper=max(min(max(1.05,mint_on_partition),0.9999),0.0001);
+
+%responses
+md.qmu.responses.IceVolume=response_function('IceVolume',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.IceMass=response_function('IceMass',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.TotalSmb=response_function('TotalSmb',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%  nond_sampling study
+md.qmu.method=dakota_method('nond_samp');
+md.qmu.method(end)=dmeth_params_set(md.qmu.method(end),'seed',1234,'samples',3,'sample_type','lhs');
+dver=textscan(IssmConfig('_DAKOTA_VERSION_'),'%[0123456789].%[0123456789].%[0123456789]');
+if ((str2num(dver{1}{1})==4 && str2num(dver{2}{1})>2) || str2num(dver{1}{1})>4)
+	md.qmu.method(end)=dmeth_params_set(md.qmu.method(end),'rng','rnum2');
+end
+
+%parameters
+md.qmu.params.direct=true;
+md.qmu.params.analysis_components='';
+md.qmu.params.interval_type='forward';
+md.qmu.params.tabular_graphics_data=true;
+md.qmu.isdakota=1;
+
+if version>=6,
+	md.qmu.params.analysis_driver='matlab';
+	md.qmu.params.evaluation_scheduling='master';
+	md.qmu.params.processors_per_evaluation=2;
+else
+	md.qmu.params.analysis_driver='stressbalance';
+	md.qmu.params.evaluation_concurrency=1;
+end
+
+md.stressbalance.reltol=10^-5; %tighten for qmu analyses
+md.transient.requested_outputs={'IceVolume','TotalSmb','IceMass'};
+
+%solve
+md=solve(md,'Transient','overwrite','y');
+md.qmu.results=md.results.dakota;
+
+%Fields and tolerances to track changes
+md.results.dakota.moments=[];
+for i=1:3,
+	md.results.dakota.moments=[md.results.dakota.moments md.results.dakota.dresp_out(i).mean];
+end
+for i=1:3,
+	md.results.dakota.moments=[md.results.dakota.moments md.results.dakota.dresp_out(i).stddev];
+end
+field_names     ={'moments'};
+field_tolerances={1e-11};
+field_values={...
+	md.results.dakota.moments,...
+	};
+
Index: /issm/trunk/test/NightlyRun/test260.py
===================================================================
--- /issm/trunk/test/NightlyRun/test260.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test260.py	(revision 22758)
@@ -0,0 +1,31 @@
+#Test Name: SquareShelfStressSSA2dEnhanced
+import numpy as np
+from model import *
+from socket import gethostname
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+from matenhancedice import *
+
+md = triangle(model(),'../Exp/Square.exp',150000.)
+md = setmask(md,'all','')
+md.materials = matenhancedice()
+md.materials.rheology_B = 3.15e8 * np.ones(md.mesh.numberofvertices,)
+md.materials.rheology_n = 3 * np.ones(md.mesh.numberofelements,)
+md.materials.rheology_E = np.ones(md.mesh.numberofvertices,)
+md = parameterize(md,'../Par/SquareShelf.py')
+md = setflowequation(md,'SSA','all')
+md.cluster = generic('name',gethostname(),'np',3)
+md = solve(md,'Stressbalance')
+
+#Fields and tolerances to track changes
+field_names      = ['Vx','Vy','Vel','Pressure']
+field_tolerances = [1e-13,1e-13,1e-13,1e-13]
+field_values = [
+	md.results.StressbalanceSolution.Vx,
+	md.results.StressbalanceSolution.Vy,
+	md.results.StressbalanceSolution.Vel,
+	md.results.StressbalanceSolution.Pressure,
+	]
Index: /issm/trunk/test/NightlyRun/test261.py
===================================================================
--- /issm/trunk/test/NightlyRun/test261.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test261.py	(revision 22758)
@@ -0,0 +1,38 @@
+#Test Name: SquareShelfConstrainedTranEnhanced
+import numpy as np
+from model import *
+from socket import gethostname
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+from matenhancedice import *
+
+md = triangle(model(),'../Exp/Square.exp',180000.)
+md = setmask(md,'all','')
+md = parameterize(md,'../Par/SquareShelfConstrained.py')
+md = md.extrude(3,1.)
+md = setflowequation(md,'SSA','all')
+md.cluster = generic('name',gethostname(),'np',3)
+md.materials = matenhancedice()
+md.materials.rheology_B = 3.15e8 * np.ones(md.mesh.numberofvertices,)
+md.materials.rheology_n = 3 * np.ones(md.mesh.numberofelements,)
+md.materials.rheology_E = np.ones(md.mesh.numberofvertices,)
+md.transient.isstressbalance = 1
+md.transient.ismasstransport = 0
+md.transient.issmb = 1
+md.transient.isthermal = 1
+md.transient.isgroundingline = 0
+md = solve(md,'Transient')
+
+#Fields and tolerances to track changes
+field_names      = ['Vx','Vy','Vel','Temperature','BasalforcingsGroundediceMeltingRate']
+field_tolerances = [1e-13,1e-13,1e-13,1e-13,1e-13]
+field_values = [
+	md.results.TransientSolution[0].Vx,
+	md.results.TransientSolution[0].Vy,
+	md.results.TransientSolution[0].Vel,
+	md.results.TransientSolution[0].Temperature,
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,
+	]
Index: /issm/trunk/test/NightlyRun/test285.m
===================================================================
--- /issm/trunk/test/NightlyRun/test285.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test285.m	(revision 22758)
@@ -14,5 +14,5 @@
 	md=solve(md,'Stressbalance');
 	field_names     ={field_names{:},['Vx' i{1}],['Vy' i{1}],['Vz' i{1}],['Vel' i{1}],['Pressure' i{1}]};
-	field_tolerances={field_tolerances{:},6.5e-08,5e-08,2e-08,5e-08,1e-13};
+	field_tolerances={field_tolerances{:},6.7e-08,5e-08,2e-08,5e-08,1e-13};
 	field_values={field_values{:},...
 	(md.results.StressbalanceSolution.Vx),...
Index: /issm/trunk/test/NightlyRun/test285.py
===================================================================
--- /issm/trunk/test/NightlyRun/test285.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test285.py	(revision 22758)
@@ -24,5 +24,5 @@
 	md=solve(md,'Stressbalance')
 	field_names     =field_names+['Vx'+i,'Vy'+i,'Vz'+i,'Vel'+i,'Pressure'+i]
-	field_tolerances=field_tolerances+[6.5e-08,5e-08,2e-08,5e-08,1e-13]
+	field_tolerances=field_tolerances+[6.7e-08,5e-08,2e-08,5e-08,1e-13]
 	field_values=field_values+[\
 		md.results.StressbalanceSolution.Vx,\
Index: /issm/trunk/test/NightlyRun/test292.m
===================================================================
--- /issm/trunk/test/NightlyRun/test292.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test292.m	(revision 22758)
@@ -6,8 +6,10 @@
 md.cluster=generic('name',oshostname(),'np',3);
 md.basalforcings=linearbasalforcings(md.basalforcings);
+md.basalforcings.deepwater_melting_rate=[50 100;0 5];
+md.timestepping.interp_forcings=0;
 md=solve(md,'Transient');
 
 %Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Base1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Base2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Base3','Surface3','Thickness3'};
 field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
Index: /issm/trunk/test/NightlyRun/test292.py
===================================================================
--- /issm/trunk/test/NightlyRun/test292.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test292.py	(revision 22758)
@@ -18,9 +18,11 @@
 md.cluster=generic('name',gethostname(),'np',3)
 md.basalforcings=linearbasalforcings(md.basalforcings)
+md.basalforcings.deepwater_melting_rate = np.array([[50.,100.],[0.,5.]])
+md.timestepping.interp_forcings=0
 md=solve(md,'Transient')
 
 # Fields and tolerances to track changes
 
-field_names     =['Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3']
+field_names     =['Vx1','Vy1','Vel1','Pressure1','Base1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Base2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Base3','Surface3','Thickness3']
 field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13]
 field_values=[\
Index: /issm/trunk/test/NightlyRun/test293.m
===================================================================
--- /issm/trunk/test/NightlyRun/test293.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test293.m	(revision 22758)
@@ -16,5 +16,8 @@
 	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','BasalforcingsFloatingiceMeltingRate2',...
 	'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3','BasalforcingsFloatingiceMeltingRate3'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_tolerances={...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,2e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,2e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,2e-13};
 field_values={...
 	(md.results.TransientSolution(1).Vx),...
Index: /issm/trunk/test/NightlyRun/test293.py
===================================================================
--- /issm/trunk/test/NightlyRun/test293.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test293.py	(revision 22758)
@@ -0,0 +1,59 @@
+#Test Name: SquareShelfTranSSA2dMismipFloatingMeltParam
+import numpy as np
+from model import *
+from socket import gethostname
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+from mismipbasalforcings import *
+
+md = triangle(model(),'../Exp/Square.exp',150000.)
+md = setmask(md,'all','')
+md = parameterize(md,'../Par/SquareShelf.py')
+md = setflowequation(md,'SSA','all')
+md.cluster = generic('name',gethostname(),'np',3)
+md.constants.yts = 365.2422 * 24. * 3600.
+md.basalforcings = mismipbasalforcings()
+md.basalforcings = md.basalforcings.initialize(md)
+md.transient.isgroundingline = 1
+md.geometry.bed = min(md.geometry.base) * np.ones(md.mesh.numberofvertices,)
+md.transient.requested_outputs = ['default','BasalforcingsFloatingiceMeltingRate']
+
+md = solve(md,'Transient')
+
+#Fields and tolerances to track changes
+field_names     =['Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','BasalforcingsFloatingiceMeltingRate1',
+	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','BasalforcingsFloatingiceMeltingRate2',
+	'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3','BasalforcingsFloatingiceMeltingRate3']
+field_tolerances = [
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,2e-13,
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,2e-13,
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,2e-13]
+field_values = [
+	md.results.TransientSolution[0].Vx,
+	md.results.TransientSolution[0].Vy,
+	md.results.TransientSolution[0].Vel,
+	md.results.TransientSolution[0].Pressure,
+	md.results.TransientSolution[0].Base,
+	md.results.TransientSolution[0].Surface,
+	md.results.TransientSolution[0].Thickness,
+	md.results.TransientSolution[0].BasalforcingsFloatingiceMeltingRate,
+	md.results.TransientSolution[1].Vx,
+	md.results.TransientSolution[1].Vy,
+	md.results.TransientSolution[1].Vel,
+	md.results.TransientSolution[1].Pressure,
+	md.results.TransientSolution[1].Base,
+	md.results.TransientSolution[1].Surface,
+	md.results.TransientSolution[1].Thickness,
+	md.results.TransientSolution[1].BasalforcingsFloatingiceMeltingRate,
+	md.results.TransientSolution[2].Vx,
+	md.results.TransientSolution[2].Vy,
+	md.results.TransientSolution[2].Vel,
+	md.results.TransientSolution[2].Pressure,
+	md.results.TransientSolution[2].Base,
+	md.results.TransientSolution[2].Surface,
+	md.results.TransientSolution[2].Thickness,
+	md.results.TransientSolution[2].BasalforcingsFloatingiceMeltingRate,
+	]
Index: /issm/trunk/test/NightlyRun/test3003.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3003.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test3003.m	(revision 22758)
@@ -16,5 +16,5 @@
 	'StressTensorxx','StressTensoryy','StressTensorzz','StressTensorxy','StressTensorxz','StressTensoryz'};
 field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09,...
-	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09};
+	1e-09,1e-09,1e-09,1e-09,1e-09,2e-09};
 field_values={...
 	(md.results.StressbalanceSolution.Vx),...
Index: /issm/trunk/test/NightlyRun/test3003.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3003.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test3003.py	(revision 22758)
@@ -23,5 +23,5 @@
 	'StressTensorxx','StressTensoryy','StressTensorzz','StressTensorxy','StressTensorxz','StressTensoryz']
 field_tolerances=[1e-09,1e-09,1e-09,1e-09,1e-09,\
-	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09]
+	1e-09,1e-09,1e-09,1e-09,1e-09,2e-09]
 field_values=[\
 	md.results.StressbalanceSolution.Vx,\
Index: /issm/trunk/test/NightlyRun/test301.py
===================================================================
--- /issm/trunk/test/NightlyRun/test301.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test301.py	(revision 22758)
@@ -19,8 +19,6 @@
 field_names     =['Vx','Vy','Vel','Pressure']
 field_tolerances=[1e-13,1e-13,1e-13,1e-13]
-field_values=[\
-	md.results.StressbalanceSolution.Vx,\
-	md.results.StressbalanceSolution.Vy,\
-	md.results.StressbalanceSolution.Vel,\
-	md.results.StressbalanceSolution.Pressure,\
-	]
+field_values=[md.results.StressbalanceSolution.Vx,
+							md.results.StressbalanceSolution.Vy,
+							md.results.StressbalanceSolution.Vel,
+							md.results.StressbalanceSolution.Pressure]
Index: /issm/trunk/test/NightlyRun/test3015.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3015.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test3015.m	(revision 22758)
@@ -75,5 +75,5 @@
 
 %Fields and tolerances to track changes
-field_names     ={'dV/dh-dV/dh0'};
-field_tolerances={1e-13};
-field_values={dVdh_ad-dVdh_an};
+field_names     ={'dV/dh'};
+field_tolerances={1e-8};
+field_values={dVdh_ad};
Index: /issm/trunk/test/NightlyRun/test3015.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3015.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test3015.py	(revision 22758)
@@ -91,5 +91,5 @@
 
 #Fields and tolerances to track changes
-field_names     =['dV/dh-dV/dh0']
-field_tolerances=[1e-13]
-field_values=[dVdh_ad-dVdh_an]
+field_names     =['dV/dh']
+field_tolerances=[1e-8]
+field_values=[dVdh_ad]
Index: /issm/trunk/test/NightlyRun/test3019.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3019.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test3019.m	(revision 22758)
@@ -33,4 +33,4 @@
 %Fields and tolerances to track changes
 field_names     ={'Jac Forward','Jac Reverse','Jac Forward - Reverse'};
-field_tolerances={1e-8,1e-8,1e-6};
+field_tolerances={1e-8,1e-8,5e-6};
 field_values={jac_forward,jac_reverse,jac_forward-jac_reverse};
Index: /issm/trunk/test/NightlyRun/test3019.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3019.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test3019.py	(revision 22758)
@@ -45,4 +45,4 @@
 #Fields and tolerances to track changes
 field_names     =['Jac Forward','Jac Reverse','Jac Forward - Reverse']
-field_tolerances=[1e-8,1e-8,1e-6]
+field_tolerances=[1e-8,1e-8,5e-6]
 field_values=[jac_forward,jac_reverse,jac_forward-jac_reverse]
Index: /issm/trunk/test/NightlyRun/test3103.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3103.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test3103.m	(revision 22758)
@@ -16,5 +16,5 @@
 	'StressTensorxx','StressTensoryy','StressTensorzz','StressTensorxy','StressTensorxz','StressTensoryz'};
 field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09,...
-	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09};
+	1e-09,1e-09,1e-09,1e-09,1e-09,1e-8};
 field_values={...
 	(md.results.StressbalanceSolution.Vx),...
Index: /issm/trunk/test/NightlyRun/test315.m
===================================================================
--- /issm/trunk/test/NightlyRun/test315.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test315.m	(revision 22758)
@@ -13,5 +13,5 @@
 	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'};
 field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...,
-	1e-10,1e-13,5e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-10,1e-13,5e-13,5e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
 	1e-10,2e-13,5e-13,2e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
Index: /issm/trunk/test/NightlyRun/test315.py
===================================================================
--- /issm/trunk/test/NightlyRun/test315.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test315.py	(revision 22758)
@@ -22,5 +22,5 @@
 	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3']
 field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,\
-	1e-10,1e-13,5e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,\
+	1e-10,1e-13,5e-13,5e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,\
 	1e-10,2e-13,5e-13,2e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13]
 field_values=[\
Index: /issm/trunk/test/NightlyRun/test316.m
===================================================================
--- /issm/trunk/test/NightlyRun/test316.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test316.m	(revision 22758)
@@ -8,6 +8,11 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1',...
+	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2',...
+	'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	2e-13,1e-13,1e-13,2e-13,1e-13,1e-13,1e-13};
 field_values={...
 	(md.results.TransientSolution(1).Vx),...
Index: /issm/trunk/test/NightlyRun/test316.py
===================================================================
--- /issm/trunk/test/NightlyRun/test316.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test316.py	(revision 22758)
@@ -18,5 +18,7 @@
 #Fields and tolerances to track changes
 field_names     =['Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3']
-field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13]
+field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,\
+						1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,\
+						2e-13,1e-13,1e-13,2e-13,1e-13,1e-13,1e-13]
 field_values=[\
 	md.results.TransientSolution[0].Vx,\
Index: /issm/trunk/test/NightlyRun/test318.py
===================================================================
--- /issm/trunk/test/NightlyRun/test318.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test318.py	(revision 22758)
@@ -20,5 +20,5 @@
 #Fields and tolerances to track changes
 field_names     =['Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsGroundediceMeltingRate']
-field_tolerances=[1e-13,1e-13,1.6e-10,1e-10,1e-13,1e-11,1e-6]
+field_tolerances=[1e-13,1e-13,2.3e-10,1e-10,1e-13,1e-11,1e-6]
 field_values=[\
 	md.results.SteadystateSolution.Vx,\
Index: /issm/trunk/test/NightlyRun/test322.m
===================================================================
--- /issm/trunk/test/NightlyRun/test322.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test322.m	(revision 22758)
@@ -24,5 +24,5 @@
 %Fields and tolerances to track changes
 field_names     ={'Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy'};
-field_tolerances={5e-05,1e-08,7e-08,5e-09,1e-08,1e-08,1e-08};
+field_tolerances={5e-05,1e-08,8e-08,5e-09,5e-08,5e-08,5e-08};
 field_values={...
 	(md.results.StressbalanceSolution.Gradient1),...
Index: /issm/trunk/test/NightlyRun/test322.py
===================================================================
--- /issm/trunk/test/NightlyRun/test322.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test322.py	(revision 22758)
@@ -36,5 +36,5 @@
 #Fields and tolerances to track changes
 field_names     =['Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy']
-field_tolerances=[5e-05,1e-08,7e-08,5e-09,1e-08,1e-08,1e-08]
+field_tolerances=[5e-05,1e-08,8e-08,5e-09,5e-08,5e-08,5e-08]
 field_values=[\
 	md.results.StressbalanceSolution.Gradient1,\
Index: /issm/trunk/test/NightlyRun/test323.m
===================================================================
--- /issm/trunk/test/NightlyRun/test323.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test323.m	(revision 22758)
@@ -5,11 +5,18 @@
 md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.timestepping.time_adapt=1;
+md.timestepping = timesteppingadaptive(md.timestepping);
+md.timestepping.time_step_max = 10000.;
 md.timestepping.final_time=1120.;
 md=solve(md,'Transient');
 
 %Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_names     ={...
+	'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1',...
+	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2',...
+	'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-12,1e-12};
 field_values={...
 	(md.results.TransientSolution(1).Vx),...
Index: /issm/trunk/test/NightlyRun/test323.py
===================================================================
--- /issm/trunk/test/NightlyRun/test323.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test323.py	(revision 22758)
@@ -15,5 +15,6 @@
 md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',gethostname(),'np',3)
-md.timestepping.time_adapt=1
+md.timestepping = timesteppingadaptive(md.timestepping);
+md.timestepping.time_step_max = 10000.;
 md.timestepping.final_time=1120.
 md=solve(md,'Transient')
@@ -21,5 +22,5 @@
 #Fields and tolerances to track changes
 field_names     =['Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3']
-field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13]
+field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-12,1e-12]
 field_values=[\
 	md.results.TransientSolution[0].Vx,\
Index: /issm/trunk/test/NightlyRun/test324.m
===================================================================
--- /issm/trunk/test/NightlyRun/test324.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test324.m	(revision 22758)
@@ -6,5 +6,6 @@
 md=setflowequation(md,'SIA','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.timestepping.time_adapt=1;
+md.timestepping = timesteppingadaptive(md.timestepping);
+md.timestepping.time_step_max = 10000.;
 md.timestepping.final_time=16000.;
 md=solve(md,'Transient');
@@ -15,5 +16,5 @@
 	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'};
 field_tolerances={1e-13,  1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
-	5*1e-11,1e-13,5e-13,1e-13,1e-13,1e-13,5e-13,1e-13,1e-13,1e-13,...
+	5e-11,1e-13,5e-13,5e-11,1e-13,1e-13,5e-13,1e-13,1e-13,1e-13,...
 	1e-10,  1e-12,1e-12,1e-12,1e-13,1e-13,1e-12,1e-12,1e-13,1e-13};
 field_values={...
Index: /issm/trunk/test/NightlyRun/test324.py
===================================================================
--- /issm/trunk/test/NightlyRun/test324.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test324.py	(revision 22758)
@@ -16,5 +16,6 @@
 md=setflowequation(md,'SIA','all')
 md.cluster=generic('name',gethostname(),'np',3)
-md.timestepping.time_adapt=1
+md.timestepping = timesteppingadaptive(md.timestepping);
+md.timestepping.time_step_max = 10000.;
 md.timestepping.final_time=16000.
 md=solve(md,'Transient')
@@ -25,5 +26,5 @@
 	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3']
 field_tolerances=[1e-13,  1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,\
-	5*1e-11,1e-13,5e-13,1e-13,1e-13,1e-13,5e-13,1e-13,1e-13,1e-13,\
+	5e-11,1e-13,5e-13,5e-11,1e-13,1e-13,5e-13,1e-13,1e-13,1e-13,\
 	1e-10,  1e-12,1e-12,1e-12,1e-13,1e-13,1e-12,1e-12,1e-13,1e-13]
 field_values=[\
Index: /issm/trunk/test/NightlyRun/test330.m
===================================================================
--- /issm/trunk/test/NightlyRun/test330.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test330.m	(revision 22758)
@@ -20,4 +20,5 @@
 md.hydrology.max_iter=200;
 md.hydrology.transfer_flag=0;
+md.hydrology.unconfined_flag=1;
 md.hydrology.sediment_porosity=0.1;
 %Sediment
Index: /issm/trunk/test/NightlyRun/test330.py
===================================================================
--- /issm/trunk/test/NightlyRun/test330.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test330.py	(revision 22758)
@@ -32,4 +32,5 @@
 md.hydrology.max_iter=200
 md.hydrology.transfer_flag=0
+md.hydrology.unconfined_flag=1
 md.hydrology.sediment_porosity=0.1
 #Sediment
Index: /issm/trunk/test/NightlyRun/test333.m
===================================================================
--- /issm/trunk/test/NightlyRun/test333.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test333.m	(revision 22758)
@@ -34,4 +34,10 @@
 
 md=solve(md,'Transient');
+%re-run with no substeps
+mdfine=md;
+mdfine.results=struct();
+mdfine.hydrology.steps_per_step=1;
+mdfine.timestepping.time_step=0.2;
+mdfine=solve(md,'Transient');
 
 %store=md.constants.g*md.hydrology.sediment_porosity*md.materials.rho_freshwater*((md.hydrology.sediment_compressibility/md.hydrology.sediment_porosity)+md.hydrology.water_compressibility);
@@ -43,22 +49,25 @@
 %Fields and tolerances to track changes
 field_names     ={'SedimentWaterHead1','EplWaterHead1','SedimentHeadResidual1',...
-						'SedimentWaterHead4','EplWaterHead4','SedimentHeadResidual4',...
-						'SedimentWaterHead5','EplWaterHead5','SedimentHeadResidual5',...
-						'SedimentWaterHead9','EplWaterHead9','SedimentHeadResidual9'};
+                  'SedimentWaterHead4','EplWaterHead4','SedimentHeadResidual4',...
+                  'SedimentWaterHead5','EplWaterHead5','SedimentHeadResidual5',...
+                  'SedimentWaterHead9','EplWaterHead9','SedimentHeadResidual9',...
+                  'EplWaterHead9'};
 field_tolerances={...
 	1e-13, 1e-13, 1e-13,...
 	1e-13, 1e-13, 1e-13,...
 	1e-13, 5e-12, 1e-11,...
-	1e-13, 5e-12, 1e-11};
-field_values={md.results.TransientSolution(1).SedimentHead, ...
-							md.results.TransientSolution(1).EplHead,...
-							md.results.TransientSolution(1).SedimentHeadResidual,...
-							md.results.TransientSolution(4).SedimentHead,...
-							md.results.TransientSolution(4).EplHead,...
-							md.results.TransientSolution(4).SedimentHeadResidual, ...
-							md.results.TransientSolution(5).SedimentHead,...
-							md.results.TransientSolution(5).EplHead,...
-							md.results.TransientSolution(5).SedimentHeadResidual, ...
-							md.results.TransientSolution(9).SedimentHead,...
-							md.results.TransientSolution(9).EplHead,...
-							md.results.TransientSolution(9).SedimentHeadResidual};
+	1e-13, 5e-12, 1e-11,...
+  1e-13};
+field_values={mdfine.results.TransientSolution(1).SedimentHead, ...
+							mdfine.results.TransientSolution(1).EplHead,...
+							mdfine.results.TransientSolution(1).SedimentHeadResidual,...
+							mdfine.results.TransientSolution(4).SedimentHead,...
+							mdfine.results.TransientSolution(4).EplHead,...
+							mdfine.results.TransientSolution(4).SedimentHeadResidual, ...
+							mdfine.results.TransientSolution(5).SedimentHead,...
+							mdfine.results.TransientSolution(5).EplHead,...
+							mdfine.results.TransientSolution(5).SedimentHeadResidual, ...
+							mdfine.results.TransientSolution(9).SedimentHead,...
+							mdfine.results.TransientSolution(9).EplHead,...
+							mdfine.results.TransientSolution(9).SedimentHeadResidual,...
+              md.results.TransientSolution(1).EplHead};
Index: /issm/trunk/test/NightlyRun/test333.py
===================================================================
--- /issm/trunk/test/NightlyRun/test333.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test333.py	(revision 22758)
@@ -42,8 +42,17 @@
 md.hydrology.epl_thick_comp=1
 md.hydrology.epl_max_thickness=1
-md.timestepping.time_step=0.2
+md.hydrology.steps_per_step=10
+md.timestepping.time_step=2.0
 md.timestepping.final_time=2.0
 
 md=solve(md,'Transient')
+
+#re-run with no substeps
+mdfine=md
+mdfine.result=[]
+mdfine.hydrology.steps_per_step=1
+mdfine.timestepping.time_step=0.2
+mdfine=solve(md,'Transient')
+
 
 # sedvol=np.zeros(10)
@@ -59,19 +68,23 @@
 						 'SedimentWaterHead4','EplWaterHead4','SedimentHeadResidual4',
 						 'SedimentWaterHead5','EplWaterHead5','SedimentHeadResidual5',
-						 'SedimentWaterHead9','EplWaterHead9','SedimentHeadResidual9']
+						 'SedimentWaterHead9','EplWaterHead9','SedimentHeadResidual9', 
+						 'EplWaterHead9']
 field_tolerances=[1e-13, 1e-13, 1e-13,
 									1e-13, 1e-13, 1e-13,
 									1e-13, 5e-12, 1e-11,
-									1e-13, 5e-12, 1e-11]
-field_values=[md.results.TransientSolution[0].SedimentHead,
-							md.results.TransientSolution[0].EplHead,
-							md.results.TransientSolution[0].SedimentHeadResidual,
-							md.results.TransientSolution[3].SedimentHead,
-							md.results.TransientSolution[3].EplHead,
-							md.results.TransientSolution[3].SedimentHeadResidual,
-							md.results.TransientSolution[4].SedimentHead,
-							md.results.TransientSolution[4].EplHead,
-							md.results.TransientSolution[4].SedimentHeadResidual,
-							md.results.TransientSolution[8].SedimentHead,
-							md.results.TransientSolution[8].EplHead,
-							md.results.TransientSolution[8].SedimentHeadResidual]
+									1e-13, 5e-12, 1e-11,
+									1e-13]
+field_values=[mdfine.results.TransientSolution[0].SedimentHead,
+							mdfine.results.TransientSolution[0].EplHead,
+							mdfine.results.TransientSolution[0].SedimentHeadResidual,
+							mdfine.results.TransientSolution[3].SedimentHead,
+							mdfine.results.TransientSolution[3].EplHead,
+							mdfine.results.TransientSolution[3].SedimentHeadResidual,
+							mdfine.results.TransientSolution[4].SedimentHead,
+							mdfine.results.TransientSolution[4].EplHead,
+							mdfine.results.TransientSolution[4].SedimentHeadResidual,
+							mdfine.results.TransientSolution[8].SedimentHead,
+							mdfine.results.TransientSolution[8].EplHead,
+							mdfine.results.TransientSolution[8].SedimentHeadResidual,
+							md.results.TransientSolution[0].EplHead]
+
Index: /issm/trunk/test/NightlyRun/test339.m
===================================================================
--- /issm/trunk/test/NightlyRun/test339.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test339.m	(revision 22758)
@@ -30,6 +30,6 @@
 	'Vx4','Vy4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SmbMassBalance4'};
 field_tolerances={...
-	1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,...
-	1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	2e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	2e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,...
 	1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,...
 	1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10};
Index: /issm/trunk/test/NightlyRun/test339.py
===================================================================
--- /issm/trunk/test/NightlyRun/test339.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test339.py	(revision 22758)
@@ -39,6 +39,6 @@
 						 'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SmbMassBalance3',
 						 'Vx4','Vy4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SmbMassBalance4']
-field_tolerances=[1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,
-									1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,
+field_tolerances=[2e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,
+									2e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,
 									1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,
 									1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10]
Index: /issm/trunk/test/NightlyRun/test340.py
===================================================================
--- /issm/trunk/test/NightlyRun/test340.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test340.py	(revision 22758)
@@ -0,0 +1,46 @@
+#Test Name: SquareSheetConstrainedSmbGradientsEla3d
+import numpy as np
+from model import *
+from socket import gethostname
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+from taoinversion import *
+
+md = triangle(model(),'../Exp/Square.exp',200000.)
+md = setmask(md,'','')
+md = parameterize(md,'../Par/SquareSheetConstrained.py')
+md.extrude(3,1.)
+md = setflowequation(md,'HO','all')
+
+#control parameters
+md.inversion = taoinversion()
+md.inversion.iscontrol = 1
+md.inversion.control_parameters = ['FrictionCoefficient']
+md.inversion.min_parameters = 1. * np.ones((md.mesh.numberofvertices,))
+md.inversion.max_parameters = 200. * np.ones((md.mesh.numberofvertices,))
+md.inversion.maxsteps = 2
+md.inversion.maxiter = 6
+md.inversion.cost_functions = [102,501]
+md.inversion.cost_functions_coefficients = np.ones((md.mesh.numberofvertices,2))
+md.inversion.cost_functions_coefficients[:,1] = 2. * 1e-7
+md.inversion.vx_obs = md.initialization.vx
+md.inversion.vy_obs = md.initialization.vy
+
+md.cluster = generic('name',gethostname(),'np',3)
+md = solve(md,'Stressbalance')
+
+#Fields and tolerances to track changes
+field_names      = ['Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy']
+field_tolerances = [3e-08,1e-07,5e-10,1e-10,1e-09,1e-09,1e-09]
+field_values = [
+	md.results.StressbalanceSolution.Gradient1,
+	md.results.StressbalanceSolution.J,
+	md.results.StressbalanceSolution.FrictionCoefficient,
+	md.results.StressbalanceSolution.Pressure,
+	md.results.StressbalanceSolution.Vel,
+	md.results.StressbalanceSolution.Vx,
+	md.results.StressbalanceSolution.Vy
+]
Index: /issm/trunk/test/NightlyRun/test342.py
===================================================================
--- /issm/trunk/test/NightlyRun/test342.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test342.py	(revision 22758)
@@ -0,0 +1,35 @@
+#Test Name: SquareSheetTherSteaPlume
+import numpy as np
+from model import *
+from socket import gethostname
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+from plumebasalforcings import *
+
+md = triangle(model(),'../Exp/Square.exp',180000.)
+md = setmask(md,'','')
+md = parameterize(md,'../Par/SquareSheetConstrained.py')
+md.basalforcings = plumebasalforcings()
+md.basalforcings = md.basalforcings.setdefaultparameters()
+md.basalforcings.floatingice_melting_rate = np.zeros((md.mesh.numberofvertices,))
+md.basalforcings.groundedice_melting_rate = np.zeros((md.mesh.numberofvertices,))
+md.basalforcings.plumex = 500000
+md.basalforcings.plumey = 500000
+md.extrude(3,1.)
+md = setflowequation(md,'SSA','all')
+md.timestepping.time_step = 0.
+md.thermal.requested_outputs = ['default','BasalforcingsGeothermalflux']
+md.cluster = generic('name',gethostname(),'np',3)
+md = solve(md,'Thermal')
+
+#Fields and tolerances to track changes
+field_names      = ['Temperature','BasalforcingsGroundediceMeltingRate','BasalforcingsGeothermalflux']
+field_tolerances = [1e-13,1e-8,1e-13]
+field_values = [
+	md.results.ThermalSolution.Temperature,
+	md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate,
+	md.results.ThermalSolution.BasalforcingsGeothermalflux,
+	]
Index: /issm/trunk/test/NightlyRun/test343.m
===================================================================
--- /issm/trunk/test/NightlyRun/test343.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test343.m	(revision 22758)
@@ -21,6 +21,12 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vel1','Bed1','Surface1','Thickness1','SMB1','TotalSmb1','Vx2','Vy2','Vel2','Bed2','Surface2','Thickness2','SMB2','TotalSmb2','Vx3','Vy3','Vel3','Bed3','Surface3','Thickness3','SMB3','TotalSmb3'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1.5e-13,1e-13};
+field_names     ={...
+	'Vx1','Vy1','Vel1','Bed1','Surface1','Thickness1','SMB1','TotalSmb1',...
+	'Vx2','Vy2','Vel2','Bed2','Surface2','Thickness2','SMB2','TotalSmb2',...
+	'Vx3','Vy3','Vel3','Bed3','Surface3','Thickness3','SMB3','TotalSmb3'};
+field_tolerances={...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-12,1e-12,1e-12,1e-13,1e-13,1e-13,1.5e-13,1e-13};
 field_values={...
 	(md.results.TransientSolution(1).Vx),...
Index: /issm/trunk/test/NightlyRun/test343.py
===================================================================
--- /issm/trunk/test/NightlyRun/test343.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test343.py	(revision 22758)
@@ -0,0 +1,66 @@
+#Test Name: SquareSheetConstrainedSmbGradientsEla2d
+import numpy as np
+from model import *
+from socket import gethostname
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+from SMBgradientsela import *
+
+md = triangle(model(),'../Exp/Square.exp',150000.)
+md = setmask(md,'','')
+md = parameterize(md,'../Par/SquareSheetConstrained.py')
+md = setflowequation(md,'SSA','all')
+md.smb = SMBgradientsela()
+md.smb.ela = 1500. * np.ones((md.mesh.numberofvertices+1,))
+md.smb.b_pos = 0.002 * np.ones((md.mesh.numberofvertices+1,))
+md.smb.b_neg = 0.005 * np.ones((md.mesh.numberofvertices+1,))
+md.smb.b_max = 4. * (md.materials.rho_freshwater / md.materials.rho_ice) * np.ones((md.mesh.numberofvertices+1,))
+md.smb.b_min = -4. * (md.materials.rho_freshwater / md.materials.rho_ice) * np.ones((md.mesh.numberofvertices+1,))
+
+#Change geometry
+md.geometry.thickness = md.geometry.surface * 30.
+md.geometry.surface = md.geometry.base + md.geometry.thickness
+
+#Transient options
+md.transient.requested_outputs = ['default','TotalSmb']
+md.cluster = generic('name',gethostname(),'np',3)
+md = solve(md,'Transient')
+
+#Fields and tolerances to track changes
+field_names     = [
+	'Vx1','Vy1','Vel1','Bed1','Surface1','Thickness1','SMB1','TotalSmb1',
+	'Vx2','Vy2','Vel2','Bed2','Surface2','Thickness2','SMB2','TotalSmb2',
+	'Vx3','Vy3','Vel3','Bed3','Surface3','Thickness3','SMB3','TotalSmb3']
+field_tolerances = [
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,
+	1e-12,1e-12,1e-12,1e-13,1e-13,1e-13,1.5e-13,1e-13]
+field_values = [
+	md.results.TransientSolution[0].Vx,
+	md.results.TransientSolution[0].Vy,
+	md.results.TransientSolution[0].Vel,
+	md.results.TransientSolution[0].Base,
+	md.results.TransientSolution[0].Surface,
+	md.results.TransientSolution[0].Thickness,
+	md.results.TransientSolution[0].SmbMassBalance,
+	md.results.TransientSolution[0].TotalSmb,
+	md.results.TransientSolution[1].Vx,
+	md.results.TransientSolution[1].Vy,
+	md.results.TransientSolution[1].Vel,
+	md.results.TransientSolution[1].Base,
+	md.results.TransientSolution[1].Surface,
+	md.results.TransientSolution[1].Thickness,
+	md.results.TransientSolution[1].TotalSmb,
+	md.results.TransientSolution[1].SmbMassBalance,
+	md.results.TransientSolution[2].Vx,
+	md.results.TransientSolution[2].Vy,
+	md.results.TransientSolution[2].Vel,
+	md.results.TransientSolution[2].Base,
+	md.results.TransientSolution[2].Surface,
+	md.results.TransientSolution[2].Thickness,
+	md.results.TransientSolution[2].SmbMassBalance,
+	md.results.TransientSolution[2].TotalSmb
+	]
Index: /issm/trunk/test/NightlyRun/test344.py
===================================================================
--- /issm/trunk/test/NightlyRun/test344.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test344.py	(revision 22758)
@@ -0,0 +1,73 @@
+#Test Name: SquareSheetConstrainedSmbGradientsEla3d
+import numpy as np
+from model import *
+from socket import gethostname
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+from SMBgradientsela import *
+
+md = triangle(model(),'../Exp/Square.exp',150000.)
+md = setmask(md,'','')
+md = parameterize(md,'../Par/SquareSheetConstrained.py')
+
+#Change geometry
+md.geometry.thickness = md.geometry.surface * 30.
+md.geometry.surface = md.geometry.base + md.geometry.thickness
+
+md = md.extrude(3,1.)
+md = setflowequation(md,'HO','all')
+md.smb = SMBgradientsela()
+md.smb.ela = 1500. * np.ones((md.mesh.numberofvertices+1,))
+md.smb.b_pos = 0.002 * np.ones((md.mesh.numberofvertices+1,))
+md.smb.b_neg = 0.005 * np.ones((md.mesh.numberofvertices+1,))
+md.smb.b_max = 4. * (md.materials.rho_freshwater / md.materials.rho_ice) * np.ones((md.mesh.numberofvertices+1,))
+md.smb.b_min = -4. * (md.materials.rho_freshwater / md.materials.rho_ice) * np.ones((md.mesh.numberofvertices+1,))
+
+
+#Transient options
+md.transient.requested_outputs = ['default','TotalSmb']
+md.cluster = generic('name',gethostname(),'np',3)
+md = solve(md,'Transient')
+
+#Fields and tolerances to track changes
+field_names     = ['Vx1','Vy1','Vz1','Vel1','Bed1','Surface1','Thickness1','Temperature1','SMB1','TotalSmb1',
+ 'Vx2','Vy2','Vz2','Vel2','Bed2','Surface2','Thickness2','Temperature2','SMB2','TotalSmb2',
+ 'Vx3','Vy3','Vz3','Vel3','Bed3','Surface3','Thickness3','Temperature3','SMB3','TotalSmb3']
+field_tolerances = [1e-09,1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,
+	1e-09,1e-09,1e-10,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,
+	1e-09,5e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10]
+field_values = [
+	md.results.TransientSolution[0].Vx,
+	md.results.TransientSolution[0].Vy,
+	md.results.TransientSolution[0].Vz,
+	md.results.TransientSolution[0].Vel,
+	md.results.TransientSolution[0].Base,
+	md.results.TransientSolution[0].Surface,
+	md.results.TransientSolution[0].Thickness,
+	md.results.TransientSolution[0].Temperature,
+	md.results.TransientSolution[0].SmbMassBalance,
+	md.results.TransientSolution[0].TotalSmb,
+	md.results.TransientSolution[1].Vx,
+	md.results.TransientSolution[1].Vy,
+	md.results.TransientSolution[1].Vz,
+	md.results.TransientSolution[1].Vel,
+	md.results.TransientSolution[1].Base,
+	md.results.TransientSolution[1].Surface,
+	md.results.TransientSolution[1].Thickness,
+	md.results.TransientSolution[1].Temperature,
+	md.results.TransientSolution[1].SmbMassBalance,
+	md.results.TransientSolution[1].TotalSmb,
+	md.results.TransientSolution[2].Vx,
+	md.results.TransientSolution[2].Vy,
+	md.results.TransientSolution[2].Vz,
+	md.results.TransientSolution[2].Vel,
+	md.results.TransientSolution[2].Base,
+	md.results.TransientSolution[2].Surface,
+	md.results.TransientSolution[2].Thickness,
+	md.results.TransientSolution[2].Temperature,
+	md.results.TransientSolution[2].SmbMassBalance,
+	md.results.TransientSolution[2].TotalSmb,
+	]
Index: /issm/trunk/test/NightlyRun/test3480.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3480.m	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test3480.m	(revision 22758)
@@ -0,0 +1,74 @@
+%Test Name: SquareShelfAdolcStaticControls
+md=triangle(model(),'../Exp/Square.exp',100000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md.initialization.vx(:)=1.;
+md.initialization.vy(:)=1.;
+md.geometry.thickness(:)=500-md.mesh.x/10000;
+md.geometry.bed =-100-md.mesh.x/1000;
+md.geometry.base=-md.geometry.thickness*md.materials.rho_ice/md.materials.rho_water;
+md.mask.groundedice_levelset=md.geometry.thickness+md.materials.rho_water/md.materials.rho_ice*md.geometry.bed;
+pos=find(md.mask.groundedice_levelset>=0);
+md.geometry.base(pos)=md.geometry.bed(pos);
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+md=setflowequation(md,'SSA','all');
+
+%control parameters
+md.inversion=adm1qn3inversion(md.inversion);
+md.inversion.iscontrol=1;
+md.autodiff.isautodiff=1;
+
+md.friction.coefficient(1:md.mesh.numberofvertices,1)=50;
+md.autodiff.independents = {independent('name','FrictionCoefficient',...
+	'md_name','md.friction.coefficient',...
+	'control_size',1,...
+	'type','vertex',...
+	'min_parameters',ones(md.mesh.numberofvertices,1),...
+	'max_parameters',500*ones(md.mesh.numberofvertices,1),...
+	'control_scaling_factor',1)...
+	};
+
+md.outputdefinition.definitions{1}=cfsurfacesquare('name','VyMisfit1',...
+	'definitionstring','Outputdefinition1',...
+	'model_string','Vy',...
+	'observation_string','VyObs',...
+	'observation',md.initialization.vy/md.constants.yts,...
+	'weights',ones(md.mesh.numberofvertices,1),...
+	'weights_string','WeightsSurfaceObservation',...
+	'datatime',0.75);
+
+md.timestepping.interp_forcings=0;
+md.timestepping.time_step=0.5;
+md.timestepping.final_time=1.5;
+
+md.transient.ismasstransport=1;
+md.transient.isstressbalance=1;
+md.transient.isgroundingline=1;
+md.transient.ismovingfront=0;
+md.transient.isthermal=0;
+
+pos=find(md.mask.groundedice_levelset<0);
+md.basalforcings.groundedice_melting_rate=zeros(md.mesh.numberofvertices,1);
+md.basalforcings.floatingice_melting_rate=25*zeros(md.mesh.numberofvertices,1);
+
+md.autodiff.dependents{1} = dependent('name','Outputdefinition1','type','scalar','fos_reverse_index',1);
+md.inversion.maxiter = 2;
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,'transient');
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient','Misfits','FrictionCoefficient','Pressure1','Vel1','Vx1','Vy1','Pressure2','Vel2','Vx2','Vy2'};
+field_tolerances={1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11};
+field_values={...
+	(md.results.TransientSolution(1).Gradient1),...
+	md.results.TransientSolution(1).J,...
+	(md.results.TransientSolution(1).FrictionCoefficient),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(7).Pressure),...
+	(md.results.TransientSolution(7).Vel),...
+	(md.results.TransientSolution(7).Vx),...
+	(md.results.TransientSolution(7).Vy)
+};
Index: /issm/trunk/test/NightlyRun/test3481.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3481.m	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test3481.m	(revision 22758)
@@ -0,0 +1,80 @@
+%Test Name: SquareShelfAdolcTransientControls
+md=triangle(model(),'../Exp/Square.exp',100000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md.initialization.vx(:)=1.;
+md.initialization.vy(:)=1.;
+md.geometry.thickness(:)=500-md.mesh.x/10000;
+md.geometry.bed =-100-md.mesh.x/1000;
+md.geometry.base=-md.geometry.thickness*md.materials.rho_ice/md.materials.rho_water;
+md.mask.groundedice_levelset=md.geometry.thickness+md.materials.rho_water/md.materials.rho_ice*md.geometry.bed;
+pos=find(md.mask.groundedice_levelset>=0);
+md.geometry.base(pos)=md.geometry.bed(pos);
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+md=setflowequation(md,'SSA','all');
+
+%control parameters
+md.inversion=adm1qn3inversion(md.inversion);
+md.inversion.iscontrol=1;
+md.autodiff.isautodiff=1;
+
+md.friction.coefficient(1:md.mesh.numberofvertices,1)=50;
+md.friction.coefficient(1:md.mesh.numberofvertices,2)=25;
+md.friction.coefficient(md.mesh.numberofvertices+1,1:2)=[0.75,1.25];
+min_parameters(1:md.mesh.numberofvertices,1:2)=1;
+min_parameters(md.mesh.numberofvertices+1,1:2)=[0.75,1.25];
+max_parameters(1:md.mesh.numberofvertices,1:2)=500;
+max_parameters(md.mesh.numberofvertices+1,1:2)=[0.75,1.25];
+md.autodiff.independents = {independent('name','FrictionCoefficient',...
+	'md_name','md.friction.coefficient',...
+	'control_size',2,...
+	'type','vertex',...
+	'min_parameters',min_parameters,...
+	'max_parameters',max_parameters,...
+	'control_scaling_factor',1)...
+	};
+
+md.outputdefinition.definitions{1}=cfsurfacesquare('name','VyMisfit1',...
+	'definitionstring','Outputdefinition1',...
+	'model_string','Vy',...
+	'observation_string','VyObs',...
+	'observation',md.initialization.vy/md.constants.yts,...
+	'weights',ones(md.mesh.numberofvertices,1),...
+	'weights_string','WeightsSurfaceObservation',...
+	'datatime',0.75);
+
+md.timestepping.interp_forcings=1;
+md.timestepping.time_step=0.5;
+md.timestepping.final_time=1.5;
+
+md.transient.ismasstransport=1;
+md.transient.isstressbalance=1;
+md.transient.isgroundingline=1;
+md.transient.ismovingfront=0;
+md.transient.isthermal=0;
+
+pos=find(md.mask.groundedice_levelset<0);
+md.basalforcings.groundedice_melting_rate=zeros(md.mesh.numberofvertices,1);
+md.basalforcings.floatingice_melting_rate=25*zeros(md.mesh.numberofvertices,1);
+
+md.autodiff.dependents{1} = dependent('name','Outputdefinition1','type','scalar','fos_reverse_index',1);
+md.inversion.maxiter = 2;
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,'transient');
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient','Misfits','FrictionCoefficient','Pressure1','Vel1','Vx1','Vy1','Pressure2','Vel2','Vx2','Vy2'};
+field_tolerances={1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11};
+field_values={...
+	(md.results.TransientSolution(1).Gradient1),...
+	md.results.TransientSolution(1).J,...
+	(md.results.TransientSolution(1).FrictionCoefficient),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(7).Pressure),...
+	(md.results.TransientSolution(7).Vel),...
+	(md.results.TransientSolution(7).Vx),...
+	(md.results.TransientSolution(7).Vy)
+};
Index: /issm/trunk/test/NightlyRun/test350.py
===================================================================
--- /issm/trunk/test/NightlyRun/test350.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test350.py	(revision 22758)
@@ -0,0 +1,94 @@
+#Test Name: SquareSheetHydrologySommers
+from operator import itemgetter
+import numpy as np
+from model import *
+from socket import gethostname
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+from frictionsommers import *
+from hydrologysommers import *
+from transient import *
+
+md = triangle(model(),'../Exp/Square.exp',50000.)
+md.mesh.x = md.mesh.x / 1000
+md.mesh.y = md.mesh.y / 1000
+md = setmask(md,'','')
+md = parameterize(md,'../Par/SquareSheetConstrained.py')
+md.transient = transient().deactivateall()
+md.transient.ishydrology = 1
+md = setflowequation(md,'SSA','all')
+md.cluster = generic('name',gethostname(),'np',2)
+
+#Use hydroogy coupled friciton law
+md.friction = frictionsommers(md)
+
+#Change hydrology class to Sommers' model
+md.hydrology = hydrologysommers()
+
+#Change geometry
+md.geometry.base = -.02 * md.mesh.x + 20.
+md.geometry.thickness = 300. * np.ones((md.mesh.numberofvertices,))
+md.geometry.bed = md.geometry.base
+md.geometry.surface = md.geometry.bed + md.geometry.thickness
+
+#define the initial water head as being such that the water pressure is 50% of the ice overburden pressure
+md.hydrology.head = 0.5 * md.materials.rho_ice / md.materials.rho_freshwater * md.geometry.thickness + md.geometry.base
+md.hydrology.gap_height = 0.01 * np.ones((md.mesh.numberofelements,))
+md.hydrology.bump_spacing = 2 * np.ones((md.mesh.numberofelements,))
+md.hydrology.bump_height = 0.05 * np.ones((md.mesh.numberofelements,))
+md.hydrology.englacial_input = 0.5 * np.ones((md.mesh.numberofvertices,))
+md.hydrology.reynolds= 1000. * np.ones((md.mesh.numberofelements,))
+md.hydrology.spchead = float('NaN') * np.ones((md.mesh.numberofvertices,))
+pos = np.intersect1d(np.array(np.where(md.mesh.vertexonboundary)), np.array(np.where(md.mesh.x == 1000)))
+md.hydrology.spchead[pos] = md.geometry.base[pos]
+
+#Define velocity
+md.initialization.vx = 1e-6 * md.constants.yts * np.ones((md.mesh.numberofvertices,))
+md.initialization.vy = np.zeros((md.mesh.numberofvertices,))
+
+md.timestepping.time_step = 3. * 3600. / md.constants.yts
+md.timestepping.final_time = .5 / 365.
+md.materials.rheology_B = (5e-25)**(-1. / 3.) * np.ones((md.mesh.numberofvertices,))
+
+#Add one moulin and Neumann BC, varying in time
+a = np.sqrt((md.mesh.x - 500.)**2 + (md.mesh.y - 500.)**2)
+pos = min(enumerate(a), key=itemgetter(1))[0]
+time = np.arange(0,md.timestepping.final_time+1,md.timestepping.time_step)
+md.hydrology.moulin_input = np.zeros((md.mesh.numberofvertices+1,np.size(time)))
+md.hydrology.moulin_input[-1,:] = time
+md.hydrology.moulin_input[pos,:] = 5. * (1. - np.sin(2. * np.pi / (1. / 365.) * time))
+md.hydrology.neumannflux = np.zeros((md.mesh.numberofelements+1,np.size(time)))
+md.hydrology.neumannflux[-1,:] = time
+segx = md.mesh.x[md.mesh.segments[:,0]-1]
+segy = md.mesh.y[md.mesh.segments[:,0]-1]
+posA = np.intersect1d(np.intersect1d(np.array(np.where(segx < 1.)),np.array(np.where(segy > 400.))), np.array(np.where(segy < 600.)))
+pos = (md.mesh.segments[posA]-1)[:,2]
+md.hydrology.neumannflux[pos,:] = np.tile(0.05*(1.-np.sin(2.*np.pi/(1./365.)*time)),(len(pos),1))
+
+md = solve(md,'Transient')
+
+#Fields and tolerances to track changes
+field_names = [
+	'HydrologyHead1','HydrologyGapHeight1',
+	'HydrologyHead2','HydrologyGapHeight2',
+	'HydrologyHead3','HydrologyGapHeight3',
+	'HydrologyHead4','HydrologyGapHeight4']
+field_tolerances = [
+	1e-13, 1e-13,
+	1e-13, 1e-13,
+	1e-13, 1e-13,
+	1e-13, 1e-12]
+field_values = [
+	md.results.TransientSolution[0].HydrologyHead,
+	md.results.TransientSolution[0].HydrologyGapHeight,
+	md.results.TransientSolution[1].HydrologyHead,
+	md.results.TransientSolution[1].HydrologyGapHeight,
+	md.results.TransientSolution[2].HydrologyHead,
+	md.results.TransientSolution[2].HydrologyGapHeight,
+	md.results.TransientSolution[3].HydrologyHead,
+	md.results.TransientSolution[3].HydrologyGapHeight
+	]
+
Index: /issm/trunk/test/NightlyRun/test4001.m
===================================================================
--- /issm/trunk/test/NightlyRun/test4001.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test4001.m	(revision 22758)
@@ -3,5 +3,5 @@
 %
 %Script control parameters
-steps=1:15;
+steps=1:11;
 final_time=1;
 
@@ -166,5 +166,5 @@
     fclose(fido);
 
-	 system(['../MITgcm/build.sh generic ' pwd]);
+	 system(['../MITgcm/build.sh generic ' pwd '/../MITgcm']);
 end
 % }}}
@@ -191,4 +191,5 @@
     !\cp ../MITgcm/build/mitgcmuv run
     !\cp ../MITgcm/input/* run
+    !\cp ../MITgcm/input/eedata_uncoupled run/eedata
     
     %load data: 
@@ -539,5 +540,4 @@
 	md.timestepping.final_time=final_time;
 	md.timestepping.time_step=time_step;
-	md.timestepping.time_adapt=0;
 	md.transient.isgroundingline=1;
 	md.transient.isthermal=0;
@@ -572,9 +572,7 @@
         end
         !\mkdir run
-		  disp('-------------- file: test4001.m line: 578'); 
         !\cp ../MITgcm/build/mitgcmuv run
-		  disp('-------------- file: test4001.m line: 580'); 
         !\cp ../MITgcm/input/* run
-		  disp('-------------- file: test4001.m line: 582'); 
+        !\cp ../MITgcm/input/eedata_uncoupled run/eedata
 
         %load data: 
@@ -653,5 +651,4 @@
 	md.timestepping.final_time=final_time;
 	md.timestepping.time_step=time_step;
-	md.timestepping.time_adapt=0;
 	md.cluster=generic('name',oshostname(),'np',2);
 	md.results.TransientSolution.Base=md.geometry.base;
Index: /issm/trunk/test/NightlyRun/test4002.m
===================================================================
--- /issm/trunk/test/NightlyRun/test4002.m	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test4002.m	(revision 22758)
@@ -0,0 +1,1043 @@
+%Test Name: IceOceanDirectCoupling
+%ISSM/MITgcm coupled set-up
+%
+%Script control parameters
+steps=[1 2 3 4 5 6 7 8 9 10 11 12];
+final_time=1/365;
+
+%Organizer
+mkdir Models
+org=organizer('repository','Models/','prefix','IceOcean.','steps',steps);
+
+presentdirectory=pwd; 
+
+% {{{ Parameters: 
+if perform(org,'Parameters'),
+	Nx=20; %number of longitude cells
+	Ny=40; %number of latitude cells
+	Nz=30; %number of MITgcm vertical cells
+	nPx=2; %number of MITgcm processes to use in x direction
+	nPy=4; %number of MITgcm processes to use in y direction
+	xgOrigin=0; %origin of longitude
+	ygOrigin=-80; %origin of latitude
+	dLong=.25; %longitude grid spacing
+	dLat=.05; %latitude grid spacing
+	delZ=30; %thickness of vertical levels
+	icefront_position_ratio=.75; 
+	ice_thickness=100;
+	rho_ice=917;
+	rho_water=1028.14;
+	di=rho_ice/rho_water;
+
+	% MITgcm initial and lateral boundary conditions
+	iniSalt  = 34.4; % initial salinity (PSU)
+	iniTheta = -1.9; % initial potential temperature (deg C)
+	obcSalt  = 34.4; % open boundary salinity (PSU)
+	obcTheta =  1.0; % open boundary potential temperature (deg C)
+	mlDepth  = 120.; % mixed layer depth (m)
+	mlSalt   = 33.4; % open boundary salinity (PSU)
+	mlTheta  = -1.9; % open boundary potential temperature (deg C)
+	obcUvel  = -0.1; % open boundary velocity (m/s)        
+
+	MITgcmDeltaT=600; % MITgcm time step in seconds
+	y2s=31536000; % year to seconds conversion, i.e., seconds per year
+
+	% start_time and time_step
+	start_time=0; % in decimal years
+	time_step=1/(365*24); % coupling interval in decimal years
+	async_step_MITgcm_multiplier=1; % used to reduce run time for MItgcm
+
+	% bedrock/bathymetry
+	hmax=1000;
+	trough_depth=200;
+	deltah=300;
+	sea_level=1095;
+
+	% issm settings:
+	numlayers=10;
+
+	savedata(org, Nx, Ny, nPx, nPy, Nz, dLong, dLat, delZ, xgOrigin, ...
+		ygOrigin, icefront_position_ratio, ice_thickness, rho_ice, ...
+		rho_water, di, hmax, trough_depth, deltah, sea_level, ...
+		iniSalt, iniTheta, obcSalt, obcTheta, mlDepth, mlSalt, ...
+		mlTheta, obcUvel, start_time, time_step, MITgcmDeltaT, y2s,...
+		numlayers,async_step_MITgcm_multiplier);
+end
+% }}}
+% {{{ Bathymetry: 
+if perform(org,'Bathymetry'),
+
+    loaddata(org,'Parameters');
+    %create lat,long
+    lat=(ygOrigin+dLat/2):dLat:(ygOrigin+Ny*dLat);
+    long=(xgOrigin+dLong/2):dLong:(xgOrigin+Nx*dLong);
+    [lat long]=meshgrid(lat,long);
+
+    longmin=min(long(:));
+    longmax=max(long(:));
+    latmin=min(lat(:));
+    latmax=max(lat(:));
+
+    %create bedrock/bathymetry:
+    bedrock=zeros(Nx,Ny);
+    bedrock=hmax-deltah*tanh(pi*(2*(lat-latmin)./(latmax-latmin)-1))+ ...
+            trough_depth*cos(2*pi*long./(longmax-longmin));
+
+    %save bathymetry file for MITgcm
+    bathymetry=bedrock-sea_level;
+    savedata(org,lat,long,bathymetry);
+
+end
+% }}}
+% {{{ IceSheetGeometry: 
+if perform(org,'IceSheetGeometry'),
+	
+	loaddata(org,'Parameters');
+	loaddata(org,'Bathymetry');
+	latmin=min(lat(:));
+	latmax=max(lat(:));
+
+	%put ice_thickness constant layer of ice over the bathymetry, unless it floats: 
+	s=size(bathymetry);
+	thickness=ice_thickness*ones(s);
+
+	%figure out ice shelf: 
+	pos=find(-di*thickness>bathymetry);
+	iceshelf_mask=zeros(s);
+	iceshelf_mask(pos)=1;
+
+	ice_mask=ones(s);
+	pos=find((lat-latmin)/(latmax-latmin)>(icefront_position_ratio));
+	ice_mask(pos)=0;
+	iceshelf_mask(pos)=0;
+
+	%compute draft of ice shelf: 
+	draft=bathymetry;
+	pos=find(iceshelf_mask);
+	draft(pos)=-di*thickness(pos);
+	pos=find(~ice_mask); 
+	draft(pos)=0;
+
+	savedata(org,ice_mask,iceshelf_mask,draft,thickness);
+end
+% }}}
+
+%Configure MITgcm
+% {{{ GetMITgcm: 
+if perform(org,'GetMITgcm'),
+  system([pwd '/../MITgcm/get_mitgcm.sh']);
+end
+% }}}
+% {{{ BuildMITgcm: 
+if perform(org,'BuildMITgcm'),
+
+    %load data: 
+    loaddata(org,'Parameters');
+
+    %specify computational grid in SIZE.h
+    fidi=fopen('../MITgcm/code/SIZE.h.bak','r');
+    fido=fopen('../MITgcm/code/SIZE.h','w');
+    tline = fgetl(fidi);
+    fprintf(fido,'%s\n',tline);
+    while 1
+        tline = fgetl(fidi);
+        if ~ischar(tline), break, end
+        %do the change here: 
+        if strcmpi(tline,'     &           sNx =  20,'),
+            fprintf(fido,'%s%i%s\n','     &           sNx =  ',round(Nx/nPx),',');
+            continue;
+        end
+        if strcmpi(tline,'     &           sNy =  20,'),
+            fprintf(fido,'%s%i%s\n','     &           sNy =  ',round(Ny/nPy),',');
+            continue;
+        end
+        if strcmpi(tline,'     &           nPx =   1,'),
+            fprintf(fido,'%s%i%s\n','     &           nPx = ',nPx,',');
+            continue;
+        end
+        if strcmpi(tline,'     &           nPy =   2,'),
+            fprintf(fido,'%s%i%s\n','     &           nPy = ',nPy,',');
+            continue;
+        end
+        fprintf(fido,'%s\n',tline);
+    end
+    %close  files
+    fclose(fidi);
+    fclose(fido);
+
+	 system(['../MITgcm/build.sh generic ' pwd '/../MITgcm']);
+end
+% }}}
+addpath(recursivepath([pwd '/../MITgcm']));
+% {{{ RunUncoupledMITgcm: 
+if perform(org,'RunUncoupledMITgcm'),
+
+    %load data: 
+    loaddata(org,'Parameters');
+    loaddata(org,'Bathymetry');
+    loaddata(org,'IceSheetGeometry');
+	 endtime = round(MITgcmDeltaT * ...
+		 floor(time_step*y2s*async_step_MITgcm_multiplier/MITgcmDeltaT));
+
+    % {{{ prepare MITgcm 
+    % rename previous run directory and create new one
+    if exist ('run.old')
+        !\rm -rf run.old
+    end
+    if exist ('run')
+        !\mv run run.old
+    end
+    !\mkdir run
+    !\cp ../MITgcm/build/mitgcmuv run
+    !\cp ../MITgcm/input/* run
+    !\cp ../MITgcm/input/eedata_uncoupled run/eedata
+    
+    %load data: 
+    loaddata(org,'Parameters');
+
+    % initial salinity
+    S=iniSalt*ones(Nx,Ny,Nz);
+    writebin('run/Salt.bin',S);
+    
+    % initial temperature
+    T=iniTheta*ones(Nx,Ny,Nz);
+    writebin('run/Theta.bin',T);
+    
+    % initial velocity
+    Z=zeros(Nx,Ny,Nz);
+    writebin('run/Uvel.bin',Z);
+    writebin('run/Vvel.bin',Z);
+    
+    % initial sea surface height
+    Z=zeros(Nx,Ny);
+    writebin('run/Etan.bin',Z);
+
+    % salinity boundary conditions
+    S=obcSalt*ones(Ny,Nz);
+    thk=delZ*ones(Nz,1);
+    bot=cumsum(thk);
+    ik=find(bot<=mlDepth);
+    S(:,ik)=mlSalt;
+    writebin('run/OBs.bin',S);
+
+    % temperature boundary conditions
+    T=obcTheta*ones(Ny,Nz);
+    T(:,ik)=mlTheta;
+    writebin('run/OBt.bin',T);
+
+    % zonal velocity boundary conditions
+    U=obcUvel*ones(Ny,Nz);
+    writebin('run/OBu.bin',U);
+    
+    % zero boundary conditions
+    Z=zeros(Ny,Nz);
+    writebin('run/zeros.bin',Z);
+
+    % build parameter file data.obcs
+    fidi=fopen('../MITgcm/input/data.obcs','r');
+    fido=fopen('run/data.obcs','w');
+    tline = fgetl(fidi);
+    fprintf(fido,'%s\n',tline);
+    while 1
+        tline = fgetl(fidi);
+        if ~ischar(tline), break, end
+        %do the change here: 
+        if strcmpi(tline,' OB_Iwest = 40*1,'),
+            fprintf(fido,'%s%i%s\n',' OB_Iwest = ',Ny,'*1,');
+            continue;
+        end
+        if strcmpi(tline,' OB_Ieast = 40*-1,'),
+            fprintf(fido,'%s%i%s\n',' OB_Ieast = ',Ny,'*-1,');
+            continue;
+        end
+        fprintf(fido,'%s\n',tline);
+    end
+    %close  files
+    fclose(fidi);
+    fclose(fido);
+
+    %save bathymetry and bedrock in run directory
+    writebin('run/bathymetry.bin',bathymetry);
+    writebin('run/icetopo.bin',draft);
+    % }}}
+
+    %start looping:  
+    for t=start_time:time_step:final_time,
+        disp(['Year: ' num2str(t)])
+        % {{{ generate MITgcm parameter file data 
+        fidi=fopen('../MITgcm/input/data','r');
+        fido=fopen('run/data','w');
+        tline = fgetl(fidi);
+        fprintf(fido,'%s\n',tline);
+        while 1
+            tline = fgetl(fidi);
+            if ~ischar(tline), break, end
+            %do the change here: 
+            if strcmpi(tline,' xgOrigin = 0.0,'),
+                fprintf(fido,'%s%i%s\n',' xgOrigin = ',xgOrigin,',');
+                continue;
+            end
+            if strcmpi(tline,' ygOrigin = -80.0,'),
+                fprintf(fido,'%s%i%s\n',' ygOrigin = ',ygOrigin,',');
+                continue;
+            end
+            if strcmpi(tline,' delX = 20*0.25,'),
+                fprintf(fido,'%s%i*%g%s\n',' delX = ',Nx,dLong,',');
+                continue;
+            end
+            if strcmpi(tline,' delY = 20*0.25,'),
+                fprintf(fido,'%s%i*%g%s\n',' delY = ',Ny,dLat,',');
+                continue;
+            end
+            if strcmpi(tline,' delZ = 30*30.0,'),
+                fprintf(fido,'%s%i*%g%s\n',' delZ = ',Nz,delZ,',');
+                continue;
+            end
+            if strcmpi(tline,' endTime=2592000.,'),
+                fprintf(fido,'%s%i%s\n',' endTime= ',endtime,',');
+                continue;
+            end
+            if strcmpi(tline,' deltaT=1200.0,'),
+                fprintf(fido,'%s%i%s\n',' deltaT= ',MITgcmDeltaT,',');
+                continue;
+            end
+            if strcmpi(tline,' pChkptFreq=2592000.,'),
+                fprintf(fido,'%s%i%s\n',' pChkptFreq= ',endtime,',');
+                continue;
+            end
+            if strcmpi(tline,' taveFreq=2592000.,'),
+                fprintf(fido,'%s%i%s\n',' taveFreq= ',endtime,',');
+                continue;
+            end
+            if strcmpi(tline,' rhoConst=1030.,'),
+                fprintf(fido,'%s%i%s\n',' rhoConst= ',rho_water,',');
+                continue;
+            end
+            if strcmpi(tline,' rhoNil=1030.,'),
+                fprintf(fido,'%s%i%s\n',' rhoNil= ',rho_water,',');
+                continue;
+            end
+            fprintf(fido,'%s\n',tline);
+        end
+        %close  files
+        fclose(fidi);
+        fclose(fido);
+        % }}}
+        % {{{ generate initial MITgcm conditions
+
+        ds=round(endtime/MITgcmDeltaT);
+        if t>start_time
+            % Read pickup file
+            fnm=['run/pickup.' myint2str(ds,10) '.data'];
+            U=readbin(fnm,[Nx Ny Nz],1,'real*8',0);
+            V=readbin(fnm,[Nx Ny Nz],1,'real*8',1);
+            T=readbin(fnm,[Nx Ny Nz],1,'real*8',2);
+            S=readbin(fnm,[Nx Ny Nz],1,'real*8',3);
+            E=readbin(fnm,[Nx Ny],1,'real*8',8*Nz);
+            writebin('run/Salt.bin' ,S);
+            writebin('run/Theta.bin',T);
+            writebin('run/Uvel.bin' ,U);
+            writebin('run/Vvel.bin' ,V);
+            writebin('run/Etan.bin' ,E);
+        end
+
+        % }}}
+        % {{{ system call to run MITgcm
+        cd run
+        eval(['!mpirun -np ' int2str(nPx*nPy) ' ./mitgcmuv']);
+        ts=round((t+time_step)*y2s/MITgcmDeltaT);
+        eval(['!\mv STDERR.0000 STDERR_' myint2str(ts,10) '.data'])
+        eval(['!\mv STDOUT.0000 STDOUT_' myint2str(ts,10) '.data'])
+        eval(['!\cp hFacC.data hFacC_' myint2str(ts,10) '.data'])
+        eval(['!\cp icetopo.bin icetopo_' myint2str(ts,10) '.data'])
+        for fld={'S','T','U','V','Eta', ...
+                 'SHICE_heatFluxtave','SHICE_fwFluxtave'}
+            eval(['!\mv ' fld{1} '.' myint2str(ds,10) '.data ' ...
+                  fld{1} '_' myint2str(ts,10) '.data'])
+        end
+        cd ..
+        % }}}
+    end
+end
+% }}}
+
+%Configure ISSM
+% {{{ CreateMesh: 
+if perform(org,'CreateMesh'),
+	
+	loaddata(org,'Parameters');
+	loaddata(org,'Bathymetry');
+	loaddata(org,'IceSheetGeometry');
+
+	%create model: 
+	md=model();
+	
+	%Grab lat,long from MITgcm: 
+	lat=lat(:);
+	long=long(:);
+
+	%project lat,long: 
+	[x,y]=ll2xy(lat,long,-1);
+
+	index=[];
+	%  C  D
+	%  A  B 
+	for j=1:Ny-1,
+		for i=1:Nx-1, 
+			A=(j-1)*Nx+i;
+			B=(j-1)*Nx+i+1;
+			C=j*Nx+i;
+			D=j*Nx+i+1;
+			index(end+1,:)=[A B C];
+			index(end+1,:)=[C B D];
+		end
+	end
+
+	%fill mesh and model: 
+	md=meshconvert(md,index,x,y);
+	md.mesh.lat=lat;
+	md.mesh.long=long;
+
+	savemodel(org,md);
+
+end
+% }}}
+% {{{ MeshGeometry: 
+if perform(org,'MeshGeometry'),
+	
+	loaddata(org,'Parameters');
+	loaddata(org,'CreateMesh');
+	loaddata(org,'Bathymetry');
+	loaddata(org,'IceSheetGeometry');
+
+	%transfer to vertices: 
+	bathymetry=bathymetry(:);
+	iceshelf_mask=iceshelf_mask(:);
+	ice_mask=ice_mask(:);
+	thickness=thickness(:);
+	draft=draft(:);
+
+	%start filling some of the fields 
+	md.geometry.bed=bathymetry;
+	md.geometry.thickness=thickness;
+	md.geometry.base=md.geometry.bed; 
+	pos=find(iceshelf_mask); md.geometry.base(pos)=draft(pos);
+	md.geometry.surface=md.geometry.base+md.geometry.thickness;
+
+	%nothing passes icefront: 
+	pos=find(~ice_mask);
+	md.geometry.thickness(pos)=1;
+	md.geometry.surface(pos)=(1-di)*md.geometry.thickness(pos);
+	md.geometry.base(pos)=-di*md.geometry.thickness(pos);
+
+	%level sets: 
+	md.mask.groundedice_levelset=-ones(md.mesh.numberofvertices,1);
+	md.mask.ice_levelset=ones(md.mesh.numberofvertices,1);
+
+	pos=find(ice_mask); md.mask.ice_levelset(pos)=-1; 
+	pos=find(~iceshelf_mask & ice_mask); md.mask.groundedice_levelset(pos)=1;
+
+	%identify edges of grounded ice: 
+	groundedice_levelset=md.mask.groundedice_levelset;
+	for i=1:md.mesh.numberofelements,
+		m=groundedice_levelset(md.mesh.elements(i,:));
+		if abs(sum(m))~=3,
+			pos=find(m==1); md.mask.groundedice_levelset(md.mesh.elements(i,pos))=0;
+		end
+	end
+
+	%identify edges of ice: 
+	ice_levelset=md.mask.ice_levelset;
+	for i=1:md.mesh.numberofelements,
+		m=ice_levelset(md.mesh.elements(i,:));
+		if abs(sum(m))~=3,
+			pos=find(m==-1); md.mask.ice_levelset(md.mesh.elements(i,pos))=0;
+		end
+	end
+
+	savemodel(org,md);
+end
+% }}}
+% {{{ ParameterizeIce: 
+if perform(org,'ParameterizeIce'),
+	
+	loaddata(org,'Parameters');
+	loaddata(org,'CreateMesh');
+	loaddata(org,'MeshGeometry');
+
+	%miscellaneous
+	md.miscellaneous.name='test4002';
+
+	%initial velocity: 
+	md.initialization.vx=zeros(md.mesh.numberofvertices,1);
+	md.initialization.vy=zeros(md.mesh.numberofvertices,1);
+	md.initialization.vz=zeros(md.mesh.numberofvertices,1);
+
+	%friction: 
+	md.friction.coefficient=30*ones(md.mesh.numberofvertices,1);
+	pos=find(md.mask.groundedice_levelset<=0);
+	md.friction.coefficient(pos)=0;
+	md.friction.p=ones(md.mesh.numberofelements,1);
+	md.friction.q=ones(md.mesh.numberofelements,1);
+
+	%temperatures and surface mass balance:
+	md.initialization.temperature=(273.15-20)*ones(md.mesh.numberofvertices,1);
+	md.initialization.pressure=md.materials.rho_ice*md.constants.g*(md.geometry.surface-md.geometry.base);
+	md.smb.mass_balance = [1*ones(md.mesh.numberofvertices,1); 1];
+
+	%Flow law 
+	md.materials.rheology_B=paterson(md.initialization.temperature);
+	md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+	md.damage.D=zeros(md.mesh.numberofvertices,1);
+	md.damage.spcdamage=NaN*ones(md.mesh.numberofvertices,1);
+	
+	%the spcs going
+	md.stressbalance.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+	md.stressbalance.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+	md.stressbalance.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+	md.stressbalance.referential=NaN*ones(md.mesh.numberofvertices,6);
+	md.stressbalance.loadingforce=0*ones(md.mesh.numberofvertices,3);
+	md.masstransport.spcthickness=NaN*ones(md.mesh.numberofvertices,1); 
+
+	%deal with water: 
+	pos=find(md.mask.ice_levelset>0); 
+	md.stressbalance.spcvx(pos)=0;
+	md.stressbalance.spcvy(pos)=0;
+	md.stressbalance.spcvz(pos)=0;
+	md.masstransport.spcthickness(pos)=0;
+
+	%get some flux at the ice divide: 
+	pos=find(md.mesh.lat==min(md.mesh.lat));
+	md.stressbalance.spcvy(pos)=200;
+
+	%deal with boundaries, excluding icefront: 
+	vertex_on_boundary=zeros(md.mesh.numberofvertices,1);
+	vertex_on_boundary(md.mesh.segments(:,1:2))=1;
+	pos=find(vertex_on_boundary & md.mask.groundedice_levelset<=0);
+	md.stressbalance.spcvx(pos)=md.initialization.vx(pos);
+	md.stressbalance.spcvy(pos)=md.initialization.vy(pos);
+	md.stressbalance.spcvz(pos)=md.initialization.vz(pos);
+	md.masstransport.spcthickness(pos)=md.geometry.thickness(pos);
+
+	md.basalforcings.groundedice_melting_rate=zeros(md.mesh.numberofvertices,1);
+	md.basalforcings.floatingice_melting_rate=zeros(md.mesh.numberofvertices,1);
+	md.thermal.spctemperature=[md.initialization.temperature; 1]; %impose observed temperature on surface
+	md.basalforcings.geothermalflux=.064*ones(md.mesh.numberofvertices,1);
+
+	%flow equations: 
+	md=setflowequation(md,'SSA','all');
+
+	savemodel(org,md);
+end
+% }}}
+% {{{ RunUncoupledISSM: 
+if perform(org,'RunUncoupledISSM'),
+	
+	loaddata(org,'Parameters');
+	loaddata(org,'ParameterizeIce');
+
+	%timestepping: 
+	md.timestepping.final_time=final_time;
+	md.timestepping.time_step=time_step;
+	md.transient.isgroundingline=1;
+	md.transient.isthermal=0;
+	md.groundingline.migration='SubelementMigration2';
+
+	md.cluster=generic('name',oshostname(),'np',2);
+	md=solve(md,'Transient');
+
+	savemodel(org,md);
+end
+% }}}
+
+%Run MITgcm/ISSM
+% {{{ RunCoupledMITgcmISSM: 
+if perform(org,'RunCoupledMITgcmISSM'),
+
+	%load data: 
+	loaddata(org,'Parameters');
+	loaddata(org,'ParameterizeIce');
+	loaddata(org,'Bathymetry');
+	loaddata(org,'IceSheetGeometry');
+        endtime = round(MITgcmDeltaT * ...
+         floor(time_step*y2s*async_step_MITgcm_multiplier/MITgcmDeltaT));
+
+        % {{{ prepare MITgcm 
+        % rename previous run directory and create new one
+        if exist ('run.old')
+            !\rm -rf run.old
+        end
+        if exist ('run')
+            !\mv run run.old
+        end
+        !\mkdir run
+        !\cp ../MITgcm/build/mitgcmuv run
+        !\cp ../MITgcm/input/* run
+        !\cp ../MITgcm/input/eedata_uncoupled run/eedata
+
+        % initial salinity
+        S=iniSalt*ones(Nx,Ny,Nz);
+        writebin('run/Salt.bin',S);
+
+        % initial temperature
+        T=iniTheta*ones(Nx,Ny,Nz);
+        writebin('run/Theta.bin',T);
+
+        % initial velocity
+        Z=zeros(Nx,Ny,Nz);
+        writebin('run/Uvel.bin',Z);
+        writebin('run/Vvel.bin',Z);
+
+        % initial sea surface height
+        Z=zeros(Nx,Ny);
+        writebin('run/Etan.bin',Z);
+
+        % salinity boundary conditions
+        S=obcSalt*ones(Ny,Nz);
+        thk=delZ*ones(Nz,1);
+        bot=cumsum(thk);
+        ik=find(bot<=mlDepth);
+        S(:,ik)=mlSalt;
+        writebin('run/OBs.bin',S);
+
+        % temperature boundary conditions
+        T=obcTheta*ones(Ny,Nz);
+        T(:,ik)=mlTheta;
+        writebin('run/OBt.bin',T);
+
+        % zonal velocity boundary conditions
+        U=obcUvel*ones(Ny,Nz);
+        writebin('run/OBu.bin',U);
+
+        % zero boundary conditions
+        Z=zeros(Ny,Nz);
+        writebin('run/zeros.bin',Z);
+
+        % build parameter file data.obcs
+        fidi=fopen('../MITgcm/input/data.obcs','r');
+        fido=fopen('run/data.obcs','w');
+        tline = fgetl(fidi);
+        fprintf(fido,'%s\n',tline);
+        while 1
+            tline = fgetl(fidi);
+            if ~ischar(tline), break, end
+            %do the change here: 
+            if strcmpi(tline,' OB_Iwest = 40*1,'),
+                fprintf(fido,'%s%i%s\n',' OB_Iwest = ',Ny,'*1,');
+                continue;
+            end
+            if strcmpi(tline,' OB_Ieast = 40*-1,'),
+                fprintf(fido,'%s%i%s\n',' OB_Ieast = ',Ny,'*-1,');
+                continue;
+            end
+            fprintf(fido,'%s\n',tline);
+        end
+        %close  files
+        fclose(fidi);
+        fclose(fido);
+
+        %save bathymetry in MITgcm run directory
+        writebin('run/bathymetry.bin',bathymetry);
+        % }}}
+            
+	% {{{ ISSM settings:
+
+	setenv('DYLD_LIBRARY_PATH', '/usr/local/gfortran/lib') 
+	%timestepping: 
+	md.timestepping.start_time=start_time;
+	md.timestepping.final_time=final_time;
+	md.timestepping.time_step=time_step;
+	md.cluster=generic('name',oshostname(),'np',2);
+	md.results.TransientSolution.Base=md.geometry.base;
+	md.transient.isgroundingline=1;
+	md.transient.isthermal=0;
+	md.groundingline.migration='SubelementMigration2';
+
+	% }}}
+
+	%start looping:
+	results=md.results;
+
+	for t=start_time:time_step:final_time
+            disp(['Year: ' num2str(t)])
+
+	    %send draft from ISSM to MITgcm:
+	    draft=md.results.TransientSolution(end).Base;
+	    pos=find(md.mask.ice_levelset>0); draft(pos)=0;
+            if t>start_time
+                old_draft=readbin('run/icetopo.bin',[Nx,Ny]);
+            end
+            writebin('run/icetopo.bin',draft);
+
+	    % {{{ generate MITgcm parameter file data 
+	    fidi=fopen('../MITgcm/input/data','r');
+	    fido=fopen('run/data','w');
+	    tline = fgetl(fidi);
+	    fprintf(fido,'%s\n',tline);
+            while 1
+                tline = fgetl(fidi);
+                if ~ischar(tline), break, end
+		%do the change here: 
+		if strcmpi(tline,' xgOrigin = 0.0,'),
+		    fprintf(fido,'%s%i%s\n',' xgOrigin = ',xgOrigin,',');
+		    continue;
+		end
+		if strcmpi(tline,' ygOrigin = -80.0,'),
+		    fprintf(fido,'%s%i%s\n',' ygOrigin = ',ygOrigin,',');
+		    continue;
+		end
+		if strcmpi(tline,' delX = 20*0.25,'),
+		    fprintf(fido,'%s%i*%g%s\n',' delX = ',Nx,dLong,',');
+		    continue;
+		end
+		if strcmpi(tline,' delY = 20*0.25,'),
+		    fprintf(fido,'%s%i*%g%s\n',' delY = ',Ny,dLat,',');
+		    continue;
+		end
+                if strcmpi(tline,' delZ = 30*30.0,'),
+                    fprintf(fido,'%s%i*%g%s\n',' delZ = ',Nz,delZ,',');
+                    continue;
+                end
+		if strcmpi(tline,' endTime=2592000.,'),
+		    fprintf(fido,'%s%i%s\n',' endTime= ',endtime,',');
+		    continue;
+		end
+		if strcmpi(tline,' deltaT=1200.0,'),
+		    fprintf(fido,'%s%i%s\n',' deltaT= ',MITgcmDeltaT,',');
+		    continue;
+		end
+		if strcmpi(tline,' pChkptFreq=2592000.,'),
+		    fprintf(fido,'%s%i%s\n',' pChkptFreq= ',endtime,',');
+		    continue;
+		end
+		if strcmpi(tline,' taveFreq=2592000.,'),
+		    fprintf(fido,'%s%i%s\n',' taveFreq= ',endtime,',');
+		    continue;
+		end
+                if strcmpi(tline,' rhoConst=1030.,'),
+                    fprintf(fido,'%s%i%s\n',' rhoConst= ',rho_water,',');
+                    continue;
+                end
+                if strcmpi(tline,' rhoNil=1030.,'),
+                    fprintf(fido,'%s%i%s\n',' rhoNil= ',rho_water,',');
+                    continue;
+                end
+		fprintf(fido,'%s\n',tline);
+	    end
+	    %close  files
+	    fclose(fidi);
+	    fclose(fido);
+	    % }}}
+
+	    % {{{ generate initial MITgcm conditions
+            ds=round(endtime/MITgcmDeltaT);
+            if t>start_time
+                % Read pickup file
+                fnm=['run/pickup.' myint2str(ds,10) '.data'];
+                U=readbin(fnm,[Nx Ny Nz],1,'real*8',0);
+                V=readbin(fnm,[Nx Ny Nz],1,'real*8',1);
+                T=readbin(fnm,[Nx Ny Nz],1,'real*8',2);
+                S=readbin(fnm,[Nx Ny Nz],1,'real*8',3);
+                E=readbin(fnm,[Nx Ny],1,'real*8',8*Nz);
+
+                % find indices of locations where ice shelf retreated
+                h=readbin('run/hFacC.data',[Nx Ny Nz]);
+                msk=sum(h,3);
+                msk(find(msk))=1;
+                [iw jw]=find(msk); % horizontal indices where there is water
+                tmp=reshape(draft,[Nx,Ny])-old_draft;
+                tmp(find(tmp<0))=0;
+                [im jm]=find(tmp); % horizontal indices where there is melt
+                
+                % Extrapolate T/S to locations where ice shelf retreated
+                for i=1:length(im)
+
+                    % first try vertical extrapolation
+                    in=find(h(im(i),jm(i),:));
+                    if length(in)>0;
+                        S(im(i),jm(i),1:min(in)  ) = S(im(i),jm(i),min(in));
+                        T(im(i),jm(i),1:min(in)  ) = T(im(i),jm(i),min(in));
+                        continue
+                    end
+
+                    % if not succesful, use closest neighbor horizontal extrapolation
+                    [y c]=min((iw-im(i)).^2+(jw-jm(i)).^2);
+                    salt=squeeze(S(iw(c),jw(c),:)); % salinity profile of closest neighbor
+                    temp=squeeze(T(iw(c),jw(c),:)); % salinity profile of closest neighbor
+                    in=find(h(iw(c),jw(c),:));
+                    salt(1:min(in))=salt(min(in));
+                    temp(1:min(in))=temp(min(in));
+                    salt(max(in):end)=salt(max(in));
+                    temp(max(in):end)=temp(max(in));
+                    S(im(i),jm(i),:)=salt;
+                    T(im(i),jm(i),:)=temp;
+                end
+
+                % Write initial conditions
+                writebin('run/Salt.bin' ,S);
+                writebin('run/Theta.bin',T);
+                writebin('run/Uvel.bin' ,U);
+                writebin('run/Vvel.bin' ,V);
+                writebin('run/Etan.bin' ,E);
+            end
+            % }}}
+
+            % {{{ system call to run MITgcm 
+            cd run
+            eval(['!mpiexec -np ' int2str(nPx*nPy) ' ./mitgcmuv']);
+            ts=round((t+time_step)*y2s/MITgcmDeltaT);
+            eval(['!\mv STDERR.0000 STDERR_' myint2str(ts,10) '.data'])
+            eval(['!\mv STDOUT.0000 STDOUT_' myint2str(ts,10) '.data'])
+            eval(['!\cp hFacC.data hFacC_' myint2str(ts,10) '.data'])
+            eval(['!\cp icetopo.bin icetopo_' myint2str(ts,10) '.data'])
+            for fld={'S','T','U','V','Eta', ...
+                     'SHICE_heatFluxtave','SHICE_fwFluxtave'}
+                eval(['!\mv ' fld{1} '.' myint2str(ds,10) '.data ' ...
+                      fld{1} '_' myint2str(ts,10) '.data'])
+            end
+            cd ..
+            % }}}
+
+	    %get melting rates from MITgcm
+	    %upward fresh water flux (kg/m^2/s):
+	    fnm=['run/SHICE_fwFluxtave_' myint2str(ts,10) '.data'];
+	    melting_rate=readbin(fnm,[Nx Ny]);
+
+	    %send averaged melting rate to ISSM
+	    %downward fresh water flux (m/y):
+	    melting_rate=-melting_rate(:)*y2s/rho_ice;
+		 md.basalforcings.floatingice_melting_rate=melting_rate;
+
+	    % {{{ run ISSM and recover results 
+
+	    md.timestepping.start_time=t;
+	    md.timestepping.final_time=t+time_step;;
+		md=solve(md,'Transient');
+
+		base=md.results.TransientSolution(end).Base;
+		thickness=md.results.TransientSolution(end).Thickness;
+		md.geometry.base=base;
+		md.geometry.thickness=thickness;
+		md.geometry.surface=md.geometry.base+md.geometry.thickness;
+		md.initialization.vx=md.results.TransientSolution(end).Vx;
+		md.initialization.vy=md.results.TransientSolution(end).Vy;
+		md.initialization.vel=md.results.TransientSolution(end).Vel;
+		md.initialization.pressure=md.results.TransientSolution(end).Pressure;
+		md.mask.groundedice_levelset=md.results.TransientSolution(end).MaskGroundediceLevelset;
+		md.results.TransientSolution(end).FloatingiceMeltingRate=md.basalforcings.floatingice_melting_rate;
+		
+		%save these results in the model, otherwise, they'll be wiped out
+		results(end+1)=md.results;
+
+		% }}}
+
+
+	end
+
+	md.results=results;
+	savemodel(org,md);
+end
+% }}}
+% {{{ RunCoupledMITgcmISSM2: 
+if perform(org,'RunCoupledMITgcmISSM2'),
+	
+	loaddata(org,'Parameters');
+	loaddata(org,'ParameterizeIce');
+	loaddata(org,'Bathymetry');
+	loaddata(org,'IceSheetGeometry');
+		endtime = round(MITgcmDeltaT * floor(final_time*y2s/MITgcmDeltaT));
+		outputtime = round(MITgcmDeltaT * floor(time_step*y2s/MITgcmDeltaT));
+
+        % {{{ prepare MITgcm 
+        % rename previous run directory and create new one
+        if exist ('run.old')
+            !\rm -rf run.old
+        end
+        if exist ('run')
+            !\mv run run.old
+        end
+        !\mkdir run
+        !\cp ../MITgcm/build/mitgcmuv run
+        !\cp ../MITgcm/input/* run
+
+        % initial salinity
+        S=iniSalt*ones(Nx,Ny,Nz);
+        writebin('run/Salt.bin',S);
+
+        % initial temperature
+        T=iniTheta*ones(Nx,Ny,Nz);
+        writebin('run/Theta.bin',T);
+
+        % initial velocity
+        Z=zeros(Nx,Ny,Nz);
+        writebin('run/Uvel.bin',Z);
+        writebin('run/Vvel.bin',Z);
+
+        % initial sea surface height
+        Z=zeros(Nx,Ny);
+        writebin('run/Etan.bin',Z);
+
+        % salinity boundary conditions
+        S=obcSalt*ones(Ny,Nz);
+        thk=delZ*ones(Nz,1);
+        bot=cumsum(thk);
+        ik=find(bot<=mlDepth);
+        S(:,ik)=mlSalt;
+        writebin('run/OBs.bin',S);
+
+        % temperature boundary conditions
+        T=obcTheta*ones(Ny,Nz);
+        T(:,ik)=mlTheta;
+        writebin('run/OBt.bin',T);
+
+        % zonal velocity boundary conditions
+        U=obcUvel*ones(Ny,Nz);
+        writebin('run/OBu.bin',U);
+
+        % zero boundary conditions
+        Z=zeros(Ny,Nz);
+        writebin('run/zeros.bin',Z);
+
+        % build parameter file data.obcs
+        fidi=fopen('../MITgcm/input/data.obcs','r');
+        fido=fopen('run/data.obcs','w');
+        tline = fgetl(fidi);
+        fprintf(fido,'%s\n',tline);
+        while 1
+            tline = fgetl(fidi);
+            if ~ischar(tline), break, end
+            %do the change here: 
+            if strcmpi(tline,' OB_Iwest = 40*1,'),
+                fprintf(fido,'%s%i%s\n',' OB_Iwest = ',Ny,'*1,');
+                continue;
+            end
+            if strcmpi(tline,' OB_Ieast = 40*-1,'),
+                fprintf(fido,'%s%i%s\n',' OB_Ieast = ',Ny,'*-1,');
+                continue;
+            end
+            fprintf(fido,'%s\n',tline);
+        end
+        %close  files
+        fclose(fidi);
+        fclose(fido);
+
+        %save bathymetry and bedrock in run directory
+        writebin('run/bathymetry.bin',bathymetry);
+        writebin('run/icetopo.bin',draft);
+        % }}}
+        % {{{ generate MITgcm parameter file data 
+        fidi=fopen('../MITgcm/input/data','r');
+        fido=fopen('run/data','w');
+        tline = fgetl(fidi);
+        fprintf(fido,'%s\n',tline);
+        while 1
+            tline = fgetl(fidi);
+            if ~ischar(tline), break, end
+            %do the change here: 
+            if strcmpi(tline,' xgOrigin = 0.0,'),
+                fprintf(fido,'%s%i%s\n',' xgOrigin = ',xgOrigin,',');
+                continue;
+            end
+            if strcmpi(tline,' ygOrigin = -80.0,'),
+                fprintf(fido,'%s%i%s\n',' ygOrigin = ',ygOrigin,',');
+                continue;
+            end
+            if strcmpi(tline,' delX = 20*0.25,'),
+                fprintf(fido,'%s%i*%g%s\n',' delX = ',Nx,dLong,',');
+                continue;
+            end
+            if strcmpi(tline,' delY = 20*0.25,'),
+                fprintf(fido,'%s%i*%g%s\n',' delY = ',Ny,dLat,',');
+                continue;
+            end
+            if strcmpi(tline,' delZ = 30*30.0,'),
+                fprintf(fido,'%s%i*%g%s\n',' delZ = ',Nz,delZ,',');
+                continue;
+            end
+            if strcmpi(tline,' endTime=2592000.,'),
+                fprintf(fido,'%s%i%s\n',' endTime= ',endtime,',');
+                continue;
+            end
+            if strcmpi(tline,' deltaT=1200.0,'),
+                fprintf(fido,'%s%i%s\n',' deltaT= ',MITgcmDeltaT,',');
+                continue;
+            end
+            if strcmpi(tline,' pChkptFreq=2592000.,'),
+                fprintf(fido,'%s%i%s\n',' pChkptFreq= ',endtime,',');
+                continue;
+            end
+            if strcmpi(tline,' taveFreq=2592000.,'),
+                fprintf(fido,'%s%i%s\n',' taveFreq= ',outputtime,',');
+                continue;
+            end
+            if strcmpi(tline,' rhoConst=1030.,'),
+                fprintf(fido,'%s%i%s\n',' rhoConst= ',rho_water,',');
+                continue;
+            end
+            if strcmpi(tline,' rhoNil=1030.,'),
+                fprintf(fido,'%s%i%s\n',' rhoNil= ',rho_water,',');
+                continue;
+            end
+            fprintf(fido,'%s\n',tline);
+        end
+        %close  files
+        fclose(fidi);
+        fclose(fido);
+        % }}}
+	        
+	md.transient.isoceancoupling=1;
+	md.transient.isgroundingline=1;
+	md.timestepping.coupling_time=time_step;
+   md.timestepping.time_step=time_step;
+	md.timestepping.final_time=final_time-time_step;
+	md.cluster.npocean=nPx*nPy;
+	md.cluster.executionpath=[pwd '/run'];
+	md.masstransport.requested_outputs={'default','BasalforcingsFloatingiceMeltingRate'};
+
+	md=solveiceocean(md,'Transient','runtimename',false);
+
+%	%eval(['!mpiexec -np ' int2str(md.cluster.np) ' ' md.cluster.codepath '/issm_ocean.exe TransientSolution ' pwd ' ' md.miscellaneous.name ' ']);
+%	eval(['!mpiexec -np ' int2str(md.cluster.np) ' ' md.cluster.codepath '/issm_ocean.exe TransientSolution ' pwd ' ' md.miscellaneous.name ' : -np ' int2str(nPx*nPy) ' ./mitgcmuv']);
+end
+% }}}
+
+%Fields and tolerances to track changes
+fnm=['run/SHICE_fwFluxtave.0000000006.data'];
+melting_rate_1=readbin(fnm,[Nx Ny]);
+fnm=['run/SHICE_fwFluxtave.0000000012.data'];
+melting_rate_2=readbin(fnm,[Nx Ny]);
+fnm=['run/SHICE_fwFluxtave.0000000018.data'];
+melting_rate_3=readbin(fnm,[Nx Ny]);
+fnm=['run/SHICE_fwFluxtave.0000000024.data'];
+melting_rate_4=readbin(fnm,[Nx Ny]);
+field_names     ={'Base1','Melting1','Vx2','Vy2','Thickness2','Base2','MaskGroundediceLevelset2','FloatingiceMeltingRate2',...
+	'Melting2','Vx3','Vy3','Thickness3','Base3','MaskGroundediceLevelset3','FloatingiceMeltingRate3',...
+	'Melting3','Vx4','Vy4','Thickness4','Base4','MaskGroundediceLevelset4','FloatingiceMeltingRate4','Melting4'};
+field_tolerances={2e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13, 1e-13, 1e-13, 1e-13, 1e-13, 1e-13, 1e-13,...
+	1e-13, 1e-13, 1e-13, 1e-13, 1e-13, 1e-13, 1e-13, 1e-13 };
+field_values={...
+	(md.results.TransientSolution(1).Base),...
+	(melting_rate_1(:)),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Base),...
+	(md.results.TransientSolution(2).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(2).BasalforcingsFloatingiceMeltingRate),...
+	(melting_rate_2(:)),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(3).BasalforcingsFloatingiceMeltingRate),...
+	(melting_rate_3(:)),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).Base),...
+	(md.results.TransientSolution(4).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(4).BasalforcingsFloatingiceMeltingRate),...
+	(melting_rate_4(:)),...
+	};
Index: /issm/trunk/test/NightlyRun/test404.m
===================================================================
--- /issm/trunk/test/NightlyRun/test404.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test404.m	(revision 22758)
@@ -10,5 +10,5 @@
 %Fields and tolerances to track changes
 field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={6e-07,6e-07,2e-06,1e-06,5e-07};
+field_tolerances={2e-06,9e-07,2e-06,1e-06,6e-07};
 field_values={...
 	(md.results.StressbalanceSolution.Vx),...
Index: /issm/trunk/test/NightlyRun/test404.py
===================================================================
--- /issm/trunk/test/NightlyRun/test404.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test404.py	(revision 22758)
@@ -20,5 +20,5 @@
 #Fields and tolerances to track changes
 field_names     =['Vx','Vy','Vz','Vel','Pressure']
-field_tolerances=[6e-07,6e-07,2e-06,1e-06,5e-07]
+field_tolerances=[2e-06,9e-07,2e-06,1e-06,6e-07]
 field_values=[\
 	md.results.StressbalanceSolution.Vx,\
Index: /issm/trunk/test/NightlyRun/test408.m
===================================================================
--- /issm/trunk/test/NightlyRun/test408.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test408.m	(revision 22758)
@@ -11,5 +11,4 @@
 md.friction.q=ones(md.mesh.numberofelements,1);
 md.friction.coefficientcoulomb=0.02*ones(md.mesh.numberofvertices,1);
-md=extrude(md,3,1);
 md.transient.isthermal=0;
 md.transient.isgroundingline=1;
@@ -17,4 +16,5 @@
 md.cluster=generic('name',oshostname(),'np',3);
 md.transient.requested_outputs={'default','GroundedArea','FloatingArea','TotalFloatingBmb','TotalGroundedBmb','TotalSmb'};
+md=extrude(md,3,1);
 md=solve(md,'Transient');
 
Index: /issm/trunk/test/NightlyRun/test408.py
===================================================================
--- /issm/trunk/test/NightlyRun/test408.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test408.py	(revision 22758)
@@ -24,8 +24,8 @@
 md.transient.isthermal=False
 md.transient.isgroundingline=True
-md.extrude(3,1.)
 md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',gethostname(),'np',3)
 md.transient.requested_outputs=['default','GroundedArea','FloatingArea','TotalFloatingBmb','TotalGroundedBmb','TotalSmb']
+md.extrude(3,1.)
 md=solve(md,'Transient')
 
Index: /issm/trunk/test/NightlyRun/test411.py
===================================================================
--- /issm/trunk/test/NightlyRun/test411.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test411.py	(revision 22758)
@@ -21,5 +21,5 @@
 #Fields and tolerances to track changes
 field_names     =['Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsGroundediceMeltingRate']
-field_tolerances=[1e-09,1e-09,1e-08,1e-09,1e-09,1e-08,1e-05
+field_tolerances=[2e-09,1e-09,1e-08,1e-09,1e-09,1e-08,1e-05
 ]
 field_values=[\
Index: /issm/trunk/test/NightlyRun/test421.m
===================================================================
--- /issm/trunk/test/NightlyRun/test421.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test421.m	(revision 22758)
@@ -10,5 +10,5 @@
 %Fields and tolerances to track changes
 field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={6e-07,6e-07,2e-05,6e-07,6e-07};
+field_tolerances={8e-07,6e-07,2e-05,6e-07,9e-07};
 field_values={...
 	(md.results.StressbalanceSolution.Vx),...
Index: /issm/trunk/test/NightlyRun/test421.py
===================================================================
--- /issm/trunk/test/NightlyRun/test421.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test421.py	(revision 22758)
@@ -20,5 +20,5 @@
 #Fields and tolerances to track changes
 field_names     =['Vx','Vy','Vz','Vel','Pressure']
-field_tolerances=[6e-07,6e-07,2e-05,6e-07,6e-07]
+field_tolerances=[8e-07,6e-07,2e-05,6e-07,9e-07]
 field_values=[\
 	md.results.StressbalanceSolution.Vx,\
Index: /issm/trunk/test/NightlyRun/test424.m
===================================================================
--- /issm/trunk/test/NightlyRun/test424.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test424.m	(revision 22758)
@@ -1,4 +1,4 @@
 %Test Name: SquareSheetShelfGroundingLine2dAggressive
-md=triangle(model(),'../Exp/Square.exp',150000.);
+md=triangle(model(),'../Exp/Square.exp',150000.); %was 150000.
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
@@ -14,5 +14,6 @@
 md.transient.isgroundingline=1;
 md.groundingline.migration='AggressiveMigration';
-md.transient.requested_outputs={'IceVolume','IceVolumeAboveFloatation'};
+md.mesh.scale_factor=1.1*ones(md.mesh.numberofvertices,1);
+md.transient.requested_outputs={'IceVolume','IceVolumeAboveFloatation','IceVolumeAboveFloatationScaled','GroundedArea','FloatingArea','GroundedAreaScaled','FloatingAreaScaled'};
 
 md.cluster=generic('name',oshostname(),'np',3);
@@ -20,10 +21,10 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Bed1','Surface1','Thickness1','Floatingice1','IceVolume1','IceVolumeAboveFloatation1',...
-	'Bed2','Surface2','Thickness2','Floatingice2','IceVolume2','IceVolumeAboveFloatation2',...
-	'Bed3','Surface3','Thickness3','Floatingice3','IceVolume3','IceVolumeAboveFloatation3'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
-	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
-	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_names     ={'Bed1','Surface1','Thickness1','Floatingice1','IceVolume1','IceVolumeAboveFloatation1','IceVolumeAboveFloatationScaled1','GroundedArea1','GroundedAreaScaled1','FloatingArea1','FloatingAreaScaled1',...
+	'Bed2','Surface2','Thickness2','Floatingice2','IceVolume2','IceVolumeAboveFloatation2','IceVolumeAboveFloatationScaled2','GroundedArea2','GroundedAreaScaled2','FloatingArea2','FloatingAreaScaled2',...
+	'Bed3','Surface3','Thickness3','Floatingice3','IceVolume3','IceVolumeAboveFloatation3','IceVolumeAboveFloatationScaled3','GroundedArea3','GroundedAreaScaled3','FloatingArea3','FloatingAreaScaled3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
 	(md.results.TransientSolution(1).Base),...
@@ -33,4 +34,9 @@
 	(md.results.TransientSolution(1).IceVolume),...
 	(md.results.TransientSolution(1).IceVolumeAboveFloatation),...
+	(md.results.TransientSolution(1).IceVolumeAboveFloatationScaled),...
+	(md.results.TransientSolution(1).GroundedArea),...
+	(md.results.TransientSolution(1).GroundedAreaScaled),...
+	(md.results.TransientSolution(1).FloatingArea),...
+	(md.results.TransientSolution(1).FloatingAreaScaled),...
 	(md.results.TransientSolution(2).Base),...
 	(md.results.TransientSolution(2).Surface),...
@@ -39,4 +45,9 @@
 	(md.results.TransientSolution(2).IceVolume),...
 	(md.results.TransientSolution(2).IceVolumeAboveFloatation),...
+	(md.results.TransientSolution(2).IceVolumeAboveFloatationScaled),...
+	(md.results.TransientSolution(2).GroundedArea),...
+	(md.results.TransientSolution(2).GroundedAreaScaled),...
+	(md.results.TransientSolution(2).FloatingArea),...
+	(md.results.TransientSolution(2).FloatingAreaScaled),...
 	(md.results.TransientSolution(3).Base),...
 	(md.results.TransientSolution(3).Surface),...
@@ -45,3 +56,8 @@
 	(md.results.TransientSolution(3).IceVolume),...
 	(md.results.TransientSolution(3).IceVolumeAboveFloatation),...
+	(md.results.TransientSolution(3).IceVolumeAboveFloatationScaled),...
+	(md.results.TransientSolution(3).GroundedArea),...
+	(md.results.TransientSolution(3).GroundedAreaScaled),...
+	(md.results.TransientSolution(3).FloatingArea),...
+	(md.results.TransientSolution(3).FloatingAreaScaled),...
 	};
Index: /issm/trunk/test/NightlyRun/test424.py
===================================================================
--- /issm/trunk/test/NightlyRun/test424.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test424.py	(revision 22758)
@@ -22,5 +22,6 @@
 md.transient.isgroundingline=True
 md.groundingline.migration='AggressiveMigration'
-md.transient.requested_outputs=['IceVolume','IceVolumeAboveFloatation']
+md.transient.requested_outputs=['IceVolume','IceVolumeAboveFloatation','IceVolumeAboveFloatationScaled','GroundedArea','FloatingArea','GroundedAreaScaled','FloatingAreaScaled']
+md.mesh.scale_factor=1.1*np.ones((md.mesh.numberofvertices))
 
 md.cluster=generic('name',gethostname(),'np',3)
@@ -28,10 +29,10 @@
 
 #Fields and tolerances to track changes
-field_names     =['Bed1','Surface1','Thickness1','Floatingice1','IceVolume1','IceVolumeAboveFloatation1',
-									'Bed2','Surface2','Thickness2','Floatingice2','IceVolume2','IceVolumeAboveFloatation2',
-									'Bed3','Surface3','Thickness3','Floatingice3','IceVolume3','IceVolumeAboveFloatation3']
-field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,
-									1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,
-									1e-13,1e-13,1e-13,1e-13,1e-13,1e-13]
+field_names     =['Bed1','Surface1','Thickness1','Floatingice1','IceVolume1','IceVolumeAboveFloatation1','IceVolumeAboveFloatationScaled1','GroundedArea1','GroundedAreaScaled1','FloatingArea1','FloatingAreaScaled1',
+									'Bed2','Surface2','Thickness2','Floatingice2','IceVolume2','IceVolumeAboveFloatation2','IceVolumeAboveFloatationScaled2','GroundedAred2','GroundedAreaScaled2','FloatingArea2','FloatingAreaScaled2',
+									'Bed3','Surface3','Thickness3','Floatingice3','IceVolume3','IceVolumeAboveFloatation3','IceVolumeAboveFloatationScaled3','GroundedArea3','GroundedAreaScaled3','FloatingArea3','FloatingAreaScaled3']
+field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,
+									1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,
+									1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13]
 field_values=[md.results.TransientSolution[0].Base,
 							md.results.TransientSolution[0].Surface,
@@ -40,4 +41,9 @@
 							md.results.TransientSolution[0].IceVolume,
 							md.results.TransientSolution[0].IceVolumeAboveFloatation,
+							md.results.TransientSolution[0].IceVolumeAboveFloatationScaled,
+							md.results.TransientSolution[0].GroundedArea,
+							md.results.TransientSolution[0].GroundedAreaScaled,
+							md.results.TransientSolution[0].FloatingArea,
+							md.results.TransientSolution[0].FloatingAreaScaled,
 							md.results.TransientSolution[1].Base,
 							md.results.TransientSolution[1].Surface,
@@ -46,4 +52,9 @@
 							md.results.TransientSolution[1].IceVolume,
 							md.results.TransientSolution[1].IceVolumeAboveFloatation,
+							md.results.TransientSolution[1].IceVolumeAboveFloatationScaled,
+							md.results.TransientSolution[1].GroundedArea,
+							md.results.TransientSolution[1].GroundedAreaScaled,
+							md.results.TransientSolution[1].FloatingArea,
+							md.results.TransientSolution[1].FloatingAreaScaled,
 							md.results.TransientSolution[2].Base,
 							md.results.TransientSolution[2].Surface,
@@ -51,3 +62,8 @@
 							md.results.TransientSolution[2].MaskGroundediceLevelset,
 							md.results.TransientSolution[2].IceVolume,
-							md.results.TransientSolution[2].IceVolumeAboveFloatation]
+							md.results.TransientSolution[2].IceVolumeAboveFloatation,
+							md.results.TransientSolution[2].IceVolumeAboveFloatationScaled,
+							md.results.TransientSolution[2].GroundedArea,
+							md.results.TransientSolution[2].GroundedAreaScaled,
+							md.results.TransientSolution[2].FloatingArea,
+							md.results.TransientSolution[2].FloatingAreaScaled]
Index: /issm/trunk/test/NightlyRun/test426.m
===================================================================
--- /issm/trunk/test/NightlyRun/test426.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test426.m	(revision 22758)
@@ -10,10 +10,11 @@
 md.geometry.surface=md.geometry.base+md.geometry.thickness;
 md.smb.mass_balance(:)=100.;
-md=extrude(md,3,1.);
 md=setflowequation(md,'SSA','all');
 md.transient.isstressbalance=0;
 md.transient.isgroundingline=1;
 md.groundingline.migration='AggressiveMigration';
-md.transient.requested_outputs={'IceVolume','IceVolumeAboveFloatation'};
+md.mesh.scale_factor=1.1*ones(md.mesh.numberofvertices,1);
+md.transient.requested_outputs={'IceVolume','IceVolumeAboveFloatation','IceVolumeAboveFloatationScaled','GroundedArea','FloatingArea','GroundedAreaScaled','FloatingAreaScaled','IceMass'};
+md=extrude(md,3,1.);
 md.cluster=generic('name',oshostname(),'np',3);
 
@@ -21,10 +22,10 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Bed1','Surface1','Thickness1','Floatingice1','IceVolume1','IceVolumeAboveFloatation1',...
-	'Bed2','Surface2','Thickness2','Floatingice2','IceVolume2','IceVolumeAboveFloatation2',...
-	'Bed3','Surface3','Thickness3','Floatingice3','IceVolume3','IceVolumeAboveFloatation3'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
-	1e-11,1e-10,1e-11,3e-11,2e-12,5e-12,...
-	1e-10,1e-10,1e-10,5e-11,2e-12,5e-12};
+field_names     ={'Bed1','Surface1','Thickness1','Floatingice1','IceVolume1','IceVolumeAboveFloatation1','IceMass1','IceVolumeAboveFloatationScaled1','GroundedArea1','GroundedAreaScaled1','FloatingArea1','FloatingAreaScaled1',...
+	'Bed2','Surface2','Thickness2','Floatingice2','IceVolume2','IceVolumeAboveFloatation2','IceMass2','IceVolumeAboveFloatationScaled2','GroundedArea2','GroundedAreaScaled2','FloatingArea2','FloatingAreaScaled2',...
+	'Bed3','Surface3','Thickness3','Floatingice3','IceVolume3','IceVolumeAboveFloatation3','IceMass3','IceVolumeAboveFloatationScaled3','GroundedArea3','GroundedAreaScaled3','FloatingArea3','FloatingAreaScaled3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-11,1e-10,2e-11,3e-11,2e-12,6e-12,2e-12,6e-12,2e-12,2e-12,6e-12,6e-12,...
+	1e-10,1e-10,1e-10,5e-11,2e-12,5e-12,2e-12,5e-12,5e-11,7e-12,7e-11,7e-11};
 field_values={...
 	(md.results.TransientSolution(1).Base),...
@@ -34,4 +35,10 @@
 	(md.results.TransientSolution(1).IceVolume),...
 	(md.results.TransientSolution(1).IceVolumeAboveFloatation),...
+	(md.results.TransientSolution(1).IceMass),...
+	(md.results.TransientSolution(1).IceVolumeAboveFloatationScaled),...
+	(md.results.TransientSolution(1).GroundedArea),...
+	(md.results.TransientSolution(1).GroundedAreaScaled),...
+	(md.results.TransientSolution(1).FloatingArea),...
+	(md.results.TransientSolution(1).FloatingAreaScaled),...
 	(md.results.TransientSolution(2).Base),...
 	(md.results.TransientSolution(2).Surface),...
@@ -40,4 +47,10 @@
 	(md.results.TransientSolution(2).IceVolume),...
 	(md.results.TransientSolution(2).IceVolumeAboveFloatation),...
+	(md.results.TransientSolution(2).IceMass),...
+	(md.results.TransientSolution(2).IceVolumeAboveFloatationScaled),...
+	(md.results.TransientSolution(2).GroundedArea),...
+	(md.results.TransientSolution(2).GroundedAreaScaled),...
+	(md.results.TransientSolution(2).FloatingArea),...
+	(md.results.TransientSolution(2).FloatingAreaScaled),...
 	(md.results.TransientSolution(3).Base),...
 	(md.results.TransientSolution(3).Surface),...
@@ -46,3 +59,9 @@
 	(md.results.TransientSolution(3).IceVolume),...
 	(md.results.TransientSolution(3).IceVolumeAboveFloatation),...
+	(md.results.TransientSolution(3).IceMass),...
+	(md.results.TransientSolution(3).IceVolumeAboveFloatationScaled),...
+	(md.results.TransientSolution(3).GroundedArea),...
+	(md.results.TransientSolution(3).GroundedAreaScaled),...
+	(md.results.TransientSolution(3).FloatingArea),...
+	(md.results.TransientSolution(3).FloatingAreaScaled),...
 	};
Index: /issm/trunk/test/NightlyRun/test426.py
===================================================================
--- /issm/trunk/test/NightlyRun/test426.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test426.py	(revision 22758)
@@ -18,10 +18,11 @@
 md.geometry.surface=md.geometry.base+md.geometry.thickness
 md.smb.mass_balance[:]=100.
-md.extrude(3,1.)
 md=setflowequation(md,'SSA','all')
 md.transient.isstressbalance=False
 md.transient.isgroundingline=True
 md.groundingline.migration='AggressiveMigration'
-md.transient.requested_outputs=['IceVolume','IceVolumeAboveFloatation']
+md.transient.requested_outputs=['IceVolume','IceVolumeAboveFloatation','IceMass','IceVolumeAboveFloatationScaled','GroundedArea','FloatingArea','GroundedAreaScaled','FloatingAreaScaled']
+md.mesh.scale_factor=1.1*np.ones((md.mesh.numberofvertices))
+md.extrude(3,1.)
 md.cluster=generic('name',gethostname(),'np',3)
 
@@ -29,28 +30,46 @@
 
 #Fields and tolerances to track changes
-field_names     =['Bed1','Surface1','Thickness1','Floatingice1','IceVolume1','IceVolumeAboveFloatation1',
-									'Bed2','Surface2','Thickness2','Floatingice2','IceVolume2','IceVolumeAboveFloatation2',
-									'Bed3','Surface3','Thickness3','Floatingice3','IceVolume3','IceVolumeAboveFloatation3',]
+field_names     =['Bed1','Surface1','Thickness1','Floatingice1','IceVolume1','IceVolumeAboveFloatation1','IceMass1','IceVolumeAboveFloatationScaled1','GroundedArea1','GroundedAreaScaled1','FloatingArea1','FloatingAreaScaled1',
+        'Bed2','Surface2','Thickness2','Floatingice2','IceVolume2','IceVolumeAboveFloatation2','IceMass2','IceVolumeAboveFloatationScaled2','GroundedArea2','GroundedAreaScaled2','FloatingArea2','FloatingAreaScaled2',
+        'Bed3','Surface3','Thickness3','Floatingice3','IceVolume3','IceVolumeAboveFloatation3','IceMass3','IceVolumeAboveFloatationScaled3','GroundedArea3','GroundedAreaScaled3','FloatingArea3','FloatingAreaScaled3']
 
-field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,
-									1e-11,1e-10,1e-11,3e-11,2e-12,5e-12,
-									1e-10,1e-10,1e-10,5e-11,2e-12,5e-12]
+field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,
+        1e-11,1e-10,2e-11,3e-11,2e-12,6e-12,2e-12,6e-12,2e-12,2e-12,6e-12,6e-12,
+        1e-10,1e-10,1e-10,5e-11,2e-12,5e-12,2e-12,5e-12,5e-11,7e-12,7e-11,7e-11]
 
 field_values=[md.results.TransientSolution[0].Base,
-							md.results.TransientSolution[0].Surface,
-							md.results.TransientSolution[0].Thickness,
-							md.results.TransientSolution[0].MaskGroundediceLevelset,
-							md.results.TransientSolution[0].IceVolume,
-							md.results.TransientSolution[0].IceVolumeAboveFloatation,
-							md.results.TransientSolution[1].Base,
-							md.results.TransientSolution[1].Surface,
-							md.results.TransientSolution[1].Thickness,
-							md.results.TransientSolution[1].MaskGroundediceLevelset,
-							md.results.TransientSolution[1].IceVolume,
-							md.results.TransientSolution[1].IceVolumeAboveFloatation,
-							md.results.TransientSolution[2].Base,
-							md.results.TransientSolution[2].Surface,
-							md.results.TransientSolution[2].Thickness,
-							md.results.TransientSolution[2].MaskGroundediceLevelset,
-							md.results.TransientSolution[2].IceVolume,
-							md.results.TransientSolution[2].IceVolumeAboveFloatation]
+        md.results.TransientSolution[0].Surface,
+        md.results.TransientSolution[0].Thickness,
+        md.results.TransientSolution[0].MaskGroundediceLevelset,
+        md.results.TransientSolution[0].IceVolume,
+        md.results.TransientSolution[0].IceVolumeAboveFloatation,
+	md.results.TransientSolution[0].IceMass,
+	md.results.TransientSolution[0].IceVolumeAboveFloatationScaled,
+	md.results.TransientSolution[0].GroundedArea,
+	md.results.TransientSolution[0].GroundedAreaScaled,
+	md.results.TransientSolution[0].FloatingArea,
+	md.results.TransientSolution[0].FloatingAreaScaled,
+        md.results.TransientSolution[1].Base,
+        md.results.TransientSolution[1].Surface,
+        md.results.TransientSolution[1].Thickness,
+        md.results.TransientSolution[1].MaskGroundediceLevelset,
+        md.results.TransientSolution[1].IceVolume,
+        md.results.TransientSolution[1].IceVolumeAboveFloatation,
+	md.results.TransientSolution[1].IceMass,
+	md.results.TransientSolution[1].IceVolumeAboveFloatationScaled,
+	md.results.TransientSolution[1].GroundedArea,
+	md.results.TransientSolution[1].GroundedAreaScaled,
+	md.results.TransientSolution[1].FloatingArea,
+	md.results.TransientSolution[1].FloatingAreaScaled,
+        md.results.TransientSolution[2].Base,
+        md.results.TransientSolution[2].Surface,
+        md.results.TransientSolution[2].Thickness,
+        md.results.TransientSolution[2].MaskGroundediceLevelset,
+        md.results.TransientSolution[2].IceVolume,
+        md.results.TransientSolution[2].IceVolumeAboveFloatation,
+	md.results.TransientSolution[2].IceMass,
+	md.results.TransientSolution[2].IceVolumeAboveFloatationScaled,
+	md.results.TransientSolution[2].GroundedArea,
+	md.results.TransientSolution[2].GroundedAreaScaled,
+	md.results.TransientSolution[2].FloatingArea,
+	md.results.TransientSolution[2].FloatingAreaScaled]
Index: /issm/trunk/test/NightlyRun/test427.m
===================================================================
--- /issm/trunk/test/NightlyRun/test427.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test427.m	(revision 22758)
@@ -24,5 +24,5 @@
 	'Bed3','Surface3','Thickness3','Floatingice3'};
 field_tolerances={1e-13,1e-13,1e-13,1e-13,...
-	5e-12,3e-12,7e-12,2e-11,...
+	5e-12,4e-12,7e-12,2e-11,...
 	1e-10,5e-11,1e-10,7e-10};
 field_values={...
Index: /issm/trunk/test/NightlyRun/test427.py
===================================================================
--- /issm/trunk/test/NightlyRun/test427.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test427.py	(revision 22758)
@@ -32,5 +32,5 @@
 									'Bed3','Surface3','Thickness3','Floatingice3']
 field_tolerances=[1e-13,1e-13,1e-13,1e-13,
-									5e-12,3e-12,7e-12,2e-11,
+									5e-12,4e-12,7e-12,2e-11,
 									1e-10,5e-11,1e-10,7e-10]
 field_values=[md.results.TransientSolution[0].Base,
Index: /issm/trunk/test/NightlyRun/test430.m
===================================================================
--- /issm/trunk/test/NightlyRun/test430.m	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test430.m	(revision 22758)
@@ -0,0 +1,80 @@
+%Test Name: MISMIP3D
+md=triangle(model(),'../Exp/Square.exp',100000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md.initialization.vx(:)=1.;
+md.initialization.vy(:)=1.;
+md.geometry.thickness(:)=500-md.mesh.x/10000;
+md.geometry.bed =-100-md.mesh.x/1000;
+md.geometry.base=-md.geometry.thickness*md.materials.rho_ice/md.materials.rho_water;
+md.mask.groundedice_levelset=md.geometry.thickness+md.materials.rho_water/md.materials.rho_ice*md.geometry.bed;
+pos=find(md.mask.groundedice_levelset>=0);
+md.geometry.base(pos)=md.geometry.bed(pos);
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+md=setflowequation(md,'SSA','all');
+
+%Boundary conditions:
+md.mask.ice_levelset=-ones(md.mesh.numberofvertices,1);
+md.mask.ice_levelset(find(md.mesh.x==max(md.mesh.x)))=0;
+md.stressbalance.spcvx(:)=NaN;
+md.stressbalance.spcvy(:)=NaN;
+md.stressbalance.spcvz(:)=NaN;
+pos=find((md.mesh.y<1000000.1 & md.mesh.y>999999.9) | (md.mesh.y<0.1 & md.mesh.y>-0.1));
+md.stressbalance.spcvy(pos)=0;
+pos2=find(md.mesh.x<0.1 & md.mesh.x>-0.1);
+md.stressbalance.spcvx(pos2)=0;
+md.stressbalance.spcvy(pos2)=0;
+
+md.materials.rheology_B=1/((10^-25)^(1/3))*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_law='None';
+md.friction.coefficient(:)=sqrt(10^7)*ones(md.mesh.numberofvertices,1);
+md.friction.p=3*ones(md.mesh.numberofelements,1);
+md.smb.mass_balance(:)=1;
+md.basalforcings.groundedice_melting_rate(:)=0;
+md.basalforcings.floatingice_melting_rate(:)=30;
+md.transient.isthermal=0;
+md.transient.isstressbalance=1;
+md.transient.isgroundingline=1;
+md.transient.ismasstransport=1;
+md.transient.issmb=1;
+md.transient.requested_outputs={'default','BasalforcingsFloatingiceMeltingRate'};
+md.groundingline.migration='SubelementMigration';
+md.timestepping.final_time=30;
+md.timestepping.time_step=10;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,'Transient');
+
+%Fields and tolerances to track changes
+field_names     ={'Bed1','Surface1','Thickness1','Floatingice1','Vx1','Vy1','Pressure1','FloatingiceMeltingrate1',...
+	'Bed2','Surface2','Thickness2','Floatingice2','Vx2','Vy2','Pressure2','FloatingiceMeltingrate2',...
+	'Bed3','Surface3','Thickness3','Floatingice3','Vx3','Vy3','Pressure3','FloatingiceMeltingrate3'};
+field_tolerances={2e-11,5e-12,2e-11,1e-11,5e-10,1e-08,1e-13,1e-13,...
+	3e-11,3e-11,9e-10,7e-11,1e-09,5e-08,1e-10,1e-13,...
+	1e-10,3e-11,1e-10,7e-11,1e-09,5e-08,1e-10,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).BasalforcingsFloatingiceMeltingRate),...
+	(md.results.TransientSolution(2).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).BasalforcingsFloatingiceMeltingRate),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).BasalforcingsFloatingiceMeltingRate),...
+	};
Index: /issm/trunk/test/NightlyRun/test430.py
===================================================================
--- /issm/trunk/test/NightlyRun/test430.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test430.py	(revision 22758)
@@ -0,0 +1,95 @@
+#Test Name: MISMIP3D
+import numpy as np
+from model import *
+from socket import gethostname
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md = triangle(model(),'../Exp/Square.exp',100000.)
+md = setmask(md,'../Exp/SquareShelf.exp','')
+md = parameterize(md,'../Par/SquareSheetShelf.py')
+md.initialization.vx[:] = 1.
+md.initialization.vy[:] = 1.
+md.geometry.thickness[:] = 500. - md.mesh.x / 10000.
+md.geometry.bed = -100. - md.mesh.x / 1000.
+md.geometry.base = -md.geometry.thickness * md.materials.rho_ice / md.materials.rho_water
+md.mask.groundedice_levelset = md.geometry.thickness + md.materials.rho_water / md.materials.rho_ice * md.geometry.bed
+pos = np.where(md.mask.groundedice_levelset >= 0.)
+md.geometry.base[pos] = md.geometry.bed[pos]
+md.geometry.surface = md.geometry.base + md.geometry.thickness
+md = setflowequation(md,'SSA','all')
+
+#Boundary conditions:
+md.mask.ice_levelset = -np.ones((md.mesh.numberofvertices,))
+md.mask.ice_levelset[np.where(md.mesh.x == max(md.mesh.x))] = 0.
+md.stressbalance.spcvx[:] = float('NaN')
+md.stressbalance.spcvy[:] = float('NaN')
+md.stressbalance.spcvz[:] = float('NaN')
+posA = np.intersect1d(np.array(np.where(md.mesh.y < 1000000.1)),np.array(np.where(md.mesh.y > 999999.9)))
+posB = np.intersect1d(np.array(np.where(md.mesh.y < 0.1)),np.array(np.where(md.mesh.y > -0.1)))
+pos = np.unique(np.concatenate((posA,posB)))
+md.stressbalance.spcvy[pos] = 0.
+pos2 = np.intersect1d(np.array(np.where(md.mesh.x < 0.1)), np.array(np.where(md.mesh.x > -0.1)))
+md.stressbalance.spcvx[pos2] = 0.
+md.stressbalance.spcvy[pos2] = 0.
+
+md.materials.rheology_B = 1. / ((10**-25)**(1. / 3.)) * np.ones((md.mesh.numberofvertices,))
+md.materials.rheology_law = 'None'
+md.friction.coefficient[:] = np.sqrt(10**7) * np.ones((md.mesh.numberofvertices,))
+md.friction.p = 3. * np.ones((md.mesh.numberofelements,))
+md.smb.mass_balance[:] = 1.
+md.basalforcings.groundedice_melting_rate[:] = 0.
+md.basalforcings.floatingice_melting_rate[:] = 30.
+md.transient.isthermal = 0
+md.transient.isstressbalance = 1
+md.transient.isgroundingline = 1
+md.transient.ismasstransport = 1
+md.transient.issmb = 1
+md.transient.requested_outputs = ['default','BasalforcingsFloatingiceMeltingRate']
+md.groundingline.migration = 'SubelementMigration'
+md.timestepping.final_time = 30
+md.timestepping.time_step = 10
+
+md.cluster = generic('name',gethostname(),'np',3)
+md = solve(md,'Transient')
+#print md.results.TransientSolution[0].BasalforcingsFloatingiceMeltingRate
+#print md.results.TransientSolution[1].BasalforcingsFloatingiceMeltingRate
+#print md.results.TransientSolution[2].BasalforcingsFloatingiceMeltingRate
+
+#Fields and tolerances to track changes
+field_names     = [
+	'Bed1','Surface1','Thickness1','Floatingice1','Vx1','Vy1','Pressure1','FloatingiceMeltingrate1',
+	'Bed2','Surface2','Thickness2','Floatingice2','Vx2','Vy2','Pressure2','FloatingiceMeltingrate2',
+	'Bed3','Surface3','Thickness3','Floatingice3','Vx3','Vy3','Pressure3','FloatingiceMeltingrate3']
+field_tolerances = [2e-11,5e-12,2e-11,1e-11,5e-10,1e-08,1e-13,1e-13,
+	3e-11,3e-11,9e-10,7e-11,1e-09,5e-08,1e-10,1e-13,
+	1e-10,3e-11,1e-10,7e-11,1e-09,5e-08,1e-10,1e-13]
+field_values = [
+	md.results.TransientSolution[0].Base,
+	md.results.TransientSolution[0].Surface,
+	md.results.TransientSolution[0].Thickness,
+	md.results.TransientSolution[0].MaskGroundediceLevelset,
+	md.results.TransientSolution[0].Vx,
+	md.results.TransientSolution[0].Vy,
+	md.results.TransientSolution[0].Pressure,
+	md.results.TransientSolution[0].BasalforcingsFloatingiceMeltingRate,
+	md.results.TransientSolution[1].Base,
+	md.results.TransientSolution[1].Surface,
+	md.results.TransientSolution[1].Thickness,
+	md.results.TransientSolution[1].MaskGroundediceLevelset,
+	md.results.TransientSolution[1].Vx,
+	md.results.TransientSolution[1].Vy,
+	md.results.TransientSolution[1].Pressure,
+	md.results.TransientSolution[1].BasalforcingsFloatingiceMeltingRate,
+	md.results.TransientSolution[2].Base,
+	md.results.TransientSolution[2].Surface,
+	md.results.TransientSolution[2].Thickness,
+	md.results.TransientSolution[2].MaskGroundediceLevelset,
+	md.results.TransientSolution[2].Vx,
+	md.results.TransientSolution[2].Vy,
+	md.results.TransientSolution[2].Pressure,
+	md.results.TransientSolution[2].BasalforcingsFloatingiceMeltingRate,
+	]
Index: /issm/trunk/test/NightlyRun/test435.m
===================================================================
--- /issm/trunk/test/NightlyRun/test435.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test435.m	(revision 22758)
@@ -33,5 +33,5 @@
 md.smb.mass_balance(:)=1;
 md.basalforcings.groundedice_melting_rate(:)=0;
-md.basalforcings.floatingice_melting_rate(:)=0;
+md.basalforcings.floatingice_melting_rate(:)=30;
 md.transient.isthermal=0;
 md.transient.isstressbalance=1;
@@ -39,4 +39,5 @@
 md.transient.ismasstransport=1;
 md.transient.issmb=1;
+md.transient.requested_outputs={'default','BasalforcingsFloatingiceMeltingRate'};
 md.groundingline.migration='SubelementMigration';
 md.timestepping.final_time=30;
@@ -47,10 +48,12 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Bed1','Surface1','Thickness1','Floatingice1','Vx1','Vy1','Vz1','Pressure1',...
-	'Bed2','Surface2','Thickness2','Floatingice2','Vx2','Vy2','Vz2','Pressure2',...
-	'Bed3','Surface3','Thickness3','Floatingice3','Vx3','Vy3','Vz3','Pressure3'};
-field_tolerances={2e-11,5e-12,2e-11,1e-11,5e-10,1e-08,6e-10,1e-13,...
-	3e-11,3e-11,9e-10,7e-11,1e-09,5e-08,1e-09,1e-10,...
-	1e-10,3e-11,1e-10,7e-11,1e-09,5e-08,1e-09,1e-10};
+field_names     ={...
+	'Bed1','Surface1','Thickness1','Floatingice1','Vx1','Vy1','Vz1','Pressure1','FloatingiceMeltingrate1',...
+	'Bed2','Surface2','Thickness2','Floatingice2','Vx2','Vy2','Vz2','Pressure2','FloatingiceMeltingrate2',...
+	'Bed3','Surface3','Thickness3','Floatingice3','Vx3','Vy3','Vz3','Pressure3','FloatingiceMeltingrate3',};
+field_tolerances={...
+	2e-11,5e-12,2e-11,1e-11,7e-10,3e-08,6e-10,1e-13,1e-13,...
+	3e-11,3e-11,9e-10,7e-11,6e-09,2e-07,1e-09,1e-10,1e-13,...
+	1e-9,2e-08,7e-09,2e-7 ,1e-03,8e-04,2e-09,1e-10,1e-13};
 field_values={...
 	(md.results.TransientSolution(1).Base),...
@@ -62,4 +65,5 @@
 	(md.results.TransientSolution(1).Vz),...
 	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).BasalforcingsFloatingiceMeltingRate),...
 	(md.results.TransientSolution(2).Base),...
 	(md.results.TransientSolution(2).Surface),...
@@ -70,4 +74,5 @@
 	(md.results.TransientSolution(2).Vz),...
 	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).BasalforcingsFloatingiceMeltingRate),...
 	(md.results.TransientSolution(3).Base),...
 	(md.results.TransientSolution(3).Surface),...
@@ -78,3 +83,4 @@
 	(md.results.TransientSolution(3).Vz),...
 	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).BasalforcingsFloatingiceMeltingRate),...
 	};
Index: /issm/trunk/test/NightlyRun/test435.py
===================================================================
--- /issm/trunk/test/NightlyRun/test435.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test435.py	(revision 22758)
@@ -0,0 +1,97 @@
+#Test Name: MISMIP3DHO
+import numpy as np
+from model import *
+from socket import gethostname
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md = triangle(model(),'../Exp/Square.exp',100000.)
+md = setmask(md,'../Exp/SquareShelf.exp','')
+md = parameterize(md,'../Par/SquareSheetShelf.py')
+md.initialization.vx[:] = 1.
+md.initialization.vy[:] = 1.
+md.geometry.thickness[:] = 500. - md.mesh.x / 10000.
+md.geometry.bed = -100. - md.mesh.x / 1000.
+md.geometry.base = -md.geometry.thickness * md.materials.rho_ice / md.materials.rho_water
+md.mask.groundedice_levelset = md.geometry.thickness + md.materials.rho_water / md.materials.rho_ice * md.geometry.bed
+pos = np.where(md.mask.groundedice_levelset >= 0)
+md.geometry.base[pos] = md.geometry.bed[pos]
+md.geometry.surface = md.geometry.base + md.geometry.thickness
+md = md.extrude(4,1.)
+md = setflowequation(md,'HO','all')
+
+#Boundary conditions:
+md.mask.ice_levelset = -np.ones((md.mesh.numberofvertices,))
+md.mask.ice_levelset[np.where(md.mesh.x == max(md.mesh.x))] = 0.
+md.stressbalance.spcvx[:] = float('Nan')
+md.stressbalance.spcvy[:] = float('Nan')
+md.stressbalance.spcvz[:] = float('Nan')
+posA = np.intersect1d(np.array(np.where(md.mesh.y < 1000000.1)),np.array(np.where(md.mesh.y > 999999.9)))
+posB = np.intersect1d(np.array(np.where(md.mesh.y < 0.1)),np.array(np.where(md.mesh.y > -0.1)))
+pos = np.unique(np.concatenate((posA,posB)))
+md.stressbalance.spcvy[pos] = 0.
+pos2 = np.intersect1d(np.array(np.where(md.mesh.x < 0.1)), np.array(np.where(md.mesh.x > -0.1)))
+md.stressbalance.spcvx[pos2] = 0.
+md.stressbalance.spcvy[pos2] = 0.
+
+md.materials.rheology_B = 1. / ((10**-25)**(1./3.)) * np.ones((md.mesh.numberofvertices,))
+md.materials.rheology_law = 'None'
+md.friction.coefficient[:] = np.sqrt(1e7) * np.ones((md.mesh.numberofvertices,))
+md.friction.p = 3. * np.ones((md.mesh.numberofelements,))
+md.smb.mass_balance[:] = 1.
+md.basalforcings.groundedice_melting_rate[:] = 0.
+md.basalforcings.floatingice_melting_rate[:] = 30.
+md.transient.isthermal = 0
+md.transient.isstressbalance = 1
+md.transient.isgroundingline = 1
+md.transient.ismasstransport = 1
+md.transient.issmb = 1
+md.transient.requested_outputs = ['default','BasalforcingsFloatingiceMeltingRate']
+md.groundingline.migration = 'SubelementMigration'
+md.timestepping.final_time = 30
+md.timestepping.time_step = 10
+
+md.cluster = generic('name',gethostname(),'np',3)
+md = solve(md,'Transient')
+
+#Fields and tolerances to track changes
+field_names     = [
+	'Bed1','Surface1','Thickness1','Floatingice1','Vx1','Vy1','Vz1','Pressure1','FloatingiceMeltingrate1',
+	'Bed2','Surface2','Thickness2','Floatingice2','Vx2','Vy2','Vz2','Pressure2','FloatingiceMeltingrate2',
+	'Bed3','Surface3','Thickness3','Floatingice3','Vx3','Vy3','Vz3','Pressure3','FloatingiceMeltingrate3']
+field_tolerances = [
+	2e-11,5e-12,2e-11,1e-11,7e-10,3e-08,6e-10,1e-13,1e-13,
+	3e-11,3e-11,9e-10,7e-11,9e-09,2e-07,1e-09,1e-10,1e-13,
+	1e-9,2e-08,7e-09,2e-7 ,1e-03,8e-04,2e-09,1e-10,1e-13]
+field_values = [
+	md.results.TransientSolution[0].Base,
+	md.results.TransientSolution[0].Surface,
+	md.results.TransientSolution[0].Thickness,
+	md.results.TransientSolution[0].MaskGroundediceLevelset,
+	md.results.TransientSolution[0].Vx,
+	md.results.TransientSolution[0].Vy,
+	md.results.TransientSolution[0].Vz,
+	md.results.TransientSolution[0].Pressure,
+	md.results.TransientSolution[0].BasalforcingsFloatingiceMeltingRate,
+	md.results.TransientSolution[1].Base,
+	md.results.TransientSolution[1].Surface,
+	md.results.TransientSolution[1].Thickness,
+	md.results.TransientSolution[1].MaskGroundediceLevelset,
+	md.results.TransientSolution[1].Vx,
+	md.results.TransientSolution[1].Vy,
+	md.results.TransientSolution[1].Vz,
+	md.results.TransientSolution[1].Pressure,
+	md.results.TransientSolution[1].BasalforcingsFloatingiceMeltingRate,
+	md.results.TransientSolution[2].Base,
+	md.results.TransientSolution[2].Surface,
+	md.results.TransientSolution[2].Thickness,
+	md.results.TransientSolution[2].MaskGroundediceLevelset,
+	md.results.TransientSolution[2].Vx,
+	md.results.TransientSolution[2].Vy,
+	md.results.TransientSolution[2].Vz,
+	md.results.TransientSolution[2].Pressure,
+	md.results.TransientSolution[2].BasalforcingsFloatingiceMeltingRate,
+	]
Index: /issm/trunk/test/NightlyRun/test436.m
===================================================================
--- /issm/trunk/test/NightlyRun/test436.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test436.m	(revision 22758)
@@ -23,5 +23,5 @@
 	field_names     ={field_names{:},['Vx' i{1}],['Vy' i{1}],['Vz' i{1}],['Vel' i{1}],['Pressure' i{1}],...
 		['Temperature' i{1}],['Waterfraction' i{1}],['Enthalpy' i{1}]};
-	field_tolerances={field_tolerances{:},2e-09,1e-09,1e-09,1e-09,1e-13,1e-10,5e-10,5e-10};
+	field_tolerances={field_tolerances{:},2e-09,1e-09,1e-09,1e-09,1e-13,1e-10,6e-10,1e-9};
 	field_values={field_values{:},...
 		(md.results.SteadystateSolution.Vx),...
Index: /issm/trunk/test/NightlyRun/test436.py
===================================================================
--- /issm/trunk/test/NightlyRun/test436.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test436.py	(revision 22758)
@@ -0,0 +1,45 @@
+#Test Name: SquareSheetShelfSteaEnthalpyRheologiesHO
+import numpy as np
+from model import *
+from socket import gethostname
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md = triangle(model(),'../Exp/Square.exp',150000.)
+md = setmask(md,'../Exp/SquareShelf.exp','')
+md = parameterize(md,'../Par/SquareSheetShelf.py')
+md = md.extrude(3,2.)
+md = setflowequation(md,'HO','all')
+md.cluster = generic('name',gethostname(),'np',3)
+md.timestepping.time_step = 0.
+md.thermal.isenthalpy = 1
+md.initialization.waterfraction = np.zeros((md.mesh.numberofvertices,))
+md.initialization.watercolumn = np.zeros((md.mesh.numberofvertices,))
+
+#Go solve
+field_names = []
+field_tolerances = []
+field_values = []
+for i in ['LliboutryDuval', 'CuffeyTemperate']:
+	print ' '
+	print '====== Testing rheology law: ' + i + ' ====='
+
+	md.materials.rheology_law = i
+	md = solve(md,'Steadystate')
+	field_names += ['Vx'+i,'Vy'+i,'Vz'+i,'Vel'+i,'Pressure'+i,
+		'Temperature'+i,'Waterfraction'+i,'Enthalpy'+i]
+	field_tolerances += [2e-09,1e-09,1e-09,1e-09,1e-13,1e-10,6e-10,1e-9]
+	field_values += [
+		md.results.SteadystateSolution.Vx,
+		md.results.SteadystateSolution.Vy,
+		md.results.SteadystateSolution.Vz,
+		md.results.SteadystateSolution.Vel,
+		md.results.SteadystateSolution.Pressure,
+		md.results.SteadystateSolution.Temperature,
+		md.results.SteadystateSolution.Waterfraction,
+		md.results.SteadystateSolution.Enthalpy,
+		]
+
Index: /issm/trunk/test/NightlyRun/test437.m
===================================================================
--- /issm/trunk/test/NightlyRun/test437.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test437.m	(revision 22758)
@@ -53,7 +53,7 @@
 						'Enthalpy4','Temperature4','Waterfraction4','BasalMeltingRate4','Watercolumn4'};
 field_tolerances={1.e-10,1.e-10,1.e-10,1.e-9,1.e-10,...
-						1.e-10,1.e-10,1.e-10,1.e-9,2.e-10,...
-						1.e-10,1.e-10,1.e-10,1.e-9,1.e-10,...
-						1.e-10,1.e-10,1.e-10,1.e-9,1.e-10};
+						1.e-10,1.e-10,1.e-10,2.e-9,2.e-10,...
+						1.e-10,1.e-10,1.e-10,2.e-9,1.e-10,...
+						1.e-10,1.e-10,1.e-10,2.e-9,1.e-10};
 i1=1;	i2=ceil(t2/md.timestepping.time_step)+2;	i3=ceil(md.timestepping.final_time/(2.*md.timestepping.time_step));	i4=size(md.results.TransientSolution,2);
 field_values={...
Index: /issm/trunk/test/NightlyRun/test437.py
===================================================================
--- /issm/trunk/test/NightlyRun/test437.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test437.py	(revision 22758)
@@ -0,0 +1,96 @@
+#Test Name: ThermalEnthBasalcondsTrans
+import numpy as np
+from model import *
+from socket import gethostname
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md = triangle(model(),'../Exp/Square.exp',300000.)
+md = setmask(md,'','')
+md = parameterize(md,'../Par/SquareThermal.py')
+
+h = 100.
+md.geometry.thickness = h * np.ones((md.mesh.numberofvertices,))
+md.geometry.base = -h * np.ones((md.mesh.numberofvertices,))
+md.geometry.surface = md.geometry.base + md.geometry.thickness
+
+md.extrude(41,2.)
+md = setflowequation(md,'HO','all')
+md.thermal.isenthalpy = True
+md.thermal.isdynamicbasalspc = True
+
+#Basal forcing
+Ts = 273.15-3.
+Tb = 273.15-1.
+Tsw = Tb
+qgeo = md.materials.thermalconductivity / max(md.geometry.thickness) * (Tb - Ts) #qgeo=kappa*(Tb-Ts)/H
+md.basalforcings.geothermalflux[np.where(md.mesh.vertexonbase)] = qgeo
+md.initialization.temperature = qgeo / md.materials.thermalconductivity * (md.geometry.surface - md.mesh.z) + Ts
+
+#Surface forcing
+pos = np.where(md.mesh.vertexonsurface)
+SPC_cold = float('NaN') * np.ones((md.mesh.numberofvertices,))
+SPC_warm = float('NaN') * np.ones((md.mesh.numberofvertices,))
+SPC_cold[pos] = Ts
+SPC_warm[pos] = Tsw
+md.thermal.spctemperature = SPC_cold
+md.timestepping.time_step = 5.
+t0 = 0.
+t1 = 10.
+t2 = 100.
+md.timestepping.final_time = 400.
+md.thermal.spctemperature = np.array([SPC_cold,SPC_cold,SPC_warm,SPC_warm,SPC_cold]).T
+md.thermal.spctemperature = np.vstack((md.thermal.spctemperature,[t0, t1-1, t1, t2-1, t2]))
+#print np.shape(md.thermal.spctemperature)
+#print md.thermal.spctemperature
+
+#Additional settings
+md.transient.ismasstransport = False
+md.transient.isstressbalance = False
+md.transient.issmb = True
+md.transient.isthermal = True
+md.thermal.stabilization = False
+
+#Go solve
+md.verbose = verbose(0)
+md.cluster = generic('name',gethostname(),'np',3)
+md = solve(md,'Transient')
+
+#Fields and tolerances to track changes
+field_names = ['Enthalpy1','Temperature1','Waterfraction1','BasalMeltingRate1','Watercolumn1',
+		   'Enthalpy2','Temperature2','Waterfraction2','BasalMeltingRate2','Watercolumn2',
+		   'Enthalpy3','Temperature3','Waterfraction3','BasalMeltingRate3','Watercolumn3',
+		   'Enthalpy4','Temperature4','Waterfraction4','BasalMeltingRate4','Watercolumn4']
+field_tolerances = [1.e-10,1.e-10,1.e-10,1.e-9,1.e-10,
+		    1.e-10,1.e-10,1.e-10,2.e-9,2.e-10,
+		    1.e-10,1.e-10,1.e-10,2.e-9,1.e-10,
+		    1.e-10,1.e-10,1.e-10,2.e-9,1.e-10]
+i1 = 0
+i2 = int(np.ceil(t2 / md.timestepping.time_step) + 2)-1
+i3 = int(np.ceil(md.timestepping.final_time / (2. * md.timestepping.time_step)))-1
+i4 = np.shape(md.results.TransientSolution)[0]-1
+field_values = [
+	md.results.TransientSolution[i1].Enthalpy,
+	md.results.TransientSolution[i1].Temperature,
+	md.results.TransientSolution[i1].Waterfraction,
+	md.results.TransientSolution[i1].BasalforcingsGroundediceMeltingRate,
+	md.results.TransientSolution[i1].Watercolumn,
+	md.results.TransientSolution[i2].Enthalpy,
+	md.results.TransientSolution[i2].Temperature,
+	md.results.TransientSolution[i2].Waterfraction,
+	md.results.TransientSolution[i2].BasalforcingsGroundediceMeltingRate,
+	md.results.TransientSolution[i2].Watercolumn,
+	md.results.TransientSolution[i3].Enthalpy,
+	md.results.TransientSolution[i3].Temperature,
+	md.results.TransientSolution[i3].Waterfraction,
+	md.results.TransientSolution[i3].BasalforcingsGroundediceMeltingRate,
+	md.results.TransientSolution[i3].Watercolumn,
+	md.results.TransientSolution[i4].Enthalpy,
+	md.results.TransientSolution[i4].Temperature,
+	md.results.TransientSolution[i4].Waterfraction,
+	md.results.TransientSolution[i4].BasalforcingsGroundediceMeltingRate,
+	md.results.TransientSolution[i4].Watercolumn,
+	]
Index: /issm/trunk/test/NightlyRun/test438.py
===================================================================
--- /issm/trunk/test/NightlyRun/test438.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test438.py	(revision 22758)
@@ -0,0 +1,53 @@
+#Test Name: TransientFrictionWaterlayer2D
+import numpy as np
+from model import *
+from socket import gethostname
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+from frictionwaterlayer import *
+
+md = triangle(model(),'../Exp/Square.exp',150000.)
+md = setmask(md,'../Exp/SquareShelf.exp','')
+md = parameterize(md,'../Par/SquareSheetShelf.py')
+md = setflowequation(md,'SSA','all')
+md.friction = frictionwaterlayer(md)
+md.friction.water_layer = np.zeros((md.mesh.numberofvertices+1,2))
+md.friction.water_layer[:,1] = 1.
+md.friction.water_layer[md.mesh.numberofvertices,:] = [1.,2.]
+md.friction.f = 0.8
+md.cluster = generic('name',gethostname(),'np',3)
+md = solve(md,'Transient')
+
+#Fields and tolerances to track changes
+field_names =['Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1',
+	      'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2',
+	      'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3']
+field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,
+		  1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,
+		  1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13]
+field_values = [
+	md.results.TransientSolution[0].Vx,
+	md.results.TransientSolution[0].Vy,
+	md.results.TransientSolution[0].Vel,
+	md.results.TransientSolution[0].Pressure,
+	md.results.TransientSolution[0].Base,
+	md.results.TransientSolution[0].Surface,
+	md.results.TransientSolution[0].Thickness,
+	md.results.TransientSolution[1].Vx,
+	md.results.TransientSolution[1].Vy,
+	md.results.TransientSolution[1].Vel,
+	md.results.TransientSolution[1].Pressure,
+	md.results.TransientSolution[1].Base,
+	md.results.TransientSolution[1].Surface,
+	md.results.TransientSolution[1].Thickness,
+	md.results.TransientSolution[2].Vx,
+	md.results.TransientSolution[2].Vy,
+	md.results.TransientSolution[2].Vel,
+	md.results.TransientSolution[2].Pressure,
+	md.results.TransientSolution[2].Base,
+	md.results.TransientSolution[2].Surface,
+	md.results.TransientSolution[2].Thickness
+	]
Index: /issm/trunk/test/NightlyRun/test439.py
===================================================================
--- /issm/trunk/test/NightlyRun/test439.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test439.py	(revision 22758)
@@ -0,0 +1,54 @@
+#Test Name: TransientFrictionWaterlayer3D
+import numpy as np
+from model import *
+from socket import gethostname
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+from frictionwaterlayer import *
+
+md = triangle(model(),'../Exp/Square.exp',150000.)
+md = setmask(md,'../Exp/SquareShelf.exp','')
+md = parameterize(md,'../Par/SquareSheetShelf.py')
+md = md.extrude(4,1.)
+md = setflowequation(md,'HO','all')
+md.friction = frictionwaterlayer(md)
+md.friction.water_layer = np.zeros((md.mesh.numberofvertices+1,2))
+md.friction.water_layer[:,1] = 1.
+md.friction.water_layer[md.mesh.numberofvertices,:] = [1.,2.]
+md.friction.f = 0.8
+md.cluster = generic('name',gethostname(),'np',3)
+md = solve(md,'Transient')
+
+#Fields and tolerances to track changes
+field_names =['Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1',
+	      'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2',
+	      'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3']
+field_tolerances = [1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,
+		    1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,
+		    1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09]
+field_values = [
+	md.results.TransientSolution[0].Vx,
+	md.results.TransientSolution[0].Vy,
+	md.results.TransientSolution[0].Vel,
+	md.results.TransientSolution[0].Pressure,
+	md.results.TransientSolution[0].Base,
+	md.results.TransientSolution[0].Surface,
+	md.results.TransientSolution[0].Thickness,
+	md.results.TransientSolution[1].Vx,
+	md.results.TransientSolution[1].Vy,
+	md.results.TransientSolution[1].Vel,
+	md.results.TransientSolution[1].Pressure,
+	md.results.TransientSolution[1].Base,
+	md.results.TransientSolution[1].Surface,
+	md.results.TransientSolution[1].Thickness,
+	md.results.TransientSolution[2].Vx,
+	md.results.TransientSolution[2].Vy,
+	md.results.TransientSolution[2].Vel,
+	md.results.TransientSolution[2].Pressure,
+	md.results.TransientSolution[2].Base,
+	md.results.TransientSolution[2].Surface,
+	md.results.TransientSolution[2].Thickness
+	]
Index: /issm/trunk/test/NightlyRun/test441.m
===================================================================
--- /issm/trunk/test/NightlyRun/test441.m	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test441.m	(revision 22758)
@@ -0,0 +1,80 @@
+%Test Name: MISMIP3D
+md=triangle(model(),'../Exp/Square.exp',100000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md.initialization.vx(:)=1.;
+md.initialization.vy(:)=1.;
+md.geometry.thickness(:)=500-md.mesh.x/10000;
+md.geometry.bed =-100-md.mesh.x/1000;
+md.geometry.base=-md.geometry.thickness*md.materials.rho_ice/md.materials.rho_water;
+md.mask.groundedice_levelset=md.geometry.thickness+md.materials.rho_water/md.materials.rho_ice*md.geometry.bed;
+pos=find(md.mask.groundedice_levelset>=0);
+md.geometry.base(pos)=md.geometry.bed(pos);
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+md=setflowequation(md,'SSA','all');
+
+%Boundary conditions:
+md.mask.ice_levelset=-ones(md.mesh.numberofvertices,1);
+md.mask.ice_levelset(find(md.mesh.x==max(md.mesh.x)))=0;
+md.stressbalance.spcvx(:)=NaN;
+md.stressbalance.spcvy(:)=NaN;
+md.stressbalance.spcvz(:)=NaN;
+pos=find((md.mesh.y<1000000.1 & md.mesh.y>999999.9) | (md.mesh.y<0.1 & md.mesh.y>-0.1));
+md.stressbalance.spcvy(pos)=0;
+pos2=find(md.mesh.x<0.1 & md.mesh.x>-0.1);
+md.stressbalance.spcvx(pos2)=0;
+md.stressbalance.spcvy(pos2)=0;
+
+md.materials.rheology_B=1/((10^-25)^(1/3))*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_law='None';
+md.friction.coefficient(:)=sqrt(10^7)*ones(md.mesh.numberofvertices,1);
+md.friction.p=3*ones(md.mesh.numberofelements,1);
+md.smb.mass_balance(:)=1;
+md.basalforcings.groundedice_melting_rate(:)=0;
+md.basalforcings.floatingice_melting_rate(:)=30;
+md.transient.isthermal=0;
+md.transient.isstressbalance=1;
+md.transient.isgroundingline=1;
+md.transient.ismasstransport=1;
+md.transient.issmb=1;
+md.transient.requested_outputs={'default','BasalforcingsFloatingiceMeltingRate'};
+md.groundingline.migration='SubelementMigration2';
+md.timestepping.final_time=30;
+md.timestepping.time_step=10;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,'Transient');
+
+%Fields and tolerances to track changes
+field_names     ={'Bed1','Surface1','Thickness1','Floatingice1','Vx1','Vy1','Pressure1','FloatingiceMeltingrate1',...
+	'Bed2','Surface2','Thickness2','Floatingice2','Vx2','Vy2','Pressure2','FloatingiceMeltingrate2',...
+	'Bed3','Surface3','Thickness3','Floatingice3','Vx3','Vy3','Pressure3','FloatingiceMeltingrate3'};
+field_tolerances={2e-11,5e-12,2e-11,1e-11,5e-10,1e-08,1e-13,1e-13,...
+	3e-11,3e-11,9e-10,7e-11,1e-09,5e-08,1e-10,1e-13,...
+	1e-10,3e-11,1e-10,7e-11,1e-09,5e-08,1e-10,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).BasalforcingsFloatingiceMeltingRate),...
+	(md.results.TransientSolution(2).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).BasalforcingsFloatingiceMeltingRate),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).BasalforcingsFloatingiceMeltingRate),...
+	};
Index: /issm/trunk/test/NightlyRun/test441.py
===================================================================
--- /issm/trunk/test/NightlyRun/test441.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test441.py	(revision 22758)
@@ -0,0 +1,93 @@
+#Test Name: MISMIP3D
+import numpy as np
+from model import *
+from socket import gethostname
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md = triangle(model(),'../Exp/Square.exp',100000.)
+md = setmask(md,'../Exp/SquareShelf.exp','')
+md = parameterize(md,'../Par/SquareSheetShelf.py')
+md.initialization.vx[:] = 1.
+md.initialization.vy[:] = 1.
+md.geometry.thickness[:] = 500. - md.mesh.x / 10000.
+md.geometry.bed = -100. - md.mesh.x / 1000.
+md.geometry.base = -md.geometry.thickness * md.materials.rho_ice / md.materials.rho_water
+md.mask.groundedice_levelset = md.geometry.thickness + md.materials.rho_water / md.materials.rho_ice * md.geometry.bed
+pos = np.array(np.where(md.mask.groundedice_levelset >= 0.))
+md.geometry.base[pos] = md.geometry.bed[pos]
+md.geometry.surface = md.geometry.base + md.geometry.thickness
+md = setflowequation(md,'SSA','all')
+
+#Boundary conditions:
+md.mask.ice_levelset = -np.ones((md.mesh.numberofvertices,))
+md.mask.ice_levelset[np.where(md.mesh.x == max(md.mesh.x))] = 0.
+md.stressbalance.spcvx[:] = float('Nan')
+md.stressbalance.spcvy[:] = float('Nan')
+md.stressbalance.spcvz[:] = float('Nan')
+posA = np.intersect1d(np.array(np.where(md.mesh.y < 1000000.1)),np.array(np.where(md.mesh.y > 999999.9)))
+posB = np.intersect1d(np.array(np.where(md.mesh.y < 0.1)),np.array(np.where(md.mesh.y > -0.1)))
+pos = np.unique(np.concatenate((posA,posB)))
+md.stressbalance.spcvy[pos] = 0.
+pos2 = np.intersect1d(np.array(np.where(md.mesh.x < 0.1)), np.array(np.where(md.mesh.x > -0.1)))
+md.stressbalance.spcvx[pos2] = 0.
+md.stressbalance.spcvy[pos2] = 0.
+
+md.materials.rheology_B = 1. / ((10**-25)**(1./3.)) * np.ones((md.mesh.numberofvertices,))
+md.materials.rheology_law = 'None'
+md.friction.coefficient[:] = np.sqrt(1e7) * np.ones((md.mesh.numberofvertices,))
+md.friction.p = 3. * np.ones((md.mesh.numberofelements,))
+md.smb.mass_balance[:] = 1.
+md.basalforcings.groundedice_melting_rate[:] = 0.
+md.basalforcings.floatingice_melting_rate[:] = 30.
+md.transient.isthermal = 0
+md.transient.isstressbalance = 1
+md.transient.isgroundingline = 1
+md.transient.ismasstransport = 1
+md.transient.issmb = 1
+md.transient.requested_outputs = ['default','BasalforcingsFloatingiceMeltingRate']
+md.groundingline.migration = 'SubelementMigration2'
+md.timestepping.final_time = 30.
+md.timestepping.time_step = 10.
+
+md.cluster = generic('name',gethostname(),'np',3)
+md = solve(md,'Transient')
+
+#Fields and tolerances to track changes
+field_names     = [
+	'Bed1','Surface1','Thickness1','Floatingice1','Vx1','Vy1','Pressure1','FloatingiceMeltingrate1',
+	'Bed2','Surface2','Thickness2','Floatingice2','Vx2','Vy2','Pressure2','FloatingiceMeltingrate2',
+	'Bed3','Surface3','Thickness3','Floatingice3','Vx3','Vy3','Pressure3','FloatingiceMeltingrate3']
+field_tolerances = [
+	2e-11,5e-12,2e-11,1e-11,5e-10,1e-08,1e-13,1e-13,
+	3e-11,3e-11,9e-10,7e-11,1e-09,5e-08,1e-10,1e-13,
+	1e-10,3e-11,1e-10,7e-11,1e-09,5e-08,1e-10,1e-13]
+field_values = [
+	md.results.TransientSolution[0].Base,
+	md.results.TransientSolution[0].Surface,
+	md.results.TransientSolution[0].Thickness,
+	md.results.TransientSolution[0].MaskGroundediceLevelset,
+	md.results.TransientSolution[0].Vx,
+	md.results.TransientSolution[0].Vy,
+	md.results.TransientSolution[0].Pressure,
+	md.results.TransientSolution[0].BasalforcingsFloatingiceMeltingRate,
+	md.results.TransientSolution[1].Base,
+	md.results.TransientSolution[1].Surface,
+	md.results.TransientSolution[1].Thickness,
+	md.results.TransientSolution[1].MaskGroundediceLevelset,
+	md.results.TransientSolution[1].Vx,
+	md.results.TransientSolution[1].Vy,
+	md.results.TransientSolution[1].Pressure,
+	md.results.TransientSolution[1].BasalforcingsFloatingiceMeltingRate,
+	md.results.TransientSolution[2].Base,
+	md.results.TransientSolution[2].Surface,
+	md.results.TransientSolution[2].Thickness,
+	md.results.TransientSolution[2].MaskGroundediceLevelset,
+	md.results.TransientSolution[2].Vx,
+	md.results.TransientSolution[2].Vy,
+	md.results.TransientSolution[2].Pressure,
+	md.results.TransientSolution[2].BasalforcingsFloatingiceMeltingRate,
+	]
Index: /issm/trunk/test/NightlyRun/test442.m
===================================================================
--- /issm/trunk/test/NightlyRun/test442.m	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test442.m	(revision 22758)
@@ -0,0 +1,86 @@
+%Test Name: MISMIP3DHO
+md=triangle(model(),'../Exp/Square.exp',100000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md.initialization.vx(:)=1.;
+md.initialization.vy(:)=1.;
+md.geometry.thickness(:)=500-md.mesh.x/10000;
+md.geometry.bed =-100-md.mesh.x/1000;
+md.geometry.base=-md.geometry.thickness*md.materials.rho_ice/md.materials.rho_water;
+md.mask.groundedice_levelset=md.geometry.thickness+md.materials.rho_water/md.materials.rho_ice*md.geometry.bed;
+pos=find(md.mask.groundedice_levelset>=0);
+md.geometry.base(pos)=md.geometry.bed(pos);
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+md=extrude(md,4,1.);
+md=setflowequation(md,'HO','all');
+
+%Boundary conditions:
+md.mask.ice_levelset=-ones(md.mesh.numberofvertices,1);
+md.mask.ice_levelset(find(md.mesh.x==max(md.mesh.x)))=0;
+md.stressbalance.spcvx(:)=NaN;
+md.stressbalance.spcvy(:)=NaN;
+md.stressbalance.spcvz(:)=NaN;
+pos=find((md.mesh.y<1000000.1 & md.mesh.y>999999.9) | (md.mesh.y<0.1 & md.mesh.y>-0.1));
+md.stressbalance.spcvy(pos)=0;
+pos2=find(md.mesh.x<0.1 & md.mesh.x>-0.1);
+md.stressbalance.spcvx(pos2)=0;
+md.stressbalance.spcvy(pos2)=0;
+
+md.materials.rheology_B=1/((10^-25)^(1/3))*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_law='None';
+md.friction.coefficient(:)=sqrt(10^7)*ones(md.mesh.numberofvertices,1);
+md.friction.p=3*ones(md.mesh.numberofelements,1);
+md.smb.mass_balance(:)=1;
+md.basalforcings.groundedice_melting_rate(:)=0;
+md.basalforcings.floatingice_melting_rate(:)=30;
+md.transient.isthermal=0;
+md.transient.isstressbalance=1;
+md.transient.isgroundingline=1;
+md.transient.ismasstransport=1;
+md.transient.issmb=1;
+md.transient.requested_outputs={'default','BasalforcingsFloatingiceMeltingRate'};
+md.groundingline.migration='SubelementMigration2';
+md.timestepping.final_time=30;
+md.timestepping.time_step=10;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,'Transient');
+
+%Fields and tolerances to track changes
+field_names     ={...
+	'Bed1','Surface1','Thickness1','Floatingice1','Vx1','Vy1','Vz1','Pressure1','FloatingiceMeltingrate1',...
+	'Bed2','Surface2','Thickness2','Floatingice2','Vx2','Vy2','Vz2','Pressure2','FloatingiceMeltingrate2',...
+	'Bed3','Surface3','Thickness3','Floatingice3','Vx3','Vy3','Vz3','Pressure3','FloatingiceMeltingrate3',};
+field_tolerances={...
+	2e-11,5e-12,2e-11,1e-11,5e-10,1e-08,6e-10,1e-13,1e-13,...
+	5e-09,5e-09,5e-09,5e-09,9e-05,9e-05,9e-05,5e-09,1e-13,...
+	8e-09,3e-08,8e-09,5e-09,8e-04,6e-04,2e-09,1e-8,4e-10};
+field_values={...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).BasalforcingsFloatingiceMeltingRate),...
+	(md.results.TransientSolution(2).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).BasalforcingsFloatingiceMeltingRate),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).MaskGroundediceLevelset),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).BasalforcingsFloatingiceMeltingRate),...
+	};
Index: /issm/trunk/test/NightlyRun/test442.py
===================================================================
--- /issm/trunk/test/NightlyRun/test442.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test442.py	(revision 22758)
@@ -0,0 +1,97 @@
+#Test Name: MISMIP3DHO
+import numpy as np
+from model import *
+from socket import gethostname
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md = triangle(model(),'../Exp/Square.exp',100000.)
+md = setmask(md,'../Exp/SquareShelf.exp','')
+md = parameterize(md,'../Par/SquareSheetShelf.py')
+md.initialization.vx[:] = 1.
+md.initialization.vy[:] = 1.
+md.geometry.thickness[:] = 500. - md.mesh.x / 10000.
+md.geometry.bed = -100. - md.mesh.x / 1000.
+md.geometry.base = -md.geometry.thickness * md.materials.rho_ice / md.materials.rho_water
+md.mask.groundedice_levelset = md.geometry.thickness + md.materials.rho_water / md.materials.rho_ice * md.geometry.bed
+pos = np.where(md.mask.groundedice_levelset >= 0.)
+md.geometry.base[pos] = md.geometry.bed[pos]
+md.geometry.surface = md.geometry.base + md.geometry.thickness
+md = md.extrude(4,1.)
+md = setflowequation(md,'HO','all')
+
+#Boundary conditions:
+md.mask.ice_levelset = -np.ones((md.mesh.numberofvertices,))
+md.mask.ice_levelset[np.where(md.mesh.x == max(md.mesh.x))] = 0.
+md.stressbalance.spcvx[:] = float('Nan')
+md.stressbalance.spcvy[:] = float('Nan')
+md.stressbalance.spcvz[:] = float('Nan')
+posA = np.intersect1d(np.array(np.where(md.mesh.y < 1000000.1)),np.array(np.where(md.mesh.y > 999999.9)))
+posB = np.intersect1d(np.array(np.where(md.mesh.y < 0.1)),np.array(np.where(md.mesh.y > -0.1)))
+pos = np.unique(np.concatenate((posA,posB)))
+md.stressbalance.spcvy[pos] = 0.
+pos2 = np.intersect1d(np.array(np.where(md.mesh.x < 0.1)), np.array(np.where(md.mesh.x > -0.1)))
+md.stressbalance.spcvx[pos2] = 0.
+md.stressbalance.spcvy[pos2] = 0.
+
+md.materials.rheology_B = 1. / ((10**-25)**(1./3.)) * np.ones((md.mesh.numberofvertices,))
+md.materials.rheology_law = 'None'
+md.friction.coefficient[:] = np.sqrt(1e7) * np.ones((md.mesh.numberofvertices,))
+md.friction.p = 3. * np.ones((md.mesh.numberofelements,))
+md.smb.mass_balance[:] = 1.
+md.basalforcings.groundedice_melting_rate[:] = 0.
+md.basalforcings.floatingice_melting_rate[:] = 30.
+md.transient.isthermal = 0
+md.transient.isstressbalance = 1
+md.transient.isgroundingline = 1
+md.transient.ismasstransport = 1
+md.transient.issmb = 1
+md.transient.requested_outputs = ['default','BasalforcingsFloatingiceMeltingRate']
+md.groundingline.migration = 'SubelementMigration2'
+md.timestepping.final_time = 30
+md.timestepping.time_step = 10
+
+md.cluster = generic('name',gethostname(),'np',3)
+md = solve(md,'Transient')
+
+#Fields and tolerances to track changes
+field_names     = [
+	'Bed1','Surface1','Thickness1','Floatingice1','Vx1','Vy1','Vz1','Pressure1','FloatingiceMeltingrate1',
+	'Bed2','Surface2','Thickness2','Floatingice2','Vx2','Vy2','Vz2','Pressure2','FloatingiceMeltingrate2',
+	'Bed3','Surface3','Thickness3','Floatingice3','Vx3','Vy3','Vz3','Pressure3','FloatingiceMeltingrate3']
+field_tolerances = [
+	2e-11,5e-12,2e-11,1e-11,5e-10,3e-08,6e-10,1e-13,1e-13,
+	3e-11,3e-11,9e-10,7e-11,7e-09,1e-07,1e-09,1e-10,1e-13,
+	1e-8,2e-08,7e-09,2e-7 ,1e-03,8e-04,2e-09,1e-10,1e-13]
+field_values = [
+	md.results.TransientSolution[0].Base,
+	md.results.TransientSolution[0].Surface,
+	md.results.TransientSolution[0].Thickness,
+	md.results.TransientSolution[0].MaskGroundediceLevelset,
+	md.results.TransientSolution[0].Vx,
+	md.results.TransientSolution[0].Vy,
+	md.results.TransientSolution[0].Vz,
+	md.results.TransientSolution[0].Pressure,
+	md.results.TransientSolution[0].BasalforcingsFloatingiceMeltingRate,
+	md.results.TransientSolution[1].Base,
+	md.results.TransientSolution[1].Surface,
+	md.results.TransientSolution[1].Thickness,
+	md.results.TransientSolution[1].MaskGroundediceLevelset,
+	md.results.TransientSolution[1].Vx,
+	md.results.TransientSolution[1].Vy,
+	md.results.TransientSolution[1].Vz,
+	md.results.TransientSolution[1].Pressure,
+	md.results.TransientSolution[1].BasalforcingsFloatingiceMeltingRate,
+	md.results.TransientSolution[2].Base,
+	md.results.TransientSolution[2].Surface,
+	md.results.TransientSolution[2].Thickness,
+	md.results.TransientSolution[2].MaskGroundediceLevelset,
+	md.results.TransientSolution[2].Vx,
+	md.results.TransientSolution[2].Vy,
+	md.results.TransientSolution[2].Vz,
+	md.results.TransientSolution[2].Pressure,
+	md.results.TransientSolution[2].BasalforcingsFloatingiceMeltingRate,
+	]
Index: /issm/trunk/test/NightlyRun/test443.m
===================================================================
--- /issm/trunk/test/NightlyRun/test443.m	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test443.m	(revision 22758)
@@ -0,0 +1,100 @@
+%Test Name: SquareSheetShelfTranSSA3dAggressiveRegionalOutput
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md.geometry.bed=md.geometry.base;
+pos=find(md.mask.groundedice_levelset<0);
+md.geometry.bed(pos)=md.geometry.base(pos)-10;
+md.friction=frictioncoulomb();
+md.friction.coefficient=20.*ones(md.mesh.numberofvertices,1);
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+md.friction.coefficientcoulomb=0.02*ones(md.mesh.numberofvertices,1);
+md.transient.isthermal=0;
+md.transient.isgroundingline=1;
+md.groundingline.migration='AggressiveMigration';
+md.mesh.scale_factor=1.1*ones(md.mesh.numberofvertices,1);
+
+md.settings.output_frequency=2;
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+regionalmask=zeros(md.mesh.numberofvertices,1);
+in=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,'../Exp/SquareHalfRight.exp','node',1);
+regionalmask(find(in))=1;
+md.transient.requested_outputs={'default','GroundedArea1','FloatingArea1','TotalFloatingBmb1','TotalGroundedBmb1','TotalSmb1',...
+	'IceMass1','IceVolume1','IceVolumeAboveFloatation1','IceVolumeAboveFloatation2','IceVolumeAboveFloatation',...
+	'IceMassScaled1','IceVolumeScaled1','IceVolumeAboveFloatationScaled1','IceVolumeAboveFloatationScaled2'};
+md.outputdefinition.definitions{1}=regionaloutput('name','GroundedArea1','outputnamestring','GroundedArea','mask',regionalmask,...
+	'definitionstring','Outputdefinition1');
+md.outputdefinition.definitions{2}=regionaloutput('name','FloatingArea1','outputnamestring','FloatingArea','mask',regionalmask,...
+	'definitionstring','Outputdefinition2');
+md.outputdefinition.definitions{3}=regionaloutput('name','TotalFloatingBmb1','outputnamestring','TotalFloatingBmb','mask',regionalmask,...
+	'definitionstring','Outputdefinition3');
+md.outputdefinition.definitions{4}=regionaloutput('name','TotalGroundedBmb1','outputnamestring','TotalGroundedBmb','mask',regionalmask,...
+	'definitionstring','Outputdefinition4');
+md.outputdefinition.definitions{5}=regionaloutput('name','IceMass1','outputnamestring','IceMass','mask',regionalmask,...
+	'definitionstring','Outputdefinition5');
+md.outputdefinition.definitions{6}=regionaloutput('name','IceVolume1','outputnamestring','IceVolume','mask',regionalmask,...
+	'definitionstring','Outputdefinition6');
+md.outputdefinition.definitions{7}=regionaloutput('name','IceVolumeAboveFloatation1','outputnamestring','IceVolumeAboveFloatation','mask',regionalmask,...
+	'definitionstring','Outputdefinition7');
+md.outputdefinition.definitions{8}=regionaloutput('name','TotalSmb1','outputnamestring','TotalSmb','mask',regionalmask,...
+	'definitionstring','Outputdefinition8');
+md.outputdefinition.definitions{9}=regionaloutput('name','IceVolumeAboveFloatation2','outputnamestring','IceVolumeAboveFloatation',...
+	'maskexpstring','../Exp/SquareHalfRight.exp','definitionstring','Outputdefinition9','model',md);
+md.outputdefinition.definitions{10}=regionaloutput('name','IceMassScaled1','outputnamestring','IceMassScaled','mask',regionalmask,...
+	'definitionstring','Outputdefinition10');
+md.outputdefinition.definitions{11}=regionaloutput('name','IceVolumeScaled1','outputnamestring','IceVolumeScaled','mask',regionalmask,...
+	'definitionstring','Outputdefinition11');
+md.outputdefinition.definitions{12}=regionaloutput('name','IceVolumeAboveFloatationScaled1','outputnamestring','IceVolumeAboveFloatationScaled','mask',regionalmask,...
+	'definitionstring','Outputdefinition12');
+md.outputdefinition.definitions{13}=regionaloutput('name','IceVolumeAboveFloatationScaled2','outputnamestring','IceVolumeAboveFloatationScaled',...
+	'maskexpstring','../Exp/SquareHalfRight.exp','definitionstring','Outputdefinition13','model',md);
+
+md=extrude(md,3,1);
+md2=collapse(md);
+md=solve(md,'Transient');
+
+%Fields and tolerances to track changes
+field_names     ={'IceMass1','IceVolume1','IceVolumeAboveFloatation1','IceVolumeAboveFloatation21',...
+	'Thickness1','GroundedArea1','FloatingArea1','TotalFloatingBmb1','TotalGroundedBmb1','TotalSmb1',...
+   'IceMassScaled1','IceVolumeScaled1','IceVolumeAboveFloatationScaled1','IceVolumeAboveFloatationScaled21',...
+	'IceMass3','IceVolume3','IceVolumeAboveFloatation3','IceVolumeAboveFloatation23',...
+	'Thickness3','GroundedArea3','FloatingArea3','TotalFloatingBmb3','TotalGroundedBmb3','TotalSmb3',...
+	'IceMassScaled3','IceVolumeScaled3','IceVolumeAboveFloatationScaled3','IceVolumeAboveFloatationScaled23',...
+	'ExtrudedMask','CollapsedMask'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).IceMass1),...
+	(md.results.TransientSolution(1).IceVolume1),...
+	(md.results.TransientSolution(1).IceVolumeAboveFloatation1),...
+	(md.results.TransientSolution(1).IceVolumeAboveFloatation2),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).GroundedArea1),...
+	(md.results.TransientSolution(1).FloatingArea1),...
+	(md.results.TransientSolution(1).TotalFloatingBmb1),...
+	(md.results.TransientSolution(1).TotalGroundedBmb1),...
+	(md.results.TransientSolution(1).TotalSmb1),...
+	(md.results.TransientSolution(1).IceMassScaled1),...
+	(md.results.TransientSolution(1).IceVolumeScaled1),...
+	(md.results.TransientSolution(1).IceVolumeAboveFloatationScaled1),...
+	(md.results.TransientSolution(1).IceVolumeAboveFloatationScaled2),...
+	(md.results.TransientSolution(3).IceMass1),...
+	(md.results.TransientSolution(3).IceVolume1),...
+	(md.results.TransientSolution(3).IceVolumeAboveFloatation1),...
+	(md.results.TransientSolution(3).IceVolumeAboveFloatation2),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).GroundedArea1),...
+	(md.results.TransientSolution(3).FloatingArea1),...
+	(md.results.TransientSolution(3).TotalFloatingBmb1),...
+	(md.results.TransientSolution(3).TotalGroundedBmb1),...
+	(md.results.TransientSolution(3).TotalSmb1),...
+	(md.results.TransientSolution(3).IceMassScaled1),...
+	(md.results.TransientSolution(3).IceVolumeScaled1),...
+	(md.results.TransientSolution(3).IceVolumeAboveFloatationScaled1),...
+	(md.results.TransientSolution(3).IceVolumeAboveFloatationScaled2),...
+	length(md.outputdefinition.definitions{1}.mask),...
+	length(md2.outputdefinition.definitions{1}.mask),...
+	};
Index: /issm/trunk/test/NightlyRun/test443.py
===================================================================
--- /issm/trunk/test/NightlyRun/test443.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test443.py	(revision 22758)
@@ -0,0 +1,93 @@
+#Test Name: SquareSheetShelfTranSSA3dAggressiveRegionalOutput
+import numpy as np
+from model import *
+from socket import gethostname
+
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+from frictioncoulomb import frictioncoulomb
+from ContourToMesh import ContourToMesh
+from regionaloutput import regionaloutput
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md.geometry.bed=copy.deepcopy(md.geometry.base)
+pos=np.nonzero(md.mask.groundedice_levelset<0.)
+md.geometry.bed[pos]=md.geometry.bed[pos]-10
+md.friction=frictioncoulomb()
+md.friction.coefficient=20*np.ones(md.mesh.numberofvertices)
+md.friction.p=1*np.ones(md.mesh.numberofelements)
+md.friction.q=1*np.ones(md.mesh.numberofelements)
+md.friction.coefficientcoulomb=0.02*np.ones(md.mesh.numberofvertices)
+md.transient.isthermal=False
+md.transient.isgroundingline=True
+md.groundingline.migration='AggressiveMigration';
+md.mesh.scale_factor=1.1*np.ones((md.mesh.numberofvertices))
+
+md.settings.output_frequency=2
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',gethostname(),'np',3)
+
+regionalmask=np.zeros((md.mesh.numberofvertices))
+inflag=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,'../Exp/SquareHalfRight.exp','node',1)
+regionalmask[np.nonzero(inflag)[0]] = 1.
+md.transient.requested_outputs=['default','GroundedArea1','FloatingArea1','TotalFloatingBmb1','TotalGroundedBmb1','TotalSmb1','IceMass1','IceVolume1','IceVolumeAboveFloatation1','IceVolumeAboveFloatation2','IceVolumeAboveFloatation','IceMassScaled1','IceVolumeScaled1','IceVolumeAboveFloatationScaled1','IceVolumeAboveFloatationScaled2']
+
+md.outputdefinition.definitions=[regionaloutput('name','GroundedArea1','outputnamestring','GroundedArea','mask',regionalmask,'definitionstring','Outputdefinition1'),
+		regionaloutput('name','FloatingArea1','outputnamestring','FloatingArea','mask',regionalmask,'definitionstring','Outputdefinition2'),
+		regionaloutput('name','TotalFloatingBmb1','outputnamestring','TotalFloatingBmb','mask',regionalmask,'definitionstring','Outputdefinition3'),
+		regionaloutput('name','TotalGroundedBmb1','outputnamestring','TotalGroundedBmb','mask',regionalmask,'definitionstring','Outputdefinition4'),
+		regionaloutput('name','IceMass1','outputnamestring','IceMass','mask',regionalmask,'definitionstring','Outputdefinition5'),
+		regionaloutput('name','IceVolume1','outputnamestring','IceVolume','mask',regionalmask,'definitionstring','Outputdefinition6'),
+		regionaloutput('name','IceVolumeAboveFloatation1','outputnamestring','IceVolumeAboveFloatation','mask',regionalmask,'definitionstring','Outputdefinition7'),
+		regionaloutput('name','TotalSmb1','outputnamestring','TotalSmb','mask',regionalmask,'definitionstring','Outputdefinition8'),
+		regionaloutput('name','IceVolumeAboveFloatation2','outputnamestring','IceVolumeAboveFloatation','maskexpstring','../Exp/SquareHalfRight.exp','definitionstring','Outputdefinition9','model',md),
+		regionaloutput('name','IceMassScaled1','outputnamestring','IceMassScaled','mask',regionalmask,'definitionstring','Outputdefinition10'),
+		regionaloutput('name','IceVolumeScaled1','outputnamestring','IceVolumeScaled','mask',regionalmask,'definitionstring','Outputdefinition11'),
+		regionaloutput('name','IceVolumeAboveFloatationScaled1','outputnamestring','IceVolumeAboveFloatationScaled','mask',regionalmask,'definitionstring','Outputdefinition12'),
+		regionaloutput('name','IceVolumeAboveFloatationScaled2','outputnamestring','IceVolumeAboveFloatationScaled','maskexpstring','../Exp/SquareHalfRight.exp','definitionstring','Outputdefinition13','model',md)]
+
+md.extrude(3,1.)
+md2=copy.deepcopy(md)
+md2.collapse()
+md=solve(md,'Transient')
+
+#Fields and tolerances to track changes
+field_names     =['IceMass1','IceVolume1','IceVolumeAboveFloatation1','IceVolumeAboveFloatation21','Thickness1','GroundedArea1','FloatingArea1','TotalFloatingBmb1','TotalGroundedBmb1','TotalSmb1','IceMassScaled1','IceVolumeScaled1','IceVolumeAboveFloatationScaled1','IceVolumeAboveFloatationScaled21','IceMass3','IceVolume3','IceVolumeAboveFloatation3','IceVolumeAboveFloatation23','Thickness3','GroundedArea3','FloatingArea3','TotalFloatingBmb3','TotalGroundedBmb3','TotalSmb3','IceMassScaled3','IceVolumeScaled3','IceVolumeAboveFloatationScaled3','IceVolumeAboveFloatationScaled23','ExtrudedMask','CollapsedMask']
+field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13]
+field_values=[\
+	md.results.TransientSolution[0].IceMass1,\
+	md.results.TransientSolution[0].IceVolume1,\
+	md.results.TransientSolution[0].IceVolumeAboveFloatation1,\
+	md.results.TransientSolution[0].IceVolumeAboveFloatation2,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].GroundedArea1,\
+	md.results.TransientSolution[0].FloatingArea1,\
+	md.results.TransientSolution[0].TotalFloatingBmb1,\
+	md.results.TransientSolution[0].TotalGroundedBmb1,\
+	md.results.TransientSolution[0].TotalSmb1,\
+	md.results.TransientSolution[0].IceMassScaled1,\
+	md.results.TransientSolution[0].IceVolumeScaled1,\
+	md.results.TransientSolution[0].IceVolumeAboveFloatationScaled1,\
+	md.results.TransientSolution[0].IceVolumeAboveFloatationScaled2,\
+	md.results.TransientSolution[2].IceMass1,\
+	md.results.TransientSolution[2].IceVolume1,\
+	md.results.TransientSolution[2].IceVolumeAboveFloatation1,\
+	md.results.TransientSolution[2].IceVolumeAboveFloatation2,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].GroundedArea1,\
+	md.results.TransientSolution[2].FloatingArea1,\
+	md.results.TransientSolution[2].TotalFloatingBmb1,\
+	md.results.TransientSolution[2].TotalGroundedBmb1,\
+	md.results.TransientSolution[2].TotalSmb1,\
+	md.results.TransientSolution[2].IceMassScaled1,\
+	md.results.TransientSolution[2].IceVolumeScaled1,\
+	md.results.TransientSolution[2].IceVolumeAboveFloatationScaled1,\
+	md.results.TransientSolution[2].IceVolumeAboveFloatationScaled2,\
+	len(md.outputdefinition.definitions[0].mask),\
+	len(md2.outputdefinition.definitions[0].mask),\
+	]
Index: /issm/trunk/test/NightlyRun/test444.m
===================================================================
--- /issm/trunk/test/NightlyRun/test444.m	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test444.m	(revision 22758)
@@ -0,0 +1,111 @@
+%Test Name: SquareSheetShelfTranSSA2dAggressiveDakotaSampRegionalOutput
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md.geometry.bed=md.geometry.base;
+pos=find(md.mask.groundedice_levelset<0);
+md.geometry.bed(pos)=md.geometry.base(pos)-10;
+md.friction.coefficient=20.*ones(md.mesh.numberofvertices,1);
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+md.transient.isthermal=0;
+md.transient.isgroundingline=1;
+md.groundingline.migration='AggressiveMigration';
+
+md.settings.output_frequency=3;
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+regionalmask=zeros(md.mesh.numberofvertices,1);
+in=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,'../Exp/SquareHalfRight.exp','node',1);
+regionalmask(find(in))=1;
+md.transient.requested_outputs={'default','GroundedArea','FloatingArea','IceVolumeAboveFloatation','GroundedArea1','FloatingArea1','TotalFloatingBmb1','TotalGroundedBmb1','TotalSmb1',...
+	'IceMass1','IceVolume1','IceVolumeAboveFloatation1','IceVolumeAboveFloatation'};
+md.outputdefinition.definitions{1}=regionaloutput('name','GroundedArea1','outputnamestring','GroundedArea','mask',regionalmask,...
+	'definitionstring','Outputdefinition1');
+md.outputdefinition.definitions{2}=regionaloutput('name','FloatingArea1','outputnamestring','FloatingArea','mask',regionalmask,...
+	'definitionstring','Outputdefinition2');
+md.outputdefinition.definitions{3}=regionaloutput('name','TotalFloatingBmb1','outputnamestring','TotalFloatingBmb','mask',regionalmask,...
+	'definitionstring','Outputdefinition3');
+md.outputdefinition.definitions{4}=regionaloutput('name','TotalGroundedBmb1','outputnamestring','TotalGroundedBmb','mask',regionalmask,...
+	'definitionstring','Outputdefinition4');
+md.outputdefinition.definitions{5}=regionaloutput('name','IceMass1','outputnamestring','IceMass','mask',regionalmask,...
+	'definitionstring','Outputdefinition5');
+md.outputdefinition.definitions{6}=regionaloutput('name','IceVolume1','outputnamestring','IceVolume','mask',regionalmask,...
+	'definitionstring','Outputdefinition6');
+md.outputdefinition.definitions{7}=regionaloutput('name','IceVolumeAboveFloatation1','outputnamestring','IceVolumeAboveFloatation','mask',regionalmask,...
+	'definitionstring','Outputdefinition7');
+md.outputdefinition.definitions{8}=regionaloutput('name','TotalSmb1','outputnamestring','TotalSmb','mask',regionalmask,...
+	'definitionstring','Outputdefinition8');
+md.outputdefinition.definitions{9}=regionaloutput('name','TotalSmb2','outputnamestring','TotalSmb','mask',regionalmask,...
+	 'definitionstring','Outputdefinition9');
+
+md=extrude(md,3,1);
+md=collapse(md);
+
+%Dakota options
+
+%dakota version
+version=IssmConfig('_DAKOTA_VERSION_'); version=version(1:3); version=str2num(version);
+
+md.qmu.variables.drag_coefficient=normal_uncertain('scaled_BasalforcingsFloatingiceMeltingRate',1,0.1);
+
+md.qmu.responses.IceMass1=response_function('Outputdefinition5',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.IceVolume1=response_function('Outputdefinition6',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.IceVolumeAboveFloatation1=response_function('Outputdefinition7',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.IceVolumeAboveFloatation=response_function('IceVolumeAboveFloatation',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.GroundedArea1=response_function('Outputdefinition1',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.FloatingArea1=response_function('Outputdefinition2',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.TotalFloatingBmb1=response_function('Outputdefinition3',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.TotalGroundedBmb1=response_function('Outputdefinition4',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.TotalSmb1=response_function('Outputdefinition8',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.TotalSmb2=response_function('Outputdefinition9',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.FloatingArea=response_function('FloatingArea',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+md.qmu.method     =dakota_method('nond_samp');
+md.qmu.method(end)=dmeth_params_set(md.qmu.method(end),...
+	'seed',1234,...
+	'samples',20,...
+	'sample_type','random');
+
+%%  a variety of parameters
+md.qmu.params.direct=true;
+md.qmu.params.analysis_components='';
+md.qmu.params.tabular_graphics_data=true;
+
+if version>=6,
+	md.qmu.params.analysis_driver='matlab';
+	md.qmu.params.evaluation_scheduling='master';
+	md.qmu.params.processors_per_evaluation=2;
+else
+	md.qmu.params.analysis_driver='stressbalance';
+	md.qmu.params.evaluation_concurrency=1;
+end
+
+%partitioning
+md.qmu.numberofpartitions=10;
+md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions,'weighting','on');
+md.qmu.partition=md.qmu.partition-1;
+md.qmu.isdakota=1;
+
+md.stressbalance.reltol=10^-5; %tighten for qmu analyses
+
+md=solve(md,'Transient','overwrite','y');
+
+%Fields and tolerances to track changes
+md.qmu.results=md.results.dakota;
+
+%we put all the mean and stdev data in the montecarlo field, which we will use to test for success.
+md.results.dakota.montecarlo=[];
+for i=1:11,
+	md.results.dakota.montecarlo=[md.results.dakota.montecarlo md.results.dakota.dresp_out(i).mean];
+end
+for i=1:11,
+	md.results.dakota.montecarlo=[md.results.dakota.montecarlo md.results.dakota.dresp_out(i).stddev];
+end
+field_names     ={'montecarlo'};
+field_tolerances={1e-11};
+field_values={...
+	md.results.dakota.montecarlo,...
+	};
+
Index: /issm/trunk/test/NightlyRun/test460.m
===================================================================
--- /issm/trunk/test/NightlyRun/test460.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test460.m	(revision 22758)
@@ -21,5 +21,5 @@
 	md=solve(md,'Stressbalance');
 	field_names     ={field_names{:},['Vx' i{1}],['Vy' i{1}],['Vz' i{1}],['Vel' i{1}],['Pressure' i{1}]};
-	field_tolerances={field_tolerances{:},6e-07,6e-07,2e-06,1e-06,5e-07};
+	field_tolerances={field_tolerances{:},2e-06,3e-06,2e-06,2e-06,5e-07};
 	field_values={field_values{:},...
 		(md.results.StressbalanceSolution.Vx),...
Index: /issm/trunk/test/NightlyRun/test460.py
===================================================================
--- /issm/trunk/test/NightlyRun/test460.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test460.py	(revision 22758)
@@ -0,0 +1,38 @@
+#Test Name: SquareSheetShelfStressFSEstar
+import numpy as np
+from model import *
+from socket import gethostname
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+from matestar import *
+
+md=triangle(model(),'../Exp/Square.exp',180000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md = md.extrude(3,1.)
+md.materials = matestar()
+md.materials.rheology_B = 3.15e8 * np.ones((md.mesh.numberofvertices,))
+md.materials.rheology_Ec = np.ones((md.mesh.numberofvertices,))
+md.materials.rheology_Es = 3 * np.ones((md.mesh.numberofvertices,))
+md.cluster = generic('name',gethostname(),'np',3)
+
+#Go solve
+field_names=[]
+field_tolerances=[]
+field_values=[]
+#md.initialization.pressure=md.constants.g*md.materials.rho_ice*(md.geometry.surface-md.mesh.y);
+for i in ['SSA','HO','FS']:
+	md = setflowequation(md,i,'all')
+	md = solve(md,'Stressbalance')
+	field_names     = field_names + ['Vx'+i,'Vy'+i,'Vz'+i,'Vel'+i,'Pressure'+i]
+	field_tolerances = field_tolerances + [2e-06,3e-06,2e-06,2e-06,5e-07]
+	field_values = field_values + [
+			md.results.StressbalanceSolution.Vx,
+			md.results.StressbalanceSolution.Vy,
+			md.results.StressbalanceSolution.Vz,
+			md.results.StressbalanceSolution.Vel,
+			md.results.StressbalanceSolution.Pressure,
+			]
Index: /issm/trunk/test/NightlyRun/test461.py
===================================================================
--- /issm/trunk/test/NightlyRun/test461.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test461.py	(revision 22758)
@@ -0,0 +1,53 @@
+#Test Name: SquareSheetShelfThermalFSEstar
+import numpy as np
+from model import *
+from socket import gethostname
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+from matestar import *
+
+md = triangle(model(),'../Exp/Square.exp',180000.)
+md = setmask(md,'../Exp/SquareShelf.exp','')
+md = parameterize(md,'../Par/SquareSheetShelf.py')
+md = md.extrude(3,1.)
+md.materials = matestar()
+md.materials.rheology_B = 3.15e8 * np.ones((md.mesh.numberofvertices,))
+md.materials.rheology_Ec = np.ones((md.mesh.numberofvertices,))
+md.materials.rheology_Es = 3. * np.ones((md.mesh.numberofvertices,))
+
+md = setflowequation(md,'FS','all')
+md.initialization.waterfraction = np.zeros((md.mesh.numberofvertices,))
+md.initialization.watercolumn = np.zeros((md.mesh.numberofvertices,))
+md.transient.isstressbalance = 0
+md.transient.ismasstransport = 0
+md.transient.issmb = 1
+md.transient.isthermal = 1
+md.transient.isgroundingline = 0
+md.thermal.isenthalpy = 1
+md.thermal.isdynamicbasalspc = 1
+md.cluster = generic('name',gethostname(),'np',3)
+md = solve(md,'Transient')
+
+#Fields and tolerances to track changes
+field_names = [
+	'Enthalpy1','Waterfraction1','Temperature1',
+	'Enthalpy2','Waterfraction2','Temperature2',
+	'Enthalpy3','Waterfraction3','Temperature3']
+field_tolerances = [
+	1e-12,1e-11,1e-12,
+	1e-12,1e-10,1e-12,
+	1e-12,1e-9,1e-12]
+field_values = [
+	   md.results.TransientSolution[0].Enthalpy,
+	   md.results.TransientSolution[0].Waterfraction,
+	   md.results.TransientSolution[0].Temperature,
+	   md.results.TransientSolution[1].Enthalpy,
+	   md.results.TransientSolution[1].Waterfraction,
+	   md.results.TransientSolution[1].Temperature,
+	   md.results.TransientSolution[2].Enthalpy,
+	   md.results.TransientSolution[2].Waterfraction,
+	   md.results.TransientSolution[2].Temperature,
+	   ]
Index: /issm/trunk/test/NightlyRun/test462.m
===================================================================
--- /issm/trunk/test/NightlyRun/test462.m	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test462.m	(revision 22758)
@@ -0,0 +1,40 @@
+%Test Name: SquareSheetShelfAmrBamgField
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.transient.isstressbalance=1;
+md.transient.ismasstransport=1;
+md.transient.issmb=0;
+md.transient.isthermal=0;
+md.transient.isgroundingline=0;
+%amr bamg settings, just field
+md.amr.hmin=10000;
+md.amr.hmax=100000;
+md.amr.fieldname='Vel';
+md.amr.keepmetric=1;
+md.amr.gradation=1.2;
+md.amr.groundingline_resolution=2000;
+md.amr.groundingline_distance=0;
+md.amr.icefront_resolution=1000;
+md.amr.icefront_distance=0;
+md.amr.thicknesserror_resolution=1000;
+md.amr.thicknesserror_threshold=0;
+md.amr.deviatoricerror_resolution=1000;
+md.amr.deviatoricerror_threshold=0;
+md.transient.amr_frequency=1;
+md.timestepping.start_time=0;
+md.timestepping.final_time=3;
+md.timestepping.time_step=1;
+md=solve(md,'Transient');
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	};
Index: /issm/trunk/test/NightlyRun/test462.py
===================================================================
--- /issm/trunk/test/NightlyRun/test462.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test462.py	(revision 22758)
@@ -0,0 +1,49 @@
+#Test Name: SquareSheetShelfAmrBamgField
+import numpy as np
+from model import *
+from socket import gethostname
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md = triangle(model(),'../Exp/Square.exp',150000.)
+md = setmask(md,'../Exp/SquareShelf.exp','')
+md = parameterize(md,'../Par/SquareSheetShelf.py')
+md = setflowequation(md,'SSA','all')
+md.cluster = generic('name',gethostname(),'np',3)
+md.transient.isstressbalance = 1
+md.transient.ismasstransport = 1
+md.transient.issmb = 0
+md.transient.isthermal = 0
+md.transient.isgroundingline = 0
+#amr bamg settings, just field
+md.amr.hmin = 10000
+md.amr.hmax = 100000
+md.amr.fieldname = 'Vel'
+md.amr.keepmetric = 1
+md.amr.gradation = 1.2
+md.amr.groundingline_resolution = 2000
+md.amr.groundingline_distance = 0
+md.amr.icefront_resolution = 1000
+md.amr.icefront_distance = 0
+md.amr.thicknesserror_resolution = 1000
+md.amr.thicknesserror_threshold = 0
+md.amr.deviatoricerror_resolution = 1000
+md.amr.deviatoricerror_threshold = 0
+md.transient.amr_frequency = 1
+md.timestepping.start_time = 0
+md.timestepping.final_time = 3
+md.timestepping.time_step = 1
+md = solve(md,'Transient')
+
+#Fields and tolerances to track changes
+field_names     = ['Vx','Vy','Vel','Pressure']
+field_tolerances = [1e-13,1e-13,1e-13,1e-13]
+field_values = [
+	md.results.TransientSolution[2].Vx,
+	md.results.TransientSolution[2].Vy,
+	md.results.TransientSolution[2].Vel,
+	md.results.TransientSolution[2].Pressure,
+	]
Index: /issm/trunk/test/NightlyRun/test463.m
===================================================================
--- /issm/trunk/test/NightlyRun/test463.m	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test463.m	(revision 22758)
@@ -0,0 +1,40 @@
+%Test Name: SquareSheetShelfAmrBamgGroundingline
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.transient.isstressbalance=1;
+md.transient.ismasstransport=1;
+md.transient.issmb=0;
+md.transient.isthermal=0;
+md.transient.isgroundingline=0;
+%amr bamg settings, just grounding line
+md.amr.hmin=10000;
+md.amr.hmax=100000;
+md.amr.fieldname='None';
+md.amr.keepmetric=0;
+md.amr.gradation=1.2;
+md.amr.groundingline_resolution=12000;
+md.amr.groundingline_distance=100000;
+md.amr.icefront_resolution=1000;
+md.amr.icefront_distance=0;
+md.amr.thicknesserror_resolution=1000;
+md.amr.thicknesserror_threshold=0;
+md.amr.deviatoricerror_resolution=1000;
+md.amr.deviatoricerror_threshold=0;
+md.transient.amr_frequency = 1;
+md.timestepping.start_time=0;
+md.timestepping.final_time=3;
+md.timestepping.time_step=1;
+md=solve(md,'Transient');
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={1e-8,1e-8,1e-8,1e-8};
+field_values={...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	};
Index: /issm/trunk/test/NightlyRun/test463.py
===================================================================
--- /issm/trunk/test/NightlyRun/test463.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test463.py	(revision 22758)
@@ -0,0 +1,49 @@
+#Test Name: SquareSheetShelfAmrBamgGroundingline
+import numpy as np
+from model import *
+from socket import gethostname
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md = triangle(model(),'../Exp/Square.exp',150000.)
+md = setmask(md,'../Exp/SquareShelf.exp','')
+md = parameterize(md,'../Par/SquareSheetShelf.py')
+md = setflowequation(md,'SSA','all')
+md.cluster = generic('name',gethostname(),'np',3)
+md.transient.isstressbalance = 1
+md.transient.ismasstransport = 1
+md.transient.issmb = 0
+md.transient.isthermal = 0
+md.transient.isgroundingline = 0
+#amr bamg settings, just grounding line
+md.amr.hmin = 10000
+md.amr.hmax = 100000
+md.amr.fieldname = 'None'
+md.amr.keepmetric = 0
+md.amr.gradation = 1.2
+md.amr.groundingline_resolution = 12000
+md.amr.groundingline_distance = 100000
+md.amr.icefront_resolution = 1000
+md.amr.icefront_distance = 0
+md.amr.thicknesserror_resolution = 1000
+md.amr.thicknesserror_threshold = 0
+md.amr.deviatoricerror_resolution = 1000
+md.amr.deviatoricerror_threshold = 0
+md.transient.amr_frequency = 1
+md.timestepping.start_time = 0
+md.timestepping.final_time = 3
+md.timestepping.time_step = 1
+md = solve(md,'Transient')
+
+#Fields and tolerances to track changes
+field_names     = ['Vx','Vy','Vel','Pressure']
+field_tolerances = [1e-8,1e-8,1e-8,1e-8]
+field_values = [
+	md.results.TransientSolution[2].Vx,
+	md.results.TransientSolution[2].Vy,
+	md.results.TransientSolution[2].Vel,
+	md.results.TransientSolution[2].Pressure,
+	]
Index: /issm/trunk/test/NightlyRun/test464.m
===================================================================
--- /issm/trunk/test/NightlyRun/test464.m	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test464.m	(revision 22758)
@@ -0,0 +1,40 @@
+%Test Name: SquareSheetShelfAmrBamgIceFront
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.transient.isstressbalance=1;
+md.transient.ismasstransport=1;
+md.transient.issmb=0;
+md.transient.isthermal=0;
+md.transient.isgroundingline=0;
+%amr bamg settings, just ice front
+md.amr.hmin=10000;
+md.amr.hmax=100000;
+md.amr.fieldname='None';
+md.amr.keepmetric=0;
+md.amr.gradation=1.2;
+md.amr.groundingline_resolution=12000;
+md.amr.groundingline_distance=0;
+md.amr.icefront_resolution=12000;
+md.amr.icefront_distance=100000;
+md.amr.thicknesserror_resolution=1000;
+md.amr.thicknesserror_threshold=0;
+md.amr.deviatoricerror_resolution=1000;
+md.amr.deviatoricerror_threshold=0;
+md.transient.amr_frequency = 1;
+md.timestepping.start_time=0;
+md.timestepping.final_time=3;
+md.timestepping.time_step=1;
+md=solve(md,'Transient');
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	};
Index: /issm/trunk/test/NightlyRun/test464.py
===================================================================
--- /issm/trunk/test/NightlyRun/test464.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test464.py	(revision 22758)
@@ -0,0 +1,49 @@
+#Test Name: SquareSheetShelfAmrBamgIceFront
+import numpy as np
+from model import *
+from socket import gethostname
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md = triangle(model(),'../Exp/Square.exp',150000.)
+md = setmask(md,'../Exp/SquareShelf.exp','')
+md = parameterize(md,'../Par/SquareSheetShelf.py')
+md = setflowequation(md,'SSA','all')
+md.cluster = generic('name',gethostname(),'np',3)
+md.transient.isstressbalance = 1
+md.transient.ismasstransport = 1
+md.transient.issmb = 0
+md.transient.isthermal = 0
+md.transient.isgroundingline = 0
+#amr bamg settings, just ice front
+md.amr.hmin = 10000
+md.amr.hmax = 100000
+md.amr.fieldname = 'None'
+md.amr.keepmetric = 0
+md.amr.gradation = 1.2
+md.amr.groundingline_resolution = 12000
+md.amr.groundingline_distance = 0
+md.amr.icefront_resolution = 12000
+md.amr.icefront_distance = 100000
+md.amr.thicknesserror_resolution = 1000
+md.amr.thicknesserror_threshold = 0
+md.amr.deviatoricerror_resolution = 1000
+md.amr.deviatoricerror_threshold = 0
+md.transient.amr_frequency = 1
+md.timestepping.start_time = 0
+md.timestepping.final_time = 3
+md.timestepping.time_step = 1
+md = solve(md,'Transient')
+
+#Fields and tolerances to track changes
+field_names     = ['Vx','Vy','Vel','Pressure']
+field_tolerances = [1e-13,1e-13,1e-13,1e-13]
+field_values = [
+	md.results.TransientSolution[2].Vx,
+	md.results.TransientSolution[2].Vy,
+	md.results.TransientSolution[2].Vel,
+	md.results.TransientSolution[2].Pressure,
+	]
Index: /issm/trunk/test/NightlyRun/test465.m
===================================================================
--- /issm/trunk/test/NightlyRun/test465.m	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test465.m	(revision 22758)
@@ -0,0 +1,40 @@
+%Test Name: SquareSheetShelfAmrBamgAll
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.transient.isstressbalance=1;
+md.transient.ismasstransport=1;
+md.transient.issmb=0;
+md.transient.isthermal=0;
+md.transient.isgroundingline=0;
+%amr bamg settings, field, grounding line and ice front
+md.amr.hmin=20000;
+md.amr.hmax=100000;
+md.amr.fieldname='Vel';
+md.amr.keepmetric=0;
+md.amr.gradation=1.2;
+md.amr.groundingline_resolution=10000;
+md.amr.groundingline_distance=100000;
+md.amr.icefront_resolution=15000;
+md.amr.icefront_distance=100000;
+md.amr.thicknesserror_resolution=1000;
+md.amr.thicknesserror_threshold=0;
+md.amr.deviatoricerror_resolution=1000;
+md.amr.deviatoricerror_threshold=0;
+md.transient.amr_frequency = 1;
+md.timestepping.start_time=0;
+md.timestepping.final_time=3;
+md.timestepping.time_step=1;
+md=solve(md,'Transient');
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={1e-8,1e-8,1e-8,1e-8};
+field_values={...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	};
Index: /issm/trunk/test/NightlyRun/test465.py
===================================================================
--- /issm/trunk/test/NightlyRun/test465.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test465.py	(revision 22758)
@@ -0,0 +1,49 @@
+#Test Name: SquareSheetShelfAmrBamgAll
+import numpy as np
+from model import *
+from socket import gethostname
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md = triangle(model(),'../Exp/Square.exp',150000.)
+md = setmask(md,'../Exp/SquareShelf.exp','')
+md = parameterize(md,'../Par/SquareSheetShelf.py')
+md = setflowequation(md,'SSA','all')
+md.cluster = generic('name',gethostname(),'np',3)
+md.transient.isstressbalance = 1
+md.transient.ismasstransport = 1
+md.transient.issmb = 0
+md.transient.isthermal = 0
+md.transient.isgroundingline = 0
+#amr bamg settings, field, grounding line and ice front
+md.amr.hmin = 20000
+md.amr.hmax = 100000
+md.amr.fieldname = 'Vel'
+md.amr.keepmetric = 0
+md.amr.gradation = 1.2
+md.amr.groundingline_resolution = 10000
+md.amr.groundingline_distance = 100000
+md.amr.icefront_resolution = 15000
+md.amr.icefront_distance = 100000
+md.amr.thicknesserror_resolution = 1000
+md.amr.thicknesserror_threshold = 0
+md.amr.deviatoricerror_resolution = 1000
+md.amr.deviatoricerror_threshold = 0
+md.transient.amr_frequency = 1
+md.timestepping.start_time = 0
+md.timestepping.final_time = 3
+md.timestepping.time_step = 1
+md = solve(md,'Transient')
+
+#Fields and tolerances to track changes
+field_names     = ['Vx','Vy','Vel','Pressure']
+field_tolerances = [1e-8,1e-8,1e-8,1e-8]
+field_values = [
+	md.results.TransientSolution[2].Vx,
+	md.results.TransientSolution[2].Vy,
+	md.results.TransientSolution[2].Vel,
+	md.results.TransientSolution[2].Pressure,
+	]
Index: /issm/trunk/test/NightlyRun/test470.m
===================================================================
--- /issm/trunk/test/NightlyRun/test470.m	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test470.m	(revision 22758)
@@ -0,0 +1,76 @@
+%Test Name: PicoMeltRate
+md=triangle(model(),'../Exp/Square.exp',90000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md.initialization.vx(:)=1.;
+md.initialization.vy(:)=1.;
+md.geometry.thickness(:)=500-md.mesh.x/10000;
+md.geometry.bed =-100-md.mesh.x/1000;
+md.geometry.base=-md.geometry.thickness*md.materials.rho_ice/md.materials.rho_water;
+md.mask.groundedice_levelset=md.geometry.thickness+md.materials.rho_water/md.materials.rho_ice*md.geometry.bed;
+pos=find(md.mask.groundedice_levelset>=0);
+md.geometry.base(pos)=md.geometry.bed(pos);
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+md=setflowequation(md,'SSA','all');
+
+%Set Pico Parameters
+md.basalforcings = basalforcingspico(md.basalforcings);
+md.basalforcings.basin_id = zeros(md.mesh.numberofelements,1);
+yE = mean(md.mesh.y(md.mesh.elements),2);
+pos1 = find(yE>=5e5);	 md.basalforcings.basin_id(pos1)=1;
+pos2 = find(yE<5e5);     md.basalforcings.basin_id(pos2)=2;
+md.basalforcings.num_basins = 2;
+md.basalforcings.farocean_temperature = [271.15 272.15 273.15; 274.15 275.15 276.15; 0.5 1 1.5]; %K
+md.basalforcings.farocean_salinity    = [31 32 33; 34 35 36; 0.5 1 1.5]; %PSU                
+md.basalforcings.maxboxcount=5;
+
+%Boundary conditions:
+md.mask.ice_levelset=-ones(md.mesh.numberofvertices,1);
+md.mask.ice_levelset(find(md.mesh.x==max(md.mesh.x)))=0;
+
+%Model conditions
+md.transient.isthermal=0;
+md.transient.isstressbalance=1;
+md.transient.isgroundingline=1;
+md.transient.ismasstransport=1;
+md.transient.issmb=1;
+md.transient.requested_outputs={'default','BasalforcingsFloatingiceMeltingRate'};
+md.groundingline.migration='SubelementMigration';
+md.timestepping.final_time=1.5;
+md.timestepping.time_step=0.5;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,'Transient');
+
+field_names     ={'Bed1','Surface1','Thickness1','Floatingice1','Vx1','Vy1','Pressure1','FloatingiceMeltingrate1',...
+	   'Bed2','Surface2','Thickness2','Floatingice2','Vx2','Vy2','Pressure2','FloatingiceMeltingrate2',...
+	   'Bed3','Surface3','Thickness3','Floatingice3','Vx3','Vy3','Pressure3','FloatingiceMeltingrate3'};
+field_tolerances={7e-09,8e-09,8e-09,7e-09,6e-08,7e-08,6e-09,8e-10,...
+	   7e-09,8e-09,8e-09,7e-09,6e-08,7e-08,6e-09,8e-10,...
+	   7e-09,8e-09,8e-09,7e-09,6e-08,7e-08,6e-09,8e-10};
+field_values={...
+	   (md.results.TransientSolution(1).Base),...
+	   (md.results.TransientSolution(1).Surface),...
+	   (md.results.TransientSolution(1).Thickness),...
+	   (md.results.TransientSolution(1).MaskGroundediceLevelset),...
+	   (md.results.TransientSolution(1).Vx),...
+	   (md.results.TransientSolution(1).Vy),...
+	   (md.results.TransientSolution(1).Pressure),...
+	   (md.results.TransientSolution(1).BasalforcingsFloatingiceMeltingRate),...
+	   (md.results.TransientSolution(2).Base),...
+	   (md.results.TransientSolution(2).Surface),...
+	   (md.results.TransientSolution(2).Thickness),...
+	   (md.results.TransientSolution(2).MaskGroundediceLevelset),...
+	   (md.results.TransientSolution(2).Vx),...
+	   (md.results.TransientSolution(2).Vy),...
+	   (md.results.TransientSolution(2).Pressure),...
+	   (md.results.TransientSolution(2).BasalforcingsFloatingiceMeltingRate),...
+	   (md.results.TransientSolution(3).Base),...
+	   (md.results.TransientSolution(3).Surface),...
+	   (md.results.TransientSolution(3).Thickness),...
+	   (md.results.TransientSolution(3).MaskGroundediceLevelset),...
+	   (md.results.TransientSolution(3).Vx),...
+	   (md.results.TransientSolution(3).Vy),...
+	   (md.results.TransientSolution(3).Pressure),...
+	   (md.results.TransientSolution(3).BasalforcingsFloatingiceMeltingRate),...
+	   };
Index: /issm/trunk/test/NightlyRun/test504.m
===================================================================
--- /issm/trunk/test/NightlyRun/test504.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test504.m	(revision 22758)
@@ -5,9 +5,15 @@
 md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
+md.geometry.bed=md.geometry.base;
+[md.mesh.lat,md.mesh.long] = xy2ll(md.mesh.x,md.mesh.y,-1);
+md.mesh.scale_factor=0.9*ones(md.mesh.numberofvertices,1);
+md.transient.requested_outputs={'default','IceVolume','IceVolumeScaled','GroundedArea','GroundedAreaScaled','FloatingArea','FloatingAreaScaled','TotalSmb','TotalSmbScaled','TotalFloatingBmb','TotalFloatingBmbScaled'};
 md=solve(md,'Transient');
 
 %Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2'};
-field_tolerances={1e-12,2e-12,2e-12,1e-13,1e-13,1e-13,1e-13,1e-12,1e-12,1e-12,1e-13,1e-13,1e-13,1e-13};
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','IceVolume1','IceVolumeScaled1','GroundedArea1','GroundedAreaScaled1','FloatingArea1','FloatingAreaScaled1','TotalSmb1','TotalSmbScaled1','TotalFloatingBmb1','TotalFloatingBmbScaled1',...
+	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','IceVolume2','IceVolumeScaled2','GroundedArea2','GroundedAreaScaled2','FloatingArea2','FloatingAreaScaled2','TotalSmb2','TotalSmbScaled2','TotalFloatingBmb2','TotalFloatingBmbScaled2'};
+field_tolerances={1e-12,2e-12,2e-12,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-12,1e-12,1e-12,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
 	(md.results.TransientSolution(1).Vx),...
@@ -18,4 +24,14 @@
 	(md.results.TransientSolution(1).Surface),...
 	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).IceVolume),...
+	(md.results.TransientSolution(1).IceVolumeScaled),...
+	(md.results.TransientSolution(1).GroundedArea),...
+	(md.results.TransientSolution(1).GroundedAreaScaled),...
+	(md.results.TransientSolution(1).FloatingArea),...
+	(md.results.TransientSolution(1).FloatingAreaScaled),...
+	(md.results.TransientSolution(1).TotalSmb),...
+	(md.results.TransientSolution(1).TotalSmbScaled),...
+	(md.results.TransientSolution(1).TotalFloatingBmb),...
+	(md.results.TransientSolution(1).TotalFloatingBmbScaled),...
 	(md.results.TransientSolution(2).Vx),...
 	(md.results.TransientSolution(2).Vy),...
@@ -25,3 +41,13 @@
 	(md.results.TransientSolution(2).Surface),...
 	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).IceVolume),...
+	(md.results.TransientSolution(2).IceVolumeScaled),...
+	(md.results.TransientSolution(2).GroundedArea),...
+	(md.results.TransientSolution(2).GroundedAreaScaled),...
+	(md.results.TransientSolution(2).FloatingArea),...
+	(md.results.TransientSolution(2).FloatingAreaScaled),...
+	(md.results.TransientSolution(2).TotalSmb),...
+	(md.results.TransientSolution(2).TotalSmbScaled),...
+	(md.results.TransientSolution(2).TotalFloatingBmb),...
+	(md.results.TransientSolution(2).TotalFloatingBmbScaled),...
 	};
Index: /issm/trunk/test/NightlyRun/test504.py
===================================================================
--- /issm/trunk/test/NightlyRun/test504.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test504.py	(revision 22758)
@@ -13,10 +13,12 @@
 md=parameterize(md,'../Par/Pig.py')
 md=setflowequation(md,'SSA','all')
+md.mesh.scale_factor=0.9*np.ones((md.mesh.numberofvertices))
+md.transient.requested_outputs=['default','IceVolume','IceVolumeScaled','GroundedArea','GroundedAreaScaled','FloatingArea','FloatingAreaScaled','TotalSmb','TotalSmbScaled','TotalFloatingBmb','TotalFloatingBmbScaled']
 md.cluster=generic('name',gethostname(),'np',3)
 md=solve(md,'Transient')
 
 # Fields and tolerances to track changes
-field_names     =['Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2']
-field_tolerances=[1e-12,2e-12,2e-12,1e-13,1e-13,1e-13,1e-13,1e-12,1e-12,1e-12,1e-13,1e-13,1e-13,1e-13]
+field_names     =['Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','IceVolume1','IceVolumeScaled1','GroundedArea1','GroundedAreaScaled1','FloatingArea1','FloatingAreaScaled1','TotalSmb1','TotalSmbScaled1','TotalFloatingBmb1','TotalFloatingBmbScaled1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','IceVolume2','IceVolumeScaled2','GroundedArea2','GroundedAreaScaled2','FloatingArea2','FloatingAreaScaled2','TotalSmb2','TotalSmbScaled2','TotalFloatingBmb2','TotalFloatingBmbScaled2']
+field_tolerances=[1e-12,2e-12,2e-12,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-12,1e-12,1e-12,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,]
 field_values=[\
 	md.results.TransientSolution[0].Vx,\
@@ -27,4 +29,14 @@
 	md.results.TransientSolution[0].Surface,\
 	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].IceVolume,\
+	md.results.TransientSolution[0].IceVolumeScaled,\
+	md.results.TransientSolution[0].GroundedArea,\
+	md.results.TransientSolution[0].GroundedAreaScaled,\
+	md.results.TransientSolution[0].FloatingArea,\
+	md.results.TransientSolution[0].FloatingAreaScaled,\
+	md.results.TransientSolution[0].TotalSmb,\
+	md.results.TransientSolution[0].TotalSmbScaled,\
+	md.results.TransientSolution[0].TotalFloatingBmb,\
+	md.results.TransientSolution[0].TotalFloatingBmbScaled,\
 	md.results.TransientSolution[1].Vx,\
 	md.results.TransientSolution[1].Vy,\
@@ -34,3 +46,13 @@
 	md.results.TransientSolution[1].Surface,\
 	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].IceVolume,\
+	md.results.TransientSolution[1].IceVolumeScaled,\
+	md.results.TransientSolution[1].GroundedArea,\
+	md.results.TransientSolution[1].GroundedAreaScaled,\
+	md.results.TransientSolution[1].FloatingArea,\
+	md.results.TransientSolution[1].FloatingAreaScaled,\
+	md.results.TransientSolution[1].TotalSmb,\
+	md.results.TransientSolution[1].TotalSmbScaled,\
+	md.results.TransientSolution[1].TotalFloatingBmb,\
+	md.results.TransientSolution[1].TotalFloatingBmbScaled,\
 	]
Index: /issm/trunk/test/NightlyRun/test505.py
===================================================================
--- /issm/trunk/test/NightlyRun/test505.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test505.py	(revision 22758)
@@ -19,7 +19,7 @@
 # Fields and tolerances to track changes
 field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', \
-				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2']
-field_tolerances=[1e-12,1e-12,1e-10,1e-12,1e-13,3e-13,7e-13,3e-13,1e-13,6e-10, \
-						2e-12,5e-12,1e-10,4e-12,3e-13,1e-11,1e-11,2e-12,1e-11,1e-8]
+        'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2']
+field_tolerances=[1e-12,1e-12,3e-10,1e-12,1e-13,1e-11,5e-12,9e-12,1e-13,5e-9, \
+        5e-11,5e-11,1e-10,2e-11,7e-12,1e-11,1e-11,5e-12,1e-11,2e-8]
 field_values=[\
 	md.results.TransientSolution[0].Vx,\
Index: /issm/trunk/test/NightlyRun/test506.m
===================================================================
--- /issm/trunk/test/NightlyRun/test506.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test506.m	(revision 22758)
@@ -3,14 +3,16 @@
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
 md=parameterize(md,'../Par/Pig.par');
+md.mesh.scale_factor=0.9*ones(md.mesh.numberofvertices,1);
 md=extrude(md,2,1.);
 md=setflowequation(md,'HO','all');
 md.cluster=generic('name',oshostname(),'np',3);
+md.transient.requested_outputs={'default','IceVolume','IceVolumeScaled','TotalSmb','TotalSmbScaled','TotalFloatingBmb','TotalFloatingBmbScaled','FloatingArea','FloatingAreaScaled','GroundedArea','GroundedAreaScaled'};
 md=solve(md,'Transient');
 
 %Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', ...
-				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2'};
-field_tolerances={1e-10,1e-10,1e-10,1e-10,1e-12,1e-11,2e-12,1e-11,1e-12,1e-09,...
-						1e-11,1e-11,1e-09,1e-11,1e-11,1e-10,1e-11,1e-10,1e-11,2e-08};
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1','IceVolume1','IceVolumeScaled1','GroundedArea1','GroundedAreaScaled1','FloatingArea1','FloatingAreaScaled1','TotalSmb1','TotalSmbScaled1','TotalFloatingBmb1','TotalFloatingBmbScaled1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2','IceVolume2','IceVolumeScaled2','GroundedArea2','GroundedAreaScaled2','FloatingArea2','FloatingAreaScaled2','TotalSmb2','TotalSmbScaled2','TotalFloatingBmb2','TotalFloatingBmbScaled2'};
+field_tolerances={1e-10,1e-10,1e-10,1e-10,1e-12,1e-11,2e-12,1e-11,1e-12,1e-09,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+						1e-11,1e-11,1e-09,1e-11,1e-11,1e-10,1e-11,1e-10,1e-11,2e-08,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
 	(md.results.TransientSolution(1).Vx),...
@@ -24,4 +26,14 @@
 	(md.results.TransientSolution(1).Temperature),...
 	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
+	(md.results.TransientSolution(1).IceVolume),...
+	(md.results.TransientSolution(1).IceVolumeScaled),...
+	(md.results.TransientSolution(1).GroundedArea),...
+	(md.results.TransientSolution(1).GroundedAreaScaled),...
+	(md.results.TransientSolution(1).FloatingArea),...
+	(md.results.TransientSolution(1).FloatingAreaScaled),...
+	(md.results.TransientSolution(1).TotalSmb),...
+	(md.results.TransientSolution(1).TotalSmbScaled),...
+	(md.results.TransientSolution(1).TotalFloatingBmb),...
+	(md.results.TransientSolution(1).TotalFloatingBmbScaled),...
 	(md.results.TransientSolution(2).Vx),...
 	(md.results.TransientSolution(2).Vy),...
@@ -34,3 +46,13 @@
 	(md.results.TransientSolution(2).Temperature),...
 	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
+	(md.results.TransientSolution(2).IceVolume),...
+	(md.results.TransientSolution(2).IceVolumeScaled),...
+	(md.results.TransientSolution(2).GroundedArea),...
+	(md.results.TransientSolution(2).GroundedAreaScaled),...
+	(md.results.TransientSolution(2).FloatingArea),...
+	(md.results.TransientSolution(2).FloatingAreaScaled),...
+	(md.results.TransientSolution(2).TotalSmb),...
+	(md.results.TransientSolution(2).TotalSmbScaled),...
+	(md.results.TransientSolution(2).TotalFloatingBmb),...
+	(md.results.TransientSolution(2).TotalFloatingBmbScaled),...
 	};
Index: /issm/trunk/test/NightlyRun/test506.py
===================================================================
--- /issm/trunk/test/NightlyRun/test506.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test506.py	(revision 22758)
@@ -12,14 +12,16 @@
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp')
 md=parameterize(md,'../Par/Pig.py')
+md.mesh.scale_factor=0.9*np.ones((md.mesh.numberofvertices))
 md.extrude(2,1.)
 md=setflowequation(md,'HO','all')
+md.transient.requested_outputs=['default','IceVolume','IceVolumeScaled','GroundedArea','GroundedAreaScaled','FloatingArea','FloatingAreaScaled','TotalSmb','TotalSmbScaled','TotalFloatingBmb','TotalFloatingBmbScaled']
 md.cluster=generic('name',gethostname(),'np',3)
 md=solve(md,'Transient')
 
 # Fields and tolerances to track changes
-field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', \
-				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2']
-field_tolerances=[1e-10,1e-10,1e-10,1e-10,1e-12,1e-11,2e-12,1e-11,1e-12,1e-09,\
-						1e-11,1e-11,1e-09,1e-11,1e-11,1e-10,1e-11,1e-10,1e-11,2e-08]
+field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1','IceVolume1','IceVolumeScaled1','GroundedArea1','GroundedAreaScaled1','FloatingArea1','FloatingAreaScaled1','TotalSmb1','TotalSmbScaled1','TotalFloatingBmb1','TotalFloatingBmbScaled1', \
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2','IceVolume2','IceVolumeScaled2','GroundedArea2','GroundedAreaScaled2','FloatingArea2','FloatingAreaScaled2','TotalSmb2','TotalSmbScaled2','TotalFloatingBmb2','TotalFloatingBmbScaled2']
+field_tolerances=[1e-10,1e-10,1e-10,1e-10,1e-12,1e-11,2e-12,1e-11,1e-12,1e-09,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,\
+						1e-11,1e-11,1e-09,1e-11,1e-11,1e-10,1e-11,1e-10,1e-11,2e-08,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13]
 field_values=[\
 	md.results.TransientSolution[0].Vx,\
@@ -33,4 +35,14 @@
 	md.results.TransientSolution[0].Temperature,\
 	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
+	md.results.TransientSolution[0].IceVolume,\
+	md.results.TransientSolution[0].IceVolumeScaled,\
+	md.results.TransientSolution[0].GroundedArea,\
+	md.results.TransientSolution[0].GroundedAreaScaled,\
+	md.results.TransientSolution[0].FloatingArea,\
+	md.results.TransientSolution[0].FloatingAreaScaled,\
+	md.results.TransientSolution[0].TotalSmb,\
+	md.results.TransientSolution[0].TotalSmbScaled,\
+	md.results.TransientSolution[0].TotalFloatingBmb,\
+	md.results.TransientSolution[0].TotalFloatingBmbScaled,\
 	md.results.TransientSolution[1].Vx,\
 	md.results.TransientSolution[1].Vy,\
@@ -43,3 +55,13 @@
 	md.results.TransientSolution[1].Temperature,\
 	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
+	md.results.TransientSolution[1].IceVolume,\
+	md.results.TransientSolution[1].IceVolumeScaled,\
+	md.results.TransientSolution[1].GroundedArea,\
+	md.results.TransientSolution[1].GroundedAreaScaled,\
+	md.results.TransientSolution[1].FloatingArea,\
+	md.results.TransientSolution[1].FloatingAreaScaled,\
+	md.results.TransientSolution[1].TotalSmb,\
+	md.results.TransientSolution[1].TotalSmbScaled,\
+	md.results.TransientSolution[1].TotalFloatingBmb,\
+	md.results.TransientSolution[1].TotalFloatingBmbScaled,\
 	]
Index: /issm/trunk/test/NightlyRun/test508.m
===================================================================
--- /issm/trunk/test/NightlyRun/test508.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test508.m	(revision 22758)
@@ -11,5 +11,5 @@
 %Fields and tolerances to track changes
 field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsGroundediceMeltingRate'};
-field_tolerances={5e-08,3e-08,5e-08,3e-08,1e-09,2e-07,8e-07};
+field_tolerances={5e-08,3e-08,5e-08,5e-08,1e-09,2e-07,8e-07};
 field_values={...
 	(md.results.SteadystateSolution.Vx),...
Index: /issm/trunk/test/NightlyRun/test508.py
===================================================================
--- /issm/trunk/test/NightlyRun/test508.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test508.py	(revision 22758)
@@ -20,5 +20,5 @@
 # Fields and tolerances to track changes
 field_names     =['Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsGroundediceMeltingRate']
-field_tolerances=[5e-08,1.6e-08,5e-08,1.6e-08,1e-09,6e-08,5e-07]
+field_tolerances=[5e-08,1.6e-08,5e-08,5e-08,1e-09,6e-08,5e-07]
 field_values=[\
 	md.results.SteadystateSolution.Vx,\
Index: /issm/trunk/test/NightlyRun/test514.m
===================================================================
--- /issm/trunk/test/NightlyRun/test514.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test514.m	(revision 22758)
@@ -3,5 +3,5 @@
 hVertices=10000.*ones(27,1);
 hVertices(1:5)=1000.;
-md=bamg(model(),'domain','../Exp/Pig.exp','hmax',20000.,'hVertices',hVertices,'gradation',3.,'geometricalmetric',1);
+md=bamg(model(),'domain','../Exp/Pig.exp','hmax',20000.,'hVertices',hVertices,'gradation',3.);
 x1=md.mesh.x;
 y1=md.mesh.y;
@@ -18,10 +18,10 @@
 metric=ComputeMetric(hessian,2./9.,1.,1000.,25.*10.^3,[]);
 md.miscellaneous.dummy=metric;
-md2=bamg(md,'metric',md.miscellaneous.dummy,'hmin',1000.,'hmax',20000.,'gradation',3.,'geometricalmetric',1);
+md2=bamg(md,'metric',md.miscellaneous.dummy,'hmin',1000.,'hmax',20000.,'gradation',3.);
 x3=md2.mesh.x;
 y3=md2.mesh.y;
 
 %refine existing mesh 2
-md2=bamg(md,'metric',md.miscellaneous.dummy,'hmin',1000.,'hmax',20000.,'gradation',3.,'geometricalmetric',1,'anisomax',1.);
+md2=bamg(md,'metric',md.miscellaneous.dummy,'hmin',1000.,'hmax',20000.,'gradation',3.,'anisomax',1.);
 x4=md2.mesh.x;
 y4=md2.mesh.y;
@@ -30,15 +30,15 @@
 hVertices=NaN*ones(md.mesh.numberofvertices,1);
 hVertices(find(md.mesh.vertexonboundary))=500;
-md2=bamg(md,'metric',md.miscellaneous.dummy,'hmin',1000.,'hmax',20000.,'gradation',3.,'geometricalmetric',1,'anisomax',1.,'hVertices',hVertices);
+md2=bamg(md,'metric',md.miscellaneous.dummy,'hmin',1000.,'hmax',20000.,'gradation',3.,'anisomax',1.,'hVertices',hVertices);
 x5=md2.mesh.x;
 y5=md2.mesh.y;
 
 %refine existing mesh 4
-md2=bamg(md,'field',md.inversion.vy_obs,'hmin',1000.,'hmax',20000.,'gradation',3.,'geometricalmetric',1,'Hessiantype',0,'err',1.);
+md2=bamg(md,'field',md.inversion.vy_obs,'hmin',1000.,'hmax',20000.,'gradation',3.,'Hessiantype',0,'err',1.);
 x6=md2.mesh.x;
 y6=md2.mesh.y;
 
 %refine existing mesh 5
-md2=bamg(md,'field',[md.inversion.vy_obs md.geometry.thickness],'hmin',1000.,'hmax',20000.,'gradation',3.,'geometricalmetric',1,'Hessiantype',1,'err',[10. 100.]); 
+md2=bamg(md,'field',[md.inversion.vy_obs md.geometry.thickness],'hmin',1000.,'hmax',20000.,'gradation',3.,'Hessiantype',1,'err',[10. 100.]); 
 x7=md2.mesh.x;
 y7=md2.mesh.y;
@@ -47,3 +47,3 @@
 field_names      = {'x1' ,'y1' ,'x2' ,'y2' ,'x3' ,'y3' ,'x4' ,'y4' ,'x5' ,'y5' ,'x6' ,'y6' ,'x7' ,'y7' };
 field_tolerances = {2e-10,7e-10,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
-field_values     = { x1  ,y1   ,y2   ,y2   ,y3   ,y3   ,y4   ,y4   ,y5   ,y5   ,y6   ,y6   ,y7   ,y7   };
+field_values     = { x1  ,y1   ,x2   ,y2   ,x3   ,y3   ,x4   ,y4   ,x5   ,y5   ,x6   ,y6   ,x7   ,y7   };
Index: /issm/trunk/test/NightlyRun/test514.py
===================================================================
--- /issm/trunk/test/NightlyRun/test514.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test514.py	(revision 22758)
@@ -14,5 +14,5 @@
 hVertices=10000.*np.ones((27))
 hVertices[0:5]=1000.
-md=bamg(model(),'domain','../Exp/Pig.exp','hmax',20000.,'hVertices',hVertices,'gradation',3.,'geometricalmetric',1)
+md=bamg(model(),'domain','../Exp/Pig.exp','hmax',20000.,'hVertices',hVertices,'gradation',3.)
 x1=md.mesh.x
 y1=md.mesh.y
@@ -29,10 +29,10 @@
 metric=ComputeMetric(hessian,2./9.,1.,1000.,25.*10.**3,[])
 md.miscellaneous.dummy=metric
-md2=bamg(copy.deepcopy(md),'metric',md.miscellaneous.dummy,'hmin',1000.,'hmax',20000.,'gradation',3.,'geometricalmetric',1)
+md2=bamg(copy.deepcopy(md),'metric',md.miscellaneous.dummy,'hmin',1000.,'hmax',20000.,'gradation',3.)
 x3=md2.mesh.x
 y3=md2.mesh.y
 
 #refine existing mesh 2
-md2=bamg(copy.deepcopy(md),'metric',md.miscellaneous.dummy,'hmin',1000.,'hmax',20000.,'gradation',3.,'geometricalmetric',1,'anisomax',1.)
+md2=bamg(copy.deepcopy(md),'metric',md.miscellaneous.dummy,'hmin',1000.,'hmax',20000.,'gradation',3.,'anisomax',1.)
 x4=md2.mesh.x
 y4=md2.mesh.y
@@ -41,15 +41,15 @@
 hVertices=np.nan*np.ones((md.mesh.numberofvertices))
 hVertices[np.nonzero(md.mesh.vertexonboundary)]=500.
-md2=bamg(copy.deepcopy(md),'metric',md.miscellaneous.dummy,'hmin',1000.,'hmax',20000.,'gradation',3.,'geometricalmetric',1,'anisomax',1.,'hVertices',hVertices)
+md2=bamg(copy.deepcopy(md),'metric',md.miscellaneous.dummy,'hmin',1000.,'hmax',20000.,'gradation',3.,'anisomax',1.,'hVertices',hVertices)
 x5=md2.mesh.x
 y5=md2.mesh.y
 
 #refine existing mesh 4
-md2=bamg(copy.deepcopy(md),'field',md.inversion.vy_obs,'hmin',1000.,'hmax',20000.,'gradation',3.,'geometricalmetric',1,'Hessiantype',0,'err',np.array([[1.]]))
+md2=bamg(copy.deepcopy(md),'field',md.inversion.vy_obs,'hmin',1000.,'hmax',20000.,'gradation',3.,'Hessiantype',0,'err',np.array([[1.]]))
 x6=md2.mesh.x
 y6=md2.mesh.y
 
 #refine existing mesh 5
-md2=bamg(copy.deepcopy(md),'field',np.hstack((md.inversion.vy_obs,md.geometry.thickness)),'hmin',1000.,'hmax',20000.,'gradation',3.,'geometricalmetric',1,'Hessiantype',1,'err',np.array([[10.,100.]])) 
+md2=bamg(copy.deepcopy(md),'field',np.hstack((md.inversion.vy_obs,md.geometry.thickness)),'hmin',1000.,'hmax',20000.,'gradation',3.,'Hessiantype',1,'err',np.array([[10.,100.]])) 
 x7=md2.mesh.x
 y7=md2.mesh.y
@@ -58,3 +58,3 @@
 field_names     =['x1','y1','x2','y2','x3','y3','x4','y4','x5','y5','x6','y6','x7','y7']
 field_tolerances = [2e-10,7e-10,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13]
-field_values=[x1, y1,	y2, y2,	y3, y3,	y4, y4,	y5, y5,	y6, y6,	y7, y7]
+field_values=[x1, y1,x2, y2,	x3, y3,	x4, y4,	x5, y5,	x6, y6,	x7, y7]
Index: /issm/trunk/test/NightlyRun/test540.m
===================================================================
--- /issm/trunk/test/NightlyRun/test540.m	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test540.m	(revision 22758)
@@ -0,0 +1,59 @@
+%Test Name: PigTranCalvingDevSSA2d
+md=triangle(model(),'../Exp/Pig.exp',10000.);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=setflowequation(md,'SSA','all');
+md.timestepping.time_step=2;
+md.timestepping.final_time=50;
+
+%calving parameters
+md.mask.ice_levelset = 1e4*(md.mask.ice_levelset + 0.5);
+md.calving=calvingvonmises();
+md.calving.meltingrate = zeros(md.mesh.numberofvertices,1);
+md.transient.ismovingfront = 1;
+md.levelset.spclevelset = NaN(md.mesh.numberofvertices,1);
+pos = find(md.mesh.vertexonboundary);
+md.levelset.spclevelset(pos) = md.mask.ice_levelset(pos);
+
+%Force MUMPS sequential analysis
+md.toolkits.DefaultAnalysis.mat_mumps_icntl_28=1;
+md.cluster=generic('name',oshostname(),'np',2);
+md=solve(md,'Transient');
+
+%Fields and tolerances to track changes
+field_names ={...
+	'Vx1' ,'Vy1' ,'Vel1' ,'Pressure1' ,'Bed1' ,'Surface1' ,'Thickness1' ,'MaskIceLevelset1' ,...
+	'Vx2' ,'Vy2' ,'Vel2' ,'Pressure2' ,'Bed2' ,'Surface2' ,'Thickness2' ,'MaskIceLevelset2' ,...
+	'Vx10','Vy10','Vel10','Pressure10','Bed10','Surface10','Thickness10','MaskIceLevelset10',...
+	};
+field_tolerances={...
+	1e-12,2e-12,2e-12,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-12,1e-12,1e-12,1e-13,1e-13,1e-13,1e-13,1e-12,...
+	1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-9,...
+	};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).MaskIceLevelset),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).MaskIceLevelset),...
+	(md.results.TransientSolution(10).Vx),...
+	(md.results.TransientSolution(10).Vy),...
+	(md.results.TransientSolution(10).Vel),...
+	(md.results.TransientSolution(10).Pressure),...
+	(md.results.TransientSolution(10).Base),...
+	(md.results.TransientSolution(10).Surface),...
+	(md.results.TransientSolution(10).Thickness),...
+	(md.results.TransientSolution(10).MaskIceLevelset),...
+	};
Index: /issm/trunk/test/NightlyRun/test540.py
===================================================================
--- /issm/trunk/test/NightlyRun/test540.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test540.py	(revision 22758)
@@ -0,0 +1,68 @@
+#Test Name: PigTranCalvingDevSSA2d
+from model import *
+from socket import gethostname
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+from calvingvonmises import *
+
+md = triangle(model(),'../Exp/Pig.exp',10000.)
+md = setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp')
+md = parameterize(md,'../Par/Pig.py')
+md = setflowequation(md,'SSA','all')
+md.timestepping.time_step = 2
+md.timestepping.final_time = 50
+
+#calving parameters
+md.mask.ice_levelset = 1e4 * (md.mask.ice_levelset + 0.5)
+md.calving = calvingvonmises()
+md.calving.meltingrate = np.zeros((md.mesh.numberofvertices,))
+md.transient.ismovingfront = 1
+md.levelset.spclevelset = float('NaN') * np.ones((md.mesh.numberofvertices,))
+pos = np.where(md.mesh.vertexonboundary)
+md.levelset.spclevelset[pos] = md.mask.ice_levelset[pos]
+
+#Force MUMPS sequential analysis
+md.toolkits.DefaultAnalysis.mat_mumps_icntl_28=1
+md.cluster = generic('name',gethostname(),'np',2)
+md = solve(md,'Transient')
+
+#Fields and tolerances to track changes
+field_names = [
+	'Vx1' ,'Vy1' ,'Vel1' ,'Pressure1' ,'Bed1' ,'Surface1' ,'Thickness1' ,'MaskIceLevelset1' ,
+	'Vx2' ,'Vy2' ,'Vel2' ,'Pressure2' ,'Bed2' ,'Surface2' ,'Thickness2' ,'MaskIceLevelset2' ,
+	'Vx10','Vy10','Vel10','Pressure10','Bed10','Surface10','Thickness10','MaskIceLevelset10',
+	]
+field_tolerances = [
+	1e-12,2e-12,2e-12,1e-13,1e-13,1e-13,1e-13,1e-13,
+	1e-12,1e-12,1e-12,1e-13,1e-13,1e-13,1e-13,1e-12,
+	1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-9,
+	]
+field_values = [
+	md.results.TransientSolution[0].Vx,
+	md.results.TransientSolution[0].Vy,
+	md.results.TransientSolution[0].Vel,
+	md.results.TransientSolution[0].Pressure,
+	md.results.TransientSolution[0].Base,
+	md.results.TransientSolution[0].Surface,
+	md.results.TransientSolution[0].Thickness,
+	md.results.TransientSolution[0].MaskIceLevelset,
+	md.results.TransientSolution[1].Vx,
+	md.results.TransientSolution[1].Vy,
+	md.results.TransientSolution[1].Vel,
+	md.results.TransientSolution[1].Pressure,
+	md.results.TransientSolution[1].Base,
+	md.results.TransientSolution[1].Surface,
+	md.results.TransientSolution[1].Thickness,
+	md.results.TransientSolution[1].MaskIceLevelset,
+	md.results.TransientSolution[9].Vx,
+	md.results.TransientSolution[9].Vy,
+	md.results.TransientSolution[9].Vel,
+	md.results.TransientSolution[9].Pressure,
+	md.results.TransientSolution[9].Base,
+	md.results.TransientSolution[9].Surface,
+	md.results.TransientSolution[9].Thickness,
+	md.results.TransientSolution[9].MaskIceLevelset,
+	]
Index: /issm/trunk/test/NightlyRun/test701.py
===================================================================
--- /issm/trunk/test/NightlyRun/test701.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test701.py	(revision 22758)
@@ -0,0 +1,74 @@
+#Test Name: FlowbandFSshelf
+import numpy as np
+from scipy.interpolate import interp1d
+from model import *
+from solve import *
+from setflowequation import *
+from bamgflowband import *
+from paterson import *
+
+x = np.arange(1,3001,100).T
+h = np.linspace(1000,300,np.size(x)).T
+b = -917./1023.*h
+
+md = bamgflowband(model(),x,b+h,b,'hmax',80.)
+
+#Geometry	    #interp1d returns a function to be called on md.mesh.x
+md.geometry.surface = interp1d(x,b+h)(md.mesh.x)
+md.geometry.base = interp1d(x,b)(md.mesh.x)
+md.geometry.thickness = md.geometry.surface-md.geometry.base
+
+#mask
+md.mask.ice_levelset = -np.ones((md.mesh.numberofvertices,))
+md.mask.ice_levelset[np.where(md.mesh.vertexflags(2))] = 0.
+md.mask.groundedice_levelset = np.zeros((md.mesh.numberofvertices,)) - 0.5
+
+#materials
+md.initialization.temperature = (273.-20.)*np.ones((md.mesh.numberofvertices,))
+md.materials.rheology_B = paterson(md.initialization.temperature)
+md.materials.rheology_n = 3.*np.ones((md.mesh.numberofelements,))
+
+#friction
+md.friction.coefficient = np.zeros((md.mesh.numberofvertices,))
+md.friction.coefficient[np.where(md.mesh.vertexflags(1))] = 20.
+md.friction.p = np.ones((md.mesh.numberofelements,))
+md.friction.q = np.ones((md.mesh.numberofelements,))
+
+#Boundary conditions
+md.stressbalance.referential = float('NaN')*np.ones((md.mesh.numberofvertices,6))
+md.stressbalance.loadingforce = 0. * np.ones((md.mesh.numberofvertices,3))
+md.stressbalance.spcvx = float('NaN') * np.ones((md.mesh.numberofvertices,))
+md.stressbalance.spcvy = float('NaN') * np.ones((md.mesh.numberofvertices,))
+md.stressbalance.spcvz = float('NaN') * np.ones((md.mesh.numberofvertices,))
+md.stressbalance.spcvx[np.where(md.mesh.vertexflags(4))] = 0.
+md.stressbalance.spcvy[np.where(md.mesh.vertexflags(4))] = 0.
+
+#Misc
+md = setflowequation(md,'FS','all')
+md.stressbalance.abstol = float('NaN')
+#md.stressbalance.reltol = 10**-16
+md.stressbalance.FSreconditioning = 1.
+md.stressbalance.maxiter = 20
+md.flowequation.augmented_lagrangian_r = 10000.
+md.miscellaneous.name  =  'test701'
+md.verbose = verbose('convergence',True)
+md.cluster = generic('np',2)
+
+#Go solve
+field_names = []
+field_tolerances = []
+field_values = []
+#md.initialization.pressure = md.constants.g*md.materials.rho_ice*(md.geometry.surface-md.mesh.y)
+for i in ['MINI','MINIcondensed','TaylorHood','LATaylorHood','CrouzeixRaviart','LACrouzeixRaviart']:
+	print ' '
+	print '======Testing ' +i+ ' Full-Stokes Finite element====='
+	md.flowequation.fe_FS = i
+	md = solve(md,'Stressbalance')
+	field_names = field_names + [['Vx'+i],['Vy'+i],['Vel'+i],['Pressure'+i]]
+	field_tolerances = field_tolerances + [9e-5,9e-5,9e-5,1e-10]
+	field_values = field_values + [
+		md.results.StressbalanceSolution.Vx,
+		md.results.StressbalanceSolution.Vy,
+		md.results.StressbalanceSolution.Vel,
+		md.results.StressbalanceSolution.Pressure
+		]
Index: /issm/trunk/test/NightlyRun/test703.py
===================================================================
--- /issm/trunk/test/NightlyRun/test703.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test703.py	(revision 22758)
@@ -0,0 +1,168 @@
+#Test Name: FlowbandFSsheetshelfTrans
+import numpy as np
+from scipy.interpolate import interp1d
+from model import  * 
+from setflowequation import  * 
+from solve import  *
+from NowickiProfile import *
+from bamgflowband import *
+from paterson import *
+
+#mesh parameters
+x = np.arange(-5,5.5,.5).T
+[b,h,sea] = NowickiProfile(x)
+x = x * 10**3
+h = h * 10**3
+b = (b-sea) * 10**3
+
+#for i in x:
+	#print i
+
+#for i in b:
+	#print '%.12f' % i
+#for i in h:
+	#print '%.11f' % i
+#print '%.12f' % sea
+
+#print x
+#print h
+#print b
+#print sea
+
+#mesh domain
+md = bamgflowband(model(),x,b+h,b,'hmax',150.)
+print md.mesh.numberofvertices
+
+#geometry
+md.geometry.surface = interp1d(x,b+h)(md.mesh.x)
+md.geometry.base = interp1d(x,b)(md.mesh.x)
+md.geometry.thickness = md.geometry.surface - md.geometry.base
+
+#mask
+md.mask.ice_levelset = -np.ones((md.mesh.numberofvertices,))
+md.mask.ice_levelset[np.where(md.mesh.vertexflags(2))] = 0
+md.mask.groundedice_levelset = np.zeros((md.mesh.numberofvertices,)) - 0.5
+
+#materials
+md.initialization.temperature = (273. - 20.) * np.ones((md.mesh.numberofvertices,))
+md.materials.rheology_B = paterson(md.initialization.temperature)
+md.materials.rheology_n = 3 * np.ones((md.mesh.numberofelements,))
+
+#friction
+md.friction.coefficient = np.zeros((md.mesh.numberofvertices,))
+md.friction.coefficient[np.where(md.mesh.vertexflags(1))] = 20
+md.friction.p = np.ones((md.mesh.numberofelements,))
+md.friction.q = np.ones((md.mesh.numberofelements,))
+
+#boundary conditions
+md.stressbalance.spcvx = float('NaN') * np.ones((md.mesh.numberofvertices,))
+md.stressbalance.spcvy = float('NaN') * np.ones((md.mesh.numberofvertices,))
+md.stressbalance.spcvz = float('NaN') * np.ones((md.mesh.numberofvertices,))
+md.stressbalance.referential = float('NaN') * np.ones((md.mesh.numberofvertices,6))
+md.stressbalance.loadingforce = 0 * np.ones((md.mesh.numberofvertices,3))
+md.stressbalance.spcvx[np.where(md.mesh.vertexflags(4))] = 800.
+md.stressbalance.spcvy[np.where(md.mesh.vertexflags(4))] = 0.
+
+#print md.stressbalance.referential
+#print md.stressbalance.loadingforce
+#print md.stressbalance.spcvx
+#print md.stressbalance.spcvy
+#print md.stressbalance.spcvz
+#print np.shape(md.stressbalance.referential)
+#print np.shape(md.stressbalance.loadingforce)
+#print np.shape(md.stressbalance.spcvx)
+#print np.shape(md.stressbalance.spcvy)
+#print np.shape(md.stressbalance.spcvz)
+
+#Misc
+md = setflowequation(md,'FS','all')
+md.flowequation.fe_FS = 'TaylorHood'
+md.stressbalance.abstol = float('NaN')
+md.miscellaneous.name = 'test703'
+
+#Transient settings
+md.timestepping.time_step = 0.000001
+md.timestepping.final_time = 0.000005
+md.stressbalance.shelf_dampening = 1.
+md.smb.mass_balance = np.zeros((md.mesh.numberofvertices,))
+md.basalforcings.groundedice_melting_rate = np.zeros((md.mesh.numberofvertices,))
+md.basalforcings.floatingice_melting_rate = np.zeros((md.mesh.numberofvertices,))
+md.basalforcings.geothermalflux = np.zeros((md.mesh.numberofvertices,))
+posb = np.intersect1d(np.where(md.mesh.x > 0.), np.where(md.mesh.vertexonbase))
+md.basalforcings.groundedice_melting_rate[posb] = 18.
+md.basalforcings.floatingice_melting_rate[posb] = 18.
+md.initialization.vx = np.zeros((md.mesh.numberofvertices,))
+md.initialization.vy = np.zeros((md.mesh.numberofvertices,))
+md.initialization.pressure = np.zeros((md.mesh.numberofvertices,))
+md.masstransport.spcthickness = float('NaN') * np.ones((md.mesh.numberofvertices,))
+md.thermal.spctemperature = float('NaN') * np.ones((md.mesh.numberofvertices,))
+md.transient.isthermal = 0
+md.masstransport.isfreesurface = 1
+
+#Go solve
+md.cluster = generic('np',3)
+md.stressbalance.shelf_dampening = 1
+md1 = solve(md,'Transient')
+
+md.stressbalance.shelf_dampening = 0
+md = solve(md,'Transient')
+
+#Fields and tolerances to track changes
+field_names      = [
+	'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1',
+	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2',
+	'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3',
+	'Vx1_damp','Vy1_damp','Vel1_damp','Pressure1_damp','Bed1_damp','Surface1_damp','Thickness1_damp',
+	'Vx2_damp','Vy2_damp','Vel2_damp','Pressure2_damp','Bed2_damp','Surface2_damp','Thickness2_damp',
+	'Vx3_damp','Vy3_damp','Vel3_damp','Pressure3_damp','Bed3_damp','Surface3_damp','Thickness3_damp']
+field_tolerances = [
+	2e-08,2e-08,2e-08,1e-08,1e-10,1e-10,1e-10,
+	2e-08,2e-08,2e-08,1e-08,1e-10,1e-10,1e-10,
+	2e-08,2e-08,2e-08,1e-08,1e-10,1e-10,1e-10,
+	5e-08,5e-08,5e-08,1e-08,1e-10,1e-10,1e-10,
+	5e-08,5e-08,5e-08,1e-08,1e-10,1e-10,1e-10,
+	5e-08,5e-08,5e-08,1e-08,1e-10,1e-10,1e-10]
+field_values = [
+	md.results.TransientSolution[0].Vx,
+	md.results.TransientSolution[0].Vy,
+	md.results.TransientSolution[0].Vel,
+	md.results.TransientSolution[0].Pressure,
+	md.results.TransientSolution[0].Base,
+	md.results.TransientSolution[0].Surface,
+	md.results.TransientSolution[0].Thickness,
+	md.results.TransientSolution[1].Vx,
+	md.results.TransientSolution[1].Vy,
+	md.results.TransientSolution[1].Vel,
+	md.results.TransientSolution[1].Pressure,
+	md.results.TransientSolution[1].Base,
+	md.results.TransientSolution[1].Surface,
+	md.results.TransientSolution[1].Thickness,
+	md.results.TransientSolution[2].Vx,
+	md.results.TransientSolution[2].Vy,
+	md.results.TransientSolution[2].Vel,
+	md.results.TransientSolution[2].Pressure,
+	md.results.TransientSolution[2].Base,
+	md.results.TransientSolution[2].Surface,
+	md.results.TransientSolution[2].Thickness,
+	md1.results.TransientSolution[0].Vx,
+	md1.results.TransientSolution[0].Vy,
+	md1.results.TransientSolution[0].Vel,
+	md1.results.TransientSolution[0].Pressure,
+	md1.results.TransientSolution[0].Base,
+	md1.results.TransientSolution[0].Surface,
+	md1.results.TransientSolution[0].Thickness,
+	md1.results.TransientSolution[1].Vx,
+	md1.results.TransientSolution[1].Vy,
+	md1.results.TransientSolution[1].Vel,
+	md1.results.TransientSolution[1].Pressure,
+	md1.results.TransientSolution[1].Base,
+	md1.results.TransientSolution[1].Surface,
+	md1.results.TransientSolution[1].Thickness,
+	md1.results.TransientSolution[2].Vx,
+	md1.results.TransientSolution[2].Vy,
+	md1.results.TransientSolution[2].Vel,
+	md1.results.TransientSolution[2].Pressure,
+	md1.results.TransientSolution[2].Base,
+	md1.results.TransientSolution[2].Surface,
+	md1.results.TransientSolution[2].Thickness,
+	]
Index: /issm/trunk/test/NightlyRun/test801.m
===================================================================
--- /issm/trunk/test/NightlyRun/test801.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test801.m	(revision 22758)
@@ -4,4 +4,5 @@
 md=parameterize(md,'../Par/ValleyGlacierShelf.par');
 md=setflowequation(md,'SSA','all');
+md.levelset.stabilization=2;
 md.cluster=generic('name',oshostname(),'np',3);
 
Index: /issm/trunk/test/NightlyRun/test801.py
===================================================================
--- /issm/trunk/test/NightlyRun/test801.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test801.py	(revision 22758)
@@ -12,4 +12,5 @@
 md=setmask(md,'','')
 md=parameterize(md,'../Par/ValleyGlacierShelf.py')
+md.levelset.stabilization=2
 md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',gethostname(),'np',3)
Index: /issm/trunk/test/NightlyRun/test803.m
===================================================================
--- /issm/trunk/test/NightlyRun/test803.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test803.m	(revision 22758)
@@ -28,5 +28,5 @@
 		'Vx2','Vy2','Vel2','Pressure2','Thickness2','Surface2','MaskIceLevelset2','Enthalpy2','Watercolumn2',...
 		'Vx3','Vy3','Vel3','Pressure3','Thickness3','Surface3','MaskIceLevelset3','Enthalpy3','Watercolumn3'};
-field_tolerances={1e-10,1e-10,1e-10,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+field_tolerances={1e-10,1e-10,1e-10,1e-13,1e-12,1e-12,1e-13,1e-13,1e-13,...
 		1e-9,1e-9,1e-10,1e-10,1e-10,1e-10,1e-10,1e-9,1e-10,...
 		1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10};
Index: /issm/trunk/test/NightlyRun/test803.py
===================================================================
--- /issm/trunk/test/NightlyRun/test803.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test803.py	(revision 22758)
@@ -35,34 +35,34 @@
 #Fields and tolerances to track changes
 field_names     =['Vx1','Vy1','Vel1','Pressure1','Thickness1','Surface1','MaskIceLevelset1','Enthalpy1','Watercolumn1',
-									'Vx2','Vy2','Vel2','Pressure2','Thickness2','Surface2','MaskIceLevelset2','Enthalpy2','Watercolumn2',
-									'Vx3','Vy3','Vel3','Pressure3','Thickness3','Surface3','MaskIceLevelset3','Enthalpy3','Watercolumn3']
-field_tolerances=[1e-10,1e-10,1e-10,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,
-									1e-9,1e-9,1e-10,1e-10,1e-10,1e-10,1e-10,1e-9,1e-10,
-									1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10]
+        'Vx2','Vy2','Vel2','Pressure2','Thickness2','Surface2','MaskIceLevelset2','Enthalpy2','Watercolumn2',
+        'Vx3','Vy3','Vel3','Pressure3','Thickness3','Surface3','MaskIceLevelset3','Enthalpy3','Watercolumn3']
+field_tolerances=[1e-10,1e-10,1e-10,1e-13,1e-12,1e-12,1e-13,1e-13,1e-13,
+        1e-9,1e-9,1e-10,1e-10,1e-10,1e-10,1e-10,1e-9,1e-10,
+        1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10]
 field_values=[md.results.TransientSolution[0].Vx,
-							md.results.TransientSolution[0].Vy,
-							md.results.TransientSolution[0].Vel,
-							md.results.TransientSolution[0].Pressure,
-							md.results.TransientSolution[0].Thickness,
-							md.results.TransientSolution[0].Surface,
-							md.results.TransientSolution[0].MaskIceLevelset,
-							md.results.TransientSolution[0].Enthalpy,
-							md.results.TransientSolution[0].Watercolumn,
-							md.results.TransientSolution[1].Vx,
-							md.results.TransientSolution[1].Vy,
-							md.results.TransientSolution[1].Vel,
-							md.results.TransientSolution[1].Pressure,
-							md.results.TransientSolution[1].Thickness,
-							md.results.TransientSolution[1].Surface,
-							md.results.TransientSolution[1].MaskIceLevelset,
-							md.results.TransientSolution[1].Enthalpy,
-							md.results.TransientSolution[1].Watercolumn,
-							md.results.TransientSolution[2].Vx,
-							md.results.TransientSolution[2].Vy,
-							md.results.TransientSolution[2].Vel,
-							md.results.TransientSolution[2].Pressure,
-							md.results.TransientSolution[2].Thickness,
-							md.results.TransientSolution[2].Surface,
-							md.results.TransientSolution[2].MaskIceLevelset,
-							md.results.TransientSolution[2].Enthalpy,
-							md.results.TransientSolution[2].Watercolumn]
+        md.results.TransientSolution[0].Vy,
+        md.results.TransientSolution[0].Vel,
+        md.results.TransientSolution[0].Pressure,
+        md.results.TransientSolution[0].Thickness,
+        md.results.TransientSolution[0].Surface,
+        md.results.TransientSolution[0].MaskIceLevelset,
+        md.results.TransientSolution[0].Enthalpy,
+        md.results.TransientSolution[0].Watercolumn,
+        md.results.TransientSolution[1].Vx,
+        md.results.TransientSolution[1].Vy,
+        md.results.TransientSolution[1].Vel,
+        md.results.TransientSolution[1].Pressure,
+        md.results.TransientSolution[1].Thickness,
+        md.results.TransientSolution[1].Surface,
+        md.results.TransientSolution[1].MaskIceLevelset,
+        md.results.TransientSolution[1].Enthalpy,
+        md.results.TransientSolution[1].Watercolumn,
+        md.results.TransientSolution[2].Vx,
+        md.results.TransientSolution[2].Vy,
+        md.results.TransientSolution[2].Vel,
+        md.results.TransientSolution[2].Pressure,
+        md.results.TransientSolution[2].Thickness,
+        md.results.TransientSolution[2].Surface,
+        md.results.TransientSolution[2].MaskIceLevelset,
+        md.results.TransientSolution[2].Enthalpy,
+        md.results.TransientSolution[2].Watercolumn]
Index: /issm/trunk/test/NightlyRun/test805.m
===================================================================
--- /issm/trunk/test/NightlyRun/test805.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test805.m	(revision 22758)
@@ -24,4 +24,5 @@
 md.calving.calvingrate=1000.*ones(md.mesh.numberofvertices,1);
 md.calving.meltingrate=zeros(md.mesh.numberofvertices,1);
+md.levelset.stabilization=2;
 
 md=solve(md,'Transient');
Index: /issm/trunk/test/NightlyRun/test805.py
===================================================================
--- /issm/trunk/test/NightlyRun/test805.py	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test805.py	(revision 22758)
@@ -33,4 +33,5 @@
 md.calving.calvingrate=1000.*np.ones((md.mesh.numberofvertices))
 md.calving.meltingrate=np.zeros((md.mesh.numberofvertices))
+md.levelset.stabilization=2
 
 md=solve(md,'Transient')
Index: /issm/trunk/test/NightlyRun/test808.m
===================================================================
--- /issm/trunk/test/NightlyRun/test808.m	(revision 22757)
+++ /issm/trunk/test/NightlyRun/test808.m	(revision 22758)
@@ -39,7 +39,7 @@
 	'Vx3','Vy3','Vel3','Pressure3','Thickness3','Surface3','MaskIceLevelset3'};
 field_tolerances={...
-	1e-8,1e-8,1e-8,1e-9,1e-9,1e-9,2e-9,...
-	1e-8,1e-8,1e-8,1e-9,1e-9,1e-9,2e-9,...
-	1e-8,1e-8,1e-8,1e-9,1e-9,1e-9,2e-9};
+	1e-8,1e-8,1e-8,1e-9,1e-9,1e-9,3e-9,...
+	1e-8,1e-8,1e-8,1e-9,1e-9,1e-9,3e-9,...
+	1e-8,1e-8,1e-8,1e-9,1e-9,1e-9,3e-9};
 field_values={...
 	md.results.TransientSolution(1).Vx,...
Index: /issm/trunk/test/NightlyRun/test808.py
===================================================================
--- /issm/trunk/test/NightlyRun/test808.py	(revision 22758)
+++ /issm/trunk/test/NightlyRun/test808.py	(revision 22758)
@@ -0,0 +1,76 @@
+#Test Name: SquareShelfLevelsetCalvingSSA2dMinThickness
+from model import *
+from socket import gethostname
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+import numpy as np
+from calvingminthickness import *
+
+md = triangle(model(),'../Exp/Square.exp',30000.)
+md = setmask(md,'all','')
+md = parameterize(md,'../Par/SquareShelf.py')
+md = setflowequation(md,'SSA','all')
+md.cluster = generic('name',gethostname(),'np',3)
+
+x = md.mesh.x
+xmin = min(x)
+xmax = max(x)
+Lx = (xmax - xmin)
+alpha = 2. / 3.
+md.mask.ice_levelset = -1 + 2 * (md.mesh.y > 9e5)
+
+md.timestepping.time_step = 1
+md.timestepping.final_time = 30
+
+#Transient
+md.transient.isstressbalance = 1
+md.transient.ismasstransport = 1
+md.transient.issmb = 1
+md.transient.isthermal = 0
+md.transient.isgroundingline = 0
+md.transient.isgia = 0
+md.transient.ismovingfront = 1
+
+md.calving = calvingminthickness()
+md.calving.min_thickness = 400
+md.calving.meltingrate = np.zeros((md.mesh.numberofvertices,))
+md.levelset.spclevelset = float('NaN')* np.ones((md.mesh.numberofvertices,))
+md.levelset.reinit_frequency = 1
+
+md = solve(md,'Transient')
+
+#Fields and tolerances to track changes
+field_names = [
+	'Vx1','Vy1','Vel1','Pressure1','Thickness1','Surface1','MaskIceLevelset1'
+	'Vx2','Vy2','Vel2','Pressure2','Thickness2','Surface2','MaskIceLevelset2'
+	'Vx3','Vy3','Vel3','Pressure3','Thickness3','Surface3','MaskIceLevelset3']
+field_tolerances = [
+	1e-8,1e-8,1e-8,1e-9,1e-9,1e-9,3e-9,
+	1e-8,1e-8,1e-8,1e-9,1e-9,1e-9,3e-9,
+	1e-8,1e-8,1e-8,1e-9,1e-9,1e-9,3e-9]
+field_values = [
+	md.results.TransientSolution[0].Vx,
+	md.results.TransientSolution[0].Vy,
+	md.results.TransientSolution[0].Vel,
+	md.results.TransientSolution[0].Pressure,
+	md.results.TransientSolution[0].Thickness,
+	md.results.TransientSolution[0].Surface,
+	md.results.TransientSolution[0].MaskIceLevelset,
+	md.results.TransientSolution[1].Vx,
+	md.results.TransientSolution[1].Vy,
+	md.results.TransientSolution[1].Vel,
+	md.results.TransientSolution[1].Pressure,
+	md.results.TransientSolution[1].Thickness,
+	md.results.TransientSolution[1].Surface,
+	md.results.TransientSolution[1].MaskIceLevelset,
+	md.results.TransientSolution[2].Vx,
+	md.results.TransientSolution[2].Vy,
+	md.results.TransientSolution[2].Vel,
+	md.results.TransientSolution[2].Pressure,
+	md.results.TransientSolution[2].Thickness,
+	md.results.TransientSolution[2].Surface,
+	md.results.TransientSolution[2].MaskIceLevelset
+	]
Index: /issm/trunk/test/Par/79North.par
===================================================================
--- /issm/trunk/test/Par/79North.par	(revision 22757)
+++ /issm/trunk/test/Par/79North.par	(revision 22758)
@@ -41,5 +41,4 @@
 
 %Numerical parameters
-md.stressbalance.viscosity_overshoot=0.3;
 md.masstransport.stabilization=1;
 md.thermal.stabilization=1;
Index: /issm/trunk/test/Par/79North.py
===================================================================
--- /issm/trunk/test/Par/79North.py	(revision 22757)
+++ /issm/trunk/test/Par/79North.py	(revision 22758)
@@ -44,5 +44,4 @@
 
 #Numerical parameters
-md.stressbalance.viscosity_overshoot=0.3
 md.masstransport.stabilization=1
 md.thermal.stabilization=1
Index: /issm/trunk/test/Par/GiaIvinsBenchmarksAB.par
===================================================================
--- /issm/trunk/test/Par/GiaIvinsBenchmarksAB.par	(revision 22757)
+++ /issm/trunk/test/Par/GiaIvinsBenchmarksAB.par	(revision 22758)
@@ -57,5 +57,4 @@
 
 %Numerical parameters
-md.stressbalance.viscosity_overshoot=0.0;
 md.masstransport.stabilization=1.;
 md.thermal.stabilization=1.;
Index: /issm/trunk/test/Par/GiaIvinsBenchmarksAB.py
===================================================================
--- /issm/trunk/test/Par/GiaIvinsBenchmarksAB.py	(revision 22758)
+++ /issm/trunk/test/Par/GiaIvinsBenchmarksAB.py	(revision 22758)
@@ -0,0 +1,83 @@
+#Geometry specific to Experiments A and B
+
+import os.path
+import inspect
+import numpy as np
+from arch import *
+from InterpFromMeshToMesh2d import *
+from paterson import *
+from verbose import *
+from SetIceSheetBC import *
+
+rad = 600000.
+nv = md.mesh.numberofvertices
+if (np.isnan(md.geometry.thickness)):
+	md.geometry.thickness = np.zeros((md.mesh.numberofvertices,))
+for i in range(nv):
+	dist = np.sqrt(md.mesh.x[i]**2 + md.mesh.y[i]**2)
+	if (dist <= rad):
+		md.geometry.thickness[i] = 2000.0
+	else:
+		md.geometry.thickness[i] = 1.0 # non-zero thickness
+
+md.geometry.thickness = md.geometry.thickness.reshape(-1,1)
+md.geometry.base = np.zeros((md.mesh.numberofvertices,))
+md.geometry.surface = md.geometry.thickness + md.geometry.base.reshape(-1,1) #would otherwise create a 91x91 matrix
+
+#Ice density used for benchmarking, not 917 kg/m^3
+md.materials.rho_ice = 1000 #kg m^3
+
+#GIA parameters specific to Experiments A  and B
+md.gia.mantle_viscosity = 1e21 * np.ones((md.mesh.numberofvertices,))		#in Pa.s
+md.gia.lithosphere_thickness = 100 * np.ones((md.mesh.numberofvertices,))	#in km
+md.materials.lithosphere_shear_modulus = 6.7*1e10				#in Pa
+md.materials.lithosphere_density = 3.36						#in g/cm^3
+md.materials.mantle_shear_modulus = 1.45*1e11					#in Pa
+md.materials.mantle_density = 3.38						#in g/cm^3
+
+#Initial velocity 
+x     = archread('../Data/SquareSheetConstrained.arch','x')
+y     = archread('../Data/SquareSheetConstrained.arch','y')
+vx    = archread('../Data/SquareSheetConstrained.arch','vx')
+vy    = archread('../Data/SquareSheetConstrained.arch','vy')
+index = archread('../Data/SquareSheetConstrained.arch','index').astype(int)
+
+md.initialization.vx = np.array(InterpFromMeshToMesh2d(index,x,y,vx,md.mesh.x,md.mesh.y)).reshape(-1,1)
+md.initialization.vy = np.array(InterpFromMeshToMesh2d(index,x,y,vy,md.mesh.x,md.mesh.y)).reshape(-1,1)
+vx    = None
+vy    = None
+x     = None
+y     = None
+index = None
+md.initialization.vz = np.zeros((md.mesh.numberofvertices,))
+md.initialization.pressure = np.zeros((md.mesh.numberofvertices,))
+
+#Materials
+md.initialization.temperature = (273. - 20.) * np.ones((md.mesh.numberofvertices,))
+md.materials.rheology_B = paterson(md.initialization.temperature)
+md.materials.rheology_n = 3. * np.ones((md.mesh.numberofelements,))
+
+#Friction
+md.friction.coefficient = 20. * np.ones((md.mesh.numberofvertices,))
+md.friction.coefficient[np.where(md.mask.groundedice_levelset < 0.)] = 0.
+md.friction.p = np.ones((md.mesh.numberofelements,))
+md.friction.q = np.ones((md.mesh.numberofelements,))
+
+#Numerical parameters
+md.masstransport.stabilization = 1
+md.thermal.stabilization = 1.
+md.verbose = verbose(0)
+md.settings.waitonlock = 30.
+md.stressbalance.restol = 0.05
+md.steadystate.reltol = 0.05
+md.stressbalance.reltol = 0.05
+md.stressbalance.abstol = float('NaN')
+md.timestepping.time_step = 1.
+md.timestepping.final_time = 3.
+
+#Boundary conditions:
+md = SetIceSheetBC(md)
+
+#Change name so that no test have the same name
+if len(inspect.stack()) > 2:
+	md.miscellaneous.name = os.path.basename(inspect.stack()[2][1]).split('.')[0]
Index: /issm/trunk/test/Par/GiaIvinsBenchmarksCD.par
===================================================================
--- /issm/trunk/test/Par/GiaIvinsBenchmarksCD.par	(revision 22757)
+++ /issm/trunk/test/Par/GiaIvinsBenchmarksCD.par	(revision 22758)
@@ -56,5 +56,4 @@
 
 %Numerical parameters
-md.stressbalance.viscosity_overshoot=0.0;
 md.masstransport.stabilization=1.;
 md.thermal.stabilization=1.;
Index: /issm/trunk/test/Par/GiaIvinsBenchmarksCD.py
===================================================================
--- /issm/trunk/test/Par/GiaIvinsBenchmarksCD.py	(revision 22758)
+++ /issm/trunk/test/Par/GiaIvinsBenchmarksCD.py	(revision 22758)
@@ -0,0 +1,83 @@
+#Geometry specific to Experiments C and D
+
+import os.path
+import inspect
+import numpy as np
+from arch import *
+from InterpFromMeshToMesh2d import *
+from paterson import *
+from verbose import *
+from SetIceSheetBC import *
+
+rad = 800000
+nv = md.mesh.numberofvertices
+if (np.isnan(md.geometry.thickness)):
+	md.geometry.thickness = np.zeros((md.mesh.numberofvertices,))
+for i in range(nv):
+	dist = np.sqrt(md.mesh.x[i]**2 + md.mesh.y[i]**2)
+	if (dist <= rad):
+		md.geometry.thickness[i] = 3000.0
+	else:
+		md.geometry.thickness[i] = 1.0 # non-zero thickness
+
+md.geometry.thickness = md.geometry.thickness.reshape(-1,1)
+md.geometry.base = np.zeros((md.mesh.numberofvertices,))
+md.geometry.surface = md.geometry.thickness + md.geometry.base.reshape(-1,1) #would otherwise create a 91x91 matrix
+
+#Ice density used for benchmarking, not 917 kg/m^3
+md.materials.rho_ice = 1000 #kg m^3
+
+#GIA parameters specific to Experiments A  and B
+md.gia.mantle_viscosity = 1e21 * np.ones((md.mesh.numberofvertices,))		#in Pa.s
+md.gia.lithosphere_thickness = 100 * np.ones((md.mesh.numberofvertices,))	#in km
+md.materials.lithosphere_shear_modulus = 6.7*1e10				#in Pa
+md.materials.lithosphere_density = 3.32						#in g/cm^3
+md.materials.mantle_shear_modulus = 1.45*1e11					#in Pa
+md.materials.mantle_density = 3.34						#in g/cm^3
+
+#Initial velocity 
+x     = archread('../Data/SquareSheetConstrained.arch','x')
+y     = archread('../Data/SquareSheetConstrained.arch','y')
+vx    = archread('../Data/SquareSheetConstrained.arch','vx')
+vy    = archread('../Data/SquareSheetConstrained.arch','vy')
+index = archread('../Data/SquareSheetConstrained.arch','index').astype(int)
+
+md.initialization.vx = np.array(InterpFromMeshToMesh2d(index,x,y,vx,md.mesh.x,md.mesh.y)).reshape(-1,1)
+md.initialization.vy = np.array(InterpFromMeshToMesh2d(index,x,y,vy,md.mesh.x,md.mesh.y)).reshape(-1,1)
+vx    = None
+vy    = None
+x     = None
+y     = None
+index = None
+md.initialization.vz = np.zeros((md.mesh.numberofvertices,))
+md.initialization.pressure = np.zeros((md.mesh.numberofvertices,))
+
+#Materials
+md.initialization.temperature = (273. - 20.) * np.ones((md.mesh.numberofvertices,))
+md.materials.rheology_B = paterson(md.initialization.temperature)
+md.materials.rheology_n = 3. * np.ones((md.mesh.numberofelements,))
+
+#Friction
+md.friction.coefficient = 20. * np.ones((md.mesh.numberofvertices,))
+md.friction.coefficient[np.where(md.mask.groundedice_levelset < 0.)] = 0.
+md.friction.p = np.ones((md.mesh.numberofelements,))
+md.friction.q = np.ones((md.mesh.numberofelements,))
+
+#Numerical parameters
+md.masstransport.stabilization = 1.
+md.thermal.stabilization = 1.
+md.verbose = verbose(0)
+md.settings.waitonlock = 30.
+md.stressbalance.restol = 0.05
+md.steadystate.reltol = 0.05
+md.stressbalance.reltol = 0.05
+md.stressbalance.abstol = float('NaN')
+md.timestepping.time_step = 1.
+md.timestepping.final_time = 3.
+
+#Boundary conditions:
+md = SetIceSheetBC(md)
+
+#Change name so that no test have the same name
+if len(inspect.stack()) > 2:
+	md.miscellaneous.name = os.path.basename(inspect.stack()[2][1]).split('.')[0]
Index: /issm/trunk/test/Par/ISMIPE.par
===================================================================
--- /issm/trunk/test/Par/ISMIPE.par	(revision 22757)
+++ /issm/trunk/test/Par/ISMIPE.par	(revision 22758)
@@ -14,4 +14,5 @@
 	md.geometry.surface(i)=(1.-coeff)*data(point1,3)+coeff*data(point2,3);
 end
+
 md.geometry.thickness=md.geometry.surface-md.geometry.base;
 md.geometry.thickness(find(~md.geometry.thickness))=0.01;
Index: /issm/trunk/test/Par/ISMIPE.py
===================================================================
--- /issm/trunk/test/Par/ISMIPE.py	(revision 22757)
+++ /issm/trunk/test/Par/ISMIPE.py	(revision 22758)
@@ -13,7 +13,8 @@
 	point1=numpy.floor(y/100.)
 	point2=numpy.minimum(point1+1,50)
-	coeff=(y-(point1-1.)*100.)/100.
+	coeff=(y-(point1)*100.)/100.
 	md.geometry.base[i]=(1.-coeff)*data[point1,1]+coeff*data[point2,1]
 	md.geometry.surface[i]=(1.-coeff)*data[point1,2]+coeff*data[point2,2]
+
 md.geometry.thickness=md.geometry.surface-md.geometry.base
 md.geometry.thickness[numpy.nonzero(numpy.logical_not(md.geometry.thickness))]=0.01
Index: /issm/trunk/test/Par/IceCube.par
===================================================================
--- /issm/trunk/test/Par/IceCube.par	(revision 22757)
+++ /issm/trunk/test/Par/IceCube.par	(revision 22758)
@@ -27,5 +27,4 @@
 
 %Numerical parameters
-md.stressbalance.viscosity_overshoot=0.0;
 md.masstransport.stabilization=1.;
 md.thermal.stabilization=1.;
Index: /issm/trunk/test/Par/IceCube.py
===================================================================
--- /issm/trunk/test/Par/IceCube.py	(revision 22757)
+++ /issm/trunk/test/Par/IceCube.py	(revision 22758)
@@ -36,5 +36,4 @@
 
 #Numerical parameters
-md.stressbalance.viscosity_overshoot=0.0
 md.masstransport.stabilization=1.
 md.thermal.stabilization=1.
Index: /issm/trunk/test/Par/Pig.par
===================================================================
--- /issm/trunk/test/Par/Pig.par	(revision 22757)
+++ /issm/trunk/test/Par/Pig.par	(revision 22758)
@@ -42,5 +42,4 @@
 
 %Numerical parameters
-md.stressbalance.viscosity_overshoot=0.3;
 md.masstransport.stabilization=1;
 md.verbose=verbose(0);
Index: /issm/trunk/test/Par/Pig.py
===================================================================
--- /issm/trunk/test/Par/Pig.py	(revision 22757)
+++ /issm/trunk/test/Par/Pig.py	(revision 22758)
@@ -42,5 +42,4 @@
 
 #Numerical parameters
-md.stressbalance.viscosity_overshoot=0.3
 md.masstransport.stabilization=1.
 md.verbose=verbose(0)
Index: /issm/trunk/test/Par/RoundSheetShelf.par
===================================================================
--- /issm/trunk/test/Par/RoundSheetShelf.par	(revision 22757)
+++ /issm/trunk/test/Par/RoundSheetShelf.par	(revision 22758)
@@ -82,5 +82,4 @@
 
 %Numerical parameters
-md.stressbalance.viscosity_overshoot=0.0;
 md.masstransport.stabilization=1;
 md.thermal.stabilization=1;
Index: /issm/trunk/test/Par/RoundSheetShelf.py
===================================================================
--- /issm/trunk/test/Par/RoundSheetShelf.py	(revision 22757)
+++ /issm/trunk/test/Par/RoundSheetShelf.py	(revision 22758)
@@ -90,5 +90,4 @@
 
 #Numerical parameters
-md.stressbalance.viscosity_overshoot=0.0
 md.masstransport.stabilization=1
 md.thermal.stabilization=1
Index: /issm/trunk/test/Par/SquareSheetConstrained.par
===================================================================
--- /issm/trunk/test/Par/SquareSheetConstrained.par	(revision 22757)
+++ /issm/trunk/test/Par/SquareSheetConstrained.par	(revision 22758)
@@ -47,5 +47,4 @@
 
 %Numerical parameters
-md.stressbalance.viscosity_overshoot=0.0;
 md.masstransport.stabilization=1.;
 md.thermal.stabilization=1.;
Index: /issm/trunk/test/Par/SquareSheetConstrained.py
===================================================================
--- /issm/trunk/test/Par/SquareSheetConstrained.py	(revision 22757)
+++ /issm/trunk/test/Par/SquareSheetConstrained.py	(revision 22758)
@@ -49,5 +49,4 @@
 
 #Numerical parameters
-md.stressbalance.viscosity_overshoot=0.0
 md.masstransport.stabilization=1.
 md.thermal.stabilization=1.
Index: /issm/trunk/test/Par/SquareSheetShelf.par
===================================================================
--- /issm/trunk/test/Par/SquareSheetShelf.par	(revision 22757)
+++ /issm/trunk/test/Par/SquareSheetShelf.par	(revision 22758)
@@ -49,5 +49,4 @@
 
 %Numerical parameters
-md.stressbalance.viscosity_overshoot=0.0;
 md.masstransport.stabilization=1;
 md.thermal.stabilization=1;
Index: /issm/trunk/test/Par/SquareSheetShelf.py
===================================================================
--- /issm/trunk/test/Par/SquareSheetShelf.py	(revision 22757)
+++ /issm/trunk/test/Par/SquareSheetShelf.py	(revision 22758)
@@ -53,5 +53,4 @@
 
 #Numerical parameters
-md.stressbalance.viscosity_overshoot=0.0
 md.masstransport.stabilization=1
 md.thermal.stabilization=1
Index: /issm/trunk/test/Par/SquareShelf.par
===================================================================
--- /issm/trunk/test/Par/SquareShelf.par	(revision 22757)
+++ /issm/trunk/test/Par/SquareShelf.par	(revision 22758)
@@ -41,5 +41,4 @@
 
 %Numerical parameters
-md.stressbalance.viscosity_overshoot=0.3;
 md.masstransport.stabilization=1;
 md.thermal.stabilization=1;
Index: /issm/trunk/test/Par/SquareShelf.py
===================================================================
--- /issm/trunk/test/Par/SquareShelf.py	(revision 22757)
+++ /issm/trunk/test/Par/SquareShelf.py	(revision 22758)
@@ -62,5 +62,4 @@
 
 #Numerical parameters
-md.stressbalance.viscosity_overshoot = 0.3
 md.masstransport.stabilization = 1.
 md.thermal.stabilization = 1.
Index: /issm/trunk/test/Par/SquareShelf2.par
===================================================================
--- /issm/trunk/test/Par/SquareShelf2.par	(revision 22757)
+++ /issm/trunk/test/Par/SquareShelf2.par	(revision 22758)
@@ -41,5 +41,4 @@
 
 %Numerical parameters
-md.stressbalance.viscosity_overshoot=0.3;
 md.masstransport.stabilization=1;
 md.thermal.stabilization=1;
Index: /issm/trunk/test/Par/SquareShelf2.py
===================================================================
--- /issm/trunk/test/Par/SquareShelf2.py	(revision 22757)
+++ /issm/trunk/test/Par/SquareShelf2.py	(revision 22758)
@@ -61,5 +61,4 @@
 
 #Numerical parameters
-md.stressbalance.viscosity_overshoot = 0.3
 md.masstransport.stabilization = 1.
 md.thermal.stabilization = 1.
Index: /issm/trunk/test/Par/SquareShelfConstrained.js
===================================================================
--- /issm/trunk/test/Par/SquareShelfConstrained.js	(revision 22757)
+++ /issm/trunk/test/Par/SquareShelfConstrained.js	(revision 22758)
@@ -51,5 +51,4 @@
 
 	//Numerical parameters
-	md.stressbalance.viscosity_overshoot=0.0;
 	md.masstransport.stabilization=1;
 	md.thermal.stabilization=1;
Index: /issm/trunk/test/Par/SquareShelfConstrained.par
===================================================================
--- /issm/trunk/test/Par/SquareShelfConstrained.par	(revision 22757)
+++ /issm/trunk/test/Par/SquareShelfConstrained.par	(revision 22758)
@@ -47,5 +47,4 @@
 
 %Numerical parameters
-md.stressbalance.viscosity_overshoot=0.0;
 md.masstransport.stabilization=1;
 md.thermal.stabilization=1;
Index: /issm/trunk/test/Par/SquareShelfConstrained.py
===================================================================
--- /issm/trunk/test/Par/SquareShelfConstrained.py	(revision 22757)
+++ /issm/trunk/test/Par/SquareShelfConstrained.py	(revision 22758)
@@ -52,5 +52,4 @@
 
 #Numerical parameters
-md.stressbalance.viscosity_overshoot=0.0
 md.masstransport.stabilization=1.
 md.thermal.stabilization=1.
Index: /issm/trunk/test/Par/SquareThermal.py
===================================================================
--- /issm/trunk/test/Par/SquareThermal.py	(revision 22757)
+++ /issm/trunk/test/Par/SquareThermal.py	(revision 22758)
@@ -26,4 +26,7 @@
 print "      creating temperatures"
 md.initialization.temperature=(273.-20.)*numpy.ones((md.mesh.numberofvertices))
+md.initialization.pressure=numpy.zeros((md.mesh.numberofvertices,))
+md.initialization.waterfraction=numpy.zeros((md.mesh.numberofvertices,))
+md.initialization.watercolumn=numpy.zeros((md.mesh.numberofvertices,))
 
 print "      creating flow law parameter"
@@ -33,5 +36,7 @@
 print "      creating surface mass balance"
 md.smb.mass_balance=numpy.ones((md.mesh.numberofvertices))/md.constants.yts    #1m/a
-md.basalforcings.melting_rate=0.*numpy.ones((md.mesh.numberofvertices))/md.constants.yts    #1m/a
+#md.basalforcings.melting_rate=0.*numpy.ones((md.mesh.numberofvertices))/md.constants.yts    #1m/a
+md.basalforcings.groundedice_melting_rate=0.*numpy.ones((md.mesh.numberofvertices))/md.constants.yts    #1m/a
+md.basalforcings.floatingice_melting_rate=0.*numpy.ones((md.mesh.numberofvertices))/md.constants.yts    #1m/a
 
 #Deal with boundary conditions:
@@ -41,5 +46,5 @@
 
 print "      boundary conditions for thermal model"
-md.thermal.spctemperature=md.initialization.temperature
+md.thermal.spctemperature[:]=md.initialization.temperature
 md.basalforcings.geothermalflux=numpy.zeros((md.mesh.numberofvertices)) 
 md.basalforcings.geothermalflux[numpy.nonzero(md.mask.groundedice_levelset>0.)[0]]=1.*10**-3    #1 mW/m^2
Index: /issm/trunk/test/Par/ValleyGlacierShelf.par
===================================================================
--- /issm/trunk/test/Par/ValleyGlacierShelf.par	(revision 22757)
+++ /issm/trunk/test/Par/ValleyGlacierShelf.par	(revision 22758)
@@ -69,5 +69,4 @@
 %Stressbalance
 md.stressbalance.maxiter = 100;
-md.stressbalance.viscosity_overshoot = 0.0;
 md.stressbalance.restol = 0.05;
 md.stressbalance.reltol = 0.05;
Index: /issm/trunk/test/Par/ValleyGlacierShelf.py
===================================================================
--- /issm/trunk/test/Par/ValleyGlacierShelf.py	(revision 22757)
+++ /issm/trunk/test/Par/ValleyGlacierShelf.py	(revision 22758)
@@ -76,5 +76,4 @@
 #Stressbalance
 md.stressbalance.maxiter=100
-md.stressbalance.viscosity_overshoot=0.0
 md.stressbalance.restol=0.05
 md.stressbalance.reltol=0.05
