Index: issm/trunk/AUTHORS
===================================================================
--- issm/trunk/AUTHORS	(revision 18081)
+++ issm/trunk/AUTHORS	(revision 18301)
@@ -11,5 +11,5 @@
    * Eric Larour <eric.larour@jpl.nasa.gov>
    * Helene Seroussi <helene.seroussi@jpl.nasa.gov>
-   * Mathieu Morlighem <mathieu.morlighem@jpl.nasa.gov>
+   * Mathieu Morlighem <mathieu.morlighem@uci.edu>
 
 Contributors:
Index: issm/trunk/configs/config-ios-armv7.sh
===================================================================
--- issm/trunk/configs/config-ios-armv7.sh	(revision 18301)
+++ issm/trunk/configs/config-ios-armv7.sh	(revision 18301)
@@ -0,0 +1,32 @@
+#!/bin/sh
+set -eu
+
+export DEVROOT=`xcode-select --print-path`
+export SDKROOT="$DEVROOT/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS7.1.sdk"
+export CLANG="$DEVROOT/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang"
+export CLANGXX="$DEVROOT/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++"
+export CC=$CLANG
+export LD=$DEVROOT/usr/bin/ld
+export CPPFLAGS="-isysroot $SDKROOT/usr/include"
+export CXX=$CLANGXX
+export CXXFLAGS="-O -arch armv7 -isysroot $SDKROOT -I$SDKROOT/usr/include" 
+export CFLAGS="-O -arch armv7 -isysroot $SDKROOT -I$SDKROOT/usr/include"
+export AR=$DEVROOT/Toolchains/XcodeDefault.xctoolchain/usr/bin/ar
+export AS=$DEVROOT/Toolchains/XcodeDefault.xctoolchain/usr/bin/as
+export LDFLAGS="-lstdc++ -arch armv7 -isysroot $SDKROOT" 
+export LIBTOOL=$DEVROOT/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool
+export STRIP=$DEVROOT/Toolchains/XcodeDefault.xctoolchain/usr/bin/strip
+export RANLIB=$DEVROOT/Toolchains/XcodeDefault.xctoolchain/usr/bin/ranlib
+
+./configure                                                        \
+	--prefix=$ISSM_DIR                                              \
+   --build="i386-apple-darwin13.1.0"                               \
+   --host="armv7-apple-darwin14.0.0"                               \
+   --enable-shared                                                 \
+   --with-ios=yes                                                  \
+   --with-Gia=no                                                   \
+   --without-fortran                                               \
+	--without-wrappers                                              \
+	--without-kriging                                               \
+	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install           \
+	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
Index: issm/trunk/configs/config-ios-armv7s.sh
===================================================================
--- issm/trunk/configs/config-ios-armv7s.sh	(revision 18301)
+++ issm/trunk/configs/config-ios-armv7s.sh	(revision 18301)
@@ -0,0 +1,32 @@
+#!/bin/sh
+set -eu
+
+export DEVROOT=`xcode-select --print-path`
+export SDKROOT="$DEVROOT/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS7.1.sdk"
+export CLANG="$DEVROOT/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang"
+export CLANGXX="$DEVROOT/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++"
+export CC=$CLANG
+export LD=$DEVROOT/usr/bin/ld
+export CPPFLAGS="-isysroot $SDKROOT/usr/include"
+export CXX=$CLANGXX
+export CXXFLAGS="-O -arch armv7s -isysroot $SDKROOT -I$SDKROOT/usr/include" 
+export CFLAGS="-O -arch armv7s -isysroot $SDKROOT -I$SDKROOT/usr/include"
+export AR=$DEVROOT/Toolchains/XcodeDefault.xctoolchain/usr/bin/ar
+export AS=$DEVROOT/Toolchains/XcodeDefault.xctoolchain/usr/bin/as
+export LDFLAGS="-lstdc++ -arch armv7s -isysroot $SDKROOT" 
+export LIBTOOL=$DEVROOT/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool
+export STRIP=$DEVROOT/Toolchains/XcodeDefault.xctoolchain/usr/bin/strip
+export RANLIB=$DEVROOT/Toolchains/XcodeDefault.xctoolchain/usr/bin/ranlib
+
+./configure                                                        \
+	--prefix=$ISSM_DIR                                              \
+   --build="i386-apple-darwin13.1.0"                               \
+   --host="armv7s-apple-darwin14.0.0"                               \
+   --enable-shared                                                 \
+   --with-ios=yes                                                  \
+   --with-Gia=no                                                   \
+   --without-fortran                                               \
+	--without-wrappers                                              \
+	--without-kriging                                               \
+	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install           \
+	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
Index: issm/trunk/configs/config-ios-simulator.sh
===================================================================
--- issm/trunk/configs/config-ios-simulator.sh	(revision 18301)
+++ issm/trunk/configs/config-ios-simulator.sh	(revision 18301)
@@ -0,0 +1,31 @@
+#!/bin/sh
+set -eu
+
+export DEVROOT=`xcode-select --print-path`
+export SDKROOT="$DEVROOT/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator7.1.sdk"
+export CLANG="$DEVROOT/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang"
+export CLANGXX="$DEVROOT/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++"
+export CC=$CLANG
+export CXX=$CLANGXX
+export LD=$DEVROOT/usr/bin/ld
+export CPPFLAGS="-isysroot $SDKROOT/usr/include"
+export CXXFLAGS="-O -arch i386 -miphoneos-version-min=7.1 -isysroot $SDKROOT -I$SDKROOT/usr/include"
+export CFLAGS="-O -arch i386 -miphoneos-version-min=7.1  -isysroot $SDKROOT -I$SDKROOT/usr/include"
+export AR=$DEVROOT/Toolchains/XcodeDefault.xctoolchain/usr/bin/ar
+export AS=$DEVROOT/Toolchains/XcodeDefault.xctoolchain/usr/bin/as
+export LDFLAGS="-lstdc++ -arch i386 -isysroot $SDKROOT" 
+export LIBTOOL=$DEVROOT/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool
+export STRIP=$DEVROOT/Toolchains/XcodeDefault.xctoolchain/usr/bin/strip
+export RANLIB=$DEVROOT/Toolchains/XcodeDefault.xctoolchain/usr/bin/ranlib
+
+./configure                                                        \
+	--prefix=$ISSM_DIR                                              \
+   --target="i386-apple-darwin13.1.0"                              \
+   --enable-shared                                                 \
+   --with-ios=yes                                                  \
+   --with-Gia=no                                                   \
+   --without-fortran                                               \
+	--without-wrappers                                              \
+	--without-kriging                                               \
+	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install           \
+	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
Index: issm/trunk/configure.ac
===================================================================
--- issm/trunk/configure.ac	(revision 18081)
+++ issm/trunk/configure.ac	(revision 18301)
@@ -2,5 +2,5 @@
 
 #AUTOCONF
-AC_INIT([Ice Sheet System Model (ISSM)],[4.7],[issm@jpl.nasa.gov],[issm],[http://issm.jpl.nasa.gov]) #Initializing configure
+AC_INIT([Ice Sheet System Model (ISSM)],[4.8],[issm@jpl.nasa.gov],[issm],[http://issm.jpl.nasa.gov]) #Initializing configure
 AC_CONFIG_AUX_DIR([./aux-config])         #Put config files in aux-config
 AC_CONFIG_MACRO_DIR([m4])                 #m4 macros are located in m4
Index: issm/trunk/etc/environment.sh
===================================================================
--- issm/trunk/etc/environment.sh	(revision 18081)
+++ issm/trunk/etc/environment.sh	(revision 18301)
@@ -102,4 +102,5 @@
 pathappend "$DAKOTA_DIR/bin"
 libpathappend "$DAKOTA_DIR/lib"
+dylibpathprepend "$DAKOTA_DIR/lib"
 
 DOXYGEN_DIR="$ISSM_DIR/externalpackages/doxygen/install"
@@ -140,7 +141,7 @@
 	export BOOSTROOT
 	export BOOST_DIR
-	libpathappend   "$BOOST_DIR/lib"
-	dylibpathappend "$BOOST_DIR/lib"
-	pathappend      "$BOOST_DIR/bin"
+	libpathprepend   "$BOOST_DIR/lib"
+	dylibpathprepend "$BOOST_DIR/lib"
+	pathprepend      "$BOOST_DIR/bin"
 fi
 
Index: issm/trunk/examples/Data/Download.sh
===================================================================
--- issm/trunk/examples/Data/Download.sh	(revision 18301)
+++ issm/trunk/examples/Data/Download.sh	(revision 18301)
@@ -0,0 +1,25 @@
+#!/bin/bash
+
+echo "Downloading Square shelf dataset"
+$ISSM_DIR/scripts/DownloadExternalPackage2.py 'http://issm.jpl.nasa.gov/files/workshop2014/SquareShelf.nc' 'SquareShelf.nc'
+
+echo "Downloading SeaRISE dataset - Antarctica"
+$ISSM_DIR/scripts/DownloadExternalPackage2.py 'http://websrv.cs.umt.edu/isis/images/c/cc/Antarctica_5km_withshelves_v0.75.nc' 'Antarctica_5km_withshelves_v0.75.nc'
+
+echo "Downloading InSAR Antarctic velocities"
+$ISSM_DIR/scripts/DownloadExternalPackage2.py 'ftp://sidads.colorado.edu/pub/DATASETS/nsidc0484_MEASURES_antarc_vel_V01/900m/antarctica_ice_velocity.nc' 'Antarctica_ice_velocity.nc' 
+
+echo "Downloading PIG errors"
+$ISSM_DIR/scripts/DownloadExternalPackage2.py 'http://issm.jpl.nasa.gov/files/workshop2014/CrossOvers2009.mat' 'CrossOvers2009.mat'
+
+echo "Downloading SeaRISE dataset - Greenland"
+$ISSM_DIR/scripts/DownloadExternalPackage2.py 'http://websrv.cs.umt.edu/isis/images/e/e9/Greenland_5km_dev1.2.nc' 'Greenland_5km_dev1.2.nc'
+
+echo "Downloading Jason Box's SMB"
+$ISSM_DIR/scripts/DownloadExternalPackage2.py 'http://issm.jpl.nasa.gov/files/workshop2014/Box_Greenland_SMB_monthly_1840-2012_5km_ver20140421.nc' 'Box_Greenland_SMB_monthly_1840-2012_5km_ver20140421.nc'
+
+echo "Downloading IceBridge Jakobshavn bedrock"
+$ISSM_DIR/scripts/DownloadExternalPackage2.py 'https://data.cresis.ku.edu/data/grids/old_versions/Jakobshavn_2008_2011_Composite.zip' 'Jakobshavn_2008_2011_Composite.zip'
+unzip Jakobshavn_2008_2011_Composite.zip
+mv Jakobshavn_2008_2011_Composite/grids/Jakobshavn_2008_2011_Composite_XYZGrid.txt .
+rm -rf Jakobshavn_2008_2011_Composite Jakobshavn_2008_2011_Composite.zip
Index: issm/trunk/examples/Greenland/CheatSheet.m
===================================================================
--- issm/trunk/examples/Greenland/CheatSheet.m	(revision 18301)
+++ issm/trunk/examples/Greenland/CheatSheet.m	(revision 18301)
@@ -0,0 +1,37 @@
+if any(steps==8)
+	disp('   Step 8: Plotting exercise');
+
+	%Load historic transient model
+	md = loadmodel('./Models/Greenland.HistoricTransient');
+
+	%Create Line Plots of relaxation run.  Create a figure.
+	figure
+
+	%Save surface mass balance, by looping through 200 years, or 1000 steps
+	surfmb=[]; for i=1:1000; surfmb=[surfmb ...
+		md.results.TransientSolution(i).SurfaceforcingsMassBalance]; end
+
+	%Plot surface mass balance time series in first subplot
+	subplot(3,1,1); plot([0.2:0.2:200],mean(surfmb));
+
+	%Title this plot Mean surface mass balance
+	title('Mean Surface mass balance');
+
+	%Save velocity by looping through 1000 steps
+	vel=[]; for i=1:1000; vel=[vel md.results.TransientSolution(i).Vel]; end
+
+	%Plot velocity time series in second subplot
+	subplot(3,1,2); plot([0.2:0.2:200],mean(vel));
+
+	%Title this plot Mean Velocity
+	title('Mean Velocity');
+
+	%Save Ice Volume by looping through 1000 steps
+	volume=[]; for i=1:1000; volume=[volume md.results.TransientSolution(i).IceVolume]; end
+
+	%Plot volume time series in third subplot
+	subplot(3,1,3); plot([0.2:0.2:200],volume);
+
+	%Title this plot Mean Velocity and add an x label of years
+	title('Ice Volume'); xlabel('years');
+end
Index: issm/trunk/examples/Greenland/DomainOutline.exp
===================================================================
--- issm/trunk/examples/Greenland/DomainOutline.exp	(revision 18301)
+++ issm/trunk/examples/Greenland/DomainOutline.exp	(revision 18301)
@@ -0,0 +1,733 @@
+## Name:DomainOutline
+## Icon:0
+# Points Count Value
+727 1.000000
+# X pos Y pos
+47662.8073760000 -2621047.2585999998
+39869.9055420000 -2638077.6292949999
+26037.5047870000 -2644088.3483640002
+24868.5695120000 -2659115.1460360000
+25647.8596950000 -2674141.9437079998
+16880.8451320000 -2687666.0616130000
+515.7512810000 -2685662.4885900002
+-7666.7956450000 -2672639.2639410002
+-22083.6640370000 -2677147.3032430001
+-30071.3884170000 -2690170.5278920000
+-44683.0793550000 -2694678.5671930001
+-41760.7411680000 -2709705.3648660001
+-37669.4677050000 -2724231.2692820001
+-44488.2568100000 -2738757.1736989999
+-55787.9644690000 -2753283.0781149999
+-67672.1397650000 -2742263.4264890002
+-87154.3943500000 -2741762.5332330000
+-105078.0685680000 -2741011.1933490001
+-97090.3441880000 -2760546.0303230002
+-99817.8598300000 -2780581.7605530000
+-82478.6532500000 -2789096.9459000002
+-77218.4445120000 -2804123.7435730002
+-77023.6219660000 -2820152.3277560002
+-95336.9412760000 -2829669.2996149999
+-112870.9704020000 -2832674.6591500002
+-123196.5653320000 -2818649.6479890002
+-122417.2751480000 -2834177.3389170002
+-120274.2271440000 -2849204.1365890000
+-105662.5362060000 -2854713.9624020001
+-89492.2649000000 -2850706.8163560000
+-77997.7346950000 -2860724.6814710000
+-92024.9579960000 -2867737.1870519998
+-84816.5238000000 -2890277.3835600000
+-94752.4736380000 -2901797.9284419999
+-114234.7282230000 -2894284.5296060001
+-127677.4838860000 -2883765.7712349999
+-146964.9159250000 -2888774.7037930000
+-139951.3042750000 -2905805.0744880000
+-154173.3501210000 -2916824.7261140002
+-165667.8803260000 -2904302.3947210000
+-162550.7195930000 -2920330.9789040000
+-152809.5923000000 -2934355.9900650000
+-147744.2061080000 -2949883.6809930000
+-163719.6548680000 -2950384.5742489998
+-175603.8301650000 -2963908.6921540000
+-189825.8760110000 -2956896.1865730002
+-195670.5523870000 -2971422.0909899999
+-210282.2433250000 -2966413.1584319999
+-222750.8862590000 -2978301.3022220000
+-214763.1618800000 -2995247.5385030000
+-222750.8862590000 -3011386.8111520000
+-206970.2600460000 -3016228.5929470002
+-217295.8549760000 -3027122.6019839998
+-232686.8360980000 -3031964.3837790000
+-212035.6462380000 -3035192.2383090002
+-212814.9364210000 -3050928.0291410000
+-197229.1327540000 -3048910.6200600001
+-185344.9574570000 -3058190.7018329999
+-174824.5399810000 -3071102.1199520002
+-182812.2643610000 -3084820.5017030002
+-192163.7465610000 -3098942.3652710002
+-176577.9428940000 -3092486.6562120002
+-184955.3123650000 -3105801.5561469998
+-182617.4418150000 -3121537.3469790001
+-199372.1807580000 -3120326.9015310002
+-218464.7902510000 -3115888.6015519998
+-205022.0345870000 -3126782.6105900002
+-189825.8760110000 -3128800.0196710001
+-198592.8905740000 -3146149.7377680000
+-213009.7589670000 -3140904.4741580002
+-225283.5793550000 -3131220.9105679998
+-222750.8862590000 -3146149.7377680000
+-208334.0178670000 -3151395.0013790000
+-195670.5523870000 -3161078.5649680002
+-213009.7589670000 -3171569.0921900002
+-227621.4499060000 -3161078.5649680002
+-242622.7859360000 -3157850.7104389998
+-240090.0928400000 -3174393.4649040001
+-220023.3706180000 -3185690.9557579998
+-233076.4811890000 -3193357.1102660000
+-258013.7670580000 -3188111.8466550000
+-275158.1510920000 -3196181.4829790001
+-258208.5896040000 -3198198.8920600000
+-252753.5583200000 -3213127.7192600002
+-270482.4099920000 -3215952.0919740000
+-258793.0572410000 -3226442.6191960000
+-275547.7961840000 -3232969.1157640000
+-276521.9089130000 -3248275.5695210001
+-293276.6478560000 -3241868.2167850002
+-282561.4078340000 -3256818.7065010001
+-288211.2616640000 -3273549.0164200002
+-302433.3075110000 -3267141.6636850000
+-305745.2907900000 -3251479.2458879999
+-313733.0151700000 -3237596.6482950002
+-310810.6769820000 -3218018.6260489998
+-325812.0130120000 -3213747.0575589999
+-338280.6559470000 -3203780.0644160002
+-336527.2530340000 -3187761.6825779998
+-321720.7395500000 -3185269.9342919998
+-325812.0130120000 -3165691.9120459999
+-313538.1926240000 -3155368.9548610002
+-329708.4639290000 -3158928.5952699999
+-338085.8334010000 -3173167.1569030001
+-351723.4116100000 -3164268.0558819999
+-342566.7519550000 -3151809.3144530002
+-325812.0130120000 -3153233.1706160000
+-310615.8544360000 -3148249.6740450002
+-329123.9962920000 -3150029.4942490002
+-343151.2195930000 -3144334.0695949998
+-361854.1839940000 -3145401.9617180000
+-377634.8102080000 -3142910.2134320000
+-388350.0502290000 -3154657.0267800000
+-397701.5324300000 -3178150.6534750001
+-417573.4321060000 -3179930.4736790000
+-432720.8850460000 -3186308.0579260001
+-451813.4945390000 -3187438.8412219998
+-467788.9432980000 -3177261.7915590000
+-482985.1018740000 -3173492.5139070000
+-490583.1811620000 -3158792.3310610000
+-492726.2291670000 -3141453.6538590002
+-490193.5360710000 -3119214.9157079998
+-505389.6946470000 -3113560.9992289999
+-489803.8909790000 -3110922.5048719998
+-478309.3607740000 -3100368.5274439999
+-495648.5673540000 -3101122.3829750000
+-512792.9513890000 -3108660.9382799999
+-501103.5986380000 -3097353.1053220001
+-493895.1644420000 -3083783.7057719999
+-486491.9077000000 -3068329.6673960001
+-503636.2917340000 -3066068.1008040002
+-522728.9012270000 -3064183.4619780001
+-521559.9659520000 -3046467.8570099999
+-531301.0932440000 -3029506.1075729998
+-543769.7361790000 -3012167.4303710000
+-545912.7841830000 -2992944.1143419999
+-550004.0576459999 -2974474.6538439998
+-567538.0867720000 -2983897.8479749998
+-585851.4060810000 -2995959.5364640001
+-589942.6795440000 -2981259.3536189999
+-572213.8278720001 -2975982.3649050002
+-565200.2162220000 -2959397.5432330002
+-548055.8321870000 -2954120.5545190000
+-545717.9616370000 -2933389.5274290000
+-536561.3019820000 -2920197.0556450002
+-545523.1390910000 -2907758.4393910002
+-533444.1412490000 -2898335.2452590000
+-530568.0950890000 -2883304.2548420001
+-545624.1658510000 -2879383.1998239998
+-559750.8495300000 -2868110.1666489998
+-577223.3267109999 -2867129.9028940001
+-590606.5007220000 -2859287.7928590002
+-573319.9009570000 -2851445.6828239998
+-551572.2431889999 -2846054.2321750000
+-530939.8499220000 -2834781.1989989998
+-528337.5660870000 -2817626.5832969998
+-543765.3916830000 -2804883.1544900001
+-528151.6886699999 -2802432.4951040000
+-528151.6886699999 -2785768.0112790000
+-513467.3727410000 -2778416.0331210000
+-513839.1275750000 -2760771.2855420001
+-525735.2822510001 -2749498.2523670001
+-509563.9469880000 -2738225.2191909999
+-517184.9210780000 -2724501.5266300002
+-532240.9918400000 -2725971.9222610001
+-524248.2629170000 -2707837.0428050002
+-512537.9856570000 -2694113.3502429998
+-521088.3468310000 -2678429.1301730000
+-538189.0691780000 -2669606.7563829999
+-556033.3011930001 -2677448.8664190001
+-539676.0885130001 -2666175.8332429999
+-526664.6693360000 -2658333.7232080000
+-517556.6759110000 -2639708.7118739998
+-526107.0370850000 -2626965.2830670001
+-538932.5788460000 -2618142.9092779998
+-550456.9786890000 -2607360.0079790000
+-565698.9268680000 -2599517.8979440001
+-581126.7524640000 -2600988.2935759998
+-583110.5023000001 -2578346.1085480000
+-572583.8192940000 -2566324.6704099998
+-556315.3091930000 -2558811.2715739999
+-538132.8567270000 -2571333.6029679999
+-524735.2601730000 -2578346.1085480000
+-519759.0100240000 -2594875.5859869998
+-503107.7114500000 -2585859.5073839999
+-486456.4128760000 -2576342.5355250002
+-477843.6722340000 -2559312.1648300001
+-474015.7875040000 -2536771.9683220000
+-473441.6047950000 -2521244.2773940000
+-474972.7586870000 -2504714.7999539999
+-485690.8359300000 -2491691.5753049999
+-486073.6244030000 -2476664.7776330002
+-492581.0284430000 -2459634.4069380001
+-474207.1817410000 -2447112.0755440001
+-465594.4410990000 -2434589.7441509999
+-462340.7390790000 -2418060.2667109999
+-462914.9217880000 -2399026.3229930000
+-468465.3546460000 -2375484.3399729999
+-473058.8163220000 -2360457.5423010001
+-478417.8549440000 -2343427.1716060000
+-504256.0768690000 -2331405.7334679998
+-489901.5091330000 -2322389.6548649999
+-475164.1529230000 -2307863.7504480002
+-462577.4401970000 -2287577.5735909999
+-457317.2314590000 -2269044.5231289999
+-439783.2023330000 -2268042.7366169998
+-436666.0415990000 -2252014.1524330000
+-435886.7514160000 -2233481.1019710000
+-448550.2168960000 -2220457.8773220000
+-440172.8474240000 -2206933.7594170002
+-429262.7848570000 -2193409.6415120000
+-433743.7034120000 -2176880.1640720000
+-426730.0917610000 -2162354.2596560000
+-419716.4801110000 -2147327.4619840002
+-428678.3172200000 -2134805.1305900002
+-427314.5593990000 -2110762.2543150000
+-426535.2692150000 -2094733.6701310000
+-427509.3819440000 -2067184.5410650000
+-428093.8495820000 -2050655.0636260000
+-425366.3339400000 -2035628.2659539999
+-432379.9455910000 -2021102.3615369999
+-446017.5238000000 -2003571.0975860001
+-430821.3652240000 -2002569.3110750001
+-428678.3172200000 -1986039.8336360001
+-424197.3986650000 -1971013.0359630000
+-418060.4884710000 -1957238.4714309999
+-433451.4695930000 -1950225.9658500000
+-426243.0353960000 -1933696.4884110000
+-441634.0165180000 -1943714.3535259999
+-433841.1146840000 -1926683.9828300001
+-448647.6281690000 -1933696.4884110000
+-464428.2543820000 -1948222.3928270000
+-465402.3671120000 -1933195.5951550000
+-463843.7867450000 -1914662.5446929999
+-456245.7074570000 -1901138.4267879999
+-468714.3503910000 -1892122.3481840000
+-480208.8805960000 -1905646.4660890000
+-479429.5904130000 -1888616.0953939999
+-478455.4776830000 -1871585.7246989999
+-478650.3002290000 -1856558.9270270001
+-484494.9766050000 -1841031.2360990001
+-494430.9264430000 -1822498.1856370000
+-505925.4566480000 -1807972.2812200000
+-508847.7948350000 -1791442.8037810000
+-504172.0537350000 -1776416.0061079999
+-510990.8428400000 -1759886.5286689999
+-502223.8282770000 -1745861.5175079999
+-512939.0682980000 -1728330.2535570001
+-511964.9555690000 -1712802.5626300001
+-505340.9890100000 -1697775.7649570000
+-506315.1017390000 -1681747.1807740000
+-507289.2144690000 -1662713.2370559999
+-508446.9486300000 -1645056.7497910000
+-502180.9448550000 -1623518.3397939999
+-505662.0580630000 -1602480.8230530000
+-505836.1137240000 -1586953.1321250000
+-509317.2269320000 -1571425.4411970000
+-516105.3976870000 -1557400.4300360000
+-530552.0175000000 -1537865.5930620001
+-533336.9080660000 -1513321.8235309999
+-522719.5127820000 -1498295.0258589999
+-506532.3363650000 -1492284.3067900001
+-522893.5684430000 -1484770.9079539999
+-515757.2863660000 -1469744.1102819999
+-532118.5184440000 -1465236.0709800001
+-535947.7429720000 -1449708.3800520001
+-544476.4703320001 -1428670.8633109999
+-551960.8637290000 -1415146.7454059999
+-565363.1495800000 -1405629.7735470000
+-567277.7618440000 -1386094.9365729999
+-582420.6042990000 -1384091.3635499999
+-593212.0552430000 -1370066.3523899999
+-606266.2297730000 -1362052.0602980000
+-613793.7528780000 -1344395.5730330001
+-621618.1005840000 -1359923.2639609999
+-634079.0987820000 -1369440.2358200001
+-633354.6221430000 -1354413.4381480000
+-638860.6446030000 -1339386.6404760000
+-649438.0035390001 -1351908.9718690000
+-667405.0241970000 -1352409.8651250000
+-679431.3364110000 -1363429.5167510000
+-679721.1270670000 -1346900.0393119999
+-676533.4298540000 -1330370.5618720001
+-690008.6953470000 -1339386.6404760000
+-701165.6355950000 -1327365.2023380001
+-688994.4280520000 -1315844.6574560001
+-709279.7739560000 -1318349.1237339999
+-717249.0169900000 -1331372.3483839999
+-735216.0376480001 -1329869.6686160001
+-741420.6668040000 -1315969.8807699999
+-750947.3474350000 -1299440.4033299999
+-734597.5036490000 -1299440.4033299999
+-722496.0444700000 -1284413.6056580001
+-707948.5456690000 -1288420.7517039999
+-689023.9233340001 -1290424.3247270000
+-678209.8534290000 -1276399.3135660000
+-672545.3406220000 -1262374.3024060000
+-693401.0468670001 -1264377.8754280000
+-709493.4127980000 -1260871.6226379999
+-725971.9955110000 -1250853.7575240000
+-725714.5176560000 -1234825.1733400000
+-720951.1773400001 -1215290.3363659999
+-737172.2821980000 -1218295.6958999999
+-749402.4803050000 -1205272.4712510000
+-736399.8486340001 -1196757.2859040000
+-720822.4384130000 -1191247.4600899999
+-710652.0631450000 -1204771.5779949999
+-697906.9093280000 -1218796.5891559999
+-684131.8440910000 -1227812.6677590001
+-668940.6506530000 -1229816.2407819999
+-666237.1331770000 -1253358.2238020001
+-653620.7182870000 -1262374.3024060000
+-648471.1611900000 -1247347.5047330000
+-634696.0959530000 -1258868.0496149999
+-632625.0227419999 -1243541.0164699999
+-618416.8083510000 -1233878.1370890001
+-601000.2874830000 -1228080.4094600000
+-615361.2783740000 -1217451.2421410000
+-598861.4165000001 -1216968.0981719999
+-610625.2069099999 -1201990.6351310001
+-617652.9258560000 -1185080.5962139999
+-631708.3637490000 -1178799.7246160000
+-648666.5551200000 -1183631.1643070001
+-656458.1565610000 -1169136.8452349999
+-653708.1795820000 -1154159.3821950001
+-665166.4169950000 -1166237.9814210001
+-676166.3249110000 -1153193.0942569999
+-676166.3249110000 -1133384.1915249999
+-689305.1038110000 -1118406.7284850001
+-709013.2721609999 -1111159.5689490000
+-711610.4726409999 -1091833.8101870001
+-716346.5441050000 -1074440.6273010001
+-701527.2237180000 -1070092.3315790000
+-680291.2903790000 -1068642.8996720000
+-664096.9815030000 -1078788.9230219999
+-650958.2026030000 -1100530.4016300000
+-628041.7277770001 -1095698.9619390001
+-611236.3129050001 -1091350.6662170000
+-588930.9440750000 -1094732.6740009999
+-577319.9301640000 -1078305.7790530000
+-565250.5867559999 -1066710.3237960001
+-550431.2663680000 -1071541.7634860000
+-540042.4644469999 -1060429.4521979999
+-531203.6819710000 -1047613.0696300000
+-510357.6695660000 -1037937.0529810000
+-498473.4942690000 -1027821.2173940000
+-486199.6738810000 -1015066.4681760001
+-487953.0767930000 -994834.7970020000
+-464964.0163830000 -990876.4265550000
+-449378.2127160000 -998353.3485110000
+-430285.6032230000 -1001432.0810810000
+-417622.1377430000 -1012427.5545450000
+-399308.8184330000 -1004950.6325890000
+-384697.1274945000 -1000332.5337340001
+-370085.4365560000 -995714.4348789999
+-375540.4678400000 -980760.5909680000
+-380021.3863940000 -966246.5659950000
+-383528.1922200000 -949973.2652690000
+-383528.1922200000 -930181.4130330000
+-384112.6598570000 -911709.0176140000
+-380216.2089400000 -883560.6055450001
+-366919.5701860000 -892846.9764360000
+-353087.1694310000 -880338.0618260000
+-336527.2530340000 -873692.7009390000
+-322694.8522790000 -888547.0370390000
+-307888.3387940000 -897146.9158330000
+-294835.2282230000 -913564.8662580000
+-275937.4412760000 -919037.5164000000
+-252169.0906820000 -915128.4805850000
+-245350.3015780000 -901446.8552300000
+-244181.3663030000 -918646.6128190000
+-231615.3120950000 -930563.0925760000
+-215445.0407900000 -924017.9382920000
+-206872.8487730000 -937108.2468600000
+-190507.7549220000 -933426.5975750000
+-186611.3040050000 -912972.9904390000
+-185961.8955186667 -896882.8194913333
+-185312.4870323333 -880792.6485436666
+-184663.0785460000 -864702.4775960000
+-175311.5963460000 -883519.7961620000
+-174532.3061620000 -902337.1147280000
+-172584.0807040000 -918700.0004370000
+-168882.4523330000 -933835.6697180000
+-152322.5359360000 -933835.6697180000
+-142581.4086430000 -921563.5054359999
+-127969.7177050000 -912154.8461530000
+-131086.8784390000 -930563.0925760000
+-115501.0747710000 -924427.0104349999
+-112189.0914910000 -905609.6918690000
+-114916.6071330000 -887610.5175890001
+-101473.8514700000 -899882.6818710000
+-84329.4674350000 -896610.1047290000
+-100110.0936490000 -892110.3111590000
+-87836.2732610000 -879838.1468770000
+-74685.7514160000 -869305.2030530000
+-57541.3673810000 -863251.9975030000
+-49553.6430020000 -850388.9357080000
+-34357.4844260000 -846227.3568920000
+-47995.0626350000 -825797.7881600000
+-30071.3884170000 -835255.9218320000
+-18771.6807580000 -850767.2610550000
+-6303.0378240000 -859847.0693810000
+7139.7178400000 -852658.8877899999
+22141.0538700000 -862873.6721560000
+31297.7135250000 -877628.3606850000
+47662.8073760000 -874601.7579100000
+49611.0328340000 -893518.0252550000
+66365.7717770000 -886708.1690110000
+81123.5796250000 -882220.1151260000
+97683.4960220000 -884202.5846670000
+80149.4668960000 -888960.5115630000
+65537.7759570000 -896493.8958170000
+68460.1141450000 -914732.6155880000
+84435.5629050000 -917508.0729450000
+100605.8342100000 -907595.7252430000
+120282.9113400000 -911957.1582320000
+129049.9259030000 -927420.4206470000
+153402.7441340000 -925437.9511060000
+169767.8379850000 -920680.0242090001
+180677.9005530000 -910371.1825990001
+192367.2533040000 -899269.3531730000
+201134.2678670000 -912353.6521400000
+182626.1260110000 -920680.0242090001
+169183.3703480000 -936539.7805320000
+163338.6939720000 -950417.0673150000
+182820.9485570000 -955174.9942120000
+187301.8671120000 -970241.7627180000
+200744.6227750000 -980550.6043280000
+198796.3973170000 -995617.3728350000
+211118.9233410000 -983385.4589040000
+211508.5684330000 -999969.0227530000
+225146.1466420000 -1008484.9068910000
+240731.9503100000 -1009829.5201760000
+238588.9023060000 -1032239.7415930000
+253785.0608820000 -1029550.5150230000
+273072.4929210000 -1036273.5814480000
+281255.0398460000 -1056890.9851510001
+286320.4260380000 -1071681.7312860000
+305413.0355310000 -1086024.2729930000
+316907.5657360000 -1095884.7704169999
+326453.8704830000 -1081990.4331380001
+341260.3839670000 -1076611.9799980000
+355677.2523600000 -1064958.6648609999
+372319.0245690000 -1056006.2810410000
+387981.0391590000 -1068027.7191780000
+383779.0352450000 -1084056.3033620000
+366207.0188750000 -1085558.9831290001
+366971.0195860000 -1102088.4605690001
+352646.0062410000 -1113108.1121950001
+362960.0158500000 -1126131.3368440000
+380914.0325760000 -1133143.8424249999
+394093.0448530000 -1123626.8705660000
+409182.0589100000 -1113108.1121950001
+409182.0589100000 -1131641.1626569999
+404407.0544620000 -1158689.3984670001
+386262.0375580000 -1153179.5726540000
+374229.0263480000 -1166202.7973030000
+364488.0172730000 -1182732.2747430000
+377285.0291950000 -1191748.3533460000
+388172.0393370000 -1202768.0049719999
+392947.0437860000 -1219798.3756680000
+380341.0320420000 -1228814.4542710001
+383588.0350670000 -1251354.6507790000
+389509.0405830000 -1265880.5551960000
+389509.0405830000 -1282910.9258910001
+399632.0500130000 -1295934.1505400001
+408609.0583760000 -1313966.3077469999
+410137.0598000000 -1333000.2514650000
+413526.9681570000 -1350406.2921020000
+416526.2265730000 -1367436.6627970000
+415776.4119690000 -1385468.8200040001
+419900.3922910000 -1406005.4434890000
+430960.1577010000 -1421032.2411610000
+431897.4259560000 -1436059.0388330000
+448018.4399430000 -1436559.9320890000
+448580.8008960000 -1456094.7690630001
+438458.3037410000 -1469117.9937120001
+432459.7869090000 -1486148.3644069999
+449705.5228020000 -1494663.5497550000
+448393.3472450000 -1513196.6002170001
+463202.1856750000 -1521210.8923090000
+447830.9862920000 -1525218.0383550001
+458140.9370980000 -1539243.0495160001
+462639.8247220000 -1554269.8471880001
+473887.0437820000 -1564287.7123030000
+458703.2980510000 -1557275.2067219999
+463014.7320240000 -1574305.5774170000
+478948.2923600000 -1567293.0718370001
+484009.5409370000 -1584824.3357879999
+475011.7656880000 -1597346.6671819999
+484009.5409370000 -1614877.9311319999
+488508.4285610000 -1630906.5153160000
+470512.8780640000 -1618384.1839230000
+461702.5564670000 -1631407.4085720000
+474074.4974330000 -1641926.1669419999
+488883.3358630000 -1648938.6725230000
+495661.8324810000 -1662963.6836830000
+478923.6439970000 -1667471.7229849999
+463095.1396700000 -1663965.4701950001
+449449.8773190000 -1652945.8185690001
+455817.6664170000 -1670477.0825199999
+441626.5935720000 -1662963.6836830000
+433439.4361610000 -1648437.7792670000
+409690.0603430000 -1652315.3206390000
+394504.9542530000 -1655951.1781029999
+411243.1427370000 -1662462.7904280000
+426707.7734010000 -1676487.8015880000
+437260.1096190000 -1691514.5992610001
+455999.6032480000 -1702534.2508870000
+441626.5935720000 -1710047.6497229999
+428891.0153770000 -1692516.3857720001
+435076.8676430000 -1708544.9699560001
+419976.1106410000 -1704036.9306540000
+408696.0270980000 -1692516.3857720001
+395050.7647470000 -1701532.4643750000
+388501.0388190000 -1718562.8350710000
+378494.5130940000 -1731085.1664640000
+376129.3342870000 -1713553.9025129999
+361938.2614420000 -1720566.4080940001
+373582.2186480000 -1732086.9529760000
+358481.4616460000 -1738598.5652999999
+369397.6715270000 -1754627.1494839999
+352659.4830430000 -1751621.7899490001
+335805.3526830000 -1754501.9261700001
+338338.0457790000 -1777042.1226780000
+354897.9621760000 -1775539.4429110000
+349053.2858010000 -1792569.8136060000
+330739.9664910000 -1791568.0270950000
+344182.7221550000 -1806093.9315110000
+341455.2065130000 -1823625.1954620001
+351780.8014430000 -1809600.1843010001
+344377.5447010000 -1826129.6617409999
+356066.8974510000 -1836147.5268550001
+345546.4799760000 -1853678.7908059999
+363080.5091020000 -1853678.7908059999
+371847.5236650000 -1841156.4594129999
+370288.9432980000 -1859689.5098750000
+386848.8596950000 -1868204.6952229999
+404772.5339130000 -1856183.2570849999
+415098.1288430000 -1867703.8019669999
+428735.7070520000 -1860691.2963870000
+421137.6277640000 -1874215.4142920000
+413929.1935680000 -1888741.3187080000
+418799.7572140000 -1903768.1163800000
+428735.7070520000 -1916791.3410300000
+415098.1288430000 -1935825.2847480001
+398148.5673540000 -1926809.2061439999
+380030.0705910000 -1929814.5656790000
+364444.2669230000 -1929814.5656790000
+348468.8181630000 -1924304.7398659999
+333077.8370420000 -1919796.7005640001
+348079.1730720000 -1935825.2847480001
+332883.0144960000 -1939832.4307939999
+318855.7911950000 -1951853.8689309999
+331908.9017660000 -1964376.2003250001
+349442.9308930000 -1959868.1610230000
+358209.9454560000 -1943338.6835840000
+358404.7680020000 -1958365.4812560000
+345936.1250670000 -1971388.7059050000
+345351.6574300000 -1987918.1833450000
+330739.9664910000 -1991925.3293910001
+337753.5781420000 -2005449.4472960001
+353534.2043550000 -2007453.0203180001
+365223.5571060000 -1997435.1552040000
+385679.9244200000 -1986415.5035770000
+399317.5026290000 -1977399.4249740001
+399122.6800840000 -1993928.9024139999
+381393.8284120000 -1998436.9417150000
+399512.3251750000 -1999939.6214820000
+395615.8742580000 -2018973.5652000001
+387822.9724240000 -2032998.5763610001
+383975.2271440000 -2048275.8206610000
+398976.5631740000 -2062801.7250780000
+397223.1602620000 -2078830.3092610000
+379299.4860440000 -2080833.8822840001
+362739.5696470000 -2085842.8148419999
+374428.9223980000 -2097363.3597240001
+390599.1937030000 -2089849.9608880000
+379299.4860440000 -2103374.0787930000
+364492.9725590000 -2111388.3708839999
+355531.1354500000 -2097363.3597240001
+343257.3150620000 -2111889.2641400001
+351829.5070790000 -2127917.8483239999
+365661.9078340000 -2119402.6629760000
+357284.5383630000 -2133928.5673929998
+374039.2773060000 -2136933.9269269998
+385533.8075110000 -2147452.6852980000
+375792.6802180000 -2160976.8032030002
+390988.8387940000 -2162479.4829699998
+378520.1958600000 -2174000.0278520002
+394105.9995280000 -2164983.9492489998
+409107.3355580000 -2161978.5897140000
+421186.3334010000 -2149957.1515759998
+437941.0723440000 -2150958.9380879998
+450409.7152780000 -2171495.5615730002
+454695.8112860000 -2156969.6571570002
+471645.3727750000 -2159975.0166910002
+459566.3749330000 -2147452.6852980000
+465605.8738540000 -2132425.8876260002
+477490.0491500000 -2120404.4494880000
+485867.4186220000 -2133427.6741370000
+493264.3211700000 -2119402.6629760000
+495978.8328800000 -2102873.1855370002
+509098.9728100000 -2110386.5843730001
+523877.9810080000 -2104876.7585600000
+541371.5009160000 -2109885.6911169998
+529608.6168400000 -2096862.4664680001
+544990.8498620000 -2099366.9327469999
+561579.5325330000 -2107381.2248390000
+576509.3469370001 -2104876.7585600000
+596868.1847600000 -2102873.1855370002
+611948.8053700000 -2108883.9046060001
+597622.2157910001 -2119402.6629760000
+580430.3082950000 -2125413.3820449999
+599130.2778520000 -2126916.0618119999
+583144.8200050000 -2134930.3539040000
+568818.2304260000 -2148454.4718089998
+582843.2075930000 -2161477.6964580002
+566706.9435400000 -2162980.3762260000
+552983.5787850000 -2170994.6683180002
+543331.9815950000 -2188025.0390130002
+547554.5553660000 -2207058.9827310001
+538053.7643820000 -2193033.9715700001
+525084.4306570000 -2209062.5557539999
+516036.0582910000 -2221083.9938920001
+529910.2292520000 -2214572.3815669999
+541220.6947100000 -2225091.1399369999
+526140.0741000000 -2223087.5669140001
+526743.2989240000 -2239617.0443540001
+521615.8879170000 -2256647.4150490002
+506233.6548950000 -2255144.7352820002
+508194.1355740000 -2275681.3587670000
+489343.3598110000 -2268167.9599310001
+488740.1349870000 -2283695.6508590002
+475770.8012620000 -2293212.6227179999
+460539.3744460000 -2281692.0778359999
+449228.9089890000 -2296217.9822519999
+448022.4593400000 -2314250.1394590000
+440180.5366230000 -2298722.4485309999
+441085.3738600000 -2277184.0385340001
+426000.8914760000 -2286450.5637659999
+431125.9775380000 -2301477.3614380001
+426190.7094780000 -2317505.9456210001
+424672.1654600000 -2332532.7432940002
+421445.2594210000 -2313498.7995750001
+409296.9072740000 -2298472.0019029998
+411764.5413040000 -2318006.8388769999
+403222.7312010000 -2304983.6142279999
+411005.2692950000 -2289956.8165560002
+393542.0130840000 -2293463.0693460000
+378356.5729000000 -2295967.5356250000
+388416.9270220000 -2308489.8670180002
+405880.1832330000 -2317005.0523660001
+417838.7173770000 -2328525.5972480001
+402463.4591910000 -2342049.7151529999
+385000.2029800000 -2341047.9286409998
+375699.1208680000 -2327022.9174799998
+384240.9309710000 -2314500.5860870001
+368865.6727850000 -2321012.1984120002
+373421.3048400000 -2337541.6758510000
+363360.9507190000 -2353069.3667790000
+351402.4165740000 -2336539.8893400002
+340392.9724410000 -2324518.4512020000
+329573.3463100000 -2313999.6928309998
+335267.8863790000 -2329527.3837589999
+336216.9763910000 -2347058.6477100002
+337166.0664020000 -2362085.4453819999
+318374.0841750000 -2366593.4846839998
+303758.0979980000 -2362586.3386380002
+290314.2882280000 -2354697.2698599999
+292067.6911410000 -2339670.4721880001
+275702.5972900000 -2347684.7642799998
+277880.2580262116 -2321542.8592617917
+269420.4169677348 -2331176.2138948478
+260960.5759092579 -2323294.3782859840
+252500.7348507810 -2343436.8470641924
+254834.4841082919 -2357157.0794203631
+258918.5453089359 -2372336.9109633607
+266740.7601810000 -2359706.2024170002
+271754.1662252456 -2369125.7927523423
+266545.9376350000 -2379241.0393909998
+291483.2235030000 -2386253.5449720002
+275897.4198350000 -2396271.4100859999
+288755.7078610000 -2404786.5954339998
+276871.5325650000 -2415806.2470600000
+263818.4219930000 -2423820.5391520001
+259532.3259840000 -2445358.9491490000
+250570.4888750000 -2432836.6177559998
+248817.0859630000 -2452371.4547290001
+247258.5055960000 -2470403.6119360002
+229919.2990160000 -2474911.6512380000
+226022.8480990000 -2490439.3421660000
+239660.4263080000 -2499956.3140250002
+227776.2510110000 -2510975.9656509999
+220178.1717230000 -2523999.1902999999
+205761.3033310000 -2533015.2689029998
+210631.8669770000 -2560063.5047129998
+203228.6102350000 -2545036.7070410000
+194266.7731260000 -2558560.8249459998
+199624.3931360000 -2581101.0214539999
+185791.9923810000 -2568077.7968049999
+189493.6207520000 -2583104.5944770002
+186571.2825650000 -2601136.7516839998
+185207.5247440000 -2584106.3809890002
+169816.5436220000 -2595126.0326149999
+156568.6105040000 -2586610.8472679998
+134748.4853690000 -2581101.0214539999
+149749.8214000000 -2579598.3416869999
+136112.2431900000 -2592120.6730809999
+146437.8381200000 -2612657.2965660002
+130462.3893610000 -2620671.5886579999
+137281.1784650000 -2635197.4930739999
+125007.3580770000 -2621172.4819140001
+106888.8613130000 -2617666.2291230001
+91887.5252830000 -2609151.0437759999
+109031.9093180000 -2607648.3640089999
+92277.1703750000 -2603641.2179629998
+97537.3791130000 -2587111.7405229998
+88380.7194580000 -2573587.6226180000
+74743.1412490000 -2567076.0102940002
+61105.5630390000 -2577093.8754090001
+66950.2394150000 -2594124.2461040001
+57598.7572140000 -2581101.0214539999
+53117.8386600000 -2598131.3921500002
+41818.1310010000 -2586610.8472679998
+30810.6571600000 -2599133.1786610000
+44253.4128240000 -2608650.1505200001
+47662.8073760000 -2621047.2585999998
+
Index: issm/trunk/examples/Greenland/Greenland.par
===================================================================
--- issm/trunk/examples/Greenland/Greenland.par	(revision 18301)
+++ issm/trunk/examples/Greenland/Greenland.par	(revision 18301)
@@ -0,0 +1,82 @@
+%Name and hemisphere
+md.miscellaneous.name='SeaRISEgreenland';
+md.mesh.hemisphere='n';
+
+disp('   Loading SeaRISE data from NetCDF');
+ncdata='../Data/Greenland_5km_dev1.2.nc';
+x1    = ncread(ncdata,'x1');
+y1    = ncread(ncdata,'y1');
+usrf  = ncread(ncdata,'usrf')';
+topg  = ncread(ncdata,'topg')';
+velx  = ncread(ncdata,'surfvelx')';
+vely  = ncread(ncdata,'surfvely')';
+temp  = ncread(ncdata,'airtemp2m')';
+smb   = ncread(ncdata,'smb')';
+gflux = ncread(ncdata,'bheatflx')';
+
+disp('   Interpolating surface and bedrock');
+md.geometry.base     = InterpFromGridToMesh(x1,y1,topg,md.mesh.x,md.mesh.y,0);
+md.geometry.surface = InterpFromGridToMesh(x1,y1,usrf,md.mesh.x,md.mesh.y,0);
+
+disp('   Constructing thickness');
+md.geometry.thickness=md.geometry.surface-md.geometry.base;
+
+%Set min thickness to 1 meter
+pos0=find(md.geometry.thickness<=0);
+md.geometry.thickness(pos0)=1;
+md.geometry.surface=md.geometry.thickness+md.geometry.base;
+
+disp('   Interpolating velocities ');
+md.inversion.vx_obs  = InterpFromGridToMesh(x1,y1,velx,md.mesh.x,md.mesh.y,0);
+md.inversion.vy_obs  = InterpFromGridToMesh(x1,y1,vely,md.mesh.x,md.mesh.y,0);
+md.inversion.vel_obs = sqrt(md.inversion.vx_obs.^2+md.inversion.vy_obs.^2);
+md.initialization.vx = md.inversion.vx_obs;
+md.initialization.vy = md.inversion.vy_obs;
+md.initialization.vz = zeros(md.mesh.numberofvertices,1);
+md.initialization.vel= md.inversion.vel_obs;
+
+disp('   Interpolating temperatures');
+md.initialization.temperature=InterpFromGridToMesh(x1,y1,temp,md.mesh.x,md.mesh.y,0)+273.15;
+
+disp('   Interpolating surface mass balance');
+md.surfaceforcings.mass_balance=InterpFromGridToMesh(x1,y1,smb,md.mesh.x,md.mesh.y,0);
+md.surfaceforcings.mass_balance=md.surfaceforcings.mass_balance*md.materials.rho_water/md.materials.rho_ice;
+
+disp('   Construct basal friction parameters');
+md.friction.coefficient=30*ones(md.mesh.numberofvertices,1);
+pos=find(md.mask.groundedice_levelset<0);
+md.friction.coefficient(pos)=0; %no friction applied on floating ice
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+disp('   Construct ice rheological properties');
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+md.materials.rheology_B=paterson(md.initialization.temperature);
+md.friction.q=ones(md.mesh.numberofelements,1);
+md.friction.p=ones(md.mesh.numberofelements,1);
+
+disp('   Set other boundary conditions');
+md.mask.ice_levelset(md.mesh.vertexonboundary==1)=0;
+md.basalforcings.floatingice_melting_rate = zeros(md.mesh.numberofvertices,1);
+md.basalforcings.groundedice_melting_rate = zeros(md.mesh.numberofvertices,1);
+md.thermal.spctemperature     = [md.initialization.temperature;1]; %impose observed temperature on surface
+md.masstransport.spcthickness    = NaN*ones(md.mesh.numberofvertices,1);
+
+disp('   Set geothermal heat flux');
+md.basalforcings.geothermalflux=InterpFromGridToMesh(x1,y1,gflux,md.mesh.x,md.mesh.y,0);
+
+disp('   Set Pressure');
+md.initialization.pressure=md.materials.rho_ice*md.constants.g*md.geometry.thickness;
+
+disp('   Single point constraint for continental model');
+%Set at least one vertex to velocity 0 so as to not get a singular problem (point on the wet peninsula)
+md.stressbalance.referential=NaN*ones(md.mesh.numberofvertices,6);
+md.stressbalance.spcvx = NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvy = NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvz = NaN*ones(md.mesh.numberofvertices,1);
+location = 1.0e+06 *[.32011 -2.2039];
+[dist pos]=min(sqrt((md.mesh.x - location(1)).^2 + (md.mesh.y - location(2)).^2));
+md.stressbalance.spcvx(pos) = 0;
+md.stressbalance.spcvy(pos) = 0;
+md.stressbalance.spcvz(pos) = 0;
+
Index: issm/trunk/examples/Greenland/Jak_grounded.exp
===================================================================
--- issm/trunk/examples/Greenland/Jak_grounded.exp	(revision 18301)
+++ issm/trunk/examples/Greenland/Jak_grounded.exp	(revision 18301)
@@ -0,0 +1,19 @@
+## Name:Jak_grouded
+## Icon:0
+# Points Count Value
+13 1.000000
+# X pos Y pos
+-414397.6663804040 -2243466.6708395295
+-421486.9037621063 -2215731.3059818177
+-342860.8164377716 -2178965.8223332223
+-275835.2993744044 -2209281.2211311869
+-226210.6377024883 -2262816.9253914217
+-228144.0660793162 -2295067.3496445753
+-333193.6745536321 -2328607.7908678548
+-379595.9555975018 -2325382.7484425395
+-422775.8560133249 -2285392.2223686292
+-427287.1888925899 -2265396.9593316740
+-411819.7618779668 -2254431.8150856020
+-413108.7141291854 -2243466.6708395295
+-414397.6663804040 -2243466.6708395295
+
Index: issm/trunk/examples/Greenland/Jak_outline.exp
===================================================================
--- issm/trunk/examples/Greenland/Jak_outline.exp	(revision 18301)
+++ issm/trunk/examples/Greenland/Jak_outline.exp	(revision 18301)
@@ -0,0 +1,17 @@
+## Name:Jak
+## Icon:0
+# Points Count Value
+11 1.000000
+# X pos Y pos
+-421561.7247949215 -2216716.3488182197
+-386019.6416099078 -2203459.4896082953
+-351446.8879663036 -2185999.2360147359
+-289086.6874689616 -2214129.6445821370
+-255160.1535196303 -2282353.9688088228
+-340138.0433165266 -2317597.8140254519
+-383306.1449952667 -2302506.6581698526
+-416391.9672407377 -2279120.5885137189
+-448056.7322601135 -2246463.4475331730
+-429126.8716234095 -2231167.6696134652
+-421561.7247949215 -2216716.3488182197
+
Index: issm/trunk/examples/Greenland/runme.m
===================================================================
--- issm/trunk/examples/Greenland/runme.m	(revision 18301)
+++ issm/trunk/examples/Greenland/runme.m	(revision 18301)
@@ -0,0 +1,327 @@
+clear all;
+steps=[1];
+
+%Location of SeaRISE dataset
+ncdata='../Data/Greenland_5km_dev1.2.nc';
+
+if any(steps==1)
+	disp('   Step 1: Mesh creation');
+
+	%Generate initial uniform mesh (resolution = 20000 m)
+	md=triangle(model,'./DomainOutline.exp',20000);
+
+	% Get velocities (Note: You can use ncdisp('file') to see an ncdump)
+	x1   = ncread(ncdata,'x1');
+	y1   = ncread(ncdata,'y1');
+	velx = ncread(ncdata,'surfvelx');
+	vely = ncread(ncdata,'surfvely');
+	vx   = InterpFromGridToMesh(x1,y1,velx',md.mesh.x,md.mesh.y,0);
+	vy   = InterpFromGridToMesh(x1,y1,vely',md.mesh.x,md.mesh.y,0);
+	vel  = sqrt(vx.^2+vy.^2);
+
+	%Mesh Greenland
+	md=bamg(md,'hmax',400000,'hmin',5000,'gradation',1.7,'field',vel,'err',8);
+	
+	%convert x,y coordinates (Polar stereo) to lat/lon
+	[md.mesh.lat,md.mesh.long]=xy2ll(md.mesh.x,md.mesh.y,+1,39,71);
+
+	save ./Models/Greenland.Mesh_generation md;
+
+	plotmodel (md,'data','mesh');
+end
+
+if any(steps==2)
+	disp('   Step 2: Parameterization');
+	md = loadmodel('./Models/Greenland.Mesh_generation');
+
+	md = setmask(md,'','');
+	md = parameterize(md,'./Greenland.par');
+	md = setflowequation(md,'SSA','all');
+
+	save ./Models/Greenland.Parameterization md; 
+end
+
+if any(steps==3)
+	disp('   Step 3: Control method friction');
+	md = loadmodel('./Models/Greenland.Parameterization');
+
+	%Control general
+	md.inversion.iscontrol=1;
+	md.inversion.nsteps=30;
+	md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
+	md.inversion.maxiter_per_step=5*ones(md.inversion.nsteps,1);
+
+	%Cost functions
+	md.inversion.cost_functions=[101 103 501];
+	md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,3);
+	md.inversion.cost_functions_coefficients(:,1)=350;
+	md.inversion.cost_functions_coefficients(:,2)=0.6;
+	md.inversion.cost_functions_coefficients(:,3)=2e-6;
+
+	%Controls
+	md.inversion.control_parameters={'FrictionCoefficient'};
+	md.inversion.gradient_scaling(1:md.inversion.nsteps)=50;
+	md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
+	md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
+
+	%Additional parameters
+	md.stressbalance.restol=0.01; md.stressbalance.reltol=0.1; 
+	md.stressbalance.abstol=NaN;
+
+	%Go solve
+	md.cluster=generic('name',oshostname,'np',2);
+	md.toolkits=toolkits;
+	md.verbose=verbose('solution',true,'control',true);
+	md=solve(md,StressbalanceSolutionEnum);
+
+	%Update model friction fields accordingly
+	md.friction.coefficient=md.results.StressbalanceSolution.FrictionCoefficient;
+
+	save ./Models/Greenland.Control_drag md; 
+end
+
+if any(steps==4)
+	disp('   Step 4: Transient run');
+	md = loadmodel('./Models/Greenland.Control_drag');
+
+	%Set surface mass balance
+	x1  = ncread(ncdata,'x1');
+	y1  = ncread(ncdata,'y1');
+	smb = ncread(ncdata,'smb');
+	smb = InterpFromGridToMesh(x1,y1,smb',md.mesh.x,md.mesh.y,0);
+	smb = smb*md.materials.rho_freshwater/md.materials.rho_ice;
+	smb = [smb smb smb-1.0];
+	md.surfaceforcings.mass_balance = [smb;1 10 20];
+
+	%Set transient options, run for 20 years, saving every timestep
+	md.timestepping.time_step=0.2;
+	md.timestepping.final_time=20;
+	md.settings.output_frequency=1;
+
+	%Additional options
+	md.inversion.iscontrol=0;
+	md.transient.requested_outputs={'IceVolume','TotalSmb', ...
+		                             'SurfaceforcingsMassBalance'};
+	md.verbose=verbose('solution',true,'module',true,'convergence',true);
+
+	%Go solve
+	md.cluster=generic('name',oshostname,'np',2);
+	md=solve(md,TransientSolutionEnum);
+
+	save ./Models/Greenland.Transient md; 
+end
+
+if any(steps==5)
+	disp('   Step 5: Plotting'); 
+	md = loadmodel('./Models/Greenland.Transient');
+
+	%Planview plots
+	plotmodel(md,'data',md.results.TransientSolution(end).Vel,'caxis',[1e-1 6000],...
+		'log', 10, 'title', 'Velocity (m/y)','gridded',1, ...
+		'data', md.results.TransientSolution(1).SurfaceforcingsMassBalance, ...
+		'title', 'Surface mass balance (m/y)', 'gridded',1,...
+		'data',md.results.TransientSolution(end).Thickness,...
+		'title','Thickness (m)', 'gridded',1, ...
+		'data',md.results.TransientSolution(end).Surface, ...
+		'title', 'Surface (m)', 'gridded',1);
+
+	%Line Plots
+	figure
+
+	%Plot surface mass balance
+	surfmb=[]; for i=1:100; surfmb=[surfmb ...
+		md.results.TransientSolution(i).SurfaceforcingsMassBalance]; end
+	subplot(3,1,1); plot([0.2:0.2:20],mean(surfmb)); title('Mean Surface mass balance');
+
+	%Plot velocity
+	vel=[]; for i=1:100; vel=[vel md.results.TransientSolution(i).Vel]; end
+	subplot(3,1,2); plot([0.2:0.2:20],mean(vel)); title('Mean Velocity');
+
+	%Plot Volume
+	volume=[]; for i=1:100; volume=[volume md.results.TransientSolution(i).IceVolume]; end
+	subplot(3,1,3); plot([0.2:0.2:20],volume); title('Ice Volume');
+	xlabel('years')
+end
+
+if any(steps==6)
+	disp('   Step 6: Extract Box SMB');
+	md = loadmodel('./Models/Greenland.Transient');
+
+	ncbox='../Data/Box_Greenland_SMB_monthly_1840-2012_5km_ver20140421.nc';
+
+	%Set surface mass balance
+	lat  = ncread(ncbox,'lat');
+	lon  = ncread(ncbox,'lon');
+	smbbox = ncread(ncbox,'SMB');
+	[x1 y1]=ll2xy(lat,lon,+1,45,70);
+
+	years_of_simulation = 1840:2012;
+	t = [years_of_simulation(1):1/12:years_of_simulation(end)+11/12];
+
+	%Area of grid for 5km box
+	area_of_grid=5000*5000;
+	totalsmb=reshape(sum(sum(smbbox/1000,1),2),length(t),1)*area_of_grid;
+
+	%save surface mass balance mat dataset
+	smbmean = mean(mean(smbbox,3),4);
+	save -v7.3 smbbox smbmean totalsmb smbbox x1 y1 t;
+
+	%plot a time series of total SMB
+	plot(t,totalsmb/1e9); title('Total Surface mass balance, Gt'); xlabel('year'); ylabel('Gt/yr');
+
+	clear smbbox
+
+end
+
+if any(steps==7)
+	disp('   Step 7: Historical Relaxation run');
+	md = loadmodel('./Models/Greenland.Control_drag');
+
+	load smbbox
+
+	%convert mesh x,y into the Box projection
+	[md.mesh.lat,md.mesh.long]  = xy2ll(md.mesh.x,md.mesh.y,+1,39,71);
+	[xi,yi]= ll2xy(md.mesh.lat,md.mesh.long,+1,45,70);
+
+	%Interpolate and set surface mass balance
+	index = BamgTriangulate(x1(:),y1(:));
+	smb_mo = InterpFromMeshToMesh2d(index,x1(:),y1(:),smbmean(:),xi,yi);
+	smb = smb_mo*12/1000*md.materials.rho_freshwater/md.materials.rho_ice;
+	md.surfaceforcings.mass_balance = [smb;1 ];
+
+	%Set transient options, run for 20 years, saving every timestep
+	md.timestepping.time_step=0.2;
+	md.timestepping.final_time=200;
+	md.settings.output_frequency=1;
+
+	%Additional options
+	md.inversion.iscontrol=0;
+	md.transient.requested_outputs={'IceVolume','TotalSmb', ...
+		'SurfaceforcingsMassBalance'};
+	md.verbose=verbose('solution',true,'module',true);
+
+	%Go solve
+	md.cluster=generic('name',oshostname,'np',2);
+	md=solve(md,TransientSolutionEnum);
+
+	save ./Models/Greenland.HistoricTransient md;
+end
+
+if any(steps==8)
+	disp('   Step 8: Plotting exercise');
+
+	%Load historic transient model
+
+
+	%Create Line Plots of relaxation run.  Create a figure.
+
+
+	%Save surface mass balance, by looping through 200 years, or 1000 steps
+
+
+	%Plot surface mass balance time series in first subplot
+
+	
+	%Title this plot Mean surface mass balance
+
+
+	%Save velocity by looping through 1000 steps
+
+
+	%Plot velocity time series in second subplot
+
+	
+	%Title this plot Mean Velocity
+
+
+	%Save Ice Volume by looping through 1000 steps
+
+
+	%Plot volume time series in third subplot
+
+	
+	%Title this plot Mean Velocity and add an x label of years
+
+end
+
+if any(steps==9)
+	disp('   Step 9: Box Transient run');
+	md = loadmodel('./Models/Greenland.HistoricTransient');
+
+	%load past transient results
+	md.geometry.base=md.results.TransientSolution(end).Base;
+	md.geometry.thickness=md.results.TransientSolution(end).Thickness;
+	md.geometry.surface=md.geometry.base+md.geometry.thickness;
+	md.initialization.vx=(md.results.TransientSolution(end).Vx);
+	md.initialization.vy=(md.results.TransientSolution(end).Vy);
+	md.results=[];
+
+	%convert mesh x,y into the Box projection
+	[md.mesh.lat,md.mesh.long]  = xy2ll(md.mesh.x,md.mesh.y,+1,39,71);
+	[xi,yi]= ll2xy(md.mesh.lat,md.mesh.long,+1,45,70);
+
+	%Set surface mass balance
+	load smbbox
+	index = BamgTriangulate(x1(:),y1(:));
+
+	%Set years to run
+	years_of_simulation = 2003:2012;
+
+	%initialize surface mass balance matrix
+	smb = nan*ones(md.mesh.numberofvertices,length(years_of_simulation)*12);
+
+	%Interpolate and set surface mass balance
+	for year=years_of_simulation
+		for month=1:12
+			smb_mo = griddata(double(x1),double(y1),...
+				double(squeeze(smbbox(:,:,month,year-1839))),xi,yi,'nearest');
+			smb(:,(year-years_of_simulation(1))*12+month) = smb_mo;
+		end
+	end
+	md.surfaceforcings.mass_balance = ...
+		[smb*12/1000*md.materials.rho_freshwater/md.materials.rho_ice; ...
+		[1/24:1/12:length(years_of_simulation)]];
+
+	%Set transient options, monthly timestep, saving every month
+	md.timestepping.time_step=1/12;
+	md.timestepping.final_time=length(years_of_simulation);
+	md.settings.output_frequency=1;
+
+	%Additional options
+	md.inversion.iscontrol=0;
+	md.transient.requested_outputs={'IceVolume','TotalSmb', ...
+		'SurfaceforcingsMassBalance'};
+	md.verbose=verbose('solution',true,'module',true);
+
+	%Go solve
+	md.cluster=generic('name',oshostname,'np',2);
+	md=solve(md,TransientSolutionEnum);
+
+	save ./Models/Greenland.BoxTransient md;
+end
+
+if any(steps==10)
+	disp('   Step 10: Plot Box Transient');
+	md = loadmodel('./Models/Greenland.BoxTransient');
+
+	%Set years run
+	years_of_simulation = 2003:2012;
+	t = [years_of_simulation(1):1/12:years_of_simulation(end)+11/12];
+
+	%Line Plots
+	figure
+
+	%Plot surface mass balance
+	surfmb=[]; for i=1:length(t); surfmb=[surfmb ...
+		md.results.TransientSolution(i).TotalSmb]; end
+	subplot(3,1,1); plot(t,surfmb); title('Total Surface mass balance');
+
+	%Plot velocity
+	vel=[]; for i=1:length(t); vel=[vel md.results.TransientSolution(i).Vel]; end
+	subplot(3,1,2); plot(t,max(vel)); title('Max Velocity');
+
+	%Plot Volume
+	volume=[]; for i=1:length(t); volume=[volume md.results.TransientSolution(i).IceVolume]; end
+	subplot(3,1,3); plot(t,volume); title('Ice Volume');
+	xlabel('years')
+end
Index: issm/trunk/examples/ISMIP/CheatyIsmipA.par
===================================================================
--- issm/trunk/examples/ISMIP/CheatyIsmipA.par	(revision 18301)
+++ issm/trunk/examples/ISMIP/CheatyIsmipA.par	(revision 18301)
@@ -0,0 +1,52 @@
+%Parameterization for ISMIP A experiment
+
+%Set the Simulation generic name #md.miscellaneous
+%->
+
+%Geometry
+disp('   Constructing Geometry');
+
+%Define the geometry of the simulation #md.geometry
+%surface is [-x*tan(0.5*pi/180)] #md.mesh
+%->
+md.geometry.surface=-md.mesh.x*tan(0.5*pi/180.);
+%base is [surface-1000+500*sin(x*2*pi/L).*sin(y*2*pi/L)]
+%L is the size of the side of the square #max(md.mesh.x)-min(md.mesh.x)
+%->
+L=max(md.mesh.x)-min(md.mesh.x);
+md.geometry.base=md.geometry.surface-1000.0+500.0*sin(md.mesh.x*2.0*pi/L).*sin(md.mesh.y*2.0*pi/L);
+%thickness is the difference between surface and base #md.geometry
+%->
+md.geometry.thickness=md.geometry.surface-md.geometry.base;
+%plot the geometry to check it out
+%->
+plotmodel(md,'data',md.geometry.thickness);
+
+disp('   Defining friction parameters');
+
+%These parameters will not be used but need to be fixed #md.friction
+%one friciton coefficient per node (md.mesh.numberofvertices,1)
+%->
+md.friction.coefficient=200.0*ones(md.mesh.numberofvertices,1);
+%one friciton exponent (p,q) per element
+%->
+md.friction.p=ones(md.mesh.numberofelements,1);
+%->
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+disp('   Construct ice rheological properties');
+
+%The rheology parameters sit in the material section #md.materials
+%B has one value per vertex
+%->
+md.materials.rheology_B=6.8067e7*ones(md.mesh.numberofvertices,1);
+%n has one value per element
+%->
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+
+disp('   Set boundary conditions');
+
+%Set the default boundary conditions for an ice-sheet 
+% #help SetIceSheetBC
+%->
+md=SetIceSheetBC(md);
Index: issm/trunk/examples/ISMIP/CheatyIsmipF.par
===================================================================
--- issm/trunk/examples/ISMIP/CheatyIsmipF.par	(revision 18301)
+++ issm/trunk/examples/ISMIP/CheatyIsmipF.par	(revision 18301)
@@ -0,0 +1,66 @@
+%Parameterization for ISMIP F experiment
+
+%Set the Simulation generic name #md.miscellaneous
+%->
+
+%Geometry
+disp('   Constructing Geometry');
+
+%Define the geometry of the simulation #md.geometry
+%surface is [-x*tan(3.0*pi/180)] #md.mesh
+%->
+md.geometry.surface=md.mesh.x*tan(3.0*pi/180.0);
+%base is [surface-1000+100*exp(-((x-L/2).^2+(y-L/2).^2)/(10000.^2))]
+%L is the size of the side of the square #max(md.mesh.x)-min(md.mesh.x)
+%->
+L=max(md.mesh.x)-min(md.mesh.x);
+%->
+md.geometry.base=md.geometry.surface-1000.0+100.0*exp(-((md.mesh.x-L/2.0).^2.0+(md.mesh.y-L/2.0).^2.0)/(10000.^2.0));
+%thickness is the difference between surface and base #md.geometry
+%->
+md.geometry.thickness=md.geometry.surface-md.geometry.base;
+%plot the geometry to check it out
+%->
+plotmodel(md,'data',md.geometry.thickness);
+
+disp('   Defining friction parameters');
+
+%These parameters will not be used but need to be fixed #md.friction
+%one friciton coefficient per node (md.mesh.numberofvertices,1)
+%conversion form year to seconds with #md.constants.yts
+%->
+md.friction.coefficient=sqrt(md.constants.yts/(1000*2.140373*10^-7))*ones(md.mesh.numberofvertices,1);
+%one friciton exponent (p,q) per element
+%->
+md.friction.p=ones(md.mesh.numberofelements,1);
+%->
+md.friction.q=zeros(md.mesh.numberofelements,1);
+
+disp('   Construct ice rheological properties');
+
+%The rheology parameters sit in the material section #md.materials
+%B has one value per vertex
+%->
+md.materials.rheology_B=(1/(2.140373*10^-7/md.constants.yts))*ones(md.mesh.numberofvertices,1);
+%n has one value per element
+%->
+md.materials.rheology_n=1*ones(md.mesh.numberofelements,1);
+
+disp('   Set boundary conditions');
+
+%Set the default boundary conditions for an ice-sheet 
+% #help SetIceSheetBC
+%->
+md=SetIceSheetBC(md);
+
+disp('   Initializing velocity and pressure');
+
+%initialize the velocity and pressurefields of #md.initialization
+%->
+md.initialization.vx=zeros(md.mesh.numberofvertices,1);
+%->
+md.initialization.vy=zeros(md.mesh.numberofvertices,1);
+%->
+md.initialization.vz=zeros(md.mesh.numberofvertices,1);
+%->
+md.initialization.pressure=zeros(md.mesh.numberofvertices,1);
Index: issm/trunk/examples/ISMIP/CheatyRunme.m
===================================================================
--- issm/trunk/examples/ISMIP/CheatyRunme.m	(revision 18301)
+++ issm/trunk/examples/ISMIP/CheatyRunme.m	(revision 18301)
@@ -0,0 +1,229 @@
+%wich steps to perform steps are from 1 to 8 
+%step 7 is specific to ISMIPA
+%step 8 is specific to ISMIPF
+
+steps=[1:7];
+
+% parameter file to be used, choose between CheatyIsmipA.par or CheatyIsmipF.par
+ParamFile='CheatyIsmipF.par'
+
+%Run Steps
+
+% {{{ Mesh Generation #1
+if any(steps==1)
+
+	%initialize md as a new model #help model
+	%->
+	md=model();
+	% generate a squaremesh #help squaremesh
+	% Side is 80 km long with 20 points
+	%->
+	if(ParamFile=='CheatyIsmipA.par'),
+		md=squaremesh(md,80000,80000,20,20);
+	elseif(ParamFile=='CheatyIsmipF.par'),
+		md=squaremesh(md,100000,100000,30,30);
+  end
+	% plot the given mesh #plotdoc
+	%->
+	plotmodel(md,'data','mesh')
+	% save the given model
+	%->
+	save ./Models/ISMIP.Mesh_generation md;
+end
+% }}}
+
+% {{{ Masks #2
+if any(steps==2)
+
+	% load the preceding step #help loadmodel
+	% path is given by the organizer with the name of the given step
+	%->
+	md = loadmodel('./Models/ISMIP.Mesh_generation');
+	% set the mask #help setmask
+	% all MISMIP nodes are grounded
+	%->
+	md=setmask(md,'','');
+	% plot the given mask #md.mask to locate the field
+	%->
+	plotmodel(md,'data',md.mask.groundedice_levelset);
+	% save the given model
+	%->
+	save ./Models/ISMIP.SetMask md;
+end
+% }}}
+
+% {{{ Parameterization #3
+if any(steps==3)
+
+	% load the preceding step #help loadmodel
+	% path is given by the organizer with the name of the given step
+	%->
+	md = loadmodel('./Models/ISMIP.SetMask');
+	% parametrize the model # help parameterize
+	% you will need to fil-up the parameter file defined by the
+	% ParamFile variable
+	%->
+	md=parameterize(md,ParamFile);
+	% save the given model
+	%->
+	save ./Models/ISMIP.Parameterization md;
+end
+% }}}
+
+% {{{ Extrusion #4
+if any(steps==4)
+	
+	% load the preceding step #help loadmodel
+	% path is given by the organizer with the name of the given step
+	%->
+	md = loadmodel('./Models/ISMIP.Parameterization');
+	% vertically extrude the preceding mesh #help extrude
+	% only 5 layers exponent 1
+	%->
+	md=extrude(md,9,1);
+	% plot the 3D geometry #plotdoc
+	%->
+	plotmodel(md,'data',md.geometry.base)
+	% save the given model
+	%->
+	save ./Models/ISMIP.Extrusion md;
+end
+% }}}
+
+% {{{ Set the flow computing method #5
+if any(steps==5)
+
+	% load the preceding step #help loadmodel
+	% path is given by the organizer with the name of the given step
+	%->
+	md = loadmodel('./Models/ISMIP.Extrusion');
+	% set the approximation for the flow computation #help setflowequation
+	% We will be using the Higher Order Model (HO)
+	%->
+	md=setflowequation(md,'HO','all');
+	% save the given model
+	%->
+	save ./Models/ISMIP.SetFlow md;
+end
+% }}}
+
+% {{{ Set Boundary Conditions #6
+if any(steps==6)
+
+	% load the preceding step #help loadmodel
+	% path is given by the organizer with the name of the given step
+	%->
+	md = loadmodel('./Models/ISMIP.SetFlow');
+	% dirichlet boundary condition are known as SPCs
+	% ice frozen to the base, no velocity	#md.stressbalance
+	% SPCs are initialized at NaN one value per vertex
+	%->
+	md.stressbalance.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+	%->
+	md.stressbalance.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+	%->
+	md.stressbalance.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+	% extract the nodenumbers at the base #md.mesh.vertexonbase
+	%->
+	basalnodes=find(md.mesh.vertexonbase);
+	% set the sliding to zero on the bed
+	%->
+	md.stressbalance.spcvx(basalnodes)=0.0;
+	%->
+	md.stressbalance.spcvy(basalnodes)=0.0;
+	% periodic boundaries have to be fixed on the sides
+	% create tabs with the side of the domain
+	% for x
+	% create maxX #help find
+	%->
+	maxX=find(md.mesh.x==max(md.mesh.x));
+	% create minX
+	%->
+	minX=find(md.mesh.x==min(md.mesh.x));
+	% for y, max X and minX should be excluded
+	% create maxY
+	%->
+	maxY=find(md.mesh.y==max(md.mesh.y) & md.mesh.x~=max(md.mesh.x) & md.mesh.x~=min(md.mesh.x));
+	% create minY
+	%->
+	minY=find(md.mesh.y==min(md.mesh.y) & md.mesh.x~=max(md.mesh.x) & md.mesh.x~=min(md.mesh.x));
+	% set the node that should be paired together
+	% #md.stressbalance.vertex_pairing
+	%->
+	md.stressbalance.vertex_pairing=[minX,maxX;minY,maxY];
+	if (ParamFile=='CheatyIsmipF.par')
+		% if we are dealing with IsmipF the solution is in
+		% masstransport
+		md.masstransport.vertex_pairing=md.stressbalance.vertex_pairing;
+  end
+	% save the given model
+	%->
+	save ./Models/ISMIP.BoundaryCondition md;
+end
+% }}}
+
+% {{{ Solving #7
+if any(steps==7)
+	% load the preceding step #help loadmodel
+	% path is given by the organizer with the name of the given step
+	%->
+	md = loadmodel('./Models/ISMIP.BoundaryCondition');
+	% Set cluster #md.cluster
+	% generic parameters #help generic
+	% set only the name and number of process
+	%->
+	md.cluster=generic('name',oshostname(),'np',2);
+	% Set which control message you want to see #help verbose
+	%->
+	md.verbose=verbose('convergence',true);
+	% Solve #help solve
+	% we are solving a StressBalanc
+	%->
+	md=solve(md,StressbalanceSolutionEnum());
+	% save the given model
+	%->
+	save ./Models/ISMIP.StressBalance md;
+	% plot the surface velocities #plotdoc
+	%->
+	plotmodel(md,'data',md.results.StressbalanceSolution.Vel)
+end
+% }}}
+
+% {{{ Solving #8
+if any(steps==8)
+	% load the preceding step #help loadmodel
+	% path is given by the organizer with the name of the given step
+	%->
+	md = loadmodel('./Models/ISMIP.BoundaryCondition');
+	% Set cluster #md.cluster
+	% generic parameters #help generic
+	% set only the name and number of process
+	%->
+	md.cluster=generic('name',oshostname(),'np',2);
+	% Set which control message you want to see #help verbose
+	%->
+	md.verbose=verbose('convergence',true);
+	% set the transient model to ignore the thermal model
+	% #md.transient 
+	%->
+	md.transient.isthermal=0;
+	% define the timestepping scheme
+	% everything here should be provided in years #md.timestepping
+	% give the length of the time_step (4 years)
+	%->
+	md.timestepping.time_step=4;
+	% give final_time (20*4 years time_steps)
+	%->
+	md.timestepping.final_time=4*20;
+	% Solve #help solve
+	% we are solving a TransientSolution
+	%->
+	md=solve(md,TransientSolutionEnum);
+	% save the given model
+	%->
+	save ./Models/ISMIP.Transient md;
+	% plot the surface velocities #plotdoc
+	%->
+	plotmodel(md,'data',md.results.TransientSolution(20).Vel)
+end
+% }}}
Index: issm/trunk/examples/ISMIP/IsmipA.par
===================================================================
--- issm/trunk/examples/ISMIP/IsmipA.par	(revision 18301)
+++ issm/trunk/examples/ISMIP/IsmipA.par	(revision 18301)
@@ -0,0 +1,52 @@
+%Parameterization for ISMIP A experiment
+
+%Set the Simulation generic name #md.miscellaneous
+%->
+
+%Geometry
+disp('   Constructing Geometry');
+
+%Define the geometry of the simulation #md.geometry
+%surface is [-x*tan(0.5*pi/180)] #md.mesh
+%->
+
+%base is [surface-1000+500*sin(x*2*pi/L).*sin(y*2*pi/L)]
+%L is the size of the side of the square #max(md.mesh.x)-min(md.mesh.x)
+%->
+
+%->
+
+%thickness is the difference between surface and base #md.geometry
+%->
+
+%plot the geometry to check it out
+%->
+
+
+disp('   Defining friction parameters');
+
+%These parameters will not be used but need to be fixed #md.friction
+%one friciton coefficient per node (md.mesh.numberofvertices,1)
+%->
+
+%one friciton exponent (p,q) per element
+%->
+
+%->
+
+
+disp('   Construct ice rheological properties');
+
+%The rheology parameters sit in the material section #md.materials
+%B has one value per vertex
+%->
+
+%n has one value per element
+%->
+
+
+disp('   Set boundary conditions');
+
+%Set the default boundary conditions for an ice-sheet 
+% #help SetIceSheetBC
+%->
Index: issm/trunk/examples/ISMIP/IsmipF.par
===================================================================
--- issm/trunk/examples/ISMIP/IsmipF.par	(revision 18301)
+++ issm/trunk/examples/ISMIP/IsmipF.par	(revision 18301)
@@ -0,0 +1,64 @@
+%Parameterization for ISMIP F experiment
+
+%Set the Simulation generic name #md.miscellaneous
+%->
+
+%Geometry
+disp('   Constructing Geometry');
+
+%Define the geometry of the simulation #md.geometry
+%surface is [-x*tan(3.0*pi/180)] #md.mesh
+%->
+
+%base is [surface-1000+100*exp(-((x-L/2).^2+(y-L/2).^2)/(0.1*L^2))]
+%L is the size of the side of the square #max(md.mesh.x)-min(md.mesh.x)
+%->
+
+%->
+
+%thickness is the difference between surface and base #md.geometry
+%->
+
+%plot the geometry to check it out
+%->
+
+
+disp('   Defining friction parameters');
+
+%These parameters will not be used but need to be fixed #md.friction
+%one friciton coefficient per node (md.mesh.numberofvertices,1)
+%conversion form year to seconds with #md.constants.yts
+%->
+
+%one friciton exponent (p,q) per element
+%->
+
+%->
+
+
+disp('   Construct ice rheological properties');
+
+%The rheology parameters sit in the material section #md.materials
+%B has one value per vertex
+%->
+
+%n has one value per element
+%->
+
+
+disp('   Set boundary conditions');
+
+%Set the default boundary conditions for an ice-sheet 
+% #help SetIceSheetBC
+%->
+
+disp('   Initializing velocity and pressure');
+
+%initialize the velocity and pressurefields of #md.initialization
+%->
+
+%->
+
+%->
+
+%->
Index: issm/trunk/examples/ISMIP/runme.m
===================================================================
--- issm/trunk/examples/ISMIP/runme.m	(revision 18301)
+++ issm/trunk/examples/ISMIP/runme.m	(revision 18301)
@@ -0,0 +1,224 @@
+%wich steps to perform steps are from 1 to 8 
+%step 7 is specific to ISMIPA
+%step 8 is specific to ISMIPF
+
+steps=[1];
+
+% parameter file to be used, choose between IsmipA.par or IsmipF.par
+ParamFile='IsmipA.par'
+
+%Run Steps
+
+% {{{ Mesh Generation #1
+if any(steps==1) 
+
+	%initialize md as a new model #help model
+	%->
+
+	% generate a squaremesh #help squaremesh
+	% Side is 80 km long with 20 points
+	%->
+
+	% plot the given mesh #plotdoc
+	%->
+
+	% save the given model
+	%->
+
+end
+% }}}
+
+% {{{ Masks #2
+if any(steps==2) 
+
+	% load the preceding step #help loadmodel
+	% path is given by the organizer with the name of the given step
+	%->
+
+	% set the mask #help setmask
+	% all MISMIP nodes are grounded
+	%->
+
+	% plot the given mask #md.mask to locate the field
+	%->
+
+	% save the given model
+	%->
+
+end
+% }}}
+
+% {{{ Parameterization #3
+if any(steps==3) 
+
+	% load the preceding step #help loadmodel
+	% path is given by the organizer with the name of the given step
+	%->
+
+	% parametrize the model # help parameterize
+	% you will need to fil-up the parameter file (given by the
+  % ParamFile variable)
+	%->
+
+	% save the given model
+	%->
+
+end
+% }}}
+
+% {{{ Extrusion #4
+if any(steps==4)
+	
+	% load the preceding step #help loadmodel
+	% path is given by the organizer with the name of the given step
+	%->
+
+	% vertically extrude the preceding mesh #help extrude
+	% only 5 layers exponent 1
+	%->
+
+	% plot the 3D geometry #plotdoc
+	%->
+
+	% save the given model
+	%->
+
+end
+% }}}
+
+% {{{ Set the flow computing method #5
+
+if any(steps==5)
+
+	% load the preceding step #help loadmodel
+	% path is given by the organizer with the name of the given step
+	%->
+
+	% set the approximation for the flow computation #help setflowequation
+	% We will be using the Higher Order Model (HO)
+	%->
+
+	% save the given model
+	%->
+
+end
+% }}}
+
+% {{{ Set Boundary Conditions #6
+if any(steps==6)
+
+	% load the preceding step #help loadmodel
+	% path is given by the organizer with the name of the given step
+	%->
+
+	% dirichlet boundary condition are known as SPCs
+	% ice frozen to the base, no velocity	#md.stressbalance
+	% SPCs are initialized at NaN one value per vertex
+	%->
+
+	%->
+
+	%->
+
+	% extract the nodenumbers at the base #md.mesh.vertexonbase
+	%->
+
+  % set the sliding to zero on the bed (Vx and Vy)
+	%->
+
+	%->
+
+	% periodic boundaries have to be fixed on the sides
+	% create tabs with the side of the domain
+	% for x
+	% create maxX #help find
+	%->
+
+	% create minX
+	%->
+
+	% for y, max X and minX should be excluded
+	% create maxY
+	%->
+
+	% create minY
+	%->
+
+	% set the node that should be paired together
+	% #md.stressbalance.vertex_pairing
+	%->
+
+	if (ParamFile=='IsmipF.par')
+		% if we are dealing with IsmipF the solution is in masstransport
+		md.masstransport.vertex_pairing=md.stressbalance.vertex_pairing;
+  end
+	% save the given model
+	%->
+
+end
+% }}}
+
+% {{{ Solving #7
+if any(steps==7)
+	% load the preceding step #help loadmodel
+	% path is given by the organizer with the name of the given step
+	%->
+
+	% Set cluster #md.cluster
+	% generic parameters #help generic
+	% set only the name and number of process
+	%->
+
+	% Set which control message you want to see #help verbose
+	%->
+
+	% Solve #help solve
+	% we are solving a StressBalanc
+	%->
+
+	% save the given model
+	%->
+
+	% plot the surface velocities #plotdoc
+	%->
+end
+% }}}
+
+% {{{ Solving #8
+if any(steps==8)
+	% load the preceding step #help loadmodel
+	% path is given by the organizer with the name of the given step
+	%->
+
+	% Set cluster #md.cluster
+	% generic parameters #help generic
+	% set only the name and number of process
+	%->
+
+	% Set which control message you want to see #help verbose
+	%->
+
+	% set the transient model to ignore the thermal model
+	% #md.transient 
+	%->
+
+	% define the timestepping scheme
+	% everything here should be provided in years #md.timestepping
+	% give the length of the time_step (4 years)
+	%->
+
+	% give final_time (20*4 years time_steps)
+	%->
+
+	% Solve #help solve
+	% we are solving a TransientSolution
+	%->
+
+	% save the given model
+	%->
+
+	% plot the surface velocities #plotdoc
+	%->
+
+end
+% }}}
Index: issm/trunk/examples/IceBridge/DomainOutline.exp
===================================================================
--- issm/trunk/examples/IceBridge/DomainOutline.exp	(revision 18301)
+++ issm/trunk/examples/IceBridge/DomainOutline.exp	(revision 18301)
@@ -0,0 +1,733 @@
+## Name:DomainOutline
+## Icon:0
+# Points Count Value
+727 1.000000
+# X pos Y pos
+47662.8073760000 -2621047.2585999998
+39869.9055420000 -2638077.6292949999
+26037.5047870000 -2644088.3483640002
+24868.5695120000 -2659115.1460360000
+25647.8596950000 -2674141.9437079998
+16880.8451320000 -2687666.0616130000
+515.7512810000 -2685662.4885900002
+-7666.7956450000 -2672639.2639410002
+-22083.6640370000 -2677147.3032430001
+-30071.3884170000 -2690170.5278920000
+-44683.0793550000 -2694678.5671930001
+-41760.7411680000 -2709705.3648660001
+-37669.4677050000 -2724231.2692820001
+-44488.2568100000 -2738757.1736989999
+-55787.9644690000 -2753283.0781149999
+-67672.1397650000 -2742263.4264890002
+-87154.3943500000 -2741762.5332330000
+-105078.0685680000 -2741011.1933490001
+-97090.3441880000 -2760546.0303230002
+-99817.8598300000 -2780581.7605530000
+-82478.6532500000 -2789096.9459000002
+-77218.4445120000 -2804123.7435730002
+-77023.6219660000 -2820152.3277560002
+-95336.9412760000 -2829669.2996149999
+-112870.9704020000 -2832674.6591500002
+-123196.5653320000 -2818649.6479890002
+-122417.2751480000 -2834177.3389170002
+-120274.2271440000 -2849204.1365890000
+-105662.5362060000 -2854713.9624020001
+-89492.2649000000 -2850706.8163560000
+-77997.7346950000 -2860724.6814710000
+-92024.9579960000 -2867737.1870519998
+-84816.5238000000 -2890277.3835600000
+-94752.4736380000 -2901797.9284419999
+-114234.7282230000 -2894284.5296060001
+-127677.4838860000 -2883765.7712349999
+-146964.9159250000 -2888774.7037930000
+-139951.3042750000 -2905805.0744880000
+-154173.3501210000 -2916824.7261140002
+-165667.8803260000 -2904302.3947210000
+-162550.7195930000 -2920330.9789040000
+-152809.5923000000 -2934355.9900650000
+-147744.2061080000 -2949883.6809930000
+-163719.6548680000 -2950384.5742489998
+-175603.8301650000 -2963908.6921540000
+-189825.8760110000 -2956896.1865730002
+-195670.5523870000 -2971422.0909899999
+-210282.2433250000 -2966413.1584319999
+-222750.8862590000 -2978301.3022220000
+-214763.1618800000 -2995247.5385030000
+-222750.8862590000 -3011386.8111520000
+-206970.2600460000 -3016228.5929470002
+-217295.8549760000 -3027122.6019839998
+-232686.8360980000 -3031964.3837790000
+-212035.6462380000 -3035192.2383090002
+-212814.9364210000 -3050928.0291410000
+-197229.1327540000 -3048910.6200600001
+-185344.9574570000 -3058190.7018329999
+-174824.5399810000 -3071102.1199520002
+-182812.2643610000 -3084820.5017030002
+-192163.7465610000 -3098942.3652710002
+-176577.9428940000 -3092486.6562120002
+-184955.3123650000 -3105801.5561469998
+-182617.4418150000 -3121537.3469790001
+-199372.1807580000 -3120326.9015310002
+-218464.7902510000 -3115888.6015519998
+-205022.0345870000 -3126782.6105900002
+-189825.8760110000 -3128800.0196710001
+-198592.8905740000 -3146149.7377680000
+-213009.7589670000 -3140904.4741580002
+-225283.5793550000 -3131220.9105679998
+-222750.8862590000 -3146149.7377680000
+-208334.0178670000 -3151395.0013790000
+-195670.5523870000 -3161078.5649680002
+-213009.7589670000 -3171569.0921900002
+-227621.4499060000 -3161078.5649680002
+-242622.7859360000 -3157850.7104389998
+-240090.0928400000 -3174393.4649040001
+-220023.3706180000 -3185690.9557579998
+-233076.4811890000 -3193357.1102660000
+-258013.7670580000 -3188111.8466550000
+-275158.1510920000 -3196181.4829790001
+-258208.5896040000 -3198198.8920600000
+-252753.5583200000 -3213127.7192600002
+-270482.4099920000 -3215952.0919740000
+-258793.0572410000 -3226442.6191960000
+-275547.7961840000 -3232969.1157640000
+-276521.9089130000 -3248275.5695210001
+-293276.6478560000 -3241868.2167850002
+-282561.4078340000 -3256818.7065010001
+-288211.2616640000 -3273549.0164200002
+-302433.3075110000 -3267141.6636850000
+-305745.2907900000 -3251479.2458879999
+-313733.0151700000 -3237596.6482950002
+-310810.6769820000 -3218018.6260489998
+-325812.0130120000 -3213747.0575589999
+-338280.6559470000 -3203780.0644160002
+-336527.2530340000 -3187761.6825779998
+-321720.7395500000 -3185269.9342919998
+-325812.0130120000 -3165691.9120459999
+-313538.1926240000 -3155368.9548610002
+-329708.4639290000 -3158928.5952699999
+-338085.8334010000 -3173167.1569030001
+-351723.4116100000 -3164268.0558819999
+-342566.7519550000 -3151809.3144530002
+-325812.0130120000 -3153233.1706160000
+-310615.8544360000 -3148249.6740450002
+-329123.9962920000 -3150029.4942490002
+-343151.2195930000 -3144334.0695949998
+-361854.1839940000 -3145401.9617180000
+-377634.8102080000 -3142910.2134320000
+-388350.0502290000 -3154657.0267800000
+-397701.5324300000 -3178150.6534750001
+-417573.4321060000 -3179930.4736790000
+-432720.8850460000 -3186308.0579260001
+-451813.4945390000 -3187438.8412219998
+-467788.9432980000 -3177261.7915590000
+-482985.1018740000 -3173492.5139070000
+-490583.1811620000 -3158792.3310610000
+-492726.2291670000 -3141453.6538590002
+-490193.5360710000 -3119214.9157079998
+-505389.6946470000 -3113560.9992289999
+-489803.8909790000 -3110922.5048719998
+-478309.3607740000 -3100368.5274439999
+-495648.5673540000 -3101122.3829750000
+-512792.9513890000 -3108660.9382799999
+-501103.5986380000 -3097353.1053220001
+-493895.1644420000 -3083783.7057719999
+-486491.9077000000 -3068329.6673960001
+-503636.2917340000 -3066068.1008040002
+-522728.9012270000 -3064183.4619780001
+-521559.9659520000 -3046467.8570099999
+-531301.0932440000 -3029506.1075729998
+-543769.7361790000 -3012167.4303710000
+-545912.7841830000 -2992944.1143419999
+-550004.0576459999 -2974474.6538439998
+-567538.0867720000 -2983897.8479749998
+-585851.4060810000 -2995959.5364640001
+-589942.6795440000 -2981259.3536189999
+-572213.8278720001 -2975982.3649050002
+-565200.2162220000 -2959397.5432330002
+-548055.8321870000 -2954120.5545190000
+-545717.9616370000 -2933389.5274290000
+-536561.3019820000 -2920197.0556450002
+-545523.1390910000 -2907758.4393910002
+-533444.1412490000 -2898335.2452590000
+-530568.0950890000 -2883304.2548420001
+-545624.1658510000 -2879383.1998239998
+-559750.8495300000 -2868110.1666489998
+-577223.3267109999 -2867129.9028940001
+-590606.5007220000 -2859287.7928590002
+-573319.9009570000 -2851445.6828239998
+-551572.2431889999 -2846054.2321750000
+-530939.8499220000 -2834781.1989989998
+-528337.5660870000 -2817626.5832969998
+-543765.3916830000 -2804883.1544900001
+-528151.6886699999 -2802432.4951040000
+-528151.6886699999 -2785768.0112790000
+-513467.3727410000 -2778416.0331210000
+-513839.1275750000 -2760771.2855420001
+-525735.2822510001 -2749498.2523670001
+-509563.9469880000 -2738225.2191909999
+-517184.9210780000 -2724501.5266300002
+-532240.9918400000 -2725971.9222610001
+-524248.2629170000 -2707837.0428050002
+-512537.9856570000 -2694113.3502429998
+-521088.3468310000 -2678429.1301730000
+-538189.0691780000 -2669606.7563829999
+-556033.3011930001 -2677448.8664190001
+-539676.0885130001 -2666175.8332429999
+-526664.6693360000 -2658333.7232080000
+-517556.6759110000 -2639708.7118739998
+-526107.0370850000 -2626965.2830670001
+-538932.5788460000 -2618142.9092779998
+-550456.9786890000 -2607360.0079790000
+-565698.9268680000 -2599517.8979440001
+-581126.7524640000 -2600988.2935759998
+-583110.5023000001 -2578346.1085480000
+-572583.8192940000 -2566324.6704099998
+-556315.3091930000 -2558811.2715739999
+-538132.8567270000 -2571333.6029679999
+-524735.2601730000 -2578346.1085480000
+-519759.0100240000 -2594875.5859869998
+-503107.7114500000 -2585859.5073839999
+-486456.4128760000 -2576342.5355250002
+-477843.6722340000 -2559312.1648300001
+-474015.7875040000 -2536771.9683220000
+-473441.6047950000 -2521244.2773940000
+-474972.7586870000 -2504714.7999539999
+-485690.8359300000 -2491691.5753049999
+-486073.6244030000 -2476664.7776330002
+-492581.0284430000 -2459634.4069380001
+-474207.1817410000 -2447112.0755440001
+-465594.4410990000 -2434589.7441509999
+-462340.7390790000 -2418060.2667109999
+-462914.9217880000 -2399026.3229930000
+-468465.3546460000 -2375484.3399729999
+-473058.8163220000 -2360457.5423010001
+-478417.8549440000 -2343427.1716060000
+-504256.0768690000 -2331405.7334679998
+-489901.5091330000 -2322389.6548649999
+-475164.1529230000 -2307863.7504480002
+-462577.4401970000 -2287577.5735909999
+-457317.2314590000 -2269044.5231289999
+-439783.2023330000 -2268042.7366169998
+-436666.0415990000 -2252014.1524330000
+-435886.7514160000 -2233481.1019710000
+-448550.2168960000 -2220457.8773220000
+-440172.8474240000 -2206933.7594170002
+-429262.7848570000 -2193409.6415120000
+-433743.7034120000 -2176880.1640720000
+-426730.0917610000 -2162354.2596560000
+-419716.4801110000 -2147327.4619840002
+-428678.3172200000 -2134805.1305900002
+-427314.5593990000 -2110762.2543150000
+-426535.2692150000 -2094733.6701310000
+-427509.3819440000 -2067184.5410650000
+-428093.8495820000 -2050655.0636260000
+-425366.3339400000 -2035628.2659539999
+-432379.9455910000 -2021102.3615369999
+-446017.5238000000 -2003571.0975860001
+-430821.3652240000 -2002569.3110750001
+-428678.3172200000 -1986039.8336360001
+-424197.3986650000 -1971013.0359630000
+-418060.4884710000 -1957238.4714309999
+-433451.4695930000 -1950225.9658500000
+-426243.0353960000 -1933696.4884110000
+-441634.0165180000 -1943714.3535259999
+-433841.1146840000 -1926683.9828300001
+-448647.6281690000 -1933696.4884110000
+-464428.2543820000 -1948222.3928270000
+-465402.3671120000 -1933195.5951550000
+-463843.7867450000 -1914662.5446929999
+-456245.7074570000 -1901138.4267879999
+-468714.3503910000 -1892122.3481840000
+-480208.8805960000 -1905646.4660890000
+-479429.5904130000 -1888616.0953939999
+-478455.4776830000 -1871585.7246989999
+-478650.3002290000 -1856558.9270270001
+-484494.9766050000 -1841031.2360990001
+-494430.9264430000 -1822498.1856370000
+-505925.4566480000 -1807972.2812200000
+-508847.7948350000 -1791442.8037810000
+-504172.0537350000 -1776416.0061079999
+-510990.8428400000 -1759886.5286689999
+-502223.8282770000 -1745861.5175079999
+-512939.0682980000 -1728330.2535570001
+-511964.9555690000 -1712802.5626300001
+-505340.9890100000 -1697775.7649570000
+-506315.1017390000 -1681747.1807740000
+-507289.2144690000 -1662713.2370559999
+-508446.9486300000 -1645056.7497910000
+-502180.9448550000 -1623518.3397939999
+-505662.0580630000 -1602480.8230530000
+-505836.1137240000 -1586953.1321250000
+-509317.2269320000 -1571425.4411970000
+-516105.3976870000 -1557400.4300360000
+-530552.0175000000 -1537865.5930620001
+-533336.9080660000 -1513321.8235309999
+-522719.5127820000 -1498295.0258589999
+-506532.3363650000 -1492284.3067900001
+-522893.5684430000 -1484770.9079539999
+-515757.2863660000 -1469744.1102819999
+-532118.5184440000 -1465236.0709800001
+-535947.7429720000 -1449708.3800520001
+-544476.4703320001 -1428670.8633109999
+-551960.8637290000 -1415146.7454059999
+-565363.1495800000 -1405629.7735470000
+-567277.7618440000 -1386094.9365729999
+-582420.6042990000 -1384091.3635499999
+-593212.0552430000 -1370066.3523899999
+-606266.2297730000 -1362052.0602980000
+-613793.7528780000 -1344395.5730330001
+-621618.1005840000 -1359923.2639609999
+-634079.0987820000 -1369440.2358200001
+-633354.6221430000 -1354413.4381480000
+-638860.6446030000 -1339386.6404760000
+-649438.0035390001 -1351908.9718690000
+-667405.0241970000 -1352409.8651250000
+-679431.3364110000 -1363429.5167510000
+-679721.1270670000 -1346900.0393119999
+-676533.4298540000 -1330370.5618720001
+-690008.6953470000 -1339386.6404760000
+-701165.6355950000 -1327365.2023380001
+-688994.4280520000 -1315844.6574560001
+-709279.7739560000 -1318349.1237339999
+-717249.0169900000 -1331372.3483839999
+-735216.0376480001 -1329869.6686160001
+-741420.6668040000 -1315969.8807699999
+-750947.3474350000 -1299440.4033299999
+-734597.5036490000 -1299440.4033299999
+-722496.0444700000 -1284413.6056580001
+-707948.5456690000 -1288420.7517039999
+-689023.9233340001 -1290424.3247270000
+-678209.8534290000 -1276399.3135660000
+-672545.3406220000 -1262374.3024060000
+-693401.0468670001 -1264377.8754280000
+-709493.4127980000 -1260871.6226379999
+-725971.9955110000 -1250853.7575240000
+-725714.5176560000 -1234825.1733400000
+-720951.1773400001 -1215290.3363659999
+-737172.2821980000 -1218295.6958999999
+-749402.4803050000 -1205272.4712510000
+-736399.8486340001 -1196757.2859040000
+-720822.4384130000 -1191247.4600899999
+-710652.0631450000 -1204771.5779949999
+-697906.9093280000 -1218796.5891559999
+-684131.8440910000 -1227812.6677590001
+-668940.6506530000 -1229816.2407819999
+-666237.1331770000 -1253358.2238020001
+-653620.7182870000 -1262374.3024060000
+-648471.1611900000 -1247347.5047330000
+-634696.0959530000 -1258868.0496149999
+-632625.0227419999 -1243541.0164699999
+-618416.8083510000 -1233878.1370890001
+-601000.2874830000 -1228080.4094600000
+-615361.2783740000 -1217451.2421410000
+-598861.4165000001 -1216968.0981719999
+-610625.2069099999 -1201990.6351310001
+-617652.9258560000 -1185080.5962139999
+-631708.3637490000 -1178799.7246160000
+-648666.5551200000 -1183631.1643070001
+-656458.1565610000 -1169136.8452349999
+-653708.1795820000 -1154159.3821950001
+-665166.4169950000 -1166237.9814210001
+-676166.3249110000 -1153193.0942569999
+-676166.3249110000 -1133384.1915249999
+-689305.1038110000 -1118406.7284850001
+-709013.2721609999 -1111159.5689490000
+-711610.4726409999 -1091833.8101870001
+-716346.5441050000 -1074440.6273010001
+-701527.2237180000 -1070092.3315790000
+-680291.2903790000 -1068642.8996720000
+-664096.9815030000 -1078788.9230219999
+-650958.2026030000 -1100530.4016300000
+-628041.7277770001 -1095698.9619390001
+-611236.3129050001 -1091350.6662170000
+-588930.9440750000 -1094732.6740009999
+-577319.9301640000 -1078305.7790530000
+-565250.5867559999 -1066710.3237960001
+-550431.2663680000 -1071541.7634860000
+-540042.4644469999 -1060429.4521979999
+-531203.6819710000 -1047613.0696300000
+-510357.6695660000 -1037937.0529810000
+-498473.4942690000 -1027821.2173940000
+-486199.6738810000 -1015066.4681760001
+-487953.0767930000 -994834.7970020000
+-464964.0163830000 -990876.4265550000
+-449378.2127160000 -998353.3485110000
+-430285.6032230000 -1001432.0810810000
+-417622.1377430000 -1012427.5545450000
+-399308.8184330000 -1004950.6325890000
+-384697.1274945000 -1000332.5337340001
+-370085.4365560000 -995714.4348789999
+-375540.4678400000 -980760.5909680000
+-380021.3863940000 -966246.5659950000
+-383528.1922200000 -949973.2652690000
+-383528.1922200000 -930181.4130330000
+-384112.6598570000 -911709.0176140000
+-380216.2089400000 -883560.6055450001
+-366919.5701860000 -892846.9764360000
+-353087.1694310000 -880338.0618260000
+-336527.2530340000 -873692.7009390000
+-322694.8522790000 -888547.0370390000
+-307888.3387940000 -897146.9158330000
+-294835.2282230000 -913564.8662580000
+-275937.4412760000 -919037.5164000000
+-252169.0906820000 -915128.4805850000
+-245350.3015780000 -901446.8552300000
+-244181.3663030000 -918646.6128190000
+-231615.3120950000 -930563.0925760000
+-215445.0407900000 -924017.9382920000
+-206872.8487730000 -937108.2468600000
+-190507.7549220000 -933426.5975750000
+-186611.3040050000 -912972.9904390000
+-185961.8955186667 -896882.8194913333
+-185312.4870323333 -880792.6485436666
+-184663.0785460000 -864702.4775960000
+-175311.5963460000 -883519.7961620000
+-174532.3061620000 -902337.1147280000
+-172584.0807040000 -918700.0004370000
+-168882.4523330000 -933835.6697180000
+-152322.5359360000 -933835.6697180000
+-142581.4086430000 -921563.5054359999
+-127969.7177050000 -912154.8461530000
+-131086.8784390000 -930563.0925760000
+-115501.0747710000 -924427.0104349999
+-112189.0914910000 -905609.6918690000
+-114916.6071330000 -887610.5175890001
+-101473.8514700000 -899882.6818710000
+-84329.4674350000 -896610.1047290000
+-100110.0936490000 -892110.3111590000
+-87836.2732610000 -879838.1468770000
+-74685.7514160000 -869305.2030530000
+-57541.3673810000 -863251.9975030000
+-49553.6430020000 -850388.9357080000
+-34357.4844260000 -846227.3568920000
+-47995.0626350000 -825797.7881600000
+-30071.3884170000 -835255.9218320000
+-18771.6807580000 -850767.2610550000
+-6303.0378240000 -859847.0693810000
+7139.7178400000 -852658.8877899999
+22141.0538700000 -862873.6721560000
+31297.7135250000 -877628.3606850000
+47662.8073760000 -874601.7579100000
+49611.0328340000 -893518.0252550000
+66365.7717770000 -886708.1690110000
+81123.5796250000 -882220.1151260000
+97683.4960220000 -884202.5846670000
+80149.4668960000 -888960.5115630000
+65537.7759570000 -896493.8958170000
+68460.1141450000 -914732.6155880000
+84435.5629050000 -917508.0729450000
+100605.8342100000 -907595.7252430000
+120282.9113400000 -911957.1582320000
+129049.9259030000 -927420.4206470000
+153402.7441340000 -925437.9511060000
+169767.8379850000 -920680.0242090001
+180677.9005530000 -910371.1825990001
+192367.2533040000 -899269.3531730000
+201134.2678670000 -912353.6521400000
+182626.1260110000 -920680.0242090001
+169183.3703480000 -936539.7805320000
+163338.6939720000 -950417.0673150000
+182820.9485570000 -955174.9942120000
+187301.8671120000 -970241.7627180000
+200744.6227750000 -980550.6043280000
+198796.3973170000 -995617.3728350000
+211118.9233410000 -983385.4589040000
+211508.5684330000 -999969.0227530000
+225146.1466420000 -1008484.9068910000
+240731.9503100000 -1009829.5201760000
+238588.9023060000 -1032239.7415930000
+253785.0608820000 -1029550.5150230000
+273072.4929210000 -1036273.5814480000
+281255.0398460000 -1056890.9851510001
+286320.4260380000 -1071681.7312860000
+305413.0355310000 -1086024.2729930000
+316907.5657360000 -1095884.7704169999
+326453.8704830000 -1081990.4331380001
+341260.3839670000 -1076611.9799980000
+355677.2523600000 -1064958.6648609999
+372319.0245690000 -1056006.2810410000
+387981.0391590000 -1068027.7191780000
+383779.0352450000 -1084056.3033620000
+366207.0188750000 -1085558.9831290001
+366971.0195860000 -1102088.4605690001
+352646.0062410000 -1113108.1121950001
+362960.0158500000 -1126131.3368440000
+380914.0325760000 -1133143.8424249999
+394093.0448530000 -1123626.8705660000
+409182.0589100000 -1113108.1121950001
+409182.0589100000 -1131641.1626569999
+404407.0544620000 -1158689.3984670001
+386262.0375580000 -1153179.5726540000
+374229.0263480000 -1166202.7973030000
+364488.0172730000 -1182732.2747430000
+377285.0291950000 -1191748.3533460000
+388172.0393370000 -1202768.0049719999
+392947.0437860000 -1219798.3756680000
+380341.0320420000 -1228814.4542710001
+383588.0350670000 -1251354.6507790000
+389509.0405830000 -1265880.5551960000
+389509.0405830000 -1282910.9258910001
+399632.0500130000 -1295934.1505400001
+408609.0583760000 -1313966.3077469999
+410137.0598000000 -1333000.2514650000
+413526.9681570000 -1350406.2921020000
+416526.2265730000 -1367436.6627970000
+415776.4119690000 -1385468.8200040001
+419900.3922910000 -1406005.4434890000
+430960.1577010000 -1421032.2411610000
+431897.4259560000 -1436059.0388330000
+448018.4399430000 -1436559.9320890000
+448580.8008960000 -1456094.7690630001
+438458.3037410000 -1469117.9937120001
+432459.7869090000 -1486148.3644069999
+449705.5228020000 -1494663.5497550000
+448393.3472450000 -1513196.6002170001
+463202.1856750000 -1521210.8923090000
+447830.9862920000 -1525218.0383550001
+458140.9370980000 -1539243.0495160001
+462639.8247220000 -1554269.8471880001
+473887.0437820000 -1564287.7123030000
+458703.2980510000 -1557275.2067219999
+463014.7320240000 -1574305.5774170000
+478948.2923600000 -1567293.0718370001
+484009.5409370000 -1584824.3357879999
+475011.7656880000 -1597346.6671819999
+484009.5409370000 -1614877.9311319999
+488508.4285610000 -1630906.5153160000
+470512.8780640000 -1618384.1839230000
+461702.5564670000 -1631407.4085720000
+474074.4974330000 -1641926.1669419999
+488883.3358630000 -1648938.6725230000
+495661.8324810000 -1662963.6836830000
+478923.6439970000 -1667471.7229849999
+463095.1396700000 -1663965.4701950001
+449449.8773190000 -1652945.8185690001
+455817.6664170000 -1670477.0825199999
+441626.5935720000 -1662963.6836830000
+433439.4361610000 -1648437.7792670000
+409690.0603430000 -1652315.3206390000
+394504.9542530000 -1655951.1781029999
+411243.1427370000 -1662462.7904280000
+426707.7734010000 -1676487.8015880000
+437260.1096190000 -1691514.5992610001
+455999.6032480000 -1702534.2508870000
+441626.5935720000 -1710047.6497229999
+428891.0153770000 -1692516.3857720001
+435076.8676430000 -1708544.9699560001
+419976.1106410000 -1704036.9306540000
+408696.0270980000 -1692516.3857720001
+395050.7647470000 -1701532.4643750000
+388501.0388190000 -1718562.8350710000
+378494.5130940000 -1731085.1664640000
+376129.3342870000 -1713553.9025129999
+361938.2614420000 -1720566.4080940001
+373582.2186480000 -1732086.9529760000
+358481.4616460000 -1738598.5652999999
+369397.6715270000 -1754627.1494839999
+352659.4830430000 -1751621.7899490001
+335805.3526830000 -1754501.9261700001
+338338.0457790000 -1777042.1226780000
+354897.9621760000 -1775539.4429110000
+349053.2858010000 -1792569.8136060000
+330739.9664910000 -1791568.0270950000
+344182.7221550000 -1806093.9315110000
+341455.2065130000 -1823625.1954620001
+351780.8014430000 -1809600.1843010001
+344377.5447010000 -1826129.6617409999
+356066.8974510000 -1836147.5268550001
+345546.4799760000 -1853678.7908059999
+363080.5091020000 -1853678.7908059999
+371847.5236650000 -1841156.4594129999
+370288.9432980000 -1859689.5098750000
+386848.8596950000 -1868204.6952229999
+404772.5339130000 -1856183.2570849999
+415098.1288430000 -1867703.8019669999
+428735.7070520000 -1860691.2963870000
+421137.6277640000 -1874215.4142920000
+413929.1935680000 -1888741.3187080000
+418799.7572140000 -1903768.1163800000
+428735.7070520000 -1916791.3410300000
+415098.1288430000 -1935825.2847480001
+398148.5673540000 -1926809.2061439999
+380030.0705910000 -1929814.5656790000
+364444.2669230000 -1929814.5656790000
+348468.8181630000 -1924304.7398659999
+333077.8370420000 -1919796.7005640001
+348079.1730720000 -1935825.2847480001
+332883.0144960000 -1939832.4307939999
+318855.7911950000 -1951853.8689309999
+331908.9017660000 -1964376.2003250001
+349442.9308930000 -1959868.1610230000
+358209.9454560000 -1943338.6835840000
+358404.7680020000 -1958365.4812560000
+345936.1250670000 -1971388.7059050000
+345351.6574300000 -1987918.1833450000
+330739.9664910000 -1991925.3293910001
+337753.5781420000 -2005449.4472960001
+353534.2043550000 -2007453.0203180001
+365223.5571060000 -1997435.1552040000
+385679.9244200000 -1986415.5035770000
+399317.5026290000 -1977399.4249740001
+399122.6800840000 -1993928.9024139999
+381393.8284120000 -1998436.9417150000
+399512.3251750000 -1999939.6214820000
+395615.8742580000 -2018973.5652000001
+387822.9724240000 -2032998.5763610001
+383975.2271440000 -2048275.8206610000
+398976.5631740000 -2062801.7250780000
+397223.1602620000 -2078830.3092610000
+379299.4860440000 -2080833.8822840001
+362739.5696470000 -2085842.8148419999
+374428.9223980000 -2097363.3597240001
+390599.1937030000 -2089849.9608880000
+379299.4860440000 -2103374.0787930000
+364492.9725590000 -2111388.3708839999
+355531.1354500000 -2097363.3597240001
+343257.3150620000 -2111889.2641400001
+351829.5070790000 -2127917.8483239999
+365661.9078340000 -2119402.6629760000
+357284.5383630000 -2133928.5673929998
+374039.2773060000 -2136933.9269269998
+385533.8075110000 -2147452.6852980000
+375792.6802180000 -2160976.8032030002
+390988.8387940000 -2162479.4829699998
+378520.1958600000 -2174000.0278520002
+394105.9995280000 -2164983.9492489998
+409107.3355580000 -2161978.5897140000
+421186.3334010000 -2149957.1515759998
+437941.0723440000 -2150958.9380879998
+450409.7152780000 -2171495.5615730002
+454695.8112860000 -2156969.6571570002
+471645.3727750000 -2159975.0166910002
+459566.3749330000 -2147452.6852980000
+465605.8738540000 -2132425.8876260002
+477490.0491500000 -2120404.4494880000
+485867.4186220000 -2133427.6741370000
+493264.3211700000 -2119402.6629760000
+495978.8328800000 -2102873.1855370002
+509098.9728100000 -2110386.5843730001
+523877.9810080000 -2104876.7585600000
+541371.5009160000 -2109885.6911169998
+529608.6168400000 -2096862.4664680001
+544990.8498620000 -2099366.9327469999
+561579.5325330000 -2107381.2248390000
+576509.3469370001 -2104876.7585600000
+596868.1847600000 -2102873.1855370002
+611948.8053700000 -2108883.9046060001
+597622.2157910001 -2119402.6629760000
+580430.3082950000 -2125413.3820449999
+599130.2778520000 -2126916.0618119999
+583144.8200050000 -2134930.3539040000
+568818.2304260000 -2148454.4718089998
+582843.2075930000 -2161477.6964580002
+566706.9435400000 -2162980.3762260000
+552983.5787850000 -2170994.6683180002
+543331.9815950000 -2188025.0390130002
+547554.5553660000 -2207058.9827310001
+538053.7643820000 -2193033.9715700001
+525084.4306570000 -2209062.5557539999
+516036.0582910000 -2221083.9938920001
+529910.2292520000 -2214572.3815669999
+541220.6947100000 -2225091.1399369999
+526140.0741000000 -2223087.5669140001
+526743.2989240000 -2239617.0443540001
+521615.8879170000 -2256647.4150490002
+506233.6548950000 -2255144.7352820002
+508194.1355740000 -2275681.3587670000
+489343.3598110000 -2268167.9599310001
+488740.1349870000 -2283695.6508590002
+475770.8012620000 -2293212.6227179999
+460539.3744460000 -2281692.0778359999
+449228.9089890000 -2296217.9822519999
+448022.4593400000 -2314250.1394590000
+440180.5366230000 -2298722.4485309999
+441085.3738600000 -2277184.0385340001
+426000.8914760000 -2286450.5637659999
+431125.9775380000 -2301477.3614380001
+426190.7094780000 -2317505.9456210001
+424672.1654600000 -2332532.7432940002
+421445.2594210000 -2313498.7995750001
+409296.9072740000 -2298472.0019029998
+411764.5413040000 -2318006.8388769999
+403222.7312010000 -2304983.6142279999
+411005.2692950000 -2289956.8165560002
+393542.0130840000 -2293463.0693460000
+378356.5729000000 -2295967.5356250000
+388416.9270220000 -2308489.8670180002
+405880.1832330000 -2317005.0523660001
+417838.7173770000 -2328525.5972480001
+402463.4591910000 -2342049.7151529999
+385000.2029800000 -2341047.9286409998
+375699.1208680000 -2327022.9174799998
+384240.9309710000 -2314500.5860870001
+368865.6727850000 -2321012.1984120002
+373421.3048400000 -2337541.6758510000
+363360.9507190000 -2353069.3667790000
+351402.4165740000 -2336539.8893400002
+340392.9724410000 -2324518.4512020000
+329573.3463100000 -2313999.6928309998
+335267.8863790000 -2329527.3837589999
+336216.9763910000 -2347058.6477100002
+337166.0664020000 -2362085.4453819999
+318374.0841750000 -2366593.4846839998
+303758.0979980000 -2362586.3386380002
+290314.2882280000 -2354697.2698599999
+292067.6911410000 -2339670.4721880001
+275702.5972900000 -2347684.7642799998
+277880.2580262116 -2321542.8592617917
+269420.4169677348 -2331176.2138948478
+260960.5759092579 -2323294.3782859840
+252500.7348507810 -2343436.8470641924
+254834.4841082919 -2357157.0794203631
+258918.5453089359 -2372336.9109633607
+266740.7601810000 -2359706.2024170002
+271754.1662252456 -2369125.7927523423
+266545.9376350000 -2379241.0393909998
+291483.2235030000 -2386253.5449720002
+275897.4198350000 -2396271.4100859999
+288755.7078610000 -2404786.5954339998
+276871.5325650000 -2415806.2470600000
+263818.4219930000 -2423820.5391520001
+259532.3259840000 -2445358.9491490000
+250570.4888750000 -2432836.6177559998
+248817.0859630000 -2452371.4547290001
+247258.5055960000 -2470403.6119360002
+229919.2990160000 -2474911.6512380000
+226022.8480990000 -2490439.3421660000
+239660.4263080000 -2499956.3140250002
+227776.2510110000 -2510975.9656509999
+220178.1717230000 -2523999.1902999999
+205761.3033310000 -2533015.2689029998
+210631.8669770000 -2560063.5047129998
+203228.6102350000 -2545036.7070410000
+194266.7731260000 -2558560.8249459998
+199624.3931360000 -2581101.0214539999
+185791.9923810000 -2568077.7968049999
+189493.6207520000 -2583104.5944770002
+186571.2825650000 -2601136.7516839998
+185207.5247440000 -2584106.3809890002
+169816.5436220000 -2595126.0326149999
+156568.6105040000 -2586610.8472679998
+134748.4853690000 -2581101.0214539999
+149749.8214000000 -2579598.3416869999
+136112.2431900000 -2592120.6730809999
+146437.8381200000 -2612657.2965660002
+130462.3893610000 -2620671.5886579999
+137281.1784650000 -2635197.4930739999
+125007.3580770000 -2621172.4819140001
+106888.8613130000 -2617666.2291230001
+91887.5252830000 -2609151.0437759999
+109031.9093180000 -2607648.3640089999
+92277.1703750000 -2603641.2179629998
+97537.3791130000 -2587111.7405229998
+88380.7194580000 -2573587.6226180000
+74743.1412490000 -2567076.0102940002
+61105.5630390000 -2577093.8754090001
+66950.2394150000 -2594124.2461040001
+57598.7572140000 -2581101.0214539999
+53117.8386600000 -2598131.3921500002
+41818.1310010000 -2586610.8472679998
+30810.6571600000 -2599133.1786610000
+44253.4128240000 -2608650.1505200001
+47662.8073760000 -2621047.2585999998
+
Index: issm/trunk/examples/IceBridge/Greenland.par
===================================================================
--- issm/trunk/examples/IceBridge/Greenland.par	(revision 18301)
+++ issm/trunk/examples/IceBridge/Greenland.par	(revision 18301)
@@ -0,0 +1,104 @@
+%Name and hemisphere
+md.miscellaneous.name='SeaRISEgreenland';
+md.mesh.hemisphere='n';
+
+disp('   Loading SeaRISE data from NetCDF');
+ncdata='../Data/Greenland_5km_dev1.2.nc';
+x1    = ncread(ncdata,'x1');
+y1    = ncread(ncdata,'y1');
+usrf  = ncread(ncdata,'usrf')';
+topg  = ncread(ncdata,'topg')';
+velx  = ncread(ncdata,'surfvelx')';
+vely  = ncread(ncdata,'surfvely')';
+temp  = ncread(ncdata,'airtemp2m')';
+smb   = ncread(ncdata,'smb')';
+gflux = ncread(ncdata,'bheatflx')';
+
+disp('   Interpolating surface and bedrock');
+md.geometry.base     = InterpFromGridToMesh(x1,y1,topg,md.mesh.x,md.mesh.y,0);
+md.geometry.surface = InterpFromGridToMesh(x1,y1,usrf,md.mesh.x,md.mesh.y,0);
+
+disp('   Constructing thickness');
+md.geometry.thickness=md.geometry.surface-md.geometry.base;
+
+%Set min thickness to 1 meter
+pos0=find(md.geometry.thickness<=0);
+md.geometry.thickness(pos0)=1;
+md.geometry.surface=md.geometry.thickness+md.geometry.base;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%Reading IceBridge data for Jakobshavn
+disp('      reading IceBridge Jakobshavn bedrock');
+fid  = fopen('../Data/Jakobshavn_2008_2011_Composite_XYZGrid.txt');
+titles = fgets(fid); data = fscanf(fid,'%g,%g,%g,%g,%g',[5 266400])';
+fclose(fid);
+
+[xi,yi]= ll2xy(md.mesh.lat,md.mesh.long,+1,45,70);
+bed  = flipud(reshape(data(:,5),[360 740])); bed(find(bed==-9999))=NaN;
+bedy = flipud(reshape(data(:,1),[360 740]));
+bedx = flipud(reshape(data(:,2),[360 740]));
+
+%Insert Icebridge bed and recalculate thickness
+bed_jks=InterpFromGridToMesh(bedx(1,:)',bedy(:,1),bed,xi,yi,NaN);
+in=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,...
+	'./Jak_grounded.exp','node',1);
+bed_jks(~in)=NaN;
+pos=find(~isnan(bed_jks));
+md.geometry.base(pos)=bed_jks(pos);
+md.geometry.thickness=md.geometry.surface-md.geometry.base;
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+disp('   Interpolating velocities ');
+md.inversion.vx_obs  = InterpFromGridToMesh(x1,y1,velx,md.mesh.x,md.mesh.y,0);
+md.inversion.vy_obs  = InterpFromGridToMesh(x1,y1,vely,md.mesh.x,md.mesh.y,0);
+md.inversion.vel_obs = sqrt(md.inversion.vx_obs.^2+md.inversion.vy_obs.^2);
+md.initialization.vx = md.inversion.vx_obs;
+md.initialization.vy = md.inversion.vy_obs;
+md.initialization.vz = zeros(md.mesh.numberofvertices,1);
+md.initialization.vel= md.inversion.vel_obs;
+
+disp('   Interpolating temperatures');
+md.initialization.temperature=InterpFromGridToMesh(x1,y1,temp,md.mesh.x,md.mesh.y,0)+273.15;
+
+disp('   Interpolating surface mass balance');
+md.surfaceforcings.mass_balance=InterpFromGridToMesh(x1,y1,smb,md.mesh.x,md.mesh.y,0);
+md.surfaceforcings.mass_balance=md.surfaceforcings.mass_balance*md.materials.rho_water/md.materials.rho_ice;
+
+disp('   Construct basal friction parameters');
+md.friction.coefficient=30*ones(md.mesh.numberofvertices,1);
+pos=find(md.mask.groundedice_levelset<0);
+md.friction.coefficient(pos)=0; %no friction applied on floating ice
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+disp('   Construct ice rheological properties');
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+md.materials.rheology_B=paterson(md.initialization.temperature);
+md.friction.q=ones(md.mesh.numberofelements,1);
+md.friction.p=ones(md.mesh.numberofelements,1);
+
+disp('   Set other boundary conditions');
+md.mask.ice_levelset(md.mesh.vertexonboundary==1)=0;
+md.basalforcings.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.masstransport.spcthickness    = NaN*ones(md.mesh.numberofvertices,1);
+
+disp('   Set geothermal heat flux');
+md.basalforcings.geothermalflux=InterpFromGridToMesh(x1,y1,gflux,md.mesh.x,md.mesh.y,0);
+
+disp('   Set Pressure');
+md.initialization.pressure=md.materials.rho_ice*md.constants.g*md.geometry.thickness;
+
+disp('   Single point constraint for continental model');
+%Set at least one vertex to velocity 0 so as to not get a singular problem (point on the wet peninsula)
+md.stressbalance.referential=NaN*ones(md.mesh.numberofvertices,6);
+md.stressbalance.spcvx = NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvy = NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvz = NaN*ones(md.mesh.numberofvertices,1);
+location = 1.0e+06 *[.32011 -2.2039];
+[dist pos]=min(sqrt((md.mesh.x - location(1)).^2 + (md.mesh.y - location(2)).^2));
+md.stressbalance.spcvx(pos) = 0;
+md.stressbalance.spcvy(pos) = 0;
+md.stressbalance.spcvz(pos) = 0;
+
Index: issm/trunk/examples/IceBridge/Greenland_cheatsheet.par
===================================================================
--- issm/trunk/examples/IceBridge/Greenland_cheatsheet.par	(revision 18301)
+++ issm/trunk/examples/IceBridge/Greenland_cheatsheet.par	(revision 18301)
@@ -0,0 +1,108 @@
+%Name and hemisphere
+md.miscellaneous.name='SeaRISEgreenland';
+md.mesh.hemisphere='n';
+
+disp('   Loading SeaRISE data from NetCDF');
+ncdata='../Data/Greenland_5km_dev1.2.nc';
+x1    = ncread(ncdata,'x1');
+y1    = ncread(ncdata,'y1');
+usrf  = ncread(ncdata,'usrf')';
+topg  = ncread(ncdata,'topg')';
+velx  = ncread(ncdata,'surfvelx')';
+vely  = ncread(ncdata,'surfvely')';
+temp  = ncread(ncdata,'airtemp2m')';
+smb   = ncread(ncdata,'smb')';
+gflux = ncread(ncdata,'bheatflx')';
+
+disp('   Interpolating surface and bedrock');
+md.geometry.base     = InterpFromGridToMesh(x1,y1,topg,md.mesh.x,md.mesh.y,0);
+md.geometry.surface = InterpFromGridToMesh(x1,y1,usrf,md.mesh.x,md.mesh.y,0);
+
+disp('   Constructing thickness');
+md.geometry.thickness=md.geometry.surface-md.geometry.base;
+
+%Set min thickness to 1 meter
+pos0=find(md.geometry.thickness<=0);
+md.geometry.thickness(pos0)=1;
+md.geometry.surface=md.geometry.thickness+md.geometry.base;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%Reading IceBridge data for Jakobshavn
+disp('      reading IceBridge Jakobshavn bedrock');
+fid  = fopen('../Data/Jakobshavn_2008_2011_Composite_XYZGrid.txt');
+titles = fgets(fid); data = fscanf(fid,'%g,%g,%g,%g,%g',[5 266400])';
+fclose(fid);
+
+[xi,yi]= ll2xy(md.mesh.lat,md.mesh.long,+1,45,70);
+bed  = flipud(reshape(data(:,5),[360 740])); bed(find(bed==-9999))=NaN;
+surf  = flipud(reshape(data(:,4),[360 740])); surf(find(surf==-9999))=NaN;
+bedy = flipud(reshape(data(:,1),[360 740]));
+bedx = flipud(reshape(data(:,2),[360 740]));
+
+%Insert Icebridge bed and recalculate thickness
+bed_jks=InterpFromGridToMesh(bedx(1,:)',bedy(:,1),bed,xi,yi,NaN);
+surf_jks=InterpFromGridToMesh(bedx(1,:)',bedy(:,1),surf,xi,yi,NaN);
+in=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,...
+	'./Jak_grounded.exp','node',1);
+bed_jks(~in)=NaN;
+surf_jks(~in)=NaN;
+pos=find(~isnan(bed_jks));
+md.geometry.base(pos)=bed_jks(pos);
+md.geometry.surface(pos)=surf_jks(pos);
+md.geometry.thickness=md.geometry.surface-md.geometry.base;
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+disp('   Interpolating velocities ');
+md.inversion.vx_obs  = InterpFromGridToMesh(x1,y1,velx,md.mesh.x,md.mesh.y,0);
+md.inversion.vy_obs  = InterpFromGridToMesh(x1,y1,vely,md.mesh.x,md.mesh.y,0);
+md.inversion.vel_obs = sqrt(md.inversion.vx_obs.^2+md.inversion.vy_obs.^2);
+md.initialization.vx = md.inversion.vx_obs;
+md.initialization.vy = md.inversion.vy_obs;
+md.initialization.vz = zeros(md.mesh.numberofvertices,1);
+md.initialization.vel= md.inversion.vel_obs;
+
+disp('   Interpolating temperatures');
+md.initialization.temperature=InterpFromGridToMesh(x1,y1,temp,md.mesh.x,md.mesh.y,0)+273.15;
+
+disp('   Interpolating surface mass balance');
+md.surfaceforcings.mass_balance=InterpFromGridToMesh(x1,y1,smb,md.mesh.x,md.mesh.y,0);
+md.surfaceforcings.mass_balance=md.surfaceforcings.mass_balance*md.materials.rho_water/md.materials.rho_ice;
+
+disp('   Construct basal friction parameters');
+md.friction.coefficient=30*ones(md.mesh.numberofvertices,1);
+pos=find(md.mask.groundedice_levelset<0);
+md.friction.coefficient(pos)=0; %no friction applied on floating ice
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+disp('   Construct ice rheological properties');
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+md.materials.rheology_B=paterson(md.initialization.temperature);
+md.friction.q=ones(md.mesh.numberofelements,1);
+md.friction.p=ones(md.mesh.numberofelements,1);
+
+disp('   Set other boundary conditions');
+md.mask.ice_levelset(md.mesh.vertexonboundary==1)=0;
+md.basalforcings.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.masstransport.spcthickness    = NaN*ones(md.mesh.numberofvertices,1);
+
+disp('   Set geothermal heat flux');
+md.basalforcings.geothermalflux=InterpFromGridToMesh(x1,y1,gflux,md.mesh.x,md.mesh.y,0);
+
+disp('   Set Pressure');
+md.initialization.pressure=md.materials.rho_ice*md.constants.g*md.geometry.thickness;
+
+disp('   Single point constraint for continental model');
+%Set at least one vertex to velocity 0 so as to not get a singular problem (point on the wet peninsula)
+md.stressbalance.referential=NaN*ones(md.mesh.numberofvertices,6);
+md.stressbalance.spcvx = NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvy = NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvz = NaN*ones(md.mesh.numberofvertices,1);
+location = 1.0e+06 *[.32011 -2.2039];
+[dist pos]=min(sqrt((md.mesh.x - location(1)).^2 + (md.mesh.y - location(2)).^2));
+md.stressbalance.spcvx(pos) = 0;
+md.stressbalance.spcvy(pos) = 0;
+md.stressbalance.spcvz(pos) = 0;
+
Index: issm/trunk/examples/IceBridge/Greenland_noOIB.par
===================================================================
--- issm/trunk/examples/IceBridge/Greenland_noOIB.par	(revision 18301)
+++ issm/trunk/examples/IceBridge/Greenland_noOIB.par	(revision 18301)
@@ -0,0 +1,82 @@
+%Name and hemisphere
+md.miscellaneous.name='SeaRISEgreenland';
+md.mesh.hemisphere='n';
+
+disp('   Loading SeaRISE data from NetCDF');
+ncdata='../Data/Greenland_5km_dev1.2.nc';
+x1    = ncread(ncdata,'x1');
+y1    = ncread(ncdata,'y1');
+usrf  = ncread(ncdata,'usrf')';
+topg  = ncread(ncdata,'topg')';
+velx  = ncread(ncdata,'surfvelx')';
+vely  = ncread(ncdata,'surfvely')';
+temp  = ncread(ncdata,'airtemp2m')';
+smb   = ncread(ncdata,'smb')';
+gflux = ncread(ncdata,'bheatflx')';
+
+disp('   Interpolating surface and bedrock');
+md.geometry.base     = InterpFromGridToMesh(x1,y1,topg,md.mesh.x,md.mesh.y,0);
+md.geometry.surface = InterpFromGridToMesh(x1,y1,usrf,md.mesh.x,md.mesh.y,0);
+
+disp('   Constructing thickness');
+md.geometry.thickness=md.geometry.surface-md.geometry.base;
+
+%Set min thickness to 1 meter
+pos0=find(md.geometry.thickness<=0);
+md.geometry.thickness(pos0)=1;
+md.geometry.surface=md.geometry.thickness+md.geometry.base;
+
+disp('   Interpolating velocities ');
+md.inversion.vx_obs  = InterpFromGridToMesh(x1,y1,velx,md.mesh.x,md.mesh.y,0);
+md.inversion.vy_obs  = InterpFromGridToMesh(x1,y1,vely,md.mesh.x,md.mesh.y,0);
+md.inversion.vel_obs = sqrt(md.inversion.vx_obs.^2+md.inversion.vy_obs.^2);
+md.initialization.vx = md.inversion.vx_obs;
+md.initialization.vy = md.inversion.vy_obs;
+md.initialization.vz = zeros(md.mesh.numberofvertices,1);
+md.initialization.vel= md.inversion.vel_obs;
+
+disp('   Interpolating temperatures');
+md.initialization.temperature=InterpFromGridToMesh(x1,y1,temp,md.mesh.x,md.mesh.y,0)+273.15;
+
+disp('   Interpolating surface mass balance');
+md.surfaceforcings.mass_balance=InterpFromGridToMesh(x1,y1,smb,md.mesh.x,md.mesh.y,0);
+md.surfaceforcings.mass_balance=md.surfaceforcings.mass_balance*md.materials.rho_water/md.materials.rho_ice;
+
+disp('   Construct basal friction parameters');
+md.friction.coefficient=30*ones(md.mesh.numberofvertices,1);
+pos=find(md.mask.groundedice_levelset<0);
+md.friction.coefficient(pos)=0; %no friction applied on floating ice
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+disp('   Construct ice rheological properties');
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+md.materials.rheology_B=paterson(md.initialization.temperature);
+md.friction.q=ones(md.mesh.numberofelements,1);
+md.friction.p=ones(md.mesh.numberofelements,1);
+
+disp('   Set other boundary conditions');
+md.mask.ice_levelset(md.mesh.vertexonboundary==1)=0;
+md.basalforcings.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.masstransport.spcthickness    = NaN*ones(md.mesh.numberofvertices,1);
+
+disp('   Set geothermal heat flux');
+md.basalforcings.geothermalflux=InterpFromGridToMesh(x1,y1,gflux,md.mesh.x,md.mesh.y,0);
+
+disp('   Set Pressure');
+md.initialization.pressure=md.materials.rho_ice*md.constants.g*md.geometry.thickness;
+
+disp('   Single point constraint for continental model');
+%Set at least one vertex to velocity 0 so as to not get a singular problem (point on the wet peninsula)
+md.stressbalance.referential=NaN*ones(md.mesh.numberofvertices,6);
+md.stressbalance.spcvx = NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvy = NaN*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvz = NaN*ones(md.mesh.numberofvertices,1);
+location = 1.0e+06 *[.32011 -2.2039];
+[dist pos]=min(sqrt((md.mesh.x - location(1)).^2 + (md.mesh.y - location(2)).^2));
+md.stressbalance.spcvx(pos) = 0;
+md.stressbalance.spcvy(pos) = 0;
+md.stressbalance.spcvz(pos) = 0;
+
Index: issm/trunk/examples/IceBridge/Jak_grounded.exp
===================================================================
--- issm/trunk/examples/IceBridge/Jak_grounded.exp	(revision 18301)
+++ issm/trunk/examples/IceBridge/Jak_grounded.exp	(revision 18301)
@@ -0,0 +1,19 @@
+## Name:Jak_grouded
+## Icon:0
+# Points Count Value
+13 1.000000
+# X pos Y pos
+-414397.6663804040 -2243466.6708395295
+-421486.9037621063 -2215731.3059818177
+-342860.8164377716 -2178965.8223332223
+-275835.2993744044 -2209281.2211311869
+-226210.6377024883 -2262816.9253914217
+-228144.0660793162 -2295067.3496445753
+-333193.6745536321 -2328607.7908678548
+-379595.9555975018 -2325382.7484425395
+-422775.8560133249 -2285392.2223686292
+-427287.1888925899 -2265396.9593316740
+-411819.7618779668 -2254431.8150856020
+-413108.7141291854 -2243466.6708395295
+-414397.6663804040 -2243466.6708395295
+
Index: issm/trunk/examples/IceBridge/Jak_outline.exp
===================================================================
--- issm/trunk/examples/IceBridge/Jak_outline.exp	(revision 18301)
+++ issm/trunk/examples/IceBridge/Jak_outline.exp	(revision 18301)
@@ -0,0 +1,17 @@
+## Name:Jak
+## Icon:0
+# Points Count Value
+11 1.000000
+# X pos Y pos
+-421561.7247949215 -2216716.3488182197
+-386019.6416099078 -2203459.4896082953
+-351446.8879663036 -2185999.2360147359
+-289086.6874689616 -2214129.6445821370
+-255160.1535196303 -2282353.9688088228
+-340138.0433165266 -2317597.8140254519
+-383306.1449952667 -2302506.6581698526
+-416391.9672407377 -2279120.5885137189
+-448056.7322601135 -2246463.4475331730
+-429126.8716234095 -2231167.6696134652
+-421561.7247949215 -2216716.3488182197
+
Index: issm/trunk/examples/IceBridge/data_gaps.exp
===================================================================
--- issm/trunk/examples/IceBridge/data_gaps.exp	(revision 18301)
+++ issm/trunk/examples/IceBridge/data_gaps.exp	(revision 18301)
@@ -0,0 +1,70 @@
+## Name:data_gaps
+## Icon:0
+# Points Count Value
+13 1.000000
+# X pos Y pos
+-183076.0390091268 -1794119.5324780210
+-233886.6983670916 -1838953.5447257366
+-239864.4229974404 -2006333.8571172084
+-299641.6693009282 -2081057.2108634012
+-269753.0461491842 -2116924.4206615738
+-257797.5968884868 -2185669.9061080711
+-278719.6330947075 -2248437.5232548732
+-254808.7345733123 -2266371.1281539593
+-224920.1114215683 -2167736.3012089850
+-198020.3505849990 -2093012.9474627920
+-123298.7927056390 -1967477.7131691882
+-180087.1766939524 -1797108.4666278686
+-183076.0390091268 -1794119.5324780210
+
+## Name:data_gaps
+## Icon:0
+# Points Count Value
+12 1.000000
+# X pos Y pos
+-90421.3072387208 -1824008.8739764981
+-117321.0680752902 -1946555.1741202541
+-156176.2781725575 -2075079.3425637058
+-177098.3143787782 -2203603.5110071572
+-174109.4520636038 -2314194.0745515227
+-72488.1333476745 -2293271.5355025884
+-93410.1695538952 -2203603.5110071572
+-30644.0609352330 -2206592.4451570050
+-6733.1624138379 -2081057.2108634012
+44077.4969441269 -1967477.7131691882
+-93410.1695538952 -1824008.8739764981
+-90421.3072387208 -1824008.8739764981
+
+## Name:data_gaps
+## Icon:0
+# Points Count Value
+15 1.000000
+# X pos Y pos
+-87432.4449235464 -2365005.9550989335
+-287686.2200402305 -2639987.8968849229
+-284697.3577250564 -2879102.6288727401
+-470006.8212658686 -2983715.3241174100
+-538750.6545148797 -3157073.5048085772
+-356430.0532892416 -3267664.0683529424
+-189053.7636394757 -3270653.0025027902
+-272741.9084643587 -3243752.5951541606
+-218942.3867912197 -3076372.2827626891
+-236875.5606822660 -3019582.5339155826
+-117321.0680752902 -2834268.6166250245
+20166.5984227317 -2669877.2383834003
+-12710.8870441865 -2469618.6503436035
+-87432.4449235464 -2367994.8892487814
+-87432.4449235464 -2365005.9550989335
+
+## Name:data_gaps
+## Icon:0
+# Points Count Value
+6 1.000000
+# X pos Y pos
+-186064.9013243013 -1555004.8004902040
+-177098.3143787782 -1695484.7055330465
+-81454.7202931975 -1698473.6396828941
+-36621.7855655816 -1513159.7223923360
+-186064.9013243013 -1552015.8663403564
+-186064.9013243013 -1555004.8004902040
+
Index: issm/trunk/examples/IceBridge/runme.m
===================================================================
--- issm/trunk/examples/IceBridge/runme.m	(revision 18301)
+++ issm/trunk/examples/IceBridge/runme.m	(revision 18301)
@@ -0,0 +1,159 @@
+clear all;
+steps=[1];
+
+%Location of SeaRISE dataset
+ncdata='../Data/Greenland_5km_dev1.2.nc';
+
+if any(steps==1)
+	disp('   Step 1: Mesh creation');
+
+	%Generate initial uniform mesh (resolution = 20000 m)
+	md=triangle(model,'./DomainOutline.exp',20000);
+
+	% Get velocities (Note: You can use ncdisp('file') to see an ncdump)
+	x1   = ncread(ncdata,'x1');
+	y1   = ncread(ncdata,'y1');
+	velx = ncread(ncdata,'surfvelx');
+	vely = ncread(ncdata,'surfvely');
+	vx   = InterpFromGridToMesh(x1,y1,velx',md.mesh.x,md.mesh.y,0);
+	vy   = InterpFromGridToMesh(x1,y1,vely',md.mesh.x,md.mesh.y,0);
+	vel  = sqrt(vx.^2+vy.^2);
+
+	%Mesh greenland without refinement in Jak basin
+	%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+	md=bamg(md,'hmax',400000,'hmin',5000,'gradation',1.7,'field',vel,'err',8);
+	save ./Models/Greenland.Mesh_generation_old md;
+	return;
+	%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+	%Refine mesh in the region of Jakobshavn (resolution = 3000 m)
+	hmaxVertices=NaN*ones(md.mesh.numberofvertices,1);
+	in=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,...
+		'./Jak_outline.exp','node',1);
+	hmaxVertices(find(in))=3000;
+	md=bamg(md,'hmax',400000,'hmin',5000,'gradation',1.7,'field',vel,...
+		'err',8,'hmaxVertices',hmaxVertices);
+
+	%convert x,y coordinates (Polar stereo) to lat/lon
+	[md.mesh.lat,md.mesh.long]=xy2ll(md.mesh.x,md.mesh.y,+1,39,71);
+
+	save ./Models/Greenland.Mesh_generation md;
+end
+
+if any(steps==2)
+	disp('   Step 2: Parameterization');
+	md = loadmodel('./Models/Greenland.Mesh_generation');
+
+	md = setmask(md,'','');
+	md = parameterize(md,'./Greenland_cheatsheet.par');
+	%md = parameterize(md,'./Greenland_noOIB.par');
+	md = setflowequation(md,'SSA','all');
+
+	save ./Models/Greenland.Parameterization2 md; 
+end
+
+if any(steps==3)
+	disp('   Step 3: Control method friction');
+	md = loadmodel('./Models/Greenland.Parameterization2');
+
+	%Control general
+	md.inversion.iscontrol=1;
+	md.inversion.nsteps=30;
+	md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
+	md.inversion.maxiter_per_step=5*ones(md.inversion.nsteps,1);
+	md.verbose=verbose('solution',true,'control',true);
+
+	%Cost functions
+	md.inversion.cost_functions=[101 103 501];
+	md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,3);
+	md.inversion.cost_functions_coefficients(:,1)=350;
+	md.inversion.cost_functions_coefficients(:,2)=0.6;
+	md.inversion.cost_functions_coefficients(:,3)=2e-6;
+
+	%Controls
+	md.inversion.control_parameters={'FrictionCoefficient'};
+	md.inversion.gradient_scaling(1:md.inversion.nsteps)=50;
+	md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
+	md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
+	in=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,...
+		'./data_gaps.exp','node',1);
+	md.inversion.cost_functions_coefficients(find(in),1)=0.0;
+	md.inversion.cost_functions_coefficients(find(in),2)=0.0;
+
+	%Additional parameters
+	md.stressbalance.restol=0.01;
+	md.stressbalance.reltol=0.1;
+	md.stressbalance.abstol=NaN;
+
+	%Go solve
+	md.cluster=generic('name',oshostname,'np',2);
+
+	md.verbose=verbose('solution',true,'control',true);
+	md=solve(md,StressbalanceSolutionEnum);
+
+	%Update model friction fields accordingly
+	md.friction.coefficient=md.results.StressbalanceSolution.FrictionCoefficient;
+
+	save ./Models/Greenland.Control_drag md; 
+end
+
+if any(steps==4)
+	disp('   Step 4: Transient run');
+	md = loadmodel('./Models/Greenland.Control_drag');
+
+	%Set surface mass balance
+	x1  = ncread(ncdata,'x1');
+	y1  = ncread(ncdata,'y1');
+	smb = ncread(ncdata,'smb');
+	smb = InterpFromGridToMesh(x1,y1,smb',md.mesh.x,md.mesh.y,0)*1000/md.materials.rho_ice;
+	smb = [smb smb smb-1.0];
+	md.surfaceforcings.mass_balance = [smb;1 10 20];
+
+	%Set transient options, run for 20 years, saving every year
+	md.timestepping.time_step=0.2; %This must be reduced for finer resolutions
+	md.timestepping.final_time=20;
+	md.settings.output_frequency=1;
+
+	%Additional options
+	md.inversion.iscontrol=0;
+	md.transient.requested_outputs={'IceVolume','TotalSmb','SurfaceforcingsMassBalance'};
+	md.verbose=verbose('solution',true,'module',true,'convergence',true);
+
+	%Go solve
+	md.cluster=generic('name',oshostname,'np',2);
+	md=solve(md,TransientSolutionEnum);
+
+	save ./Models/Greenland.Transient md; 
+end
+
+if any(steps==5)
+	disp('   Step 5: Plotting'); 
+	md = loadmodel('./Models/Greenland.Transient');
+
+	%Planview plots
+	plotmodel(md,'data',md.results.TransientSolution(end).Vel,'caxis',[1e-1 6000],...
+		'log', 10, 'title', 'Velocity (m/y)','gridded',1, ...
+		'data', md.results.TransientSolution(end).SurfaceforcingsMassBalance, ...
+		'title', 'Surface mass balance (m/y)','gridded',1, ...
+		'data',md.results.TransientSolution(end).Thickness,...
+		'title','Thickness (m)','gridded',1, ...
+		'data',md.results.TransientSolution(end).Surface, ...
+		'title', 'Surface (m)','gridded',1);
+
+	%Line Plots
+	figure
+
+	%Plot surface mass balance
+	surfmb=[]; for i=1:100; surfmb=[surfmb ...
+		md.results.TransientSolution(i).SurfaceforcingsMassBalance]; end
+	subplot(3,1,1); plot([0.2:0.2:20],mean(surfmb)); title('Mean Surface mass balance');
+
+	%Plot velocity
+	vel=[]; for i=1:100; vel=[vel md.results.TransientSolution(i).Vel]; end
+	subplot(3,1,2); plot([0.2:0.2:20],mean(vel)); title('Mean Velocity');
+
+	%Plot Volume
+	volume=[]; for i=1:100; volume=[volume md.results.TransientSolution(i).IceVolume]; end
+	subplot(3,1,3); plot([0.2:0.2:20],volume); title('Ice Volume');
+	xlabel('years')
+end
Index: issm/trunk/examples/IceflowModels/Contour.exp
===================================================================
--- issm/trunk/examples/IceflowModels/Contour.exp	(revision 18301)
+++ issm/trunk/examples/IceflowModels/Contour.exp	(revision 18301)
@@ -0,0 +1,11 @@
+## Name:Contour
+## Icon:0
+# Points Count Value
+5 1.000000
+# X pos Y pos
+260815.7808871837 745919.4159004869
+712422.3484428506 757574.3645213632
+640499.8210173184 195805.8409951325
+342774.0098139530 279721.4710654409
+260815.7808871837 745919.4159004869
+
Index: issm/trunk/examples/IceflowModels/EISMINT.par
===================================================================
--- issm/trunk/examples/IceflowModels/EISMINT.par	(revision 18301)
+++ issm/trunk/examples/IceflowModels/EISMINT.par	(revision 18301)
@@ -0,0 +1,53 @@
+disp('      creating thickness');
+hmin=0.01;
+hmax=2756.7;
+radius=sqrt((md.mesh.x).^2+(md.mesh.y).^2);
+radiusmax=max(radius);
+radius(find(radius>(1.-10^-9)*radiusmax))=radiusmax;    %eliminate roundoff issues in next statement
+md.geometry.thickness=hmin*ones(size(md.mesh.x,1),1)+hmax*(4.*((1./2.)^(4./3.)*ones(size(md.mesh.x,1),1)-((radius)./(2.*radiusmax)).^(4./3.))).^(3./8.);
+md.geometry.base=0.*md.geometry.thickness;
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+
+disp('      creating drag');
+md.friction.coefficient=20.*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+disp('      creating temperatures');
+tmin=238.15; %K
+st=1.67*10^-2/1000.; %k/m
+md.initialization.temperature=tmin+st*radius;
+md.basalforcings.geothermalflux=4.2*10^-2*ones(md.mesh.numberofvertices,1);
+
+disp('      creating flow law parameter');
+md.materials.rheology_B=6.81*10^7*ones(md.mesh.numberofvertices,1); %to have the same B as the analytical solution 
+md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
+
+disp('      creating surface mass balance');
+smb_max=0.5; %m/yr
+sb=10^-2/1000.; %m/yr/m
+rel=450.*1000.; %m
+md.surfaceforcings.mass_balance=min(smb_max,sb*(rel-radius));
+
+disp('      creating velocities');
+constant=0.3;
+md.inversion.vx_obs=constant/2.*md.mesh.x.*(md.geometry.thickness).^-1;
+md.inversion.vy_obs=constant/2.*md.mesh.y.*(md.geometry.thickness).^-1;
+md.inversion.vel_obs=sqrt((md.inversion.vx_obs).^2+(md.inversion.vy_obs).^2);
+md.initialization.vx=zeros(md.mesh.numberofvertices,1);
+md.initialization.vy=zeros(md.mesh.numberofvertices,1);
+md.initialization.vz=zeros(md.mesh.numberofvertices,1);
+md.initialization.pressure=zeros(md.mesh.numberofvertices,1);
+
+%Deal with boundary conditions:
+disp('      boundary conditions for stressbalance model:');
+md=SetMarineIceSheetBC(md,'./RoundFront.exp');
+
+radius=sqrt((md.mesh.x).^2+(md.mesh.y).^2);
+pos=find(radius==min(radius));
+md.mesh.x(pos)=0.; md.mesh.y(pos)=0.; %the closest node to the center is changed to be exactly at the center
+
+md.stressbalance.spcvx(pos)=0.;
+md.stressbalance.spcvy(pos)=0.;
+md.stressbalance.spcvz(pos)=0.;
Index: issm/trunk/examples/IceflowModels/RoundFront.exp
===================================================================
--- issm/trunk/examples/IceflowModels/RoundFront.exp	(revision 18301)
+++ issm/trunk/examples/IceflowModels/RoundFront.exp	(revision 18301)
@@ -0,0 +1,47 @@
+## Name:
+## Icon:0
+# Points Count Value
+41 1
+# X pos Y pos
+1000000.000000 0.000000
+987688.340595 156434.465040
+951056.516295 309016.994375
+891006.524188 453990.499740
+809016.994375 587785.252292
+707106.781187 707106.781187
+587785.252292 809016.994375
+453990.499740 891006.524188
+309016.994375 951056.516295
+156434.465040 987688.340595
+0.000000 1000000.000000
+-156434.465040 987688.340595
+-309016.994375 951056.516295
+-453990.499740 891006.524188
+-587785.252292 809016.994375
+-707106.781187 707106.781187
+-809016.994375 587785.252292
+-891006.524188 453990.499740
+-951056.516295 309016.994375
+-987688.340595 156434.465040
+-1000000.000000 0.000000
+-987688.340595 -156434.465040
+-951056.516295 -309016.994375
+-891006.524188 -453990.499740
+-809016.994375 -587785.252292
+-707106.781187 -707106.781187
+-587785.252292 -809016.994375
+-453990.499740 -891006.524188
+-309016.994375 -951056.516295
+-156434.465040 -987688.340595
+-0.000000 -1000000.000000
+156434.465040 -987688.340595
+309016.994375 -951056.516295
+453990.499740 -891006.524188
+587785.252292 -809016.994375
+707106.781187 -707106.781187
+809016.994375 -587785.252292
+891006.524188 -453990.499740
+951056.516295 -309016.994375
+987688.340595 -156434.465040
+1000000.000000 0.000000
+
Index: issm/trunk/examples/IceflowModels/Square.exp
===================================================================
--- issm/trunk/examples/IceflowModels/Square.exp	(revision 18301)
+++ issm/trunk/examples/IceflowModels/Square.exp	(revision 18301)
@@ -0,0 +1,10 @@
+## Name:domainoutline
+## Icon:0
+# Points Count  Value
+5 1.
+# X pos Y pos
+0 0
+1000000 0
+1000000 1000000
+0 1000000
+0 0
Index: issm/trunk/examples/IceflowModels/SquareFront.exp
===================================================================
--- issm/trunk/examples/IceflowModels/SquareFront.exp	(revision 18301)
+++ issm/trunk/examples/IceflowModels/SquareFront.exp	(revision 18301)
@@ -0,0 +1,10 @@
+## Name:icefront
+## Icon:0
+# Points Count  Value
+5 1.
+# X pos Y pos
+-1000 900000
+-1000 1100000
+1100000 1100000
+1100000 900000
+-1000 900000
Index: issm/trunk/examples/IceflowModels/SquareShelf.par
===================================================================
--- issm/trunk/examples/IceflowModels/SquareShelf.par	(revision 18301)
+++ issm/trunk/examples/IceflowModels/SquareShelf.par	(revision 18301)
@@ -0,0 +1,55 @@
+%Start defining model parameters here
+
+%Geometry
+hmin=300;
+hmax=1000;
+ymin=min(md.mesh.y);
+ymax=max(md.mesh.y);
+xmin=min(md.mesh.x);
+xmax=max(md.mesh.x);
+md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y-ymin)/(ymax-ymin)+0.1*(hmin-hmax)*(md.mesh.x-xmin)/(xmax-xmin);
+md.geometry.base=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+
+%Initial velocity and pressure
+x     = transpose(ncread('../Data/SquareShelf.nc','x'));
+y     = transpose(ncread('../Data/SquareShelf.nc','y'));
+vx    = transpose(ncread('../Data/SquareShelf.nc','vx'));
+vy    = transpose(ncread('../Data/SquareShelf.nc','vy'));
+index = transpose(ncread('../Data/SquareShelf.nc','index'));
+md.initialization.vx=InterpFromMeshToMesh2d(index,x,y,vx,md.mesh.x,md.mesh.y);
+md.initialization.vy=InterpFromMeshToMesh2d(index,x,y,vy,md.mesh.x,md.mesh.y);
+clear vx vy x y index;
+md.initialization.vz=zeros(md.mesh.numberofvertices,1);
+md.initialization.pressure=zeros(md.mesh.numberofvertices,1);
+
+%Materials
+md.initialization.temperature=(273-20)*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_B=paterson(md.initialization.temperature);
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+
+%Friction
+md.friction.coefficient=20*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+%Numerical parameters
+md.stressbalance.viscosity_overshoot=0.3;
+md.masstransport.stabilization=1;
+md.thermal.stabilization=1;
+md.settings.waitonlock=30;
+md.verbose=verbose(0);
+md.stressbalance.restol=0.10;
+md.steadystate.reltol=0.02;
+md.stressbalance.reltol=0.02;
+md.stressbalance.abstol=NaN;
+md.timestepping.time_step=1;
+md.timestepping.final_time=3;
+
+%Boundary conditions:
+md=SetIceShelfBC(md,'./SquareFront.exp');
+
+%Change name so that no test have the same name
+A=dbstack;
+if (length(A)>2), md.miscellaneous.name=A(3).file(1:end-2); end
Index: issm/trunk/examples/IceflowModels/eismint.m
===================================================================
--- issm/trunk/examples/IceflowModels/eismint.m	(revision 18301)
+++ issm/trunk/examples/IceflowModels/eismint.m	(revision 18301)
@@ -0,0 +1,51 @@
+md=model();
+
+%Create mesh with roundmesh
+md=roundmesh(md,750000,30000);
+
+%Set mask
+md=setmask(md,'','');
+
+%Parameterize model
+md=parameterize(md,'EISMINT.par');
+
+%We extrude the model to have a 3d model
+md=extrude(md,10,1);
+
+%Set ice flow approximation
+md=setflowequation(md,'SIA','all');
+
+%Create boundary conditions: zero velocity on the bed
+pos=find(md.mesh.vertexonbase);
+md.stressbalance.spcvx(pos)=0;
+md.stressbalance.spcvy(pos)=0;
+md.stressbalance.spcvz(pos)=0;
+
+%Go Solve
+md.cluster=generic('np',2);
+md.verbose.convergence=1;
+md=solve(md,StressbalanceSolutionEnum());
+vel=DepthAverage(md,sqrt(md.results.StressbalanceSolution.Vx.^2+md.results.StressbalanceSolution.Vy.^2));
+
+%Calculate analytical velocity
+constant=0.3;
+vx_obs=constant/2*md.mesh.x.*(md.geometry.thickness).^-1;
+vy_obs=constant/2*md.mesh.y.*(md.geometry.thickness).^-1;
+vel_obs=sqrt(vx_obs.^2+vy_obs.^2);
+vel_obs=project2d(md,vel_obs,1);
+
+plotmodel(md,...
+	'data',vel    ,'view',2,'caxis',[0 200],'title','Modelled velocity',...
+	'data',vel_obs,'view',2,'caxis',[0 200],'title','Analytical velocity',...
+	'data',abs(vel-vel_obs)./(vel_obs+eps)*100,'caxis',[0 30],'view',2,'title','Relative misfit (%)');
+
+subplot(2,2,4)
+hold on;
+plot(sqrt((md.mesh.x2d).^2+(md.mesh.y2d).^2),vel,'r.');
+plot(sqrt((md.mesh.x2d).^2+(md.mesh.y2d).^2),vel_obs,'b.');
+title('Analytical vs calculated velocity');
+xlabel('distance to the center of the icesheet [m]');
+ylabel('velocity (m/yr)');
+legend('calculated velocity','exact velocity');
+axis([0 750000 0 200]);
+hold off;
Index: issm/trunk/examples/IceflowModels/runme.m
===================================================================
--- issm/trunk/examples/IceflowModels/runme.m	(revision 18301)
+++ issm/trunk/examples/IceflowModels/runme.m	(revision 18301)
@@ -0,0 +1,8 @@
+md=triangle(model(),'Square.exp',80000.);
+md=setmask(md,'all','');
+md=parameterize(md,'SquareShelf.par');
+md=extrude(md,3,1);
+%Set flow equation
+md=setflowequation(md,'HO','Contour.exp','fill','SSA','coupling','tiling');
+%Solve
+md=solve(md,StressbalanceSolutionEnum);
Index: issm/trunk/examples/Inversion/CheatSheet.m
===================================================================
--- issm/trunk/examples/Inversion/CheatSheet.m	(revision 18301)
+++ issm/trunk/examples/Inversion/CheatSheet.m	(revision 18301)
@@ -0,0 +1,77 @@
+step=1;
+if step==1
+	%Generate observation
+	md = model;
+	md = triangle(md,'DomainOutline.exp',100000);
+
+	%Hands on: STEP 2
+	md = setmask(md,'','');
+
+	md = parameterize(md,'Square.par');
+	md = setflowequation(md,'SSA','all');
+	md.cluster = generic('np',2);
+
+	%Hands on: STEP 1
+	md.geometry.base    = md.geometry.base+100;
+	md.geometry.surface = md.geometry.surface+100;
+
+	%Hands on: STEP 3
+	md.materials.rheology_B(:) = 1.8*10^8;
+
+	%Hands on: STEP 4
+	md.friction.coefficient(:)=50;
+	md.friction.coefficient(find(md.mesh.x<600000 & md.mesh.x>400000))=10;
+
+	md = solve(md,StressbalanceSolutionEnum);
+
+	plotmodel(md,'data',md.friction.coefficient,'figure',1);
+	plotmodel(md,'data',md.results.StressbalanceSolution.Vel,'figure',2);
+
+	save model1 md
+end
+if step==2
+	loadmodel('model1.mat');
+
+	%Hands on: STEP 1
+	md.friction.coefficient(:)=50;
+
+	%results of previous run are taken as observations
+	md.inversion=m1qn3inversion();
+	md.inversion.vx_obs  = md.results.StressbalanceSolution.Vx;
+	md.inversion.vy_obs  = md.results.StressbalanceSolution.Vy;
+	md.inversion.vel_obs = md.results.StressbalanceSolution.Vel;
+
+	md = solve(md,StressbalanceSolutionEnum);
+
+	plotmodel(md,'data',md.friction.coefficient,'figure',1);
+	plotmodel(md,'data',md.results.StressbalanceSolution.Vel,'figure',2);
+
+	save model2 md
+end
+if step==3
+	%invert for ice rigidity
+	loadmodel('model2.mat');
+
+	%Set up inversion parameters
+	maxsteps = 20;
+	md.inversion.iscontrol = 1;
+
+	%Hands on: STEP 1
+	md.inversion.control_parameters = {'FrictionCoefficient'};
+	md.inversion.maxsteps = maxsteps;
+
+	%Hands on: STEP 2
+	md.inversion.cost_functions = 101;
+	md.inversion.cost_functions_coefficients = ones(md.mesh.numberofvertices,1);
+
+	%Hands on: STEP 3
+	md.inversion.min_parameters = 1*ones(md.mesh.numberofvertices,1);
+	md.inversion.max_parameters = 100*ones(md.mesh.numberofvertices,1);
+
+	%Go solve!
+	md.verbose=verbose(0);
+	md=solve(md,StressbalanceSolutionEnum);
+
+	plotmodel(md,'data',md.results.StressbalanceSolution.FrictionCoefficient,'figure',1,'caxis',[10 50]);
+	plotmodel(md,'data',md.results.StressbalanceSolution.Vel,'figure',2);  
+end
Index: issm/trunk/examples/Inversion/DomainOutline.exp
===================================================================
--- issm/trunk/examples/Inversion/DomainOutline.exp	(revision 18301)
+++ issm/trunk/examples/Inversion/DomainOutline.exp	(revision 18301)
@@ -0,0 +1,10 @@
+## Name:DomainOutline
+## Icon:0
+# Points Count  Value
+5 1.000000
+# X pos Y pos
+0 0
+1000000 0
+1000000 1000000
+0 1000000
+0 0
Index: issm/trunk/examples/Inversion/Front.exp
===================================================================
--- issm/trunk/examples/Inversion/Front.exp	(revision 18301)
+++ issm/trunk/examples/Inversion/Front.exp	(revision 18301)
@@ -0,0 +1,10 @@
+## Name:icefront
+## Icon:0
+# Points Count  Value
+5 1.
+# X pos Y pos
+-1000 900000
+-1000 1100000
+1100000 1100000
+1100000 900000
+-1000 900000
Index: issm/trunk/examples/Inversion/Square.par
===================================================================
--- issm/trunk/examples/Inversion/Square.par	(revision 18301)
+++ issm/trunk/examples/Inversion/Square.par	(revision 18301)
@@ -0,0 +1,24 @@
+%Start defining model parameters here
+
+disp('      creating thickness');
+hmin = 300;
+hmax = 1000;
+ymin = min(md.mesh.y);
+ymax = max(md.mesh.y);
+md.geometry.thickness = hmax+(hmin-hmax)*(md.mesh.y-ymin)/(ymax-ymin);
+md.geometry.base      = -md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface   = md.geometry.base+md.geometry.thickness;
+
+disp('      creating drag');
+md.friction.coefficient=200*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
+md.friction.p = ones(md.mesh.numberofelements,1);
+md.friction.q = ones(md.mesh.numberofelements,1);
+
+disp('      creating flow law paramter');
+md.materials.rheology_B=1.8*10^8*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_B(find(md.mesh.x<md.mesh.y))=1.4*10^8;
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+
+disp('      creating boundary conditions');
+md=SetIceShelfBC(md,'Front.exp');
Index: issm/trunk/examples/Inversion/runme.m
===================================================================
--- issm/trunk/examples/Inversion/runme.m	(revision 18301)
+++ issm/trunk/examples/Inversion/runme.m	(revision 18301)
@@ -0,0 +1,78 @@
+step=1;
+if step==1
+	%Generate observation
+	md = model;
+	md = triangle(md,'DomainOutline.exp',100000);
+	md = setmask(md,'all','');
+	md = parameterize(md,'Square.par');
+	md = setflowequation(md,'SSA','all');
+	md.cluster = generic('np',2);
+
+	md = solve(md,StressbalanceSolutionEnum);
+
+	plotmodel(md,'data',md.materials.rheology_B,'caxis',[ 1.3 1.9]*10^8,'figure',1,'gridded#all',1);
+	plotmodel(md,'data',md.results.StressbalanceSolution.Vel,'figure',2,'gridded#all',1);  
+
+	save model1 md
+end
+if step==2
+	%Modify rheology, now constant
+	loadmodel('model1.mat');
+	md.materials.rheology_B(:) = 1.8*10^8;
+
+	%results of previous run are taken as observations
+	md.inversion=m1qn3inversion();
+	md.inversion.vx_obs  = md.results.StressbalanceSolution.Vx;
+	md.inversion.vy_obs  = md.results.StressbalanceSolution.Vy;
+	md.inversion.vel_obs = md.results.StressbalanceSolution.Vel;
+
+	md = solve(md,StressbalanceSolutionEnum);
+
+	plotmodel(md,'data',md.materials.rheology_B,'caxis',[ 1.3 1.9]*10^8,'figure',1);
+	plotmodel(md,'data',md.results.StressbalanceSolution.Vel,'figure',2);  
+
+	save model2 md
+end
+if step==3
+	%invert for ice rigidity
+	loadmodel('model2.mat');
+
+	%Set up inversion parameters
+	maxsteps = 20;
+	md.inversion.iscontrol = 1;
+	md.inversion.control_parameters = {'MaterialsRheologyBbar'};
+	md.inversion.maxsteps = maxsteps;
+	md.inversion.cost_functions = 101;
+	md.inversion.cost_functions_coefficients = ones(md.mesh.numberofvertices,1);
+	md.inversion.min_parameters    = paterson(273)*ones(md.mesh.numberofvertices,1);
+	md.inversion.max_parameters    = paterson(200)*ones(md.mesh.numberofvertices,1);
+
+	%Go solve!
+	md.verbose=verbose(0);
+	md=solve(md,StressbalanceSolutionEnum);
+
+	plotmodel(md,'data',md.results.StressbalanceSolution.MaterialsRheologyBbar,'caxis',[ 1.3 1.9]*10^8,'figure',1);
+	plotmodel(md,'data',md.results.StressbalanceSolution.Vel,'figure',2);  
+end
+if step==4
+	%invert for ice rigidity
+	loadmodel('model2.mat');
+
+	%Set up inversion parameters
+	maxsteps = 20;
+	md.inversion.iscontrol = 1;
+	md.inversion.control_parameters = {'MaterialsRheologyBbar'};
+	md.inversion.maxsteps = maxsteps;
+	md.inversion.cost_functions = [101 502];
+	md.inversion.cost_functions_coefficients      = ones(md.mesh.numberofvertices,1);
+	md.inversion.cost_functions_coefficients(:,2) = 10^-16*ones(md.mesh.numberofvertices,1);
+	md.inversion.min_parameters    = paterson(273)*ones(md.mesh.numberofvertices,1);
+	md.inversion.max_parameters    = paterson(200)*ones(md.mesh.numberofvertices,1);
+
+	%Go solve!
+	md.verbose=verbose(0);
+	md=solve(md,StressbalanceSolutionEnum);
+
+	plotmodel(md,'data',md.results.StressbalanceSolution.MaterialsRheologyBbar,'caxis',[ 1.3 1.9]*10^8,'figure',1);
+	plotmodel(md,'data',md.results.StressbalanceSolution.Vel,'figure',2);  
+end
Index: issm/trunk/examples/Jakobshavn/Jks.par
===================================================================
--- issm/trunk/examples/Jakobshavn/Jks.par	(revision 18081)
+++ issm/trunk/examples/Jakobshavn/Jks.par	(revision 18301)
@@ -6,5 +6,5 @@
 %Load SeaRISE dataset
 disp('   Loading SeaRISE data from NetCDF');
-ncdata = './Greenland_5km_v1.1.nc';
+ncdata = '../Data/Greenland_5km_dev1.2.nc';
 x1    = ncread(ncdata,'x1');
 y1    = ncread(ncdata,'y1');
@@ -58,3 +58,4 @@
 disp('   Set other boundary conditions');
 md=SetMarineIceSheetBC(md,'./Front.exp');
-md.basalforcings.melting_rate=zeros(md.mesh.numberofvertices,1);
+md.basalforcings.floatingice_melting_rate=zeros(md.mesh.numberofvertices,1);
+md.basalforcings.groundedice_melting_rate=zeros(md.mesh.numberofvertices,1);
Index: issm/trunk/examples/Jakobshavn/runme.m
===================================================================
--- issm/trunk/examples/Jakobshavn/runme.m	(revision 18081)
+++ issm/trunk/examples/Jakobshavn/runme.m	(revision 18301)
@@ -1,3 +1,3 @@
-steps=[1:3];
+steps=[4];
 
 if any(steps==1)
@@ -6,7 +6,7 @@
 
 	%Get observed velocity field on mesh nodes
-	ncdata='Greenland_5km_v1.1.nc';
+	ncdata='../Data/Greenland_5km_dev1.2.nc';
 	if ~exist(ncdata,'file'), 
-		error('Download Greenland5km_v1.1.nc first on http://websrv.cs.umt.edu/isis/index.php/Present_Day_Greenland');
+		error('File Greenland_5km_dev1.2.nc not downloaded in Data Directory.  Please cd ../Data and run the download script.');
 	end
 	x1   = ncread(ncdata,'x1');
@@ -84,5 +84,5 @@
 		'colorbar#1','off','colorbar#2','on','colorbartitle#2','[m/yr]',...
 		'caxis#1-2',[0,7000],...
-		'data',md.geometry.bed,'title','Bed elevation',...
+		'data',md.geometry.base,'title','Base elevation',...
 		'data',md.results.StressbalanceSolution.FrictionCoefficient,...
 		'title','Friction Coefficient',...
Index: issm/trunk/examples/Pig/CheatSheet.m
===================================================================
--- issm/trunk/examples/Pig/CheatSheet.m	(revision 18301)
+++ issm/trunk/examples/Pig/CheatSheet.m	(revision 18301)
@@ -0,0 +1,18 @@
+if any(steps==6)
+	% Load Model
+	md = loadmodel('./Models/PIG.Control_drag');
+	md.inversion.iscontrol=0;
+
+	disp('   Extruding mesh')
+	number_of_layers=3;
+	md=extrude(md,number_of_layers,0.9);
+
+	disp('   Using HO Ice Flow Model')
+	md=setflowequation(md, 'HO', 'all');
+
+	% Solve
+	md=solve(md,StressbalanceSolutionEnum);
+
+	% Save Model
+	save ./Models/PIG.ModelHO md;
+end
Index: issm/trunk/examples/Pig/DomainOutline.bkp
===================================================================
--- issm/trunk/examples/Pig/DomainOutline.bkp	(revision 18301)
+++ issm/trunk/examples/Pig/DomainOutline.bkp	(revision 18301)
@@ -0,0 +1,120 @@
+## Name:
+## Icon:0
+# Points Count Value
+114 25000.000000
+# X pos Y pos
+-1712113.0179281300 -349656.0205056490
+-1711509.1917759699 -349354.1074295690
+-1709240.6586108401 -349354.1074295690
+-1707080.1508345299 -348922.0058743060
+-1705459.7700022999 -347193.5996532570
+-1703083.2114483600 -345249.1426545770
+-1701138.7544496800 -344168.8887664210
+-1698438.1197292900 -343952.8379887900
+-1698006.0181740201 -341900.3556012940
+-1693793.0280102200 -340279.9747690600
+-1691092.3932898301 -339631.8224361670
+-1688391.7585694401 -339415.7716585360
+-1686447.3015707601 -340063.9239914290
+-1683530.6160727399 -341036.1524907690
+-1682558.3875734000 -343304.6856558960
+-1682134.7209454600 -344182.1487658350
+-1682126.2860181299 -345681.2442098390
+-1681072.0444963200 -345932.4393879640
+-1680634.4718407800 -346682.5639403050
+-1680571.9614614199 -348557.8753211580
+-1677446.4424933300 -348370.3441830730
+-1675508.6207331200 -349495.5310115840
+-1676616.9911885399 -353567.0975933760
+-1672991.8601872099 -353799.6175753630
+-1668839.1631938200 -353999.1991486380
+-1667132.2298986400 -355121.4651541420
+-1666069.5534494901 -357496.8595698890
+-1662944.0344814099 -358309.4945015920
+-1660756.1712037399 -358747.0671571240
+-1657922.9836098100 -361682.8074238540
+-1656579.2228470000 -364003.8487410000
+-1653004.8841628900 -364748.0635758530
+-1653442.4568184200 -361622.5446077650
+-1651129.5727820301 -355684.0585683980
+-1648929.2928810001 -350845.9692010000
+-1646260.7698359799 -347802.2804785470
+-1644571.8968503401 -341785.6704672340
+-1643503.3064999001 -340869.0986596620
+-1643190.7546030900 -336680.9032424240
+-1642690.6715682000 -335243.1645171040
+-1641913.0916588283 -332341.0814454452
+-1640683.9739821283 -330436.6112348017
+-1637816.0327364956 -328532.1410241582
+-1635241.2508976001 -328652.8685499910
+-1631765.4107996500 -327017.1790921330
+-1625934.5618617306 -322342.6128395668
+-1620608.3852626982 -320438.1426289233
+-1616101.6204481323 -320438.1426289233
+-1611594.8556335662 -320914.2601815842
+-1607907.5026034669 -321866.4952869060
+-1602991.0318966676 -324723.2006028712
+-1599713.3847588014 -327579.9059188365
+-1593977.5022675355 -328532.1410241582
+-1590699.8551296694 -334721.6692087495
+-1589259.8391499999 -338300.0840570000
+-1588627.0898328500 -343572.9950327750
+-1588056.6000060199 -345432.3563530700
+-1586993.9235568701 -347432.6884926460
+-1589259.8391499999 -349315.9832070000
+-1585493.6744521901 -352996.1122558430
+-1585118.6121760199 -354496.3613605250
+-1585861.9157163899 -356240.3342513760
+-1586368.8197632500 -358747.0671571240
+-1587889.0972700799 -360996.6006787950
+-1586681.3716600600 -363935.4286441500
+-1585806.2263489999 -365748.2296456410
+-1586743.8820394201 -368373.6655788350
+-1586056.2678664399 -370123.9562009640
+-1585493.6744521901 -371124.1222707520
+-1586243.7990045301 -373562.0270658610
+-1428620.2472997301 -364425.2597226670
+-1414257.6683934701 -327460.5482541260
+-1412220.4351378100 -325972.8942023180
+-1404515.9240538401 -296165.1737279960
+-1387984.9332285200 -267002.0106682320
+-1375329.9306695000 -287124.5773036880
+-1374139.7661228001 -286331.1342725540
+-1347030.4625590600 -322432.7921891520
+-1351262.1587251101 -326267.7668396330
+-1381809.7154237600 -297174.8556980530
+-1381677.4749185799 -295852.4506461620
+-1382481.1222932001 -294804.4361498400
+-1398663.5713381099 -316073.2308695170
+-1409694.4697897099 -363328.2128408530
+-1202495.3746585899 -351317.7619567180
+-1191463.4809399999 -350233.9748030000
+-1232161.1083569999 -292094.5070650000
+-1231243.1167609999 -288422.5406810000
+-1360067.9373810000 -107884.1934940000
+-1423274.3497420000 -81217.9259650000
+-1402446.7987670000 -45916.9921070000
+-1478343.8065599999 60338.8188030000
+-1513291.7310790000 4210.3339700000
+-1523175.9925589999 11976.5394190000
+-1503760.4789370000 36334.1837800000
+-1528509.5619775900 63667.6809196406
+-1623055.4918765700 62841.1506965373
+-1648011.3012850001 32874.5178730000
+-1638219.3909290000 20634.6299280000
+-1650153.2816760000 31038.5346810000
+-1725734.5897359999 -61372.6193030000
+-1719614.6457630000 -69022.5492690000
+-1759088.2843859999 -114004.1374660000
+-1755416.3180020000 -117064.1094530000
+-1761230.2647760001 -126856.0198080000
+-1758170.2927900001 -130527.9861920000
+-1762148.2563720001 -135423.9413700000
+-1764902.2311590000 -131445.9777880000
+-1769798.1863370000 -134199.9525750000
+-1775000.1387139999 -131445.9777880000
+-1794277.9622269999 -153477.7760890000
+-1712576.7101950001 -225081.1205660000
+-1729939.5891459100 -335652.4567604720
+-1712113.0179281300 -349656.0205056490
+
Index: issm/trunk/examples/Pig/DomainOutline.exp
===================================================================
--- issm/trunk/examples/Pig/DomainOutline.exp	(revision 18301)
+++ issm/trunk/examples/Pig/DomainOutline.exp	(revision 18301)
@@ -0,0 +1,101 @@
+## Name:
+## Icon:0
+# Points Count Value
+95 25000.000000
+# X pos Y pos
+-1712113.0179281300 -349656.0205056490
+-1711509.1917759699 -349354.1074295690
+-1709240.6586108401 -349354.1074295690
+-1707080.1508345299 -348922.0058743060
+-1705459.7700022999 -347193.5996532570
+-1703083.2114483600 -345249.1426545770
+-1701138.7544496800 -344168.8887664210
+-1698438.1197292900 -343952.8379887900
+-1698006.0181740201 -341900.3556012940
+-1693793.0280102200 -340279.9747690600
+-1691092.3932898301 -339631.8224361670
+-1688391.7585694401 -339415.7716585360
+-1686447.3015707601 -340063.9239914290
+-1683530.6160727399 -341036.1524907690
+-1682558.3875734000 -343304.6856558960
+-1682134.7209454600 -344182.1487658350
+-1682126.2860181299 -345681.2442098390
+-1681072.0444963200 -345932.4393879640
+-1680634.4718407800 -346682.5639403050
+-1680571.9614614199 -348557.8753211580
+-1677446.4424933300 -348370.3441830730
+-1675508.6207331200 -349495.5310115840
+-1676616.9911885399 -353567.0975933760
+-1672991.8601872099 -353799.6175753630
+-1668839.1631938200 -353999.1991486380
+-1667132.2298986400 -355121.4651541420
+-1666069.5534494901 -357496.8595698890
+-1662944.0344814099 -358309.4945015920
+-1660756.1712037399 -358747.0671571240
+-1657922.9836098100 -361682.8074238540
+-1656579.2228470000 -364003.8487410000
+-1653004.8841628900 -364748.0635758530
+-1653442.4568184200 -361622.5446077650
+-1651129.5727820301 -355684.0585683980
+-1648929.2928810001 -350845.9692010000
+-1646260.7698359799 -347802.2804785470
+-1644571.8968503401 -341785.6704672340
+-1643503.3064999001 -340869.0986596620
+-1643190.7546030900 -336680.9032424240
+-1642690.6715682000 -335243.1645171040
+-1641913.0916588283 -332341.0814454452
+-1640683.9739821283 -330436.6112348017
+-1637816.0327364956 -328532.1410241582
+-1635241.2508976001 -328652.8685499910
+-1631765.4107996500 -327017.1790921330
+-1625934.5618617306 -322342.6128395668
+-1620608.3852626982 -320438.1426289233
+-1616101.6204481323 -320438.1426289233
+-1611594.8556335662 -320914.2601815842
+-1607907.5026034669 -321866.4952869060
+-1602991.0318966676 -324723.2006028712
+-1599713.3847588014 -327579.9059188365
+-1593977.5022675355 -328532.1410241582
+-1590699.8551296694 -334721.6692087495
+-1589259.8391499999 -338300.0840570000
+-1588627.0898328500 -343572.9950327750
+-1588056.6000060199 -345432.3563530700
+-1586993.9235568701 -347432.6884926460
+-1589259.8391499999 -349315.9832070000
+-1585493.6744521901 -352996.1122558430
+-1585118.6121760199 -354496.3613605250
+-1585861.9157163899 -356240.3342513760
+-1586368.8197632500 -358747.0671571240
+-1587889.0972700799 -360996.6006787950
+-1586681.3716600600 -363935.4286441500
+-1585806.2263489999 -365748.2296456410
+-1586743.8820394201 -368373.6655788350
+-1586056.2678664399 -370123.9562009640
+-1585493.6744521901 -371124.1222707520
+-1586243.7990045301 -373562.0270658610
+-1414257.6683934701 -327460.5482541260
+-1412220.4351378100 -325972.8942023180
+-1404515.9240538401 -296165.1737279960
+-1387984.9332285200 -267002.0106682320
+-1360067.9373810000 -107884.1934940000
+-1423274.3497420000 -81217.9259650000
+-1402446.7987670000 -45916.9921070000
+-1478343.8065599999 60338.8188030000
+-1503760.4789370000 36334.1837800000
+-1528509.5619775900 63667.6809196406
+-1623055.4918765700 62841.1506965373
+-1725734.5897359999 -61372.6193030000
+-1719614.6457630000 -69022.5492690000
+-1759088.2843859999 -114004.1374660000
+-1755416.3180020000 -117064.1094530000
+-1761230.2647760001 -126856.0198080000
+-1758170.2927900001 -130527.9861920000
+-1762148.2563720001 -135423.9413700000
+-1764902.2311590000 -131445.9777880000
+-1769798.1863370000 -134199.9525750000
+-1775000.1387139999 -131445.9777880000
+-1794277.9622269999 -153477.7760890000
+-1712576.7101950001 -225081.1205660000
+-1729939.5891459100 -335652.4567604720
+-1712113.0179281300 -349656.0205056490
+
Index: issm/trunk/examples/Pig/Pig.par
===================================================================
--- issm/trunk/examples/Pig/Pig.par	(revision 18301)
+++ issm/trunk/examples/Pig/Pig.par	(revision 18301)
@@ -0,0 +1,135 @@
+% Parameters to change/Try
+friction_coefficient = 10; % default [10]
+Temp_change          =  0;  % default [0 K]
+
+%Name and hemisphere
+md.miscellaneous.name='PIG';
+md.mesh.hemisphere='s';
+
+% {{{ NetCdf Loading
+disp('   Loading SeaRISE data from NetCDF');
+ncdata='../Data/Antarctica_5km_withshelves_v0.75.nc';
+x1    = ncread(ncdata,'x1');
+y1    = ncread(ncdata,'y1');
+usrf  = ncread(ncdata,'usrf')';
+topg  = ncread(ncdata,'topg')';
+temp  = ncread(ncdata,'presartm')';
+smb   = ncread(ncdata,'presprcp')';
+gflux = ncread(ncdata,'bheatflx_fox')';
+
+disp('   Loading velocities data from NetCDF');
+nsidc_vel='../Data/Antarctica_ice_velocity.nc';
+
+xmin = ncreadatt(nsidc_vel,'/','xmin');
+xmin = strtrim(xmin);  %this is a string, and we need to recover the double value
+xmin = xmin(1:end-2);  %get rid of the unit
+xmin = str2num(xmin);  %convert to double
+
+ymax = ncreadatt(nsidc_vel,'/','ymax'); 
+ymax = strtrim(ymax);  
+ymax = ymax(1:end-2);  
+ymax = str2num(ymax); 
+
+nx = ncreadatt(nsidc_vel,'/','nx');
+ny = ncreadatt(nsidc_vel,'/','ny');
+
+spacing = ncreadatt(nsidc_vel,'/','spacing'); 
+spacing = strtrim(spacing);  
+spacing = spacing(1:end-2);  
+spacing = str2num(spacing); 
+
+velx = double(ncread(nsidc_vel,'vx'));
+vely = double(ncread(nsidc_vel,'vy'));
+
+x2=xmin+(0:1:nx)'*spacing; 
+x2=double(x2);
+
+y2=(ymax-ny*spacing)+(0:1:ny)'*spacing; 
+y2=double(y2);
+% }}}
+% {{{ Geometry
+disp('   Interpolating surface and ice base');
+md.geometry.base    = InterpFromGridToMesh(x1,y1,topg,md.mesh.x,md.mesh.y,0);
+md.geometry.surface = InterpFromGridToMesh(x1,y1,usrf,md.mesh.x,md.mesh.y,0);
+clear usrf, topg;
+
+disp('   Constructing thickness');
+md.geometry.thickness=md.geometry.surface-md.geometry.base;
+
+%ensure hydrostatic equilibrium on ice shelf: 
+di=md.materials.rho_ice/md.materials.rho_water;
+
+%Get the node numbers of floating nodes
+pos=find(md.mask.groundedice_levelset<0); 
+
+%apply a flotation criterion on the precedingly defined nodes and
+%redefine base and thickness accordingly
+md.geometry.thickness(pos)=1/(1-di)*md.geometry.surface(pos);
+md.geometry.base(pos)=md.geometry.surface(pos)-md.geometry.thickness(pos);
+md.geometry.hydrostatic_ratio=ones(md.mesh.numberofvertices,1);
+
+%Set min thickness to 1 meter
+pos0=find(md.geometry.thickness<=0);
+md.geometry.thickness(pos0)=1;
+md.geometry.surface=md.geometry.thickness+md.geometry.base;
+% }}} 
+% {{{ Initialization parameters
+disp('   Interpolating temperatures');
+md.initialization.temperature=InterpFromGridToMesh(x1,y1,temp,md.mesh.x,md.mesh.y,0)+273.15+Temp_change;
+clear temp;
+
+disp('   Set observed velocities')
+vx_obs=InterpFromGridToMesh(x2,y2,flipud(velx'),md.mesh.x,md.mesh.y,0);
+vy_obs=InterpFromGridToMesh(x2,y2,flipud(vely'),md.mesh.x,md.mesh.y,0);
+clear velx vely;
+
+vel_obs=sqrt(vx_obs.^2+vy_obs.^2);
+md.initialization.vx=vx_obs;
+md.initialization.vy=vy_obs;
+md.initialization.vz=zeros(md.mesh.numberofvertices,1);
+md.initialization.vel=vel_obs;
+
+disp('   Set Pressure');
+md.initialization.pressure=md.materials.rho_ice*md.constants.g*md.geometry.thickness;
+
+% }}}
+
+disp('   Construct ice rheological properties');
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+md.materials.rheology_B=paterson(md.initialization.temperature);
+
+% {{{ Forcings
+disp('   Interpolating surface mass balance');
+md.surfaceforcings.mass_balance=InterpFromGridToMesh(x1,y1,smb,md.mesh.x,md.mesh.y,0);
+md.surfaceforcings.mass_balance=md.surfaceforcings.mass_balance*md.materials.rho_water/md.materials.rho_ice;
+clear smb;
+
+disp('   Set geothermal heat flux');
+md.basalforcings.geothermalflux=InterpFromGridToMesh(x1,y1,gflux,md.mesh.x,md.mesh.y,0);
+clear gflux;
+% }}}
+
+% {{{ Friction and inversion set up
+disp('   Construct basal friction parameters');
+md.friction.coefficient=friction_coefficient*ones(md.mesh.numberofvertices,1);
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+%no friction applied on floating ice
+pos=find(md.mask.groundedice_levelset<0);
+md.friction.coefficient(pos)=0;
+
+md.inversion=m1qn3inversion();
+md.inversion.vx_obs=vx_obs;
+md.inversion.vy_obs=vy_obs;
+md.inversion.vel_obs=vel_obs;
+% }}}
+
+
+disp('   Set boundary conditions');
+md=SetMarineIceSheetBC(md);
+md.basalforcings.floatingice_melting_rate = zeros(md.mesh.numberofvertices,1);
+md.basalforcings.groundedice_melting_rate = zeros(md.mesh.numberofvertices,1);
+md.thermal.spctemperature     = [md.initialization.temperature;1]; %impose observed temperature on surface
+md.masstransport.spcthickness    = NaN*ones(md.mesh.numberofvertices,1);
+
Index: issm/trunk/examples/Pig/PigRegion.m
===================================================================
--- issm/trunk/examples/Pig/PigRegion.m	(revision 18301)
+++ issm/trunk/examples/Pig/PigRegion.m	(revision 18301)
@@ -0,0 +1,54 @@
+% {{{ Getting the velocity in PIG vicinity for the ExpDraw
+
+% Load Velocities
+% http://nsidc.org/data/nsidc-0484.html
+nsidc_vel='../Data/Antarctica_ice_velocity.nc'; 	
+
+% Get necessary data to build up the velocity grid
+xmin = ncreadatt(nsidc_vel,'/','xmin');
+xmin = strtrim(xmin);  % this is a string, and we need to recover the double value
+xmin = xmin(1:end-2);  % get rid of the unit
+xmin = str2num(xmin);  % convert to double
+
+ymax = ncreadatt(nsidc_vel,'/','ymax'); 
+ymax = strtrim(ymax);  
+ymax = ymax(1:end-2);  
+ymax = str2num(ymax); 
+	
+nx = ncreadatt(nsidc_vel,'/','nx');
+ny = ncreadatt(nsidc_vel,'/','ny');
+
+spacing = ncreadatt(nsidc_vel,'/','spacing'); 
+spacing = strtrim(spacing);
+spacing = spacing(1:end-2);  
+spacing = str2num(spacing); 
+
+
+x=xmin+(0:1:nx-1)'*spacing; 
+x=double(x);
+y=(ymax)-(0:1:ny-1)'*spacing; 
+y=double(y);
+
+posx=find(x<=-12.0e5);
+id1x=find(x>=-18.0e5,1);
+id2x=posx(end);
+
+posy=find(y>=-4.0e5);
+id1y=find(y<=1.0e5,1);
+id2y=posy(end);
+
+%Get velocity subset
+vx = double(ncread(nsidc_vel,'vx'));
+vx_obs = vx(id1x:id2x,id1y:id2y);
+vx_obs = flipud(vx_obs');
+
+vy = double(ncread(nsidc_vel,'vy'));
+vy_obs = vy (id1x:id2x,id1y:id2y);
+vy_obs = flipud(vy_obs');
+
+xred=x(id1x:id2x);
+yred=y(id1y:id2y);
+vel_obs=sqrt(vx_obs.^2.+vy_obs.^2.);
+imagesc(xred,yred,vel_obs)
+
+%}}}
Index: issm/trunk/examples/Pig/runme.m
===================================================================
--- issm/trunk/examples/Pig/runme.m	(revision 18301)
+++ issm/trunk/examples/Pig/runme.m	(revision 18301)
@@ -0,0 +1,228 @@
+%Which steps to be performed
+steps=[1] ;
+
+%Run Steps
+
+% {{{ Mesh Generation #1
+if any(steps==1)
+
+	md.miscellaneous.name='PIG.Mesh_generation';
+
+	%Mesh parameters
+	domain =['./DomainOutline.exp'];
+	hmax=40000;    % maximum element size of the final mesh
+	hmin=5000;     % minimum element size of the final mesh
+	hinit=10000;   % element size for the initial mesh
+	gradation=1.7; % maximum size ratio between two neighboring elements
+	err=8;         % maximum error between interpolated and control field
+
+	% Generate an initial uniform mesh (resolution = hinit m)
+	md=bamg(model,'domain',domain,'hmax',hinit,'MaxCornerAngle',1);
+
+	%ploting
+	plotmodel(md,'data','mesh')
+
+	% Load Velocities
+	% http://nsidc.org/data/nsidc-0484.html
+	nsidc_vel='../Data/Antarctica_ice_velocity.nc'; 	
+
+	% Get necessary data to build up the velocity grid
+	xmin = ncreadatt(nsidc_vel,'/','xmin');
+	xmin = strtrim(xmin);  % this is a string, and we need to recover the double value
+	xmin = xmin(1:end-2);  % get rid of the unit
+	xmin = str2num(xmin);  % convert to double
+	
+	ymax = ncreadatt(nsidc_vel,'/','ymax'); 
+	ymax = strtrim(ymax);  
+	ymax = ymax(1:end-2);  
+	ymax = str2num(ymax); 
+	
+	nx = ncreadatt(nsidc_vel,'/','nx');
+	ny = ncreadatt(nsidc_vel,'/','ny');
+	
+	spacing = ncreadatt(nsidc_vel,'/','spacing'); 
+	spacing = strtrim(spacing);
+	spacing = spacing(1:end-2);  
+	spacing = str2num(spacing); 
+	
+	% Get velocities (Note: You can use ncdisp('file') to see an ncdump)
+	vx = double(ncread(nsidc_vel,'vx'));
+	vy = double(ncread(nsidc_vel,'vy'));
+	
+	x=xmin+(0:1:nx)'*spacing; 
+	x=double(x);
+	y=(ymax-ny*spacing)+(0:1:ny)'*spacing; 
+	y=double(y);
+
+	% Interpolate velocities onto coarse mesh
+	vx_obs=InterpFromGridToMesh(x,y,flipud(vx'),md.mesh.x,md.mesh.y,0);
+	vy_obs=InterpFromGridToMesh(x,y,flipud(vy'),md.mesh.x,md.mesh.y,0);
+	vel_obs=sqrt(vx_obs.^2+vy_obs.^2);
+	clear vx vy x y;
+
+	% Adapt the mesh to minimize error in velocity interpolation
+	md=bamg(md,'hmax',hmax,'hmin',hmin,'gradation',gradation,'field',vel_obs,'err',err);
+	
+	%ploting
+	plotmodel(md,'data','mesh')
+
+	% Convert x,y coordinates (Polar stereo) to lat/lon
+	[md.mesh.lat,md.mesh.long]=xy2ll(md.mesh.x,md.mesh.y,-1);
+	
+	% Save model
+	save ./Models/PIG.Mesh_generation md;
+end
+% }}}
+
+% {{{ Masks #2
+if any(steps==2) 
+
+	md = loadmodel('./Models/PIG.Mesh_generation');	
+
+	% Load SeaRISe dataset for Antarctica  
+	% http://websrv.cs.umt.edu/isis/index.php/Present_Day_Antarctica
+	searise='../Data/Antarctica_5km_withshelves_v0.75.nc';
+	
+	%read thickness mask from SeaRISE
+	x1=double(ncread(searise,'x1'));
+	y1=double(ncread(searise,'y1'));
+	thkmask=double(ncread(searise,'thkmask'));
+	
+	%interpolate onto our mesh vertices
+	groundedice=double(InterpFromGridToMesh(x1,y1,thkmask',md.mesh.x,md.mesh.y,0));
+	groundedice(groundedice<=0)=-1;
+	clear thkmask;
+
+	%fill in the md.mask structure
+	md.mask.groundedice_levelset=groundedice; %ice is grounded for mask equal one
+	md.mask.ice_levelset=-1*ones(md.mesh.numberofvertices,1);%ice is present when negatvie
+
+	%ploting
+	plotmodel(md,'data',md.mask.groundedice_levelset,'title','grounded/floating','data',md.mask.ice_levelset,'title','ice/no-ice')
+	
+	% Save model
+	save ./Models/PIG.SetMask md;
+end
+% }}}
+
+% {{{ Parameterization #3
+if any(steps==3) 
+
+	md = loadmodel('./Models/PIG.SetMask');
+	md = parameterize(md,'./Pig.par');
+
+	% Use a MacAyeal flow model
+	md = setflowequation(md,'SSA','all');
+	
+	% Save model
+	save ./Models/PIG.Parameterization md;
+end
+% }}}
+
+% {{{ Control Method #4
+if any(steps==4)
+
+	md = loadmodel('./Models/PIG.Parameterization');
+
+	% Control general
+	md.inversion.iscontrol=1;
+	md.inversion.maxsteps=20;
+	md.inversion.maxiter=40;
+	md.inversion.dxmin=0.1;
+	md.inversion.gttol=1.0e-4;
+	md.verbose=verbose('solution',true,'control',true);
+
+	% Cost functions
+	md.inversion.cost_functions=[101 103 501];
+	md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,3);
+	md.inversion.cost_functions_coefficients(:,1)=1;
+	md.inversion.cost_functions_coefficients(:,2)=1;
+	md.inversion.cost_functions_coefficients(:,3)=8e-15;
+
+	% Controls
+	md.inversion.control_parameters={'FrictionCoefficient'};
+	md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
+	md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
+
+	% Additional parameters
+	md.stressbalance.restol=0.01;
+	md.stressbalance.reltol=0.1;
+	md.stressbalance.abstol=NaN;
+
+	% Solve
+	md.toolkits=toolkits;
+	md.cluster=generic('name',oshostname,'np',2);
+	md=solve(md,StressbalanceSolutionEnum);
+
+	% Update model friction fields accordingly
+	md.friction.coefficient=md.results.StressbalanceSolution.FrictionCoefficient;
+
+	plotmodel(md,'data',md.friction.coefficient)
+
+	% Save model
+	save ./Models/PIG.Control_drag md;
+end
+% }}}
+
+% {{{ Plot #5
+if any(steps==5)
+
+	md = loadmodel('./Models/PIG.Control_drag');
+
+	plotmodel(md,'nlines',2,'ncols',2,'unit#all','km','axis#all','equal',...
+		'xlim#all',[min(md.mesh.x) max(md.mesh.x)]/10^3,...
+		'ylim#all',[min(md.mesh.y) max(md.mesh.y)]/10^3,...
+		'FontSize#all',12,...
+		'data',md.initialization.vel,'title','Observed velocity',...
+		'data',md.results.StressbalanceSolution.Vel,'title','Modeled Velocity',...
+		'data',md.geometry.base,'title','Bed elevation',...
+		'data',md.results.StressbalanceSolution.FrictionCoefficient,'title','Friction Coefficient',...
+		'colorbar#all','on','colorbartitle#1-2','[m/yr]',...
+		'caxis#1-2',([1.5,4000]),...
+		'colorbartitle#3','[m]', 'log#1-2',10);
+end
+% }}}
+
+% {{{ HO #6
+if any(steps==6)
+
+	% Load Model
+
+	% Disable inversion
+
+	% Extrude Mesh
+
+	% Set Flowequation
+
+	% Solve
+
+	% Save Model
+
+end
+% }}}
+
+% {{{ Plot #7
+if any(steps==7)
+
+	mdHO = loadmodel('./Models/PIG.ModelHO');
+	mdSSA = loadmodel('./Models/PIG.Control_drag');
+
+	basal=find(mdHO.mesh.vertexonbase);
+	surf=find(mdHO.mesh.vertexonsurface);
+
+	plotmodel(mdHO,'nlines',3,'ncols',2,'unit#all','km','axis#all','equal',...
+						'xlim#all',[min(mdHO.mesh.x) max(mdHO.mesh.x)]/10^3,...
+						'ylim#all',[min(mdHO.mesh.y) max(mdHO.mesh.y)]/10^3,...
+						'FontSize#all',12,...
+						'data',mdHO.initialization.vel,'title','Observed velocity',...
+						'data',(mdHO.results.StressbalanceSolution.Vel(surf)-mdHO.initialization.vel(surf)),'title','(HO-observed) velocities',...
+						'data',mdSSA.results.StressbalanceSolution.Vel,'title','Modeled SSA Velocity',...
+						'data',(mdHO.results.StressbalanceSolution.Vel(surf)-mdSSA.results.StressbalanceSolution.Vel),'title','(HO-SSA) velocities',...
+						'data',mdHO.results.StressbalanceSolution.Vel,'title','Modeled HO surface Velocities',...
+						'data',(mdHO.results.StressbalanceSolution.Vel(surf)-mdHO.results.StressbalanceSolution.Vel(basal)),'title','(HOsurf-HO base) velocities',...
+						'caxis#1',([1.5,4000]),'caxis#3',([1.5,4000]),'caxis#5',([1.5,4000]),...
+						'colorbar#all','on','view#all',2,...
+						'colorbartitle#all','[m/yr]',...
+						'layer#5',1, 'log#1', 10,'log#3', 10,'log#5', 10);
+end
+% }}}
Index: issm/trunk/examples/SquareIceShelf/Front.exp
===================================================================
--- issm/trunk/examples/SquareIceShelf/Front.exp	(revision 18081)
+++ issm/trunk/examples/SquareIceShelf/Front.exp	(revision 18301)
@@ -4,7 +4,7 @@
 5 1.
 # X pos Y pos
--1000 900000
+-1000 999999
 -1000 1100000
 1100000 1100000
-1100000 900000
--1000 900000
+1100000 999999
+-1000 999999
Index: issm/trunk/examples/UncertaintyQuantification/ErrorContour.exp
===================================================================
--- issm/trunk/examples/UncertaintyQuantification/ErrorContour.exp	(revision 18301)
+++ issm/trunk/examples/UncertaintyQuantification/ErrorContour.exp	(revision 18301)
@@ -0,0 +1,24 @@
+## Name:ErrorContour
+## Icon:0
+# Points Count Value
+18 1.000000
+# X pos Y pos
+-1642090.6657102096 -328038.7002928721
+-1665417.0018035804 -319119.8070807009
+-1681882.6508106657 -304712.3641995014
+-1666103.0705122089 -245710.4552574461
+-1632485.7037894099 -232675.1497935036
+-1616020.0547823247 -224442.3252899610
+-1598182.2683579824 -200429.9204879618
+-1596810.1309407253 -181219.9966463624
+-1615333.9860736963 -160637.9353875059
+-1559762.4206747836 -147602.6299235635
+-1527517.1913692418 -188080.6837326479
+-1566623.1077610692 -218953.7756209326
+-1533691.8097468987 -229244.8062503609
+-1523400.7791174706 -309514.8451599012
+-1533691.8097468987 -350678.9676776142
+-1594751.9248148398 -371261.0289364707
+-1636602.1160411814 -349306.8302603571
+-1642090.6657102096 -328038.7002928721
+
Index: issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux1.exp
===================================================================
--- issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux1.exp	(revision 18301)
+++ issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux1.exp	(revision 18301)
@@ -0,0 +1,22 @@
+## Name:MassFlux1
+## Icon:0
+# Points Count Value
+16 1.000000
+# X pos Y pos
+-1638344.3538415846 -328022.1178486745
+-1636175.0592654669 -328022.1178486745
+-1634647.1933393457 -327710.7373731936
+-1631836.4701132313 -326087.2311287920
+-1629847.9500851235 -324428.7567974643
+-1626413.2336729371 -321756.7703747695
+-1622074.6445207016 -320098.2960434417
+-1618278.3790124957 -319637.6087291840
+-1614210.9516822749 -319729.7461920356
+-1609601.2007080249 -320466.8458948479
+-1604539.5133637502 -322954.5573918396
+-1602370.2187876324 -324613.0317231673
+-1599206.6641974607 -326824.3308316044
+-1595681.5605112694 -327008.6057573075
+-1593150.7168391321 -327653.5679972683
+-1590710.2604409996 -330786.2417342208
+
Index: issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux10.exp
===================================================================
--- issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux10.exp	(revision 18301)
+++ issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux10.exp	(revision 18301)
@@ -0,0 +1,8 @@
+## Name:MassFlux11
+## Icon:0
+# Points Count Value
+2 1.000000
+# X pos Y pos
+-1539536.1089629673 -171232.8272031187
+-1540384.1546699132 -200614.0179257037
+
Index: issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux11.exp
===================================================================
--- issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux11.exp	(revision 18301)
+++ issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux11.exp	(revision 18301)
@@ -0,0 +1,8 @@
+## Name:MassFlux12
+## Icon:0
+# Points Count Value
+2 1.000000
+# X pos Y pos
+-1559431.5986180613 -236969.7272119786
+-1549112.1094185982 -261719.2194756830
+
Index: issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux12.exp
===================================================================
--- issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux12.exp	(revision 18301)
+++ issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux12.exp	(revision 18301)
@@ -0,0 +1,8 @@
+## Name:MassFlux13
+## Icon:0
+# Points Count Value
+2 1.000000
+# X pos Y pos
+-1572656.1032135738 -292391.9615161452
+-1573651.1418990945 -315407.7936937447
+
Index: issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux13.exp
===================================================================
--- issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux13.exp	(revision 18301)
+++ issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux13.exp	(revision 18301)
@@ -0,0 +1,8 @@
+## Name:MassFlux14
+## Icon:0
+# Points Count Value
+2 1.000000
+# X pos Y pos
+-1579674.9916810417 -321516.2892665596
+-1587436.3185859676 -337140.9687259690
+
Index: issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux14.exp
===================================================================
--- issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux14.exp	(revision 18301)
+++ issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux14.exp	(revision 18301)
@@ -0,0 +1,8 @@
+## Name:MassFlux14
+## Icon:0
+# Points Count Value
+2 1.000000
+# X pos Y pos
+-1579674.9916810417 -321516.2892665596
+-1587436.3185859676 -337140.9687259690
+
Index: issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux15.exp
===================================================================
--- issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux15.exp	(revision 18301)
+++ issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux15.exp	(revision 18301)
@@ -0,0 +1,127 @@
+## Name:
+## Icon:0
+# Points Count Value
+121 25000.000000
+# X pos Y pos
+-1712012.0818103175 -348661.1275967784
+-1711738.9446965172 -348380.8584401013
+-1709339.1962288069 -348358.9741029009
+-1707566.1624406802 -348048.0535193763
+-1706142.6423542583 -346463.0619396989
+-1703644.8906504354 -344421.7875470470
+-1701428.0245438961 -343211.6412474416
+-1699098.6802015656 -343202.0651453367
+-1698767.2671226400 -341251.8958583454
+-1694089.8466347910 -339325.0408948531
+-1691249.4280928215 -338644.2293668062
+-1688271.0930389061 -338423.0784381799
+-1686131.0738047434 -339115.2406933784
+-1682853.5065837551 -340300.2702040364
+-1681648.3224467863 -342890.2203795200
+-1681160.5378740367 -343956.3892846339
+-1681343.2453770319 -345059.2736684235
+-1680476.2008784728 -345129.3389066600
+-1679673.6094558411 -346405.5378093903
+-1679898.5797234357 -347818.5803631411
+-1677215.4777375804 -347397.3820658240
+-1674583.5118423651 -349115.8291018623
+-1675803.3920552148 -352985.6713725598
+-1672935.8509424068 -352801.1873251720
+-1668529.5198238282 -353048.3463822120
+-1666370.5689502691 -354473.4893832008
+-1665423.6161039397 -356733.4691418489
+-1662720.0686237188 -357334.8975107344
+-1660276.4961961196 -357869.6209268258
+-1657124.6115999895 -361080.6428832713
+-1655993.6074009922 -363193.2597271361
+-1653688.2093358042 -364017.9494011777
+-1654435.7188006472 -361506.6539926908
+-1652050.9793420888 -355295.4585798742
+-1649364.4081354018 -349945.5944371450
+-1645761.7354861272 -350839.5079576963
+-1645996.5509334437 -351783.7951824765
+-1645345.5744557772 -351250.5634369315
+-1644300.2406060672 -352221.4198542684
+-1644633.1139884400 -348521.7302174515
+-1647057.7191411837 -348406.3266729190
+-1645415.0137059502 -341247.9400814587
+-1644395.7076754270 -340417.8557739360
+-1644169.8943326229 -336477.7151767056
+-1643216.0658811626 -334392.3056475453
+-1641434.0471865973 -334447.2336099123
+-1641190.7738541283 -334332.2252321915
+-1641050.9552025823 -333796.1902735520
+-1639787.1689887117 -331073.8439645328
+-1637807.1154673321 -329711.1825533187
+-1635805.1587214153 -327827.0308139678
+-1632065.9795259857 -326063.4189332099
+-1625929.4636559838 -324999.2470617331
+-1619584.9279456623 -324892.7557348280
+-1615193.9710026928 -325097.1546172730
+-1611296.7956007582 -324995.1262699560
+-1608304.4173934418 -325211.0183405159
+-1603316.9037486394 -326424.5673739603
+-1600245.1111844976 -328836.3685103582
+-1595818.7639296530 -331148.7367850624
+-1591649.1976614639 -334787.7632693424
+-1588371.5600852505 -337840.7799059978
+-1587648.7608976758 -343365.9382903088
+-1587132.8425864622 -345049.3782468919
+-1586012.7810109658 -347625.9740446581
+-1588260.6470941922 -349356.1732009141
+-1584626.3352827206 -352498.3947002917
+-1584121.7278491815 -354575.2387267592
+-1584906.9380743054 -356537.0120279597
+-1585446.5634405916 -359133.6460951389
+-1586894.3150289655 -361098.6217195836
+-1585768.2162689434 -363527.8170254802
+-1584807.6500740163 -365694.8871387623
+-1585744.0045738907 -368358.0113804646
+-1585152.9531241022 -369694.9777909298
+-1584499.3876485692 -371017.3807505022
+-1585456.9434211247 -372944.8898924028
+-1429208.6248950495 -363616.6734221856
+-1415050.5145378630 -326851.1264040734
+-1413047.7406149551 -325411.1419014899
+-1405442.9810691341 -295790.2533492565
+-1388007.7873070226 -266002.2718567938
+-1375120.7873420289 -286146.6923060659
+-1373971.2210923850 -285345.4403176561
+-1346034.9931278315 -322527.8743193840
+-1351274.5360716779 -327267.6902373450
+-1382747.3419384742 -297522.4999399224
+-1382639.2845126297 -296126.1700367680
+-1382479.2357768724 -295804.4343703665
+-1397758.7640077863 -316499.0520702488
+-1408929.4248104726 -362684.2359936420
+-1202573.2098436793 -350320.7957165864
+-1192371.9994205239 -349816.1301302491
+-1233144.4335198263 -292276.3631183850
+-1232225.6096719459 -288608.8406540032
+-1360692.9373680721 -108664.8182541504
+-1424223.8165527256 -81531.7934136631
+-1403445.8481024427 -45960.5859752788
+-1478312.1378749039 59339.3203815984
+-1513118.6444103392 3225.4273728387
+-1524169.2804273698 11860.8708815790
+-1504759.9852699745 36302.7657860445
+-1528911.0294425790 62751.8076344339
+-1622627.2364271644 61937.4929792271
+-1647011.3496706884 32864.6807476235
+-1637527.3859760596 19912.7371761968
+-1650069.2631712460 30042.0704865309
+-1724734.6043381831 -61378.0233897057
+-1718614.9048978437 -69045.3133313945
+-1758091.3164752426 -113926.3236823874
+-1754430.7541207569 -116894.8054778867
+-1760233.4203404333 -126776.6398906443
+-1757170.3120773330 -130521.7753713153
+-1762186.6328915418 -136423.2047200473
+-1765126.7323215308 -132420.4516091067
+-1769785.4415677825 -135199.8713571306
+-1774818.6171028516 -132429.3647437230
+-1793280.1507095622 -153411.6536596067
+-1711636.5537849038 -224740.3773715630
+-1729008.9305659365 -335286.5679692774
+-1712012.0818103175 -348661.1275967784
+
Index: issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux2.exp
===================================================================
--- issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux2.exp	(revision 18301)
+++ issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux2.exp	(revision 18301)
@@ -0,0 +1,171 @@
+## Name:MassFlux2
+## Icon:0
+# Points Count Value
+165 1.000000
+# X pos Y pos
+-1609993.8450579999 -266189.3103270000
+-1609790.4465310001 -265898.8271340000
+-1609587.0480040000 -265608.3439410000
+-1609383.6494770001 -265317.8607480000
+-1609136.7086169999 -265274.3184150000
+-1608933.3100900000 -264983.8352220000
+-1608686.3692300001 -264940.2928890000
+-1608236.0298430000 -264606.2673630000
+-1607989.0889830000 -264562.7250310000
+-1607785.6904559999 -264272.2418380000
+-1607538.7495960000 -264228.6995050000
+-1607291.8087370000 -264185.1571720000
+-1607044.8678770000 -264141.6148390000
+-1606797.9270170000 -264098.0725060000
+-1606304.0452970001 -264010.9878410000
+-1606057.1044369999 -263967.4455080000
+-1605810.1635769999 -263923.9031750000
+-1605563.2227179999 -263880.3608420000
+-1605316.2818580000 -263836.8185100000
+-1605069.3409980000 -263793.2761770000
+-1604778.8578049999 -263996.6747040000
+-1604531.9169449999 -263953.1323710000
+-1604038.0352250000 -263866.0477060000
+-1603791.0943660000 -263822.5053730000
+-1603500.6111730000 -264025.9039000000
+-1603253.6703130000 -263982.3615680000
+-1602963.1871199999 -264185.7600950000
+-1602716.2462599999 -264142.2177620000
+-1602425.7630680001 -264345.6162900000
+-1601888.3390150000 -264505.4724840000
+-1601641.3981550001 -264461.9301510000
+-1601350.9149630000 -264665.3286790000
+-1601060.4317699999 -264868.7272060000
+-1600479.4653840000 -265275.5242610000
+-1600188.9821919999 -265478.9227880000
+-1599898.4989990001 -265682.3213160000
+-1599608.0158060000 -265885.7198430000
+-1599027.0494210001 -266292.5168980000
+-1598736.5662280000 -266495.9154250000
+-1598446.0830349999 -266699.3139520000
+-1598402.5407030000 -266946.2548130000
+-1598605.9392299999 -267236.7380050000
+-1598518.8545639999 -267730.6197260000
+-1598722.2530910000 -268021.1029190000
+-1598678.7107579999 -268268.0437790000
+-1598635.1684250000 -268514.9846390000
+-1598591.6260919999 -268761.9254990000
+-1598795.0246190000 -269052.4086920000
+-1598751.4822869999 -269299.3495520000
+-1598707.9399540001 -269546.2904130000
+-1598620.8552880001 -270040.1721330000
+-1598577.3129550000 -270287.1129930000
+-1598533.7706220001 -270534.0538530000
+-1598737.1691490000 -270824.5370460000
+-1598693.6268170001 -271071.4779060000
+-1598650.0844840000 -271318.4187660000
+-1598606.5421509999 -271565.3596270000
+-1598316.0589580000 -271768.7581540000
+-1598228.9742930001 -272262.6398740000
+-1597938.4911000000 -272466.0384020000
+-1597648.0079069999 -272669.4369290000
+-1597067.0415220000 -273076.2339840000
+-1597023.4991890001 -273323.1748440000
+-1596979.9568560000 -273570.1157040000
+-1596936.4145229999 -273817.0565640000
+-1596892.8721900000 -274063.9974240000
+-1596805.7875250001 -274557.8791450000
+-1596762.2451919999 -274804.8200050000
+-1596718.7028590001 -275051.7608650000
+-1596675.1605260000 -275298.7017250000
+-1596631.6181930001 -275545.6425850000
+-1596341.1350010000 -275749.0411130000
+-1596297.5926679999 -275995.9819730000
+-1595963.5671420000 -276446.3213600000
+-1595920.0248090001 -276693.2622210000
+-1595629.5416170000 -276896.6607480000
+-1595339.0584239999 -277100.0592750000
+-1595048.5752310001 -277303.4578030000
+-1594467.6088459999 -277710.2548570000
+-1594177.1256530001 -277913.6533850000
+-1593886.6424600000 -278117.0519120000
+-1593392.7607410001 -278029.9672470000
+-1593102.2775480000 -278233.3657740000
+-1592898.8790209999 -277942.8825810000
+-1592695.4804940000 -277652.3993880000
+-1592201.5987740001 -277565.3147220000
+-1591998.2002470000 -277274.8315290000
+-1592041.7425800001 -277027.8906690000
+-1591838.3440530000 -276737.4074760000
+-1591881.8863860001 -276490.4666160000
+-1591722.0301910001 -275953.0425630000
+-1591765.5725240000 -275706.1017030000
+-1591562.1739970001 -275415.6185100000
+-1591605.7163300000 -275168.6776500000
+-1591402.3178030001 -274878.1944570000
+-1591198.9192760000 -274587.7112640000
+-1591242.4616090001 -274340.7704040000
+-1591039.0630820000 -274050.2872110000
+-1591082.6054150001 -273803.3463510000
+-1590922.7492209999 -273265.9222970000
+-1590966.2915530000 -273018.9814370000
+-1590762.8930259999 -272728.4982440000
+-1590806.4353590000 -272481.5573840000
+-1590603.0368319999 -272191.0741910000
+-1590399.6383050000 -271900.5909980000
+-1590443.1806379999 -271653.6501380000
+-1590239.7821110000 -271363.1669450000
+-1590036.3835839999 -271072.6837520000
+-1590123.4682499999 -270578.8020320000
+-1589920.0697230001 -270288.3188390000
+-1589716.6711960000 -269997.8356460000
+-1589760.2135280001 -269750.8947860000
+-1589556.8150010000 -269460.4115930000
+-1589600.3573340001 -269213.4707330000
+-1589440.5011400001 -268676.0466800000
+-1589484.0434729999 -268429.1058190000
+-1589280.6449460001 -268138.6226260000
+-1589077.2464190000 -267848.1394340000
+-1588873.8478920001 -267557.6562410000
+-1588423.5085050000 -267223.6307150000
+-1588220.1099779999 -266933.1475220000
+-1587973.1691180000 -266889.6051890000
+-1587726.2282580000 -266846.0628560000
+-1587479.2873980000 -266802.5205230000
+-1586985.4056780001 -266715.4358580000
+-1586738.4648190001 -266671.8935250000
+-1586491.5239589999 -266628.3511920000
+-1586244.5830989999 -266584.8088590000
+-1585997.6422389999 -266541.2665270000
+-1585750.7013790000 -266497.7241940000
+-1585256.8196590000 -266410.6395280000
+-1585009.8787990001 -266367.0971960000
+-1584762.9379400001 -266323.5548630000
+-1584472.4547470000 -266526.9533900000
+-1584428.9124139999 -266773.8942500000
+-1584138.4292210001 -266977.2927780000
+-1583804.4036960001 -267427.6321650000
+-1583760.8613630000 -267674.5730250000
+-1583470.3781699999 -267877.9715530000
+-1583179.8949770001 -268081.3700800000
+-1583136.3526450000 -268328.3109400000
+-1582845.8694519999 -268531.7094680000
+-1582802.3271190000 -268778.6503280000
+-1582468.3015940001 -269228.9897150000
+-1582424.7592610000 -269475.9305750000
+-1582134.2760679999 -269679.3291030000
+-1582090.7337350000 -269926.2699630000
+-1581800.2505419999 -270129.6684900000
+-1581509.7673500001 -270333.0670180000
+-1581219.2841570000 -270536.4655450000
+-1581132.1994910000 -271030.3472650000
+-1580841.7162990000 -271233.7457930000
+-1580551.2331060001 -271437.1443200000
+-1580507.6907730000 -271684.0851800000
+-1580217.2075799999 -271887.4837080000
+-1580173.6652470001 -272134.4245680000
+-1579839.6397220001 -272584.7639550000
+-1579796.0973890000 -272831.7048160000
+-1579505.6141959999 -273035.1033430000
+-1579462.0718640001 -273282.0442030000
+-1579418.5295309999 -273528.9850630000
+-1579128.0463380001 -273732.3835910000
+-1579084.5040050000 -273979.3244510000
+-1578750.4784800000 -274429.6638380000
+-1578706.9361469999 -274676.6046980000
+
Index: issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux3.exp
===================================================================
--- issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux3.exp	(revision 18301)
+++ issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux3.exp	(revision 18301)
@@ -0,0 +1,10 @@
+## Name:MassFlux4
+## Icon:0
+# Points Count Value
+4 1.000000
+# X pos Y pos
+-1605390.0162510793 -209047.7381093690
+-1592454.5133393104 -208141.0538114636
+-1574086.0992045982 -208918.2117810968
+-1560891.8862345938 -210472.5277203633
+
Index: issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux4.exp
===================================================================
--- issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux4.exp	(revision 18301)
+++ issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux4.exp	(revision 18301)
@@ -0,0 +1,8 @@
+## Name:MassFlux5
+## Icon:0
+# Points Count Value
+2 1.000000
+# X pos Y pos
+-1660144.8928561222 -319887.0521198768
+-1630434.8468677206 -298387.4931837295
+
Index: issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux5.exp
===================================================================
--- issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux5.exp	(revision 18301)
+++ issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux5.exp	(revision 18301)
@@ -0,0 +1,8 @@
+## Name:MassFlux6
+## Icon:0
+# Points Count Value
+2 1.000000
+# X pos Y pos
+-1635925.9455644884 -157610.4872330402
+-1625288.0602165582 -120861.2411445094
+
Index: issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux6.exp
===================================================================
--- issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux6.exp	(revision 18301)
+++ issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux6.exp	(revision 18301)
@@ -0,0 +1,8 @@
+## Name:MassFlux7
+## Icon:0
+# Points Count Value
+2 1.000000
+# X pos Y pos
+-1642052.5574172530 -95522.7999921589
+-1610982.9267521810 -78949.7704229522
+
Index: issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux7.exp
===================================================================
--- issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux7.exp	(revision 18301)
+++ issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux7.exp	(revision 18301)
@@ -0,0 +1,8 @@
+## Name:MassFlux8
+## Icon:0
+# Points Count Value
+2 1.000000
+# X pos Y pos
+-1605014.5365509845 -81707.1563440522
+-1566756.1417461073 -82763.2940976564
+
Index: issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux8.exp
===================================================================
--- issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux8.exp	(revision 18301)
+++ issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux8.exp	(revision 18301)
@@ -0,0 +1,8 @@
+## Name:MassFlux9
+## Icon:0
+# Points Count Value
+2 1.000000
+# X pos Y pos
+-1555378.1885604258 -45179.9925785796
+-1550583.9034971579 -68415.0231578706
+
Index: issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux9.exp
===================================================================
--- issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux9.exp	(revision 18301)
+++ issm/trunk/examples/UncertaintyQuantification/MassFluxes/MassFlux9.exp	(revision 18301)
@@ -0,0 +1,8 @@
+## Name:MassFlux10
+## Icon:0
+# Points Count Value
+2 1.000000
+# X pos Y pos
+-1565010.6613481115 -111795.8673475993
+-1537474.3225972611 -138442.9656094175
+
Index: issm/trunk/examples/UncertaintyQuantification/runme.m
===================================================================
--- issm/trunk/examples/UncertaintyQuantification/runme.m	(revision 18301)
+++ issm/trunk/examples/UncertaintyQuantification/runme.m	(revision 18301)
@@ -0,0 +1,291 @@
+%PIG Uncertainty Quantification Application
+steps=[1:3]; 
+
+if any(steps==1) 
+	disp('   Step 1: plot flux gates'); 
+	
+	md = loadmodel('../Pig/Models/PIG.Control_drag');
+
+	texts=cell(1,13);
+	textpositions=cell(1,13);
+
+	for i=1:13,
+		contour=expread(['./MassFluxes/MassFlux' num2str(i) '.exp']);
+		textpositions{i}=[contour.x(end) contour.y(end)];
+	end
+
+	plotmodel(md,'data',md.results.StressbalanceSolution.Vel,'log',10,'expdisp',...
+		{'MassFluxes/MassFlux1.exp','MassFluxes/MassFlux2.exp',...
+		'MassFluxes/MassFlux3.exp','MassFluxes/MassFlux4.exp',...
+		'MassFluxes/MassFlux5.exp','MassFluxes/MassFlux6.exp',...
+		'MassFluxes/MassFlux7.exp','MassFluxes/MassFlux8.exp',...
+		'MassFluxes/MassFlux9.exp','MassFluxes/MassFlux10.exp',...
+		'MassFluxes/MassFlux11.exp','MassFluxes/MassFlux12.exp',...
+		'MassFluxes/MassFlux13.exp'},...
+		'expstyle',{'k-','k-','k-','k-','k-','k-','k-',...
+		'k-','k-','k-','k-','k-','k-'},'linewidth',2,...
+		'text',{'1','2','3','4','5','6','7',...
+		'8','9','10','11','12','13'},...
+		'textposition',textpositions);
+
+end
+if any(steps==2) 
+	disp('   Step 2: compute cross overs from CRESIS'); 
+	
+	md = loadmodel('../Pig/Models/PIG.Control_drag');
+
+	%load cross overs: CRESIS McCord Antarctica, 2009 (courtesy of John Paden)
+	load('../Data/CrossOvers2009.mat');
+	
+	%interpolate cross over errors over our mesh vertices
+	DeltaHH=InterpFromMeshToMesh2d(index,x,y,dhh,md.mesh.x,md.mesh.y);
+
+	%avoid NaN values
+	pos=find(isnan(DeltaHH)); DeltaHH(pos)=0;
+
+	%filter out unrealistic error ranges
+	flags=ContourToNodes(md.mesh.x,md.mesh.y,'ErrorContour.exp',1);
+	pos=find(~flags); DeltaHH(pos)=0; 
+
+	%avoid large unrealistic values
+	pos=find(DeltaHH>1); DeltaHH(pos)=1;
+	pos=find(DeltaHH<-1); DeltaHH(pos)=-1;
+	
+	%transform into absolute errors and setup a minimum error everywhere.
+	DeltaHH=abs(DeltaHH);
+	pos=find(DeltaHH==0); pos2=find(DeltaHH~=0); 
+	DeltaHH(pos)=min(DeltaHH(pos2));
+
+	save Models/PIG.CrossOvers DeltaHH
+
+end
+if any(steps==3) 
+	disp('   Step 3: sampling analysis'); 
+	
+	%load model and cross over errors
+	md = loadmodel('../Pig/Models/PIG.Control_drag');
+	load -mat Models/PIG.CrossOvers
+
+	%partition the mesh
+	md.qmu.numberofpartitions=50;
+	md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions,...
+	'weighting','on');
+	md.qmu.partition=md.qmu.partition-1; %switch partition to c-indexing
+
+	%make DeltaHH into our 3 sigma deviation
+	DeltaHH=DeltaHH/6; %2 (to transform DeltaHH into a radius) x 3 (for 3 sigma)
+	DeltaHH_on_partition=AreaAverageOntoPartition(md,DeltaHH);
+	DeltaHH_on_grids=DeltaHH_on_partition(md.qmu.partition+1); %just to check in case
+	
+	md.qmu.variables.thickness=normal_uncertain('scaled_Thickness',1,1);
+	md.qmu.variables.thickness.stddev=DeltaHH_on_partition;
+
+	%responses
+	md.qmu.responses.MassFlux1=response_function('indexed_MassFlux_1',[],...
+		[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux2=response_function('indexed_MassFlux_2',[],...
+		[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]); %grounding line
+	md.qmu.responses.MassFlux3=response_function('indexed_MassFlux_3',[],...
+		[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux4=response_function('indexed_MassFlux_4',[],...
+		[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux5=response_function('indexed_MassFlux_5',[],...
+		[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux6=response_function('indexed_MassFlux_6',[],...
+		[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux7=response_function('indexed_MassFlux_7',[],...
+		[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux8=response_function('indexed_MassFlux_8',[],...
+		[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux9=response_function('indexed_MassFlux_9',[],...
+		[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux10=response_function('indexed_MassFlux_10',[],...
+		[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux11=response_function('indexed_MassFlux_11',[],...
+		[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux12=response_function('indexed_MassFlux_12',[],...
+		[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux13=response_function('indexed_MassFlux_13',[],...
+		[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+	%mass flux profiles
+	md.qmu.mass_flux_profiles={'MassFlux1.exp',...
+	                           'MassFlux2.exp',...
+	                           'MassFlux3.exp',...
+	                           'MassFlux4.exp',...
+	                           'MassFlux5.exp',...
+	                           'MassFlux6.exp',...
+	                           'MassFlux7.exp',...
+	                           'MassFlux8.exp',...
+	                           'MassFlux9.exp',...
+	                           'MassFlux10.exp',...
+	                           'MassFlux11.exp',...
+	                           'MassFlux12.exp',...
+	                           'MassFlux13.exp'};
+	md.qmu.mass_flux_profile_directory='../MassFluxes/';
+
+	%%  sampling analysis
+	md.qmu.method     =dakota_method('nond_samp');
+	md.qmu.method(end)=dmeth_params_set(md.qmu.method(end),...
+	'seed',1234,...
+	'samples',30,...
+	'sample_type','lhs'); %random or lhs
+
+	%%  a variety of parameters
+	md.qmu.params.direct=true;
+	md.qmu.params.analysis_driver='';
+	md.qmu.params.analysis_components='';
+	md.qmu.params.evaluation_concurrency=1;
+	md.qmu.params.tabular_graphics_data=true;
+
+	md.stressbalance.restol=10^-5; %tighten tolerances for UQ analyses
+	
+	%solve
+	md.qmu.isdakota=1; md.inversion.iscontrol=0;
+	md.cluster=generic('name',oshostname,'np',4);
+	md=solve(md,StressbalanceSolutionEnum,'overwrite','y');
+
+	save ./Models/PIG.Sampling md; 
+end
+if any(steps==4) 
+	disp('   Step 4: sensitivity analysis'); 
+	
+	%load model
+	md = loadmodel('../Pig/Models/PIG.Control_drag');
+
+	%partition the mesh
+	md.qmu.numberofpartitions=10;
+	md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions,'weighting','on');
+	md.qmu.partition=md.qmu.partition-1; %switch partition to c-indexing
+
+	%all types of variables and responses: scaled_Thickness, indexed_MassFlux_i,MaxVel,nodal_DragCoefficient_i. scaled variables are expanded.
+
+	%variables
+	md.qmu.variables.DragCoefficient=normal_uncertain(...
+	'scaled_FrictionCoefficient',1,0.05);
+	md.qmu.variables.rheology_B=normal_uncertain(...
+	'scaled_MaterialsRheologyB',1,0.05);
+	md.qmu.variables.Thickness=normal_uncertain('scaled_Thickness',1,0.05);
+
+	%responses
+	md.qmu.responses.MassFlux1=response_function('indexed_MassFlux_1',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux2=response_function('indexed_MassFlux_2',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux3=response_function('indexed_MassFlux_3',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux4=response_function('indexed_MassFlux_4',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux5=response_function('indexed_MassFlux_5',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux6=response_function('indexed_MassFlux_6',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux7=response_function('indexed_MassFlux_7',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux8=response_function('indexed_MassFlux_8',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux9=response_function('indexed_MassFlux_9',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux10=response_function('indexed_MassFlux_10',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux11=response_function('indexed_MassFlux_11',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux12=response_function('indexed_MassFlux_12',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+	md.qmu.responses.MassFlux13=response_function('indexed_MassFlux_13',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+	%mass flux profiles
+	md.qmu.mass_flux_profiles={'MassFlux1.exp',...
+	                           'MassFlux2.exp',...
+	                           'MassFlux3.exp',...
+	                           'MassFlux4.exp',...
+	                           'MassFlux5.exp',...
+	                           'MassFlux6.exp',...
+	                           'MassFlux7.exp',...
+	                           'MassFlux8.exp',...
+	                           'MassFlux9.exp',...
+	                           'MassFlux10.exp',...
+	                           'MassFlux11.exp',...
+	                           'MassFlux12.exp',...
+	                           'MassFlux13.exp'};
+	md.qmu.mass_flux_profile_directory='../MassFluxes/';
+
+	%method: local reliability
+	md.qmu.method     =dakota_method('nond_l');
+	md.qmu.method(end)=dmeth_params_set(md.qmu.method(end),...
+	'output','quiet');
+
+	%parameters
+	md.qmu.params.direct=true;
+	md.qmu.params.analysis_driver='';
+	md.qmu.params.analysis_components='';
+	md.qmu.params.evaluation_concurrency=1;
+	md.qmu.params.tabular_graphics_data=false;
+
+	md.stressbalance.restol=10^-5; %tighten for qmu analyses
+	
+	%solve
+	md.qmu.isdakota=1; 
+	md.inversion.iscontrol=0;
+	md.cluster=generic('name',oshostname,'np',2);
+	md.verbose=verbose('qmu',true);
+	md=solve(md,StressbalanceSolutionEnum,'overwrite','y');
+	
+	save ./Models/PIG.Sensitivity md; 
+end
+if any(steps==5) 
+	disp('   Step 5: plot partition');
+	
+	%load model
+	md = loadmodel('./Models/PIG.Sampling');
+	
+	plotmodel(md,'data','mesh','partitionedges','on','meshlinewidth',1.5,...
+	'linewidth',2, 'axis#all','image','unit','km','colorbar','off',...
+	'title','','meshcolor','b','grid','on');
+
+end 
+if any(steps==6) 
+	disp('   Step 6: plot histogram'); 
+	
+	%load model
+	md = loadmodel('./Models/PIG.Sampling');
+
+	%which profile are we looking at?
+	index=1; 	
+
+	%retrieve results for the specific profile, mass flux in m^3 water equiv/s
+	result=md.results.dakota.dresp_dat(md.qmu.numberofpartitions+index);
+	result.sample=result.sample/1e12*60*60*24*365;
+		
+	%plot histogram
+	plot_hist_norm(result,'cdfleg','off','cdfplt','off','nrmplt','off',...
+	'xlabelplt','M (Gt/yr)','ylabelplt','F','FontSize',8,'FaceColor',...
+	'none','EdgeColor','red');
+
+end
+if any(steps==7) 
+	disp('   Step 7: plot sensitivity'); 
+	
+	%load model
+	md = loadmodel('./Models/PIG.Sensitivity');
+	%copy dakota results into model qmu
+	md.qmu.results=md.results.dakota;
+
+	%which profile are we looking at?
+	index=1; 	
+
+	%To plot sensitivities
+	sa=md.results.dakota.dresp_out(index).sens(1:10); sa=sa(md.qmu.partition+1)/1e12*60*60*24*365;
+	sb=md.results.dakota.dresp_out(index).sens(11:20); sb=sb(md.qmu.partition+1)/1e12*60*60*24*365;
+	sh=md.results.dakota.dresp_out(index).sens(21:30); sh=sh(md.qmu.partition+1)/1e12*60*60*24*365;
+
+	plotmodel(md,'data',sh,'data',sa,'data',sb,'expdisp#all',...
+		['MassFluxes/MassFlux' num2str(index) '.exp'],...
+		'expstyle#all','b-','linewidth#all',2,...
+		'nlines',3,'ncols',1, 'axis#all','image',...
+		'colorbar#all','on','colorbarfontsize#all',10,...
+		'colorbartitle#1','S_{H}', 'colorbartitle#2','S_{\alpha}',...
+		'colorbartitle#3','S_{B}','unit#all','km','figure',1);
+
+	%To plot importance factors
+	ifa=importancefactors(md,'scaled_FrictionCoefficient',['indexed_MassFlux_' num2str(index)]);
+	ifb=importancefactors(md,'scaled_MaterialsRheologyB',['indexed_MassFlux_' num2str(index)]);
+	ifh=importancefactors(md,'scaled_Thickness',['indexed_MassFlux_' num2str(index)]);
+
+	plotmodel(md,'data',ifh,'data',ifa,'data',ifb,'expdisp#all',...
+		['MassFluxes/MassFlux' num2str(index) '.exp'],...
+		'expstyle#all','b-','linewidth#all',2,'log#all',10,...
+		'nlines',3,'ncols',1, 'axis#all','image','caxis#all',[1e-10 1],...
+		'colorbar#all','on','colorbarfontsize#all',10,...
+		'colorbartitle#1','If_{H}', 'colorbartitle#2','If_{\alpha}',...
+		'colorbartitle#3','If_{B}','unit#all','km','figure',2);
+
+end
Index: issm/trunk/externalpackages/android/android-ndk/android_aux.sh
===================================================================
--- issm/trunk/externalpackages/android/android-ndk/android_aux.sh	(revision 18301)
+++ issm/trunk/externalpackages/android/android-ndk/android_aux.sh	(revision 18301)
@@ -0,0 +1,43 @@
+#!/bin/bash
+#
+# android_aux.sh serves as an auxiliary script for all installation
+# scripts with the Android suffix.
+#
+# TODO: include M4 macros for generic options.
+#
+
+sdk_rev=22.6.2
+ndk_rev=9
+api_levels="android-14,android-15,android-16"
+host_triplet="arm-linux-androideabi"
+default_droid="android-4.1"
+
+step=0;
+j=1;
+
+echo ""
+echo "This install script utilizes 'android_aux.sh' to allow for options."
+echo "For usage information enter: '--help'"
+echo Number of arguments is: $#
+
+for arg in $* 
+do 
+    if [[ "$arg" =~ --step=([0-9])* ]]; then
+        step=${BASH_REMATCH[1]}; 
+        echo "Setting step to: " $step
+    elif [[ "$arg" == "--help" ]]; then
+        echo ""
+        echo "USAGE: $ install.sh [--step=#] [-j#]"
+        echo ""
+        echo "Where '#' is some integer."
+        echo "To check the number of steps check the install script."
+        echo ""
+        exit 1;
+    elif [[ "$arg" =~ -j=([1-9]+[0-9]*) ]]; then
+        j=${BASH_REMATCH[1]}; 
+        echo "Number of jobs set to: " $j
+    else
+        echo "Option not recognized"
+        exit 1;
+    fi
+done
Index: issm/trunk/externalpackages/android/android-ndk/installNDK-linux-x86.sh
===================================================================
--- issm/trunk/externalpackages/android/android-ndk/installNDK-linux-x86.sh	(revision 18301)
+++ issm/trunk/externalpackages/android/android-ndk/installNDK-linux-x86.sh	(revision 18301)
@@ -0,0 +1,39 @@
+#!/bin/bash
+
+# This installs the Android NDK (Native Development Kit)
+# which is needed for the compilation of C/C++ code into the 
+# native architecture of the Android device.
+
+# The android-ndk-r8-darwin-x86.tar.bz2 ndk.tar.bz2 file was downloaded 
+# from the android developer website: 
+source $ANDROID_DIR/android_aux.sh
+
+if [[ $step == "1" || $step == "0" ]]; then
+    # Cleanup the install
+    rm -rf install
+    rm -rf $ANDROID_DIR/arm-linux-android-${default_droid}
+
+    # Download from ISSM server
+#    $ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/android-ndk-r'${ndk_rev}'-darwin-x86.tar.bz2' 'ndk.tar.bz2'
+    # Download from google
+#    if ["$(uname -m)" = "x86_64"]; then
+#	wget 'https://dl.google.com/android/ndk/android-ndk-r'${ndk_rev}'d-linux-x86_64.tar.bz2' 'ndk.tar.bz2'
+#   fi
+
+#    if ["$(uname -m)" = "x86"]; then
+	wget 'https://dl.google.com/android/ndk/android-ndk-r'${ndk_rev}'d-linux-x86.tar.bz2'
+ #   fi
+    # Install Android NDK
+    mv 'android-ndk-r'${ndk_rev}'d-linux-x86.tar.bz2' ndk.tar.bz2
+    tar -xvf ndk.tar.bz2
+    rm -rf ndk.tar ndk.tar.bz2
+
+    # Move to install
+    mv android-ndk-r${ndk_rev}d install
+fi
+
+# Create Standalone Development Directory
+# Note: API-14 corresponds to Android 4.0.
+if [[ $step == "2" || $step == "0" ]]; then
+    $ANDROID_DIR/android-ndk/install/build/tools/make-standalone-toolchain.sh --platform=android-14 --install-dir=$ANDROID_DIR/android-ndk/install/arm-linux-android-install
+fi
Index: issm/trunk/externalpackages/android/android-sdk/installSDK-linux-x86.sh
===================================================================
--- issm/trunk/externalpackages/android/android-sdk/installSDK-linux-x86.sh	(revision 18301)
+++ issm/trunk/externalpackages/android/android-sdk/installSDK-linux-x86.sh	(revision 18301)
@@ -0,0 +1,85 @@
+#!/bin/bash
+
+# This installs the Android SDK (Software Development Kit)
+# which is needed for the compilation of the Java project. 
+
+source $ANDROID_DIR/android_aux.sh
+
+# Different steps here. 
+#   0: do all
+#   1: install sdk, ant and sdk tools
+#   2: install an emulator.
+#   3: test the emulator
+#   4: cleanup
+
+present_dir=`pwd`;
+sd_card="issm-sdcard"
+
+if [[ $step == "1" || $step == "0" ]]; then
+
+	# Cleanup the install
+	rm -rf install
+
+	# Download from ISSM server
+#	$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://developer.android.com/sdk/index.html#download' 'android-sdk-linux.zip'
+	
+	#Download from Google server
+	wget https://dl.google.com/android/android-sdk_r$sdk_rev-linux.tgz
+
+	# Install Android SDK.
+	tar -zxvf android-sdk_r$sdk_rev-linux.tgz
+	rm -rf android-sdk_r$sdk_rev-linux.tgz
+	# Move to install
+	mv -f android-sdk-linux install
+
+	# Post_install configuration: 
+	# We need specific settings for specific platforms, for the SDK to 
+	# function properly
+
+	# For now, we need to install:  
+	# android sdk platform tools  
+	# and a specific android api: API 16, API 15 and API 14
+	# Note: API 16, API 15 and 14 correspond to Android 4.1, 4.0.3 and 4.0 respectively. 
+
+	cd install/tools/ && source ./android update sdk -t platform-tool,${api_levels},system-image --no-ui
+
+fi
+
+if [[ $step == "2" || $step == "0" ]]; then
+
+	# Once this is done, we need to install an emulator. Location will default to ~/.android/avd, 
+	# which we will move to $ISSM_DIR/externalpackages/android-emulators.  
+	# For now, it's called: Android-4.0.3
+
+	# Here we delete the Android-4.0.3 device if it already exists.
+	cd $present_dir/install/tools
+
+    if [ -e $ANDROID_DIR/android-emulators/$default_droid ] 
+    then
+        echo "Deleting previously created device: $default_droid"
+	    ./android delete avd -n $default_droid
+    fi
+
+	# Android will prompt the user to specify hardware emulation options. For now, default
+	# default settings will suffice. Press 'enter' to take default settings or enter 'no'.
+
+	./android create avd -f -n $default_droid -t 1 -p $ANDROID_DIR/android-emulators/$default_droid --abi armeabi-v7a
+    echo "Creating an SD Card"
+    ./mksdcard -l $sd_card 2G $ANDROID_DIR/android-emulators/$sd_card.img
+fi
+
+if [[ $step == "3" || $step == "0" ]]; then
+    # Here we will start up our default emulator to test that it is working properly.
+    # Once the device has booted we will use the Android Debug Bridge tool to gain
+    # a terminal in our device.
+
+	cd $present_dir/install/tools
+	./emulator -avd $default_droid -sdcard $ANDROID_DIR/android-emulators/$sd_card.img &
+
+    cd ../platform-tools
+    ./adb wait-for-device shell
+fi
+
+#if [[ $step == "4" || $step == "0" ]]; then
+#	rm -rf install
+#fi
Index: issm/trunk/externalpackages/autotools/install.sh
===================================================================
--- issm/trunk/externalpackages/autotools/install.sh	(revision 18081)
+++ issm/trunk/externalpackages/autotools/install.sh	(revision 18301)
@@ -10,7 +10,7 @@
 echo " === INSTALLING AUTOCONF =="
 rm -rf src
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/autoconf-2.68.tar.gz' 'autoconf-2.68.tar.gz'
-tar -zxvf autoconf-2.68.tar.gz
-mv autoconf-2.68 src
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/autoconf-2.69.tar.gz' 'autoconf-2.69.tar.gz'
+tar -zxvf autoconf-2.69.tar.gz
+mv autoconf-2.69 src
 cd src 
 ./configure --prefix="$ISSM_DIR/externalpackages/autotools/install" 
@@ -22,7 +22,7 @@
 echo " === INSTALLING AUTOMAKE =="
 rm -rf src
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/automake-1.11.3.tar.gz' 'automake-1.11.3.tar.gz'
-tar -zxvf  automake-1.11.3.tar.gz
-mv automake-1.11.3 src
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/automake-1.14.tar.gz' 'automake-1.14.tar.gz'
+tar -zxvf  automake-1.14.tar.gz
+mv automake-1.14 src
 cd src 
 ./configure --prefix="$ISSM_DIR/externalpackages/autotools/install" 
Index: issm/trunk/externalpackages/boost/configs/1.55/cas128strong.hpp.patch
===================================================================
--- issm/trunk/externalpackages/boost/configs/1.55/cas128strong.hpp.patch	(revision 18301)
+++ issm/trunk/externalpackages/boost/configs/1.55/cas128strong.hpp.patch	(revision 18301)
@@ -0,0 +1,17 @@
+199c199
+<     explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : v_(0)
+---
+>     explicit base_atomic(value_type const& v) BOOST_NOEXCEPT 
+200a201
+> 	memset(&v_, 0, sizeof(v_));
+207c208,209
+<         storage_type value_s = 0;
+---
+> 	storage_type value_s;
+> 	memset(&value_s, 0, sizeof(value_s));
+250c252,254
+<         storage_type expected_s = 0, desired_s = 0;
+---
+> 	storage_type expected_s, desired_s; 
+> 	memset(&expected_s, 0, sizeof(expected_s));
+> 	memset(&desired_s, 0, sizeof(desired_s));
Index: issm/trunk/externalpackages/boost/configs/1.55/gcc-atomic.hpp.patch
===================================================================
--- issm/trunk/externalpackages/boost/configs/1.55/gcc-atomic.hpp.patch	(revision 18301)
+++ issm/trunk/externalpackages/boost/configs/1.55/gcc-atomic.hpp.patch	(revision 18301)
@@ -0,0 +1,28 @@
+961c961
+<     explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : v_(0)
+---
+>     explicit base_atomic(value_type const& v) BOOST_NOEXCEPT
+962a963
+>         memset(&v_, 0, sizeof(v_));
+968c969,970
+<         storage_type tmp = 0;
+---
+>         storage_type tmp;
+>         memset(&tmp, 0, sizeof(tmp));
+983c985,986
+<         storage_type tmp = 0;
+---
+>         storage_type tmp;
+>         memset(&tmp, 0, sizeof(tmp));
+997c1000,1002
+<         storage_type expected_s = 0, desired_s = 0;
+---
+> 	storage_type expected_s, desired_s;
+> 	memset(&expected_s, 0, sizeof(expected_s));
+> 	memset(&desired_s, 0, sizeof(desired_s));
+1013c1018,1020
+<         storage_type expected_s = 0, desired_s = 0;
+---
+> 	storage_type expected_s, desired_s;
+> 	memset(&expected_s, 0, sizeof(expected_s));
+> 	memset(&desired_s, 0, sizeof(desired_s));
Index: issm/trunk/externalpackages/boost/install-1.49-linux.sh
===================================================================
--- issm/trunk/externalpackages/boost/install-1.49-linux.sh	(revision 18301)
+++ issm/trunk/externalpackages/boost/install-1.49-linux.sh	(revision 18301)
@@ -0,0 +1,35 @@
+#!/bin/bash
+set -eu
+
+#Note of caution:  stop after boostrap phase, and run 
+#bjam --debug-configuration, to figure out which paths boost is using to include 
+#python. make sure everyone of these paths is covered by python. If not, just make 
+#symlinks in externalpackages/python to what boost is expecting. Ther is NO WAY 
+#to get the boost library to include python support without doing that. 
+
+#Some cleanup
+rm -rf install boost_1_49_0 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/boost_1_49_0.tar.gz' 'boost_1_49_0.tar.gz'
+
+#Untar 
+tar -zxvf  boost_1_49_0.tar.gz
+
+#Move boost into install directory
+mv boost_1_49_0/* src
+rm -rf boost_1_49_0
+#Configure and compile
+cd src 
+./bootstrap.sh \
+	--prefix="$ISSM_DIR/externalpackages/boost/install" \
+	--with-python=python3.2 \
+	--with-python-root="$ISSM_DIR/externalpackages/python/install" 
+
+#Compile boost
+./bjam install
+
+#put bjam into install also: 
+mkdir ../install/bin
+cp bjam ../install/bin
Index: issm/trunk/externalpackages/boost/install-1.55-macosx-mavericks.sh
===================================================================
--- issm/trunk/externalpackages/boost/install-1.55-macosx-mavericks.sh	(revision 18301)
+++ issm/trunk/externalpackages/boost/install-1.55-macosx-mavericks.sh	(revision 18301)
@@ -0,0 +1,40 @@
+#!/bin/bash
+set -eu
+
+#Note of caution:  stop after boostrap phase, and run 
+#bjam --debug-configuration, to figure out which paths boost is using to include 
+#python. make sure everyone of these paths is covered by python. If not, just make 
+#symlinks in externalpackages/python to what boost is expecting. Ther is NO WAY 
+#to get the boost library to include python support without doing that. 
+
+#Some cleanup
+rm -rf install boost_1_55_0 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/boost_1_55_0.tar.gz' 'boost_1_55_0.tar.gz'
+
+#Untar 
+tar -zxvf  boost_1_55_0.tar.gz
+
+#Move boost into install directory
+mv boost_1_55_0/* src
+rm -rf boost_1_55_0
+
+patch src/boost/atomic/detail/cas128strong.hpp ./configs/1.55/cas128strong.hpp.patch
+patch src/boost/atomic/detail/gcc-atomic.hpp ./configs/1.55/gcc-atomic.hpp.patch
+
+#Configure and compile
+cd src 
+./bootstrap.sh \
+	--prefix="$ISSM_DIR/externalpackages/boost/install" \
+	--with-python=python3.2 \
+	--with-python-root="$ISSM_DIR/externalpackages/python/install" 
+
+#Compile boost
+./b2 toolset=clang cxxflags=-stdlib=libstdc++ linkflags=-stdlib=libstdc++ -j2 variant=release link=static threading=multi install
+#./bjam install
+
+#put bjam into install also: 
+mkdir ../install/bin
+cp bjam ../install/bin
Index: issm/trunk/externalpackages/dakota/install-5.2-discover.sh
===================================================================
--- issm/trunk/externalpackages/dakota/install-5.2-discover.sh	(revision 18301)
+++ issm/trunk/externalpackages/dakota/install-5.2-discover.sh	(revision 18301)
@@ -0,0 +1,52 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf Dakota
+rm -rf src
+rm -rf install
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/Dakota_5_2.src.tar.gz' 'Dakota_5_2.src.tar.gz'
+
+#Untar 
+tar -zxvf Dakota_5_2.src.tar.gz
+
+#Move Dakota to src directory
+mv Dakota/* src
+rm -rf Dakota
+
+#Apply patches
+patch src/src/ParallelLibrary.C configs/5.2/ParallelLibrary.C.patch
+patch src/src/ParallelLibrary.H configs/5.2/ParallelLibrary.H.patch
+#patch src/src/NIDRProblemDescDB.C configs/5.2/NIDRProblemDescDB.C.patch    #  causes segfault in 5.2
+patch src/src/NonDSampling.C configs/5.2/NonDSampling.C.patch
+patch src/src/NonDLocalReliability.C configs/5.2/NonDLocalReliability.C.patch
+patch src/src/NonDUnilevelRBDO.C configs/5.2/NonDUnilevelRBDO.C.patch    #  source not even used?
+patch src/packages/pecos/src/pecos_global_defs.hpp configs/5.2/pecos_global_defs.hpp.patch
+
+#Configure dakota
+cd src
+./configure \
+--prefix="$ISSM_DIR/externalpackages/dakota/install/" \
+--without-graphics  \
+--with-pic \
+--disable-mpi \
+--with-plugin \
+--with-blas="-L/usr/local/intel/mkl/10.1.2.024/lib/64 -lmkl_lapack -lmkl -lguide -lpthread" \
+--with-lapack="-L/usr/local/intel/mkl/10.1.2.024/lib/64 -lmkl_lapack -lmkl -lguide -lpthread"
+
+cd ..
+
+#Compile and install dakota
+cd src
+if [ $# -eq 0 ];
+then
+	make
+	make install
+else
+	make -j $1
+	make -j $1 install
+fi
+cd ..
Index: issm/trunk/externalpackages/dakota/install-5.3.1-macosx64.sh
===================================================================
--- issm/trunk/externalpackages/dakota/install-5.3.1-macosx64.sh	(revision 18301)
+++ issm/trunk/externalpackages/dakota/install-5.3.1-macosx64.sh	(revision 18301)
@@ -0,0 +1,50 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf Dakota
+rm -rf src 
+rm -rf build 
+rm -rf install 
+mkdir src build install 
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/dakota-5.3.1-public-src.tar.gz' 'dakota-5.3.1-public-src.tar.gz'
+
+#Untar 
+tar -zxvf dakota-5.3.1-public-src.tar.gz
+
+#Move Dakota to src directory
+mv dakota-5.3.1.src/* src
+rm -rf dakota-5.3.1.src
+
+#Set up Dakota cmake variables and config
+export DAK_SRC=$ISSM_DIR/externalpackages/dakota/src
+export DAK_BUILD=$ISSM_DIR/externalpackages/dakota/build
+cp $DAK_SRC/cmake/BuildDakotaTemplate.cmake $DAK_SRC/cmake/BuildDakotaCustom.cmake
+patch $DAK_SRC/cmake/BuildDakotaCustom.cmake configs/5.3.1/BuildDakotaCustom.cmake.patch
+patch $DAK_SRC/cmake/DakotaDev.cmake configs/5.3.1/DakotaDev.cmake.patch
+
+#Apply patches
+patch src/src/ParallelLibrary.cpp configs/5.3.1/ParallelLibrary.cpp.patch
+patch src/src/ParallelLibrary.hpp configs/5.3.1/ParallelLibrary.hpp.patch
+patch src/src/NonDSampling.cpp configs/5.3.1/NonDSampling.cpp.patch
+patch src/src/NonDLocalReliability.cpp configs/5.3.1/NonDLocalReliability.cpp.patch
+patch src/packages/pecos/src/pecos_global_defs.hpp configs/5.3.1/pecos_global_defs.hpp.patch
+
+#Configure dakota
+cd $DAK_BUILD
+cmake -D CMAKE_C_COMPILER=/usr/local/gfortran/bin/x86_64-apple-darwin10-gcc -D CMAKE_CXX_COMPILER=/usr/local/gfortran/bin/x86_64-apple-darwin10-g++ -D CMAKE_Fortran_COMPILER=/usr/local/gfortran/bin/x86_64-apple-darwin10-gfortran -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/gsl/finite.patch
===================================================================
--- issm/trunk/externalpackages/gsl/finite.patch	(revision 18301)
+++ issm/trunk/externalpackages/gsl/finite.patch	(revision 18301)
@@ -0,0 +1,354 @@
+diff -ruN src/gsl_math.h src-mod/gsl_math.h
+--- src/gsl_math.h	2010-12-26 09:57:08.000000000 -0800
++++ src-mod/gsl_math.h	2014-05-27 18:47:26.000000000 -0700
+@@ -116,7 +116,7 @@
+ #define GSL_SIGN(x)    ((x) >= 0.0 ? 1 : -1)
+ 
+ /* Return nonzero if x is a real number, i.e. non NaN or infinite. */
+-#define GSL_IS_REAL(x) (gsl_finite(x))
++#define GSL_IS_REAL(x) (isfinite(x))
+ 
+ /* Definition of an arbitrary function with parameters */
+ 
+diff -ruN src/integration/cquad.c src-mod/integration/cquad.c
+--- src/integration/cquad.c	2011-05-01 11:46:28.000000000 -0700
++++ src-mod/integration/cquad.c	2014-05-27 18:47:26.000000000 -0700
+@@ -235,7 +235,7 @@
+     {
+       iv->fx[i] = GSL_FN_EVAL (f, m + xi[i] * h);
+       neval++;
+-      if (!finite (iv->fx[i]))
++      if (!isfinite (iv->fx[i]))
+ 	{
+ 	  nans[nnans++] = i;
+ 	  iv->fx[i] = 0.0;
+@@ -319,7 +319,7 @@
+ 	  nnans = 0;
+ 	  for (i = 0; i <= 32; i += skip[d])
+ 	    {
+-	      if (!finite (iv->fx[i]))
++	      if (!isfinite (iv->fx[i]))
+ 		{
+ 		  nans[nnans++] = i;
+ 		  iv->fx[i] = 0.0;
+@@ -444,7 +444,7 @@
+ 	  nnans = 0;
+ 	  for (i = 0; i <= 32; i += skip[0])
+ 	    {
+-	      if (!finite (ivl->fx[i]))
++	      if (!isfinite (ivl->fx[i]))
+ 		{
+ 		  nans[nnans++] = i;
+ 		  ivl->fx[i] = 0.0;
+@@ -510,7 +510,7 @@
+ 	  nnans = 0;
+ 	  for (i = 0; i <= 32; i += skip[0])
+ 	    {
+-	      if (!finite (ivr->fx[i]))
++	      if (!isfinite (ivr->fx[i]))
+ 		{
+ 		  nans[nnans++] = i;
+ 		  ivr->fx[i] = 0.0;
+diff -ruN src/linalg/balance.c src-mod/linalg/balance.c
+--- src/linalg/balance.c	2010-12-26 09:57:08.000000000 -0800
++++ src-mod/linalg/balance.c	2014-05-27 18:47:27.000000000 -0700
+@@ -54,7 +54,7 @@
+       
+       double f = 1.0;
+       
+-      if (s == 0.0 || !gsl_finite(s))
++      if (s == 0.0 || !isfinite(s))
+         {
+           gsl_vector_set (D, j, f);
+           continue;
+diff -ruN src/min/min.h src-mod/min/min.h
+--- src/min/min.h	2010-12-26 09:57:08.000000000 -0800
++++ src-mod/min/min.h	2014-05-27 18:47:27.000000000 -0700
+@@ -20,6 +20,6 @@
+ #define SAFE_FUNC_CALL(f, x, yp) \
+ do { \
+   *yp = GSL_FN_EVAL(f,x); \
+-  if (!gsl_finite(*yp)) \
++  if (!isfinite(*yp)) \
+     GSL_ERROR("computed function value is infinite or NaN", GSL_EBADFUNC); \
+ } while (0)
+diff -ruN src/multimin/simplex.c src-mod/multimin/simplex.c
+--- src/multimin/simplex.c	2010-12-26 09:57:08.000000000 -0800
++++ src-mod/multimin/simplex.c	2014-05-27 18:47:27.000000000 -0700
+@@ -122,7 +122,7 @@
+ 	     we finish the contraction (and do not abort) to allow the user
+ 	     to handle the situation */
+ 
+-          if(!gsl_finite(newval))
++          if(!isfinite(newval))
+ 	    {
+ 	      status = GSL_EBADFUNC;
+ 	    }
+@@ -260,7 +260,7 @@
+ 
+   val = GSL_MULTIMIN_FN_EVAL (f, x);
+   
+-  if (!gsl_finite(val))
++  if (!isfinite(val))
+     {
+       GSL_ERROR("non-finite function value encountered", GSL_EBADFUNC);
+     }
+@@ -283,7 +283,7 @@
+       gsl_vector_set (xtemp, i, val);
+       val = GSL_MULTIMIN_FN_EVAL (f, xtemp);
+   
+-      if (!gsl_finite(val))
++      if (!isfinite(val))
+         {
+           GSL_ERROR("non-finite function value encountered", GSL_EBADFUNC);
+         }
+@@ -374,14 +374,14 @@
+ 
+   val = nmsimplex_move_corner (-1.0, state, hi, xc, f);
+ 
+-  if (gsl_finite(val) && val < gsl_vector_get (y1, lo))
++  if (isfinite(val) && val < gsl_vector_get (y1, lo))
+     {
+ 
+       /* reflected point becomes lowest point, try expansion */
+ 
+       val2 = nmsimplex_move_corner (-2.0, state, hi, xc2, f);
+ 
+-      if (gsl_finite(val2) && val2 < gsl_vector_get (y1, lo))
++      if (isfinite(val2) && val2 < gsl_vector_get (y1, lo))
+         {
+           gsl_matrix_set_row (x1, hi, xc2);
+           gsl_vector_set (y1, hi, val2);
+@@ -397,9 +397,9 @@
+      or
+      we got a non-finite (illegal) function value */
+ 
+-  else if (!gsl_finite(val) || val > gsl_vector_get (y1, s_hi))
++  else if (!isfinite(val) || val > gsl_vector_get (y1, s_hi))
+     {
+-      if (gsl_finite(val) && val <= gsl_vector_get (y1, hi))
++      if (isfinite(val) && val <= gsl_vector_get (y1, hi))
+         {
+ 
+           /* if trial point is better than highest point, replace 
+@@ -413,7 +413,7 @@
+ 
+       val2 = nmsimplex_move_corner (0.5, state, hi, xc2, f);
+ 
+-      if (gsl_finite(val2) && val2 <= gsl_vector_get (y1, hi))
++      if (isfinite(val2) && val2 <= gsl_vector_get (y1, hi))
+         {
+           gsl_matrix_set_row (state->x1, hi, xc2);
+           gsl_vector_set (y1, hi, val2);
+diff -ruN src/multimin/simplex2.c src-mod/multimin/simplex2.c
+--- src/multimin/simplex2.c	2010-12-26 09:57:08.000000000 -0800
++++ src-mod/multimin/simplex2.c	2014-05-27 18:47:27.000000000 -0700
+@@ -171,7 +171,7 @@
+ 	     we finish the contraction (and do not abort) to allow the user
+ 	     to handle the situation */
+ 
+-	  if (!gsl_finite (newval))
++	  if (!isfinite (newval))
+ 	    {
+ 	      status = GSL_EBADFUNC;
+ 	    }
+@@ -367,7 +367,7 @@
+ 
+   val = GSL_MULTIMIN_FN_EVAL (f, x);
+ 
+-  if (!gsl_finite (val))
++  if (!isfinite (val))
+     {
+       GSL_ERROR ("non-finite function value encountered", GSL_EBADFUNC);
+     }
+@@ -394,7 +394,7 @@
+ 	val = GSL_MULTIMIN_FN_EVAL (f, xtemp);
+       }
+ 
+-      if (!gsl_finite (val))
++      if (!isfinite (val))
+ 	{
+ 	  GSL_ERROR ("non-finite function value encountered", GSL_EBADFUNC);
+ 	}
+@@ -477,13 +477,13 @@
+ 
+   val = try_corner_move (-1.0, state, hi, xc, f);
+ 
+-  if (gsl_finite (val) && val < gsl_vector_get (y1, lo))
++  if (isfinite (val) && val < gsl_vector_get (y1, lo))
+     {
+       /* reflected point is lowest, try expansion */
+ 
+       val2 = try_corner_move (-2.0, state, hi, xc2, f);
+ 
+-      if (gsl_finite (val2) && val2 < gsl_vector_get (y1, lo))
++      if (isfinite (val2) && val2 < gsl_vector_get (y1, lo))
+ 	{
+ 	  update_point (state, hi, xc2, val2);
+ 	}
+@@ -492,12 +492,12 @@
+ 	  update_point (state, hi, xc, val);
+ 	}
+     }
+-  else if (!gsl_finite (val) || val > gsl_vector_get (y1, s_hi))
++  else if (!isfinite (val) || val > gsl_vector_get (y1, s_hi))
+     {
+       /* reflection does not improve things enough, or we got a
+          non-finite function value */
+ 
+-      if (gsl_finite (val) && val <= gsl_vector_get (y1, hi))
++      if (isfinite (val) && val <= gsl_vector_get (y1, hi))
+ 	{
+ 	  /* if trial point is better than highest point, replace
+ 	     highest point */
+@@ -509,7 +509,7 @@
+ 
+       val2 = try_corner_move (0.5, state, hi, xc2, f);
+ 
+-      if (gsl_finite (val2) && val2 <= gsl_vector_get (y1, hi))
++      if (isfinite (val2) && val2 <= gsl_vector_get (y1, hi))
+ 	{
+ 	  update_point (state, hi, xc2, val2);
+ 	}
+@@ -605,7 +605,7 @@
+ 
+   val = GSL_MULTIMIN_FN_EVAL (f, x);
+ 
+-  if (!gsl_finite (val))
++  if (!isfinite (val))
+     {
+       GSL_ERROR ("non-finite function value encountered", GSL_EBADFUNC);
+     }
+@@ -669,7 +669,7 @@
+ 
+ 	val = GSL_MULTIMIN_FN_EVAL (f, &r_i.vector);
+ 
+-	if (!gsl_finite (val))
++	if (!isfinite (val))
+ 	  {
+ 	    GSL_ERROR ("non-finite function value encountered", GSL_EBADFUNC);
+ 	  }
+diff -ruN src/roots/newton.c src-mod/roots/newton.c
+--- src/roots/newton.c	2010-12-26 09:57:08.000000000 -0800
++++ src-mod/roots/newton.c	2014-05-27 18:47:27.000000000 -0700
+@@ -83,12 +83,12 @@
+   state->f = f_new ;
+   state->df = df_new ;
+ 
+-  if (!gsl_finite(f_new))
++  if (!isfinite(f_new))
+     {
+       GSL_ERROR ("function value is not finite", GSL_EBADFUNC);
+     }
+ 
+-  if (!gsl_finite (df_new))
++  if (!isfinite (df_new))
+     {
+       GSL_ERROR ("derivative value is not finite", GSL_EBADFUNC);
+     }
+diff -ruN src/roots/roots.h src-mod/roots/roots.h
+--- src/roots/roots.h	2010-12-26 09:57:08.000000000 -0800
++++ src-mod/roots/roots.h	2014-05-27 18:47:27.000000000 -0700
+@@ -28,7 +28,7 @@
+ #define SAFE_FUNC_CALL(f, x, yp) \
+ do { \
+   *yp = GSL_FN_EVAL(f,x); \
+-  if (!gsl_finite(*yp)) \
++  if (!isfinite(*yp)) \
+     GSL_ERROR("function value is not finite", GSL_EBADFUNC); \
+ } while (0)
+ 
+diff -ruN src/roots/secant.c src-mod/roots/secant.c
+--- src/roots/secant.c	2010-12-26 09:57:08.000000000 -0800
++++ src-mod/roots/secant.c	2014-05-27 18:47:27.000000000 -0700
+@@ -94,12 +94,12 @@
+   state->f = f_new ;
+   state->df = df_new ;
+ 
+-  if (!gsl_finite (f_new))
++  if (!isfinite (f_new))
+     {
+       GSL_ERROR ("function value is not finite", GSL_EBADFUNC);
+     }
+ 
+-  if (!gsl_finite (df_new))
++  if (!isfinite (df_new))
+     {
+       GSL_ERROR ("derivative value is not finite", GSL_EBADFUNC);
+     }
+diff -ruN src/roots/steffenson.c src-mod/roots/steffenson.c
+--- src/roots/steffenson.c	2010-12-26 09:57:08.000000000 -0800
++++ src-mod/roots/steffenson.c	2014-05-27 18:47:27.000000000 -0700
+@@ -105,7 +105,7 @@
+   state->f = f_new ;
+   state->df = df_new ;
+ 
+-  if (!gsl_finite (f_new))
++  if (!isfinite (f_new))
+     {
+       GSL_ERROR ("function value is not finite", GSL_EBADFUNC);
+     }
+@@ -126,7 +126,7 @@
+         *root = x_1 - u * u / v ;  /* accelerated value */
+     }
+ 
+-  if (!gsl_finite (df_new))
++  if (!isfinite (df_new))
+     {
+       GSL_ERROR ("derivative value is not finite", GSL_EBADFUNC);
+     }
+diff -ruN src/specfunc/hyperg_U.c src-mod/specfunc/hyperg_U.c
+--- src/specfunc/hyperg_U.c	2010-12-26 09:57:08.000000000 -0800
++++ src-mod/specfunc/hyperg_U.c	2014-05-27 18:47:28.000000000 -0700
+@@ -524,7 +524,7 @@
+         t_err = a0_err + b0_err;
+         dchu_val += t_val;
+         dchu_err += t_err;
+-        if(!finite(t_val) || fabs(t_val) < EPS*fabs(dchu_val)) break;
++        if(!isfinite(t_val) || fabs(t_val) < EPS*fabs(dchu_val)) break;
+       }
+ 
+       result->val  = dchu_val;
+diff -ruN src/sys/ldfrexp.c src-mod/sys/ldfrexp.c
+--- src/sys/ldfrexp.c	2010-12-26 09:57:08.000000000 -0800
++++ src-mod/sys/ldfrexp.c	2014-05-27 18:47:28.000000000 -0700
+@@ -60,7 +60,7 @@
+       *e = 0;
+       return 0.0;
+     }
+-  else if (!finite (x))
++  else if (!isfinite (x))
+     {
+       *e = 0;
+       return x;
+@@ -85,7 +85,7 @@
+ 
+       f = x * pow (2.0, -ei);
+ 
+-      if (!finite (f))
++      if (!isfinite (f))
+         {
+           /* This should not happen */
+           *e = 0;
+diff -ruN src/test/results.c src-mod/test/results.c
+--- src/test/results.c	2010-12-26 09:57:08.000000000 -0800
++++ src-mod/test/results.c	2014-05-27 18:47:28.000000000 -0700
+@@ -24,7 +24,10 @@
+ #include <stdlib.h>
+ #include <gsl/gsl_sys.h>
+ #include <gsl/gsl_machine.h>
++#include <stdarg.h>
++#define STDC_HEADERS
+ 
++/*
+ #if HAVE_VPRINTF
+ #ifdef STDC_HEADERS
+ #include <stdarg.h>
+@@ -32,6 +35,7 @@
+ #include <varargs.h>
+ #endif
+ #endif
++*/
+ 
+ #include <gsl/gsl_test.h>
+ 
Index: issm/trunk/externalpackages/petsc/install-3.2-discover-intel13.sh
===================================================================
--- issm/trunk/externalpackages/petsc/install-3.2-discover-intel13.sh	(revision 18301)
+++ issm/trunk/externalpackages/petsc/install-3.2-discover-intel13.sh	(revision 18301)
@@ -0,0 +1,39 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.2-p3 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-3.2-p3.tar.gz' 'petsc-3.2-p3.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.2-p3.tar.gz
+mv petsc-3.2-p3/* src/
+rm -rf petsc-3.2-p3
+
+#configure
+cd src
+./config/configure.py \
+	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
+	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	--PETSC_ARCH="$ISSM_ARCH" \
+	--with-batch=1 \
+	--with-debugging=0 \
+	--with-shared-libraries=1 \
+	--known-mpi-shared-libraries=1 \
+	--with-mpi-dir=/usr/local/intel/mpi/4.0.3.008/lib64/ \
+	--with-blas-lapack-dir=/usr/local/intel/Composer/composer_xe_2013.3.163/mkl/ \
+	--with-scalapack-lib=/usr/local/intel/Composer/composer_xe_2013.3.163/mkl/lib/intel64/libmkl_scalapack_lp64.a \
+	--with-scalapack-include=/usr/local/intel/Composer/composer_xe_2013.3.163/mkl/include/ \
+	--with-blacs-lib=/usr/local/intel/Composer/composer_xe_2013.3.163/mkl/lib/intel64/libmkl_blacs_intelmpi_lp64.a \
+	--with-blacs-include=/usr/local/intel/Composer/composer_xe_2013.3.163/mkl/include/ \
+	--download-mumps=yes \
+	--download-scalapack=no \
+	--download-blacs=no \
+	--download-plapack=no \
+	--download-parmetis=yes \
+	--with-pic=1
+
+echo "== Follow PETSc's instructions"
Index: issm/trunk/externalpackages/petsc/install-3.5-linux64.sh
===================================================================
--- issm/trunk/externalpackages/petsc/install-3.5-linux64.sh	(revision 18301)
+++ issm/trunk/externalpackages/petsc/install-3.5-linux64.sh	(revision 18301)
@@ -0,0 +1,34 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.5.1 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.5.1.tar.gz' 'petsc-3.5.1.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.5.1.tar.gz
+mv petsc-3.5.1/* src/
+rm -rf petsc-3.5.1
+
+#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=0 \
+	--with-valgrind=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.5-macosx64.sh
===================================================================
--- issm/trunk/externalpackages/petsc/install-3.5-macosx64.sh	(revision 18301)
+++ issm/trunk/externalpackages/petsc/install-3.5-macosx64.sh	(revision 18301)
@@ -0,0 +1,32 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.5.1 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.5.1.tar.gz' 'petsc-3.5.1.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.5.1.tar.gz
+mv petsc-3.5.1/* src/
+rm -rf petsc-3.5.1
+
+#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=0 \
+	--with-valgrind=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-3.5-pleiades.sh
===================================================================
--- issm/trunk/externalpackages/petsc/install-3.5-pleiades.sh	(revision 18301)
+++ issm/trunk/externalpackages/petsc/install-3.5-pleiades.sh	(revision 18301)
@@ -0,0 +1,59 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.5.1 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.5.1.tar.gz' 'petsc-3.5.1.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.5.1.tar.gz
+mv petsc-3.5.1/* src/
+rm -rf petsc-3.5.1
+
+#configure
+cd src
+./config/configure.py \
+	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
+	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	--with-blas-lapack-dir="/nasa/intel/mkl/10.0.011/" \
+	--with-mpi-lib="/nasa/sgi/mpt/2.06rp16/lib/libmpi.so" \
+	--with-mpi-include="/nasa/sgi/mpt/2.06rp16/include" \
+	--known-mpi-shared-libraries=1 \
+	--with-debugging=0 \
+	--with-valgrind=0 \
+	--with-batch=1  \
+	--with-shared-libraries=1 \
+	--download-metis=1 \
+	--download-parmetis=1 \
+	--download-mumps=1 \
+	--download-scalapack=1 \
+	--download-fblaslapack=1 \
+	--COPTFLAGS="-lmpi -O3" \
+	--FOPTFLAGS="-lmpi -O3" \
+	--CXXOPTFLAGS="-lmpi -O3"
+
+#prepare script to reconfigure petsc
+cat > script.queue << EOF
+#PBS -S /bin/bash
+#PBS -l select=1:ncpus=1:model=wes 
+#PBS -l walltime=200 
+#PBS -W group_list=s1010
+#PBS -m e 
+
+. /usr/share/modules/init/bash 
+module load comp-intel/11.1.046
+module load math/intel_mkl_64_10.0.011
+module load mpi-sgi/mpt.2.06rp16
+
+export PATH="$PATH:." 
+export MPI_GROUP_MAX=64 
+mpiexec -np 1 ./conftest-arch-linux2-c-opt
+EOF
+
+#print instructions
+echo "== Now: cd src/ "
+echo "== qsub -q devel script.queue "
+echo "== Then run reconfigure script generated by PETSc and follow instructions"
Index: issm/trunk/externalpackages/triangle/configs/ios/configure.make
===================================================================
--- issm/trunk/externalpackages/triangle/configs/ios/configure.make	(revision 18301)
+++ issm/trunk/externalpackages/triangle/configs/ios/configure.make	(revision 18301)
@@ -0,0 +1,7 @@
+CC=${host_triplet}-clang
+AR=${host-triplet}-ar
+RANLIB=${host-triplet}-ranlib
+CSWITCHES = $(CFLAGS) -DNO_TIMER
+TRILIBDEFS = -DTRILIBRARY
+OBJ_EXT=o
+LIB_EXT=a
Index: issm/trunk/externalpackages/triangle/install-iosarmv7.sh
===================================================================
--- issm/trunk/externalpackages/triangle/install-iosarmv7.sh	(revision 18301)
+++ issm/trunk/externalpackages/triangle/install-iosarmv7.sh	(revision 18301)
@@ -0,0 +1,27 @@
+#!/bin/bash
+set -eu
+
+host_triplet="armv7-apple-darwin14.0.0"
+
+#cleanup
+rm -rf install triangle
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/triangle.zip' 'triangle.zip'
+
+#untar
+cd install
+cp ../triangle.zip ./
+unzip triangle.zip
+rm triangle.zip
+
+#copy new makefile
+cp ../configs/ios/configure.make ./
+cp ../makefile ./
+
+#compile triangle
+make
+
+#patch triangle.h
+patch triangle.h ../triangle.h.patch
Index: issm/trunk/externalpackages/triangle/install-iosarmv7s.sh
===================================================================
--- issm/trunk/externalpackages/triangle/install-iosarmv7s.sh	(revision 18301)
+++ issm/trunk/externalpackages/triangle/install-iosarmv7s.sh	(revision 18301)
@@ -0,0 +1,27 @@
+#!/bin/bash
+set -eu
+
+host_triplet="armv7s-apple-darwin14.0.0"
+
+#cleanup
+rm -rf install triangle
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/triangle.zip' 'triangle.zip'
+
+#untar
+cd install
+cp ../triangle.zip ./
+unzip triangle.zip
+rm triangle.zip
+
+#copy new makefile
+cp ../configs/ios/configure.make ./
+cp ../makefile ./
+
+#compile triangle
+make
+
+#patch triangle.h
+patch triangle.h ../triangle.h.patch
Index: issm/trunk/externalpackages/triangle/install-iosi386.sh
===================================================================
--- issm/trunk/externalpackages/triangle/install-iosi386.sh	(revision 18301)
+++ issm/trunk/externalpackages/triangle/install-iosi386.sh	(revision 18301)
@@ -0,0 +1,27 @@
+#!/bin/bash
+set -eu
+
+host_triplet="i386-apple-darwin13.1.0"
+
+#cleanup
+rm -rf install triangle
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/triangle.zip' 'triangle.zip'
+
+#untar
+cd install
+cp ../triangle.zip ./
+unzip triangle.zip
+rm triangle.zip
+
+#copy new makefile
+cp ../configs/ios/configure.make ./
+cp ../makefile ./
+
+#compile triangle
+make
+
+#patch triangle.h
+patch triangle.h ../triangle.h.patch
Index: issm/trunk/externalpackages/vim/addons/vim/syntax/c.vim
===================================================================
--- issm/trunk/externalpackages/vim/addons/vim/syntax/c.vim	(revision 18081)
+++ issm/trunk/externalpackages/vim/addons/vim/syntax/c.vim	(revision 18301)
@@ -412,4 +412,5 @@
 syn keyword cType BoolInput
 syn keyword cType BoolParam
+syn keyword cType classes
 syn keyword cType Constraint
 syn keyword cType Constraints
@@ -417,6 +418,6 @@
 syn keyword cType Contours
 syn keyword cType ControlInput
+syn keyword cType DatasetInput
 syn keyword cType DataSetParam
-syn keyword cType DatasetInput
 syn keyword cType Definition
 syn keyword cType DependentObject
@@ -431,6 +432,6 @@
 syn keyword cType ElementHook
 syn keyword cType ElementMatrix
+syn keyword cType Elements
 syn keyword cType ElementVector
-syn keyword cType Elements
 syn keyword cType ExponentialVariogram
 syn keyword cType ExternalResult
@@ -439,9 +440,10 @@
 syn keyword cType Friction
 syn keyword cType Gauss
+syn keyword cType GaussianVariogram
+syn keyword cType gaussobjects
 syn keyword cType GaussPenta
 syn keyword cType GaussSeg
 syn keyword cType GaussTetra
 syn keyword cType GaussTria
-syn keyword cType GaussianVariogram
 syn keyword cType GenericExternalResult
 syn keyword cType GenericOption
@@ -457,4 +459,5 @@
 syn keyword cType IntVecParam
 syn keyword cType IoModel
+syn keyword cType krigingobjects
 syn keyword cType Load
 syn keyword cType Loads
@@ -464,4 +467,5 @@
 syn keyword cType Matice
 syn keyword cType Matpar
+syn keyword cType matrixobjects
 syn keyword cType MatrixParam
 syn keyword cType Misfit
@@ -472,6 +476,6 @@
 syn keyword cType Observations
 syn keyword cType Option
+syn keyword cType Options
 syn keyword cType OptionUtilities
-syn keyword cType Options
 syn keyword cType Param
 syn keyword cType Parameters
@@ -485,10 +489,10 @@
 syn keyword cType Quadtree
 syn keyword cType Results
+syn keyword cType Riftfront
 syn keyword cType RiftStruct
-syn keyword cType Riftfront
 syn keyword cType Seg
 syn keyword cType SegInput
+syn keyword cType Segment
 syn keyword cType SegRef
-syn keyword cType Segment
 syn keyword cType SpcDynamic
 syn keyword cType SpcStatic
@@ -510,8 +514,5 @@
 syn keyword cType Vertex
 syn keyword cType Vertices
-syn keyword cType classes
-syn keyword cType gaussobjects
-syn keyword cType krigingobjects
-syn keyword cType matrixobjects
+syn keyword cType AdjointBalancethickness2Analysis
 syn keyword cType AdjointBalancethicknessAnalysis
 syn keyword cType AdjointHorizAnalysis
@@ -578,7 +579,13 @@
 syn keyword cConstant BalancethicknessStabilizationEnum
 syn keyword cConstant BalancethicknessThickeningRateEnum
+syn keyword cConstant BasalforcingsEnum
 syn keyword cConstant BasalforcingsGeothermalfluxEnum
-syn keyword cConstant BasalforcingsMeltingRateCorrectionEnum
-syn keyword cConstant BasalforcingsMeltingRateEnum
+syn keyword cConstant BasalforcingsGroundediceMeltingRateEnum
+syn keyword cConstant BasalforcingsFloatingiceMeltingRateEnum
+syn keyword cConstant BasalforcingsDeepwaterMeltingRateEnum
+syn keyword cConstant BasalforcingsDeepwaterElevationEnum
+syn keyword cConstant BasalforcingsUpperwaterElevationEnum
+syn keyword cConstant FloatingMeltRateEnum
+syn keyword cConstant LinearFloatingMeltRateEnum
 syn keyword cConstant BedEnum
 syn keyword cConstant BaseEnum
@@ -624,4 +631,7 @@
 syn keyword cConstant FrictionPEnum
 syn keyword cConstant FrictionQEnum
+syn keyword cConstant FrictionMEnum
+syn keyword cConstant FrictionCEnum
+syn keyword cConstant FrictionLawEnum
 syn keyword cConstant GeometryHydrostaticRatioEnum
 syn keyword cConstant HydrologyModelEnum
@@ -682,7 +692,7 @@
 syn keyword cConstant InversionMaxstepsEnum
 syn keyword cConstant InversionFatolEnum
-syn keyword cConstant InversionFgtolEnum
+syn keyword cConstant InversionFrtolEnum
 syn keyword cConstant InversionGatolEnum
-syn keyword cConstant InversionGgtolEnum
+syn keyword cConstant InversionGrtolEnum
 syn keyword cConstant InversionGttolEnum
 syn keyword cConstant InversionAlgorithmEnum
@@ -690,5 +700,4 @@
 syn keyword cConstant InversionNstepsEnum
 syn keyword cConstant InversionDxminEnum
-syn keyword cConstant InversionEpsrelEnum
 syn keyword cConstant InversionNumControlParametersEnum
 syn keyword cConstant InversionNumCostFunctionsEnum
@@ -733,5 +742,5 @@
 syn keyword cConstant DamageEvolutionRequestedOutputsEnum
 syn keyword cConstant MaterialsRhoIceEnum
-syn keyword cConstant MaterialsRhoWaterEnum
+syn keyword cConstant MaterialsRhoSeawaterEnum
 syn keyword cConstant MaterialsRhoFreshwaterEnum
 syn keyword cConstant MaterialsMuWaterEnum
@@ -821,4 +830,5 @@
 syn keyword cConstant TimesteppingTimeAdaptEnum
 syn keyword cConstant TimesteppingTimeStepEnum
+syn keyword cConstant TimesteppingInterpForcingsEnum
 syn keyword cConstant TransientIsstressbalanceEnum
 syn keyword cConstant TransientIsgroundinglineEnum
@@ -859,4 +869,11 @@
 syn keyword cConstant SurfaceforcingsBNegEnum
 syn keyword cConstant SMBhenningEnum
+syn keyword cConstant SMBcomponentsEnum
+syn keyword cConstant SurfaceforcingsAccumulationEnum
+syn keyword cConstant SurfaceforcingsEvaporationEnum
+syn keyword cConstant SurfaceforcingsRunoffEnum
+syn keyword cConstant SMBmeltcomponentsEnum
+syn keyword cConstant SurfaceforcingsMeltEnum
+syn keyword cConstant SurfaceforcingsRefreezeEnum
 syn keyword cConstant SurfaceforcingsIspddEnum
 syn keyword cConstant SurfaceforcingsIssmbgradientsEnum
@@ -865,4 +882,5 @@
 syn keyword cConstant ConfigurationTypeEnum
 syn keyword cConstant AdjointBalancethicknessAnalysisEnum
+syn keyword cConstant AdjointBalancethickness2AnalysisEnum
 syn keyword cConstant AdjointHorizAnalysisEnum
 syn keyword cConstant AnalysisCounterEnum
@@ -1011,5 +1029,4 @@
 syn keyword cConstant FractionIncrementEnum
 syn keyword cConstant FrictionEnum
-syn keyword cConstant GroundinglineMeltingRateEnum
 syn keyword cConstant InternalEnum
 syn keyword cConstant MassFluxEnum
@@ -1107,4 +1124,6 @@
 syn keyword cConstant P1bubblecondensedEnum
 syn keyword cConstant P2Enum
+syn keyword cConstant P2bubbleEnum
+syn keyword cConstant P2bubblecondensedEnum
 syn keyword cConstant P2xP1Enum
 syn keyword cConstant P1xP2Enum
@@ -1118,4 +1137,5 @@
 syn keyword cConstant XTaylorHoodEnum
 syn keyword cConstant OneLayerP4zEnum
+syn keyword cConstant CrouzeixRaviartEnum
 syn keyword cConstant SaveResultsEnum
 syn keyword cConstant BoolExternalResultEnum
@@ -1161,5 +1181,5 @@
 syn keyword cConstant AugmentedLagrangianThetaEnum
 syn keyword cConstant NoneEnum
-syn keyword cConstant AgressiveMigrationEnum
+syn keyword cConstant AggressiveMigrationEnum
 syn keyword cConstant SoftMigrationEnum
 syn keyword cConstant SubelementMigrationEnum
Index: issm/trunk/jenkins/imac-012301-gil
===================================================================
--- issm/trunk/jenkins/imac-012301-gil	(revision 18081)
+++ issm/trunk/jenkins/imac-012301-gil	(revision 18301)
@@ -22,12 +22,9 @@
 	--with-math-lib="/usr/lib/libm.dylib" \
 	--with-graphics-lib="/usr/X11/lib/libX11.dylib" \
-	--with-cxxoptflags=" -fno-common -no-cpp-precomp -fexceptions -arch x86_64 -mmacosx-version-min=10.5  -O3 -DNDEBUG -w "\
 	--with-numthreads=8 \
 	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install  \
-	--with-petsc-arch=$ISSM_ARCH \
 	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
 	--with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
 	--with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install \
-	--with-tao-dir=$ISSM_DIR/externalpackages/tao/install \
 	--enable-development'
 
@@ -62,6 +59,5 @@
 						mpich     install-3.0-macosx64.sh    
 						cmake     install.sh                
-						petsc     install-3.4-macosx64.sh    
-						tao       install-2.2.sh
+						petsc     install-3.5-macosx64.sh    
 						triangle  install-macosx64.sh 
 						shell2junit  install.sh "
Index: issm/trunk/jenkins/linux64_larsen
===================================================================
--- issm/trunk/jenkins/linux64_larsen	(revision 18081)
+++ issm/trunk/jenkins/linux64_larsen	(revision 18301)
@@ -20,5 +20,4 @@
 	--with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib/ -lmpich" \
 	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
-	--with-petsc-arch=$ISSM_ARCH \
 	--with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
 	--with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
@@ -26,8 +25,6 @@
 	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
 	--with-chaco-dir="$ISSM_DIR/externalpackages/chaco/install" \
+	--with-graphics-lib="/usr/lib/x86_64-linux-gnu/libX11.so" \
 	--with-numthreads=18 \
-	--with-cxxoptflags="-mtune=barcelona -ffast-math -O3 -msse4.2 -Wno-write-strings "\
-	--with-graphics-lib="/usr/lib/x86_64-linux-gnu/libX11.so" \
-	--with-tao-dir=$ISSM_DIR/externalpackages/tao/install \
 	--enable-development \
 	--enable-debugging '
@@ -63,9 +60,8 @@
 						mpich     install-3.0-linux64.sh    
 						cmake     install.sh                
-						petsc     install-3.4-linux64.sh    
+						petsc     install-3.5-linux64.sh    
 						triangle  install-linux64.sh        
 						boost     install.sh                
 						dakota    install-5.3.1-linux64.sh  
-						tao       install-2.2.sh
 						chaco     install.sh 
 						shell2junit install.sh"
Index: issm/trunk/jenkins/linux64_murdo
===================================================================
--- issm/trunk/jenkins/linux64_murdo	(revision 18081)
+++ issm/trunk/jenkins/linux64_murdo	(revision 18301)
@@ -20,5 +20,4 @@
 	--with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib/ -lmpich" \
 	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
-	--with-petsc-arch=$ISSM_ARCH \
 	--with-python-dir=$ISSM_DIR/externalpackages/python/install\
 	--with-python-numpy-dir=$ISSM_DIR/externalpackages/python/install/lib/python2.7/site-packages/numpy/core/include/numpy\
@@ -26,10 +25,8 @@
 	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
 	--with-chaco-dir="$ISSM_DIR/externalpackages/chaco/install" \
-	--with-numthreads=18 \
-	--with-cxxoptflags="-mtune=barcelona -ffast-math -O3 -msse4.2 -Wno-write-strings "\
 	--with-graphics-lib="/usr/lib/x86_64-linux-gnu/libX11.so" \
 	--with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
 	--with-boost-dir=$ISSM_DIR/externalpackages/boost/install/ \
-	--with-tao-dir=$ISSM_DIR/externalpackages/tao/install \
+	--with-numthreads=18 \
 	--enable-development \
 	--enable-debugging '
@@ -65,9 +62,8 @@
 						mpich     install-3.0-linux64.sh    
 						cmake     install.sh                
-						petsc     install-3.4-linux64.sh    
+						petsc     install-3.5-linux64.sh    
 						triangle  install-linux64.sh        
 						boost     install.sh                
 						dakota    install-5.3.1-linux64.sh  
-						tao       install-2.2.sh
 						chaco     install.sh 
 						python        install-2.7.3-linux64.sh    
Index: issm/trunk/jenkins/windows
===================================================================
--- issm/trunk/jenkins/windows	(revision 18081)
+++ issm/trunk/jenkins/windows	(revision 18301)
@@ -26,5 +26,5 @@
 	--with-mpi-libflags="-Wl,libpetsc.lib" \
 	--with-mpi-include="$ISSM_DIR/externalpackages/petsc/install/include/mpiuni" \
-	--enable-development'
+	--enable-debugging '
 
 #MATLAB path
@@ -100,6 +100,6 @@
 #ex: "'id',[101 102 103]"
 
-#In Windows, we don't yet have MUMPS, can't do full stokes, so exclude all FS runs. Also exclude all runs with Dakota. And exclude higher order runs that have penalties.
-MATLAB_NROPTIONS="'exclude',[104, 124, 204, 211, 215, 220, 221, 285, 290, 308, 322, 404, 421, 422, 503, 507, 510, 511, 701, 702, 703, 218, 234, 235, 412, 413, 414, 417, 418, 420, 205, 274, 331, 405, 409, 455, 612, 514, 435 280]"
+#In Windows, we don't yet have MUMPS, can't do full stokes, so exclude all FS runs. Also exclude all runs with Dakota. And exclude higher order runs that have penalties. And 800+ tests because we don't want to have --with-development since we do the binaries with this version
+MATLAB_NROPTIONS="'exclude',[104, 124, 204, 211, 215, 220, 221, 285, 290, 308, 322, 404, 421, 422, 503, 507, 510, 511, 701, 702, 703, 218, 234, 235, 412, 413, 414, 417, 418, 420, 205, 274, 331, 405, 409, 455, 612, 514, 435, 280,801,802,803,804,805,291]"
 PYTHON_NROPTIONS=""
 
Index: issm/trunk/m4/analyses.m4
===================================================================
--- issm/trunk/m4/analyses.m4	(revision 18081)
+++ issm/trunk/m4/analyses.m4	(revision 18301)
@@ -374,4 +374,18 @@
 AC_MSG_RESULT($HAVE_SMOOTHEDSURFACESLOPEY)
 dnl }}}
+dnl with-UzawaPressure{{{
+AC_ARG_WITH([UzawaPressure],
+	AS_HELP_STRING([--with-UzawaPressure = YES], [compile with UzawaPressure capabilities (default is yes)]),
+	[UZAWAPRESSURE=$withval],[UZAWAPRESSURE=yes])
+AC_MSG_CHECKING(for UzawaPressure capability compilation)
+
+HAVE_UZAWAPRESSURE=no 
+if test "x$UZAWAPRESSURE" = "xyes"; then
+	HAVE_UZAWAPRESSURE=yes
+	AC_DEFINE([_HAVE_UZAWAPRESSURE_],[1],[with UzawaPressurecapability])
+fi
+AM_CONDITIONAL([UZAWAPRESSURE], [test x$HAVE_UZAWAPRESSURE = xyes])
+AC_MSG_RESULT($HAVE_UZAWAPRESSURE)
+dnl }}}
 dnl with-Thermal{{{
 AC_ARG_WITH([Thermal],
Index: issm/trunk/m4/issm_options.m4
===================================================================
--- issm/trunk/m4/issm_options.m4	(revision 18081)
+++ issm/trunk/m4/issm_options.m4	(revision 18301)
@@ -168,4 +168,5 @@
 		
 		dnl 4. get MEXLIB MEXLINK and MEXEXT (experimental) except for windows
+		AC_MSG_CHECKING([matlab's mex compilation flags])
   		case "${host_os}" in
   			*cygwin*) 
@@ -184,6 +185,20 @@
 	         MEXLIB=$( $MATLAB_ROOT/bin/mex -v 2>&1 < /dev/null | grep CXXLIBS     | sed -e "s/         CXXLIBS            = //g")
 		      MEXEXT=$( $MATLAB_ROOT/bin/mex -v 2>&1 < /dev/null | grep LDEXTENSION | sed -e "s/         LDEXTENSION        = //g")
+
+				dnl version 2014 and up
+				if test "x$MEXEXT" = "x" ; then
+					 echo "#include <mex.h>" > conftest.cpp
+					 echo "void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){}" >> conftest.cpp
+					 $MATLAB_ROOT/bin/mex -v -lmex conftest.cpp > conftest.tmp 2>&1 
+					 rm -f conftest.cpp
+					 MEXLINK=$(cat conftest.tmp | grep LDFLAGS  | sed -e "s/LDFLAGS ://g")
+					 MEXLIB=$( cat conftest.tmp | grep LINKLIBS | sed -e "s/LINKLIBS ://g")
+					 MEXEXT=$( cat conftest.tmp | grep LDEXT    | sed -e "s/LDEXT ://g" | awk '{print $[1]}')
+					 rm -f conftest.tmp
+				fi
+
   			;;
       esac
+		AC_MSG_RESULT(done)
 	   if test "x$MEXEXT" = "x" ; then
 			AC_MSG_ERROR([Couldn't find mex... check your installation of matlab])
@@ -191,5 +206,4 @@
 
 		AC_SUBST([MATLABINCL])
-		AC_SUBST([MEX])
 		MATLABWRAPPEREXT=$MEXEXT
 		AC_SUBST([MATLABWRAPPEREXT])
@@ -332,8 +346,12 @@
 					DAKOTALIB="-L$DAKOTA_ROOT/lib -ldakota -lteuchos -lpecos -llhs -lsparsegrid -lsurfpack -lconmin -lddace -lfsudace -ljega -lcport -loptpp -lpsuade -lncsuopt -lcolin -linterfaces -lmomh -lscolib -lpebbl -ltinyxml -lutilib -l3po -lhopspack -lnidr -lamplsolver -lboost_signals -lboost_regex -lboost_filesystem -lboost_system"
 					dnl DAKOTALIB+= "-lgslcblas -L/usr/lib -lblas -llapack"
+				else if test x$DAKOTA_VERSION = x5.3 || test x$DAKOTA_VERSION = x5.3.1; then
+					DAKOTAFLAGS="-DDISABLE_DAKOTA_CONFIG_H -DBOOST_MULTI_INDEX_DISABLE_SERIALIZATION -DDAKOTA_PLUGIN -DBOOST_DISABLE_ASSERTS -DDAKOTA_HAVE_BOOST_FS -DHAVE_UNISTD_H -DHAVE_SYSTEM -DHAVE_WORKING_FORK -DHAVE_WORKING_VFORK -DHAVE_SYS_WAIT_H -DHAVE_USLEEP -DDAKOTA_F90 -DDAKOTA_HAVE_MPI -DHAVE_PECOS -DHAVE_SURFPACK -DDAKOTA_COLINY -DDAKOTA_UTILIB -DHAVE_ADAPTIVE_SAMPLING -DHAVE_CONMIN -DDAKOTA_DDACE -DHAVE_FSUDACE -DDAKOTA_HOPS -DHAVE_JEGA -DHAVE_NCSU -DHAVE_NL2SOL -DHAVE_OPTPP -DDAKOTA_OPTPP -DHAVE_PSUADE -DHAVE_AMPL"
+					DAKOTALIB="-L$DAKOTA_ROOT/lib -ldakota_src -ldakota_src_fortran -lnidr -lteuchos -lpecos -lpecos_src -llhs -lmods -lmod -ldfftpack -lsparsegrid -lsurfpack -lsurfpack_fortran -lutilib -lcolin -linterfaces -lscolib -l3po -lpebbl -ltinyxml -lconmin -ldace -lanalyzer -lrandom -lsampling -lbose -lfsudace -lhopspack -ljega -ljega_fe -lmoga -lsoga -leutils -lutilities -lncsuopt -lcport -loptpp -lpsuade -lamplsolver -L$BOOST_ROOT/lib -lboost_signals -lboost_regex -lboost_filesystem -lboost_system "
 				else
 					AC_MSG_ERROR([Dakota version not found or version ($DAKOTA_VERSION) not supported!]);
 				fi
 				fi
+                                fi
 			;;
 		esac
@@ -921,21 +939,30 @@
 	dnl Check whether tao is enabled
 	AC_MSG_CHECKING([for tao])
-	if test "x$TAO_ROOT" = "xno" ; then
-		HAVE_TAO=no
-	else
-		HAVE_TAO=yes
-		if ! test -d "$TAO_ROOT"; then
-			AC_MSG_ERROR([tao directory provided ($TAO_ROOT) does not exist]);
-		fi
-	fi
-	AC_MSG_RESULT($HAVE_TAO)
-	
-	dnl tao headers and libraries
-	if test "x$HAVE_TAO" == "xyes"; then
-	  TAOINCL="-I$TAO_ROOT/ -I$TAO_ROOT/include -I$TAO_ROOT/bmake/ "
-	  TAOLIB="-L$TAO_ROOT/lib -ltao -lpetsc"
-	  AC_DEFINE([_HAVE_TAO_],[1],[with Tao in ISSM src])
-	  AC_SUBST([TAOINCL])
-	  AC_SUBST([TAOLIB])
+
+	if test "$HAVE_PETSC" = "yes" && test "x$PETSC_MAJOR" = "x3" && test $PETSC_MINOR -ge 5; then
+		dnl in petsc >=3.5, tao is provided
+		HAVE_TAO="yes"
+		AC_DEFINE([_HAVE_TAO_],[1],[with Tao in ISSM src])
+		AC_MSG_RESULT($HAVE_TAO)
+	else
+
+		if test "x$TAO_ROOT" = "xno" ; then
+			HAVE_TAO=no
+		else
+			HAVE_TAO=yes
+			if ! test -d "$TAO_ROOT"; then
+				AC_MSG_ERROR([tao directory provided ($TAO_ROOT) does not exist]);
+			fi
+		fi
+		AC_MSG_RESULT($HAVE_TAO)
+
+		dnl tao headers and libraries
+		if test "x$HAVE_TAO" == "xyes"; then
+		  TAOINCL="-I$TAO_ROOT/ -I$TAO_ROOT/include -I$TAO_ROOT/bmake/ "
+		  TAOLIB="-L$TAO_ROOT/lib -ltao -lpetsc"
+		  AC_DEFINE([_HAVE_TAO_],[1],[with Tao in ISSM src])
+		  AC_SUBST([TAOINCL])
+		  AC_SUBST([TAOLIB])
+		fi
 	fi
 	dnl }}}
@@ -1609,22 +1636,4 @@
 	AC_MSG_RESULT($HAVE_KRIGING)
 	dnl }}}
-	dnl with-gia{{{
-		AC_ARG_WITH([gia],
-		AS_HELP_STRING([--with-gia = YES], [compile with gia capabilities (default is no)]),
-		[GIA=$withval],[GIA=no]) 
-	   AC_MSG_CHECKING(for gia capability compilation)
-
-		HAVE_GIA=no
-		if test "x$GIA" = "xyes"; then
-			if test "x$HAVE_MATH77" = "xno"; then
-				 AC_MSG_ERROR([gia requires compilation of math77 library! Reconfigure with --with-math77 option on]);
-			else
-				HAVE_GIA=yes
-				AC_DEFINE([_HAVE_GIA_],[1],[with gia capability])
-		   fi
-		fi
-		AM_CONDITIONAL([GIA], [test x$HAVE_GIA = xyes])
-		AC_MSG_RESULT($HAVE_GIA)
-		dnl }}}
 	AX_ANALYSES_SELECTION
 
Index: issm/trunk/src/ad/todo
===================================================================
--- issm/trunk/src/ad/todo	(revision 18081)
+++ 	(revision )
@@ -1,65 +1,0 @@
-Externalpackages: out into astrid-r1b
-
-Get a wiki together. OpenAD. Get ISSM website together.
-https://trac.mcs.anl.gov/projects/ADIC/wiki/ADIC/ISSM
-
-Switch to metis 5.0
-
-Hard stuff: 
-wrap MatSetValues and MatAssembly into one routine. 
-To do so, store Ke matrices into elements, do not add to global. 
-Once all the Ke are built, loop through them and do all the MatSetValues
-at once, followed by MatAssembly. 
-Do the same for VecSet and VecAssembly.
-
-Wrap all Petsc data types Matrix and Vector objects, and map all operations 
-onto these new objects.  Make this preprocessable for configuration using autotools.
-We will probably duplicate data, ex: 
-
-Matrix{
-	ifdef  PETSC_WRAPPER
-	Mat pmatrix; 
-	endif
-	ifdef  DOUBLE_WRAPPER
-	double* pmatrix; 
-	endif
-	adouble* amatrix;
-}
-
-amatrix will be used in adolc. pmatrix will be used in Petsc routines. Matrix will 
-have routines to map one into the other.
-
-
-Ad: 
-Eric: 
-Create ISSM namespace.
-Make Matrix Assembly one homogeneous block.
-Make Validation suite for Jean for his prognostic capabilities.
-Jean: 
-typedef all double to ISSM_DOUBLE 
-
-Create an alloc layer with template functions for new and delete.
-Check that the new code  is modular --without-kml, options are up to date.
-
-Replace memcpy, realloc with x layers.  Replace all calls to malloc and free in the code.
-
-
-
-Questions: 
-set of active IssmDouble variables different from set of independent variables activated with <<=? 
-same thing dependent variables? 
-
-
-
-Bullet points: 
-- nightly run on with adolc compiled, running from test2000 on.  once a day.
-- run valgrind on new adolc or old adolc. send a text on how to run it. 
-- make gdb wrapper.
-- think about ModelProcessor setup. need to keep track, before we partition, on cpu 0, of the independent declarations. 
-
-
-MPI: what's missing that equivalent of MPI.h -> no well defined api.  
-What's exposed is the internals of it.
-
-Wanted to look at changing the way for the matrices and vertices would be implemented.
-
Index: issm/trunk/src/ad/wrappers.txt
===================================================================
--- issm/trunk/src/ad/wrappers.txt	(revision 18081)
+++ 	(revision )
@@ -1,146 +1,0 @@
-A typical prognostic solution calls the following routines: 
-
-		femmodel->SetCurrentConfiguration
-		femmodel->parameters->FindParam
-
-		solver_linear
-				femmodel->parameters->FindParam
-				UpdateConstraintsx
-						parameters->FindParam
-						SpcNodesx
-								constraint->ConstrainNode(nodes,parameters);
-						NodesDofx
-								nodes->NumberOfNodes
-										MPI_Allreduce 
-								nodes->FlagClones
-										this->NumberOfNodes
-										Ranks
-										MPI_Allreduce 
-										node->SetClone
-								nodes->DistributeDofs
-										node->InAnalysis
-										node->DistributeDofs
-										MPI_Gather
-										MPI_Bcast
-										node->OffsetDofs
-										this->MaxNumDofs
-										this->NumberOfNodes
-										node->ShowTrueDofs
-										MPI_Allreduce 
-										node->UpdateCloneDofs
-				SystemMatricesx
-						parameters->FindParam
-						nodes->NumberOfDofs
-						nodes->MaxNumDofs
-						NewMat
-						NewVec
-						element->CreateKMatrix
-						element->CreatePVector
-						load->CreateKMatrix
-						load->CreatePVector
-						MatAssemblyBegin
-						MatAssemblyEnd
-						MatCompress
-						VecAssemblyBegin
-						VecAssemblyEnd
-						MatNorm
-			CreateNodalConstraintsx
-						nodes->NumberOfDofs
-						ys=NewVec
-						node->CreateNodalConstraints
-						VecAssemblyBegin
-						VecAssemblyEnd
-			Reduceloadx
-						MatGetSize
-						MatGetLocalSize
-						NewVec
-						VecDuplicate
-						VecSet
-						VecAssemblyBegin
-						VecAssemblyEnd
-						MatMultPatch
-						MatMultPatch
-						VecAXPY(pf,a,Kfsy_s);  
-						VecFree
-			Solverx
-						MatGetSize
-						PetscOptionsGetString
-						VecDuplicate
-						MatGetLocalSize
-						PetscOptionsDetermineSolverType
-						MatConvert
-						KSPCreate
-						KSPSetOperators
-						KSPSetFromOptions
-						KSPGetPC
-						PCFactorSetMatSolverPackage
-						KSPSolve
-						KSPGetIterationNumber
-						KSPFree
-			Mergesolutionfromftogx
-						parameters->FindParam
-						nodes->NumberOfDofs
-						VecSet(ys,0.0);
-						NewVec
-						VecMergex
-						VecMergex
-			InputUpdateFromSolutionx
-						VecToMPISerial
-						InputUpdateFromSolutionx
-						element->InputUpdateFromSolution
-			VecFree
-
-		InputToResultx
-						element->InputToResult(enum_type,step,time);
-
-
-
-
-
-The resulting MPI routines that are called are the following: 
-
-MPI_Allreduce 
-MPI_Allreduce 
-MPI_Gather
-MPI_Bcast
-MPI_Allreduce 
-
-The resulting PETSC routines that are called are the following:
-
-MatAssemblyBegin
-MatAssemblyEnd
-MatSetValues
-MatCompress
-MatNorm
-MatGetSize
-MatGetLocalSize
-MatConvert
-
-VecDuplicate
-VecSet
-VecAssemblyBegin
-VecAssemblyEnd
-VecAXPY
-
-KSPCreate
-KSPSetOperators
-KSPSetFromOptions
-KSPGetPC
-KSPSetUp
-KSPSolve
-KSPGetIterationNumber
-PCFactorSetMatSolverPackage
-VecSet
-
-
-The resulting routines are wrappers to PETSC routines, with essentially a PETSC flavor to it: 
-
-NewMat
-NewVec
-MatMultPatch
-PetscOptionsGetString
-PetscOptionsDetermineSolverType
-VecMergex
-VecToMPISerial
-VecFree
-KSPFree
Index: issm/trunk/src/c/Makefile.am
===================================================================
--- issm/trunk/src/c/Makefile.am	(revision 18081)
+++ issm/trunk/src/c/Makefile.am	(revision 18301)
@@ -317,4 +317,6 @@
 					./modules/InputUpdateFromVectorx/InputUpdateFromVectorx.h\
 					./modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp\
+					./modules/FloatingiceMeltingRatex/FloatingiceMeltingRatex.h\
+					./modules/FloatingiceMeltingRatex/FloatingiceMeltingRatex.cpp\
 					./modules/ConfigureObjectsx/ConfigureObjectsx.h\
 					./modules/ConfigureObjectsx/ConfigureObjectsx.cpp\
@@ -352,8 +354,9 @@
 					./analyses/EnumToAnalysis.cpp\
 					./analyses/Analysis.h\
+					./solutionsequences/solutionsequence_la.cpp\
+					./solutionsequences/solutionsequence_la_theta.cpp\
 					./solutionsequences/solutionsequence_linear.cpp\
 					./solutionsequences/solutionsequence_nonlinear.cpp\
 					./solutionsequences/solutionsequence_newton.cpp\
-					./solutionsequences/solutionsequence_la_theta.cpp\
 					./solutionsequences/convergence.cpp\
 					./classes/Options/Options.h\
@@ -374,10 +377,6 @@
 					./cores/thermal_core.cpp\
 					./solutionsequences/solutionsequence_thermal_nonlinear.cpp\
-					./modules/ControlInputGetGradientx/ControlInputGetGradientx.cpp\
-					./modules/ControlInputGetGradientx/ControlInputGetGradientx.h\
 					./modules/ControlInputSetGradientx/ControlInputSetGradientx.cpp\
 					./modules/ControlInputSetGradientx/ControlInputSetGradientx.h\
-					./modules/ControlInputScaleGradientx/ControlInputScaleGradientx.cpp\
-					./modules/ControlInputScaleGradientx/ControlInputScaleGradientx.h\
 					./modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp\
 					./modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h\
@@ -400,6 +399,4 @@
 					./modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h\
 					./modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp\
-					./modules/Orthx/Orthx.h\
-					./modules/Orthx/Orthx.cpp\
 					./modules/Gradjx/Gradjx.h\
 					./modules/Gradjx/Gradjx.cpp\
@@ -418,5 +415,5 @@
 					./cores/controltao_core.cpp\
 					./cores/controlm1qn3_core.cpp\
-					./cores/gradient_core.cpp\
+					./cores/controlvalidation_core.cpp\
 					./cores/adjointstressbalance_core.cpp\
 					./cores/adjointbalancethickness_core.cpp\
@@ -437,5 +434,4 @@
 					./cores/damage_core.cpp\
 					./cores/levelsetfunctionslope_core.cpp\
-					./analyses/DamageEvolutionAnalysis.cpp\
 					./modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp\
 					./classes/Loads/Riftfront.cpp\
@@ -542,4 +538,7 @@
 if STRESSBALANCE
 issm_sources += ./analyses/StressbalanceAnalysis.cpp
+endif
+if UZAWAPRESSURE
+issm_sources += ./analyses/UzawaPressureAnalysis.cpp
 endif
 if STRESSBALANCESIA
@@ -826,10 +825,4 @@
 			./modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp\
 			./modules/InterpFromMeshToGridx/InterpFromMeshToGridx.h\
-			./modules/HoleFillerx/HoleFillerx.cpp\
-			./modules/HoleFillerx/HoleFillerx.h\
-			./modules/EdgeDetectionx/EdgeDetectionx.cpp\
-			./modules/EdgeDetectionx/EdgeDetectionx.h\
-			./modules/AverageFilterx/AverageFilterx.cpp\
-			./modules/AverageFilterx/AverageFilterx.h\
 			./modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp\
 			./modules/MeshProfileIntersectionx/MeshProfileIntersectionx.h\
Index: issm/trunk/src/c/analyses/AdjointBalancethickness2Analysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/AdjointBalancethickness2Analysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/AdjointBalancethickness2Analysis.cpp	(revision 18301)
@@ -38,71 +38,75 @@
 ElementMatrix* AdjointBalancethickness2Analysis::CreateKMatrix(Element* element){/*{{{*/
 
-	_error_("not implemented");
 	Balancethickness2Analysis* analysis = new Balancethickness2Analysis();
 	ElementMatrix* Ke = analysis->CreateKMatrix(element);
 	delete analysis;
 
-	/*Transpose and return Ke*/
-	Ke->Transpose();
 	return Ke;
 }/*}}}*/
 ElementVector* AdjointBalancethickness2Analysis::CreatePVector(Element* element){/*{{{*/
-
-	_error_("not implemented");
-	/*Intermediaries*/
-	int      domaintype;
-	Element* basalelement;
-
-	/*Get basal element*/
-	element->FindParam(&domaintype,DomainTypeEnum);
-	switch(domaintype){
-		case Domain2DhorizontalEnum:
-			basalelement = element;
-			break;
-		case Domain3DEnum:
-			if(!element->IsOnBase()) return NULL;
-			basalelement = element->SpawnBasalElement();
-			break;
-		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
-	}
 
 	/*Intermediaries */
 	int         num_responses,i;
-	IssmDouble  dH[2];
-	IssmDouble  vx,vy,vel,Jdet;
-	IssmDouble  thickness,thicknessobs,weight;
+	IssmDouble  hobs,hu2,weight,Jdet;
+	IssmDouble  NUMxH2,NUMyH2,DENH2;
+	IssmDouble  NUMxUbar,NUMyUbar,DENUbar;
+	IssmDouble  vxobs,vyobs,vxobsbar,vyobsbar,vbarobs2,vbarobs;
+	IssmDouble  nux,nuy,phi,dphi[2];
 	int        *responses = NULL;
 	IssmDouble *xyz_list  = NULL;
 
 	/*Fetch number of nodes and dof for this finite element*/
-	int numnodes = basalelement->GetNumberOfNodes();
+	int numnodes = element->GetNumberOfNodes();
 
 	/*Initialize Element vector and vectors*/
-	ElementVector* pe     = basalelement->NewElementVector(SSAApproximationEnum);
+	ElementVector* pe     = element->NewElementVector(SSAApproximationEnum);
 	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
 	IssmDouble*    dbasis = xNew<IssmDouble>(2*numnodes);
 
 	/*Retrieve all inputs and parameters*/
-	basalelement->GetVerticesCoordinates(&xyz_list);
-	basalelement->FindParam(&num_responses,InversionNumCostFunctionsEnum);
-	basalelement->FindParam(&responses,NULL,InversionCostFunctionsEnum);
-	Input* thickness_input    = basalelement->GetInput(ThicknessEnum);                          _assert_(thickness_input);
-	Input* thicknessobs_input = basalelement->GetInput(InversionThicknessObsEnum);              _assert_(thicknessobs_input);
-	Input* weights_input      = basalelement->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
-	Input* vx_input           = basalelement->GetInput(VxEnum);                                 _assert_(vx_input);
-	Input* vy_input           = basalelement->GetInput(VyEnum);                                 _assert_(vy_input);
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	element->FindParam(&responses,NULL,InversionCostFunctionsEnum);
+	Input* thicknessobs_input = element->GetInput(InversionThicknessObsEnum);              _assert_(thicknessobs_input);
+	Input* weights_input      = element->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+	Input* potential_input = element->GetInput(PotentialEnum);             _assert_(potential_input);
+	Input* vxobs_input     = element->GetInput(BalancethicknessVxObsEnum); _assert_(vxobs_input);
+	Input* vyobs_input     = element->GetInput(BalancethicknessVyObsEnum); _assert_(vyobs_input);
+	Input* nux_input       = element->GetInput(BalancethicknessNuxEnum);   _assert_(nux_input);
+	Input* nuy_input       = element->GetInput(BalancethicknessNuyEnum);   _assert_(nuy_input);
 
 	/* Start  looping on the number of gaussian points: */
-	Gauss* gauss=basalelement->NewGauss(2);
+	Gauss* gauss=element->NewGauss(2);
 	for(int ig=gauss->begin();ig<gauss->end();ig++){
 		gauss->GaussPoint(ig);
 
-		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
-		basalelement->NodalFunctions(basis,gauss);
-		basalelement->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
-
-		thickness_input->GetInputValue(&thickness, gauss);
-		thickness_input->GetInputDerivativeValue(&dH[0],xyz_list,gauss);
-		thicknessobs_input->GetInputValue(&thicknessobs, gauss);
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis,gauss);
+		element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+		vxobs_input->GetInputValue(&vxobs,gauss);
+		vyobs_input->GetInputValue(&vyobs,gauss);
+		nux_input->GetInputValue(&nux,gauss);
+		nuy_input->GetInputValue(&nuy,gauss);
+		potential_input->GetInputValue(&phi,gauss);
+		potential_input->GetInputDerivativeValue(&dphi[0],xyz_list,gauss);
+		thicknessobs_input->GetInputValue(&hobs,gauss);
+
+		vxobsbar = nux*vxobs;
+		vyobsbar = nuy*vyobs;
+
+		vbarobs2 = (nux*nux*vxobs*vxobs + nuy*nuy*vyobs*vyobs);
+		vbarobs  = sqrt(vbarobs2);
+		hu2 = hobs*hobs*vbarobs2;
+
+		/*H^2 - Hobs^2*/
+		NUMxH2 = 2.*dbasis[0]*dphi[0]*(dphi[0]*dphi[0] + dphi[1]*dphi[1] - hu2);
+		NUMyH2 = 2.*dbasis[1]*dphi[1]*(dphi[0]*dphi[0] + dphi[1]*dphi[1] - hu2);
+		DENH2 = vbarobs2*vbarobs2+1.e-14;
+
+		/*Ubar-Ubar_obs*/
+		NUMxUbar = (vyobsbar*dphi[0]*dphi[1] - vxobsbar*dphi[1]*dphi[1])*vbarobs*dbasis[0];
+		NUMyUbar = (vyobsbar*dphi[0]*dphi[0] - vxobsbar*dphi[0]*dphi[1])*vbarobs*dbasis[1];
+		DENUbar  = pow(dphi[0]*dphi[0] + dphi[1]*dphi[1],3./2.)+1.e-14;
 
 		/*Loop over all requested responses*/
@@ -111,26 +115,11 @@
 
 			switch(responses[resp]){
-				case ThicknessAbsMisfitEnum:
-					for(i=0;i<numnodes;i++) pe->values[i]+=(thicknessobs-thickness)*weight*Jdet*gauss->weight*basis[i];
-					break;
-				case ThicknessAbsGradientEnum:
-					for(i=0;i<numnodes;i++) pe->values[i]+= - weight*dH[0]*dbasis[0*numnodes+i]*Jdet*gauss->weight;
-					for(i=0;i<numnodes;i++) pe->values[i]+= - weight*dH[1]*dbasis[1*numnodes+i]*Jdet*gauss->weight;
-					break;
-				case ThicknessAlongGradientEnum:
-					vx_input->GetInputValue(&vx,gauss);
-					vy_input->GetInputValue(&vy,gauss);
-					vel = sqrt(vx*vx+vy*vy);
-					vx  = vx/(vel+1.e-9);
-					vy  = vy/(vel+1.e-9);
-					for(i=0;i<numnodes;i++) pe->values[i]+= - weight*(dH[0]*vx+dH[1]*vy)*(dbasis[0*numnodes+i]*vx+dbasis[1*numnodes+i]*vy)*Jdet*gauss->weight;
-					break;
-				case ThicknessAcrossGradientEnum:
-					vx_input->GetInputValue(&vx,gauss);
-					vy_input->GetInputValue(&vy,gauss);
-					vel = sqrt(vx*vx+vy*vy);
-					vx  = vx/(vel+1.e-9);
-					vy  = vy/(vel+1.e-9);
-					for(i=0;i<numnodes;i++) pe->values[i]+= - weight*(dH[0]*(-vy)+dH[1]*vx)*(dbasis[0*numnodes+i]*(-vy)+dbasis[1*numnodes+i]*vx)*Jdet*gauss->weight;
+				case Balancethickness2MisfitEnum:
+					/*J = (H^2 - Hobs^2)^2*/
+					//for(i=0;i<numnodes;i++) pe->values[i]+=(NUMxH2+NUMyH2)/DENH2 *weight*Jdet*gauss->weight; NOT WORKING
+					/*J = phi^2*/
+					//for(i=0;i<numnodes;i++) pe->values[i]+= phi*basis[i]*weight*Jdet*gauss->weight; OK
+					/*J = (ubar - nux*uobs)^2*/
+					for(i=0;i<numnodes;i++) pe->values[i]+=(NUMxUbar-NUMyUbar)/DENUbar *weight*Jdet*gauss->weight;
 					break;
 				default:
@@ -145,5 +134,4 @@
 	xDelete<IssmDouble>(basis);
 	xDelete<IssmDouble>(dbasis);
-	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
 	delete gauss;
 	return pe;
@@ -151,4 +139,88 @@
 void AdjointBalancethickness2Analysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 	_error_("not implemented yet");
+}/*}}}*/
+void AdjointBalancethickness2Analysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	/*The gradient of the cost function is calculated in 2 parts.
+	 *
+	 * dJ    \partial J   \partial lambda^T(KU-F)
+	 * --  = ---------- + ------------------------
+	 * dk    \partial k   \parial k                  
+	 *
+	 * */
+
+	/*If on water, grad = 0: */
+	if(!element->IsIceInElement()) return;
+
+	/*Get list of cost functions*/
+	int *responses = NULL;
+	int num_responses,resp;
+	element->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	element->FindParam(&responses,NULL,InversionCostFunctionsEnum);
+
+	/*Check that control_type is supported*/
+	if(control_type!=BalancethicknessApparentMassbalanceEnum){
+		_error_("Control "<<EnumToStringx(control_type)<<" not supported");
+	}
+
+	/*Deal with first part (partial derivative a J with respect to k)*/
+	for(resp=0;resp<num_responses;resp++) switch(responses[resp]){
+		case Balancethickness2MisfitEnum: /*Nothing, \partial J/\partial k = 0*/ break;
+		default: _error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+	}
+
+	/*Deal with second term*/
+	switch(control_type){
+		case BalancethicknessApparentMassbalanceEnum: GradientJAdot(element,gradient,control_index); break;
+		default: _error_("control type not supported yet: " << EnumToStringx(control_type));
+	}
+
+	/*Clean up and return*/
+	xDelete<int>(responses);
+
+}/*}}}*/
+void AdjointBalancethickness2Analysis::GradientJAdot(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble Jdet,weight;
+	IssmDouble lambda; 
+	IssmDouble *xyz_list= NULL;
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Retrieve all inputs we will be needing: */
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* adjoint_input = element->GetInput(AdjointEnum);                            _assert_(adjoint_input);
+	Input* weights_input = element->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctionsP1(basis,gauss);
+		weights_input->GetInputValue(&weight,gauss,Balancethickness2MisfitEnum);
+		adjoint_input->GetInputValue(&lambda,gauss);
+
+		/*Build gradient vector (actually -dJ/da): */
+		for(int i=0;i<numvertices;i++){
+			ge[i]+= - weight*Jdet*gauss->weight*basis[i]*lambda;
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(ge);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
 }/*}}}*/
 void AdjointBalancethickness2Analysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
Index: issm/trunk/src/c/analyses/AdjointBalancethickness2Analysis.h
===================================================================
--- issm/trunk/src/c/analyses/AdjointBalancethickness2Analysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/AdjointBalancethickness2Analysis.h	(revision 18301)
@@ -27,4 +27,6 @@
 		ElementVector* CreatePVector(Element* element);
 		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void GradientJAdot(Element* element,Vector<IssmDouble>* gradient,int control_index);
 		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
 		void UpdateConstraints(FemModel* femmodel);
Index: issm/trunk/src/c/analyses/AdjointBalancethicknessAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/AdjointBalancethicknessAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/AdjointBalancethicknessAnalysis.cpp	(revision 18301)
@@ -150,4 +150,170 @@
 	_error_("not implemented yet");
 }/*}}}*/
+void AdjointBalancethicknessAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	/*The gradient of the cost function is calculated in 2 parts.
+	 *
+	 * dJ    \partial J   \partial lambda^T(KU-F)
+	 * --  = ---------- + ------------------------
+	 * dk    \partial k   \parial k                  
+	 *
+	 * */
+
+	/*If on water, grad = 0: */
+	if(!element->IsIceInElement()) return;
+
+	/*Get list of cost functions*/
+	int *responses = NULL;
+	int num_responses,resp;
+	element->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	element->FindParam(&responses,NULL,InversionCostFunctionsEnum);
+
+	/*Check that control_type is supported*/
+	if(control_type!=VxEnum && 
+		control_type!=VyEnum && 
+		control_type!=BalancethicknessThickeningRateEnum){
+		_error_("Control "<<EnumToStringx(control_type)<<" not supported");
+	}
+
+	/*Deal with first part (partial derivative a J with respect to k)*/
+	for(resp=0;resp<num_responses;resp++) switch(responses[resp]){
+		case ThicknessAbsMisfitEnum:      /*Nothing, \partial J/\partial k = 0*/ break;
+		case ThicknessAbsGradientEnum:    /*Nothing, \partial J/\partial k = 0*/ break;
+		case ThicknessAlongGradientEnum:  /*Nothing, \partial J/\partial k = 0*/ break;
+		case ThicknessAcrossGradientEnum: /*Nothing, \partial J/\partial k = 0*/ break;
+		default: _error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+	}
+
+	/*Deal with second term*/
+	switch(control_type){
+		case BalancethicknessThickeningRateEnum: GradientJDhDt(element,gradient,control_index); break;
+		case VxEnum:                             GradientJVx(  element,gradient,control_index); break;
+		case VyEnum:                             GradientJVy(  element,gradient,control_index); break;
+		default: _error_("control type not supported yet: " << EnumToStringx(control_type));
+	}
+
+	/*Clean up and return*/
+	xDelete<int>(responses);
+
+}/*}}}*/
+void AdjointBalancethicknessAnalysis::GradientJVx(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble Jdet,weight;
+	IssmDouble thickness,Dlambda[3],dp[3];
+	IssmDouble *xyz_list= NULL;
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Retrieve all inputs we will be needing: */
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* thickness_input = element->GetInput(ThicknessEnum); _assert_(thickness_input);
+	Input* adjoint_input   = element->GetInput(AdjointEnum);   _assert_(adjoint_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		adjoint_input->GetInputDerivativeValue(&Dlambda[0],xyz_list,gauss);
+		thickness_input->GetInputValue(&thickness, gauss);
+		thickness_input->GetInputDerivativeValue(&dp[0],xyz_list,gauss);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctionsP1(basis,gauss);
+
+		/*Build gradient vector (actually -dJ/dD): */
+		for(int i=0;i<numvertices;i++){
+			ge[i]+=thickness*Dlambda[0]*Jdet*gauss->weight*basis[i];
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+}/*}}}*/
+void AdjointBalancethicknessAnalysis::GradientJVy(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble Jdet,weight;
+	IssmDouble thickness,Dlambda[3],dp[3];
+	IssmDouble *xyz_list= NULL;
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Retrieve all inputs we will be needing: */
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* thickness_input = element->GetInput(ThicknessEnum); _assert_(thickness_input);
+	Input* adjoint_input   = element->GetInput(AdjointEnum);   _assert_(adjoint_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		adjoint_input->GetInputDerivativeValue(&Dlambda[0],xyz_list,gauss);
+		thickness_input->GetInputValue(&thickness, gauss);
+		thickness_input->GetInputDerivativeValue(&dp[0],xyz_list,gauss);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctionsP1(basis,gauss);
+
+		/*Build gradient vector (actually -dJ/dvy): */
+		for(int i=0;i<numvertices;i++){
+			ge[i]+=thickness*Dlambda[1]*Jdet*gauss->weight*basis[i];
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+}/*}}}*/
+void AdjointBalancethicknessAnalysis::GradientJDhDt(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	IssmDouble* lambda        = xNew<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Retrieve all inputs we will be needing: */
+	element->GradientIndexing(&vertexpidlist[0],control_index);
+	element->GetInputListOnVertices(lambda,AdjointEnum);
+	for(int i=0;i<numvertices;i++){
+		ge[i]=-lambda[i];
+		_assert_(!xIsNan<IssmDouble>(ge[i]));
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,INS_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(ge);
+	xDelete<IssmDouble>(lambda);
+	xDelete<int>(vertexpidlist);
+}/*}}}*/
 void AdjointBalancethicknessAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
Index: issm/trunk/src/c/analyses/AdjointBalancethicknessAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/AdjointBalancethicknessAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/AdjointBalancethicknessAnalysis.h	(revision 18301)
@@ -27,4 +27,8 @@
 		ElementVector* CreatePVector(Element* element);
 		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void GradientJVx(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void GradientJVy(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void GradientJDhDt(Element* element,Vector<IssmDouble>* gradient,int control_index);
 		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
 		void UpdateConstraints(FemModel* femmodel);
Index: issm/trunk/src/c/analyses/AdjointHorizAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/AdjointHorizAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/AdjointHorizAnalysis.cpp	(revision 18301)
@@ -900,4 +900,642 @@
 	   _error_("not implemented yet");
 }/*}}}*/
+void AdjointHorizAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	/*The gradient of the cost function is calculated in 2 parts.
+	 *
+	 * dJ    \partial J   \partial lambda^T(KU-F)
+	 * --  = ---------- + ------------------------
+	 * dk    \partial k   \parial k                  
+	 *
+	 * */
+
+	/*If on water, grad = 0: */
+	if(!element->IsIceInElement()) return;
+
+	/*Get Approximation*/
+	int approximation;
+	element->GetInputValue(&approximation,ApproximationEnum);
+
+	/*Get list of cost functions*/
+	int *responses = NULL;
+	int num_responses,resp;
+	element->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	element->FindParam(&responses,NULL,InversionCostFunctionsEnum);
+
+	/*Check that control_type is supported*/
+	if(control_type!=MaterialsRheologyBbarEnum && 
+		control_type!=FrictionCoefficientEnum   && 
+		control_type!=DamageDbarEnum){
+		_error_("Control "<<EnumToStringx(control_type)<<" not supported");
+	}
+
+	/*Deal with first part (partial derivative a J with respect to k)*/
+	for(resp=0;resp<num_responses;resp++) switch(responses[resp]){
+		case SurfaceAbsVelMisfitEnum:     /*Nothing, \partial J/\partial k = 0*/ break;
+		case SurfaceRelVelMisfitEnum:     /*Nothing, \partial J/\partial k = 0*/ break;
+		case SurfaceLogVelMisfitEnum:     /*Nothing, \partial J/\partial k = 0*/ break;
+		case SurfaceLogVxVyMisfitEnum:    /*Nothing, \partial J/\partial k = 0*/ break;
+		case SurfaceAverageVelMisfitEnum: /*Nothing, \partial J/\partial k = 0*/ break;
+		case DragCoefficientAbsGradientEnum: GradientJDragGradient(element,gradient,control_index); break;
+		case RheologyBbarAbsGradientEnum:    GradientJBGradient(element,gradient,control_index);    break;
+		default: _error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+	}
+
+	/*Deal with second term*/
+	switch(control_type){
+		case FrictionCoefficientEnum:
+			switch(approximation){
+				case SSAApproximationEnum: GradientJDragSSA(element,gradient,control_index); break;
+				case HOApproximationEnum:  GradientJDragHO( element,gradient,control_index); break;
+				case FSApproximationEnum:  GradientJDragFS( element,gradient,control_index); break;
+				case NoneApproximationEnum: /*Gradient is 0*/                    break;
+				default: _error_("approximation " << EnumToStringx(approximation) << " not supported yet");
+			}
+			break;
+		case MaterialsRheologyBbarEnum:
+			switch(approximation){
+				case SSAApproximationEnum: GradientJBbarSSA(element,gradient,control_index); break;
+				case HOApproximationEnum:  GradientJBbarHO( element,gradient,control_index); break;
+				case FSApproximationEnum:  GradientJBbarFS( element,gradient,control_index); break;
+				case NoneApproximationEnum: /*Gradient is 0*/                    break;
+				default: _error_("approximation " << EnumToStringx(approximation) << " not supported yet");
+			}
+			break;
+		case DamageDbarEnum:
+			switch(approximation){
+				case SSAApproximationEnum: GradientJDSSA(element,gradient,control_index); break;
+				case NoneApproximationEnum: /*Gradient is 0*/                 break;
+				default: _error_("approximation " << EnumToStringx(approximation) << " not supported yet");
+			}
+			break;
+		default: _error_("control type not supported yet: " << EnumToStringx(control_type));
+	}
+
+	/*Clean up and return*/
+	xDelete<int>(responses);
+                         
+}/*}}}*/
+void AdjointHorizAnalysis::GradientJDragGradient(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*return if floating (gradient is 0)*/
+	if(element->IsFloating()) return;
+
+	/*Intermediaries*/
+	int      domaintype,dim;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			dim          = 2;
+			break;
+		case Domain2DverticalEnum:
+			if(!element->IsOnBase()) return;
+			basalelement = element->SpawnBasalElement();
+			dim          = 1;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return;
+			basalelement = element->SpawnBasalElement();
+			dim          = 2;
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Intermediaries*/
+	IssmDouble Jdet,weight;
+	IssmDouble dk[3]; 
+	IssmDouble *xyz_list= NULL;
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = basalelement->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* dbasis        = xNew<IssmDouble>(2*numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Retrieve all inputs we will be needing: */
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	basalelement->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* dragcoefficient_input = basalelement->GetInput(FrictionCoefficientEnum);                _assert_(dragcoefficient_input);
+	Input* weights_input         = basalelement->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctionsP1Derivatives(dbasis,xyz_list,gauss);
+		weights_input->GetInputValue(&weight,gauss,DragCoefficientAbsGradientEnum);
+
+		/*Build alpha_complement_list: */
+		dragcoefficient_input->GetInputDerivativeValue(&dk[0],xyz_list,gauss);
+
+		/*Build gradient vector (actually -dJ/ddrag): */
+		for(int i=0;i<numvertices;i++){
+			if(dim==2){
+				ge[i]+=-weight*Jdet*gauss->weight*(dbasis[0*numvertices+i]*dk[0]+dbasis[1*numvertices+i]*dk[1]);
+			}
+			else{
+				ge[i]+=-weight*Jdet*gauss->weight*dbasis[0*numvertices+i]*dk[0];
+			}
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(dbasis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+
+}/*}}}*/
+void AdjointHorizAnalysis::GradientJBGradient(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*Intermediaries*/
+	int      domaintype,dim;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			dim          = 2;
+			break;
+		case Domain2DverticalEnum:
+			if(!element->IsOnBase()) return;
+			basalelement = element->SpawnBasalElement();
+			dim          = 1;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return;
+			basalelement = element->SpawnBasalElement();
+			dim          = 2;
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Intermediaries*/
+	IssmDouble Jdet,weight;
+	IssmDouble dk[3]; 
+	IssmDouble *xyz_list= NULL;
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = basalelement->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* dbasis        = xNew<IssmDouble>(2*numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Retrieve all inputs we will be needing: */
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	basalelement->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* rheologyb_input = basalelement->GetInput(MaterialsRheologyBbarEnum);              _assert_(rheologyb_input);
+	Input* weights_input   = basalelement->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctionsP1Derivatives(dbasis,xyz_list,gauss);
+		weights_input->GetInputValue(&weight,gauss,RheologyBbarAbsGradientEnum);
+
+		/*Build alpha_complement_list: */
+		rheologyb_input->GetInputDerivativeValue(&dk[0],xyz_list,gauss);
+
+		/*Build gradje_g_gaussian vector (actually -dJ/ddrag): */
+		for(int i=0;i<numvertices;i++){
+			if(dim==2){
+				ge[i]+=-weight*Jdet*gauss->weight*(dbasis[0*numvertices+i]*dk[0]+dbasis[1*numvertices+i]*dk[1]);
+			}
+			else{
+				ge[i]+=-weight*Jdet*gauss->weight*dbasis[0*numvertices+i]*dk[0];
+			}
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(dbasis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+}/*}}}*/
+void AdjointHorizAnalysis::GradientJDragSSA(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*return if floating (gradient is 0)*/
+	if(element->IsFloating()) return;
+
+	/*Intermediaries*/
+	int      domaintype,dim;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			dim          = 2;
+			break;
+		case Domain2DverticalEnum:
+			if(!element->IsOnBase()) return;
+			basalelement = element->SpawnBasalElement();
+			dim          = 1;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return;
+			basalelement = element->SpawnBasalElement();
+			dim          = 2;
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Intermediaries*/
+	IssmDouble Jdet,weight;
+	IssmDouble drag,dalpha2dk;
+	IssmDouble vx,vy,lambda,mu;
+	IssmDouble *xyz_list= NULL;
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = basalelement->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Build friction element, needed later: */
+	Friction* friction=new Friction(basalelement,dim);
+
+	/*Retrieve all inputs we will be needing: */
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	basalelement->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* vx_input        = basalelement->GetInput(VxEnum);                   _assert_(vx_input);
+	Input* vy_input        = basalelement->GetInput(VyEnum);                   _assert_(vy_input);
+	Input* adjointx_input  = basalelement->GetInput(AdjointxEnum);             _assert_(adjointx_input);
+	Input* adjointy_input  = basalelement->GetInput(AdjointyEnum);             _assert_(adjointy_input);
+	Input* dragcoeff_input = basalelement->GetInput(FrictionCoefficientEnum);  _assert_(dragcoeff_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		adjointx_input->GetInputValue(&lambda, gauss);
+		adjointy_input->GetInputValue(&mu, gauss);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		dragcoeff_input->GetInputValue(&drag, gauss);
+
+		friction->GetAlphaComplement(&dalpha2dk,gauss);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctionsP1(basis,gauss);
+
+		/*Build gradient vector (actually -dJ/dD): */
+		for(int i=0;i<numvertices;i++){
+			ge[i]+=-2.*drag*dalpha2dk*((lambda*vx+mu*vy))*Jdet*gauss->weight*basis[i];
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+	delete friction;
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+}/*}}}*/
+void AdjointHorizAnalysis::GradientJDragHO(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*return if floating or not on bed (gradient is 0)*/
+	if(element->IsFloating()) return;
+	if(!element->IsOnBase()) return;
+
+	/*Intermediaries*/
+	int        dim=3;
+	IssmDouble Jdet,weight;
+	IssmDouble drag,dalpha2dk;
+	IssmDouble vx,vy,lambda,mu;
+	IssmDouble *xyz_list_base= NULL;
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Build friction element, needed later: */
+	Friction* friction=new Friction(element,dim);
+
+	/*Retrieve all inputs we will be needing: */
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	element->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* vx_input        = element->GetInput(VxEnum);                   _assert_(vx_input);
+	Input* vy_input        = element->GetInput(VyEnum);                   _assert_(vy_input);
+	Input* adjointx_input  = element->GetInput(AdjointxEnum);             _assert_(adjointx_input);
+	Input* adjointy_input  = element->GetInput(AdjointyEnum);             _assert_(adjointy_input);
+	Input* dragcoeff_input = element->GetInput(FrictionCoefficientEnum);  _assert_(dragcoeff_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGaussBase(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		adjointx_input->GetInputValue(&lambda, gauss);
+		adjointy_input->GetInputValue(&mu, gauss);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		dragcoeff_input->GetInputValue(&drag, gauss);
+
+		friction->GetAlphaComplement(&dalpha2dk,gauss);
+
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		element->NodalFunctionsP1(basis,gauss);
+
+		/*Build gradient vector (actually -dJ/dD): */
+		for(int i=0;i<numvertices;i++){
+			ge[i]+=-2.*drag*dalpha2dk*((lambda*vx+mu*vy))*Jdet*gauss->weight*basis[i];
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list_base);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+	delete friction;
+}/*}}}*/
+void AdjointHorizAnalysis::GradientJDragFS(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*return if floating or not on bed (gradient is 0)*/
+	if(element->IsFloating()) return;
+	if(!element->IsOnBase()) return;
+
+	/*Intermediaries*/
+	int        dim=3;
+	IssmDouble Jdet,weight;
+	IssmDouble drag,dalpha2dk,normal[3];
+	IssmDouble vx,vy,vz,lambda,mu,xi;
+	IssmDouble *xyz_list_base= NULL;
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Build friction element, needed later: */
+	Friction* friction=new Friction(element,dim);
+
+	/*Retrieve all inputs we will be needing: */
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	element->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* vx_input        = element->GetInput(VxEnum);                   _assert_(vx_input);
+	Input* vy_input        = element->GetInput(VyEnum);                   _assert_(vy_input);
+	Input* vz_input        = element->GetInput(VzEnum);                   _assert_(vy_input);
+	Input* adjointx_input  = element->GetInput(AdjointxEnum);             _assert_(adjointx_input);
+	Input* adjointy_input  = element->GetInput(AdjointyEnum);             _assert_(adjointy_input);
+	Input* adjointz_input  = element->GetInput(AdjointzEnum);             _assert_(adjointz_input);
+	Input* dragcoeff_input = element->GetInput(FrictionCoefficientEnum);  _assert_(dragcoeff_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGaussBase(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		adjointx_input->GetInputValue(&lambda, gauss);
+		adjointy_input->GetInputValue(&mu, gauss);
+		adjointz_input->GetInputValue(&xi    ,gauss);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vz_input->GetInputValue(&vz,gauss);
+		dragcoeff_input->GetInputValue(&drag, gauss);
+
+		friction->GetAlphaComplement(&dalpha2dk,gauss);
+		element->NormalBase(&normal[0],xyz_list_base);
+
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		element->NodalFunctionsP1(basis,gauss);
+
+		/*Build gradient vector (actually -dJ/dk): */
+		for(int i=0;i<numvertices;i++){
+			ge[i]+=(
+						-lambda*(2*drag*dalpha2dk*(vx - vz*normal[0]*normal[2]))
+						-mu    *(2*drag*dalpha2dk*(vy - vz*normal[1]*normal[2]))
+						-xi    *(2*drag*dalpha2dk*(-vx*normal[0]*normal[2]-vy*normal[1]*normal[2]))
+						)*Jdet*gauss->weight*basis[i];
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list_base);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+	delete friction;
+}/*}}}*/
+void AdjointHorizAnalysis::GradientJBbarSSA(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*Intermediaries*/
+	int      domaintype,dim;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			dim          = 2;
+			break;
+		case Domain2DverticalEnum:
+			if(!element->IsOnBase()) return;
+			basalelement = element->SpawnBasalElement();
+			dim          = 1;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return;
+			basalelement = element->SpawnBasalElement();
+			dim          = 2;
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Intermediaries*/
+	IssmDouble Jdet,weight;
+	IssmDouble thickness,dmudB;
+	IssmDouble dvx[3],dvy[3],dadjx[3],dadjy[3]; 
+	IssmDouble *xyz_list= NULL;
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = basalelement->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Retrieve all inputs we will be needing: */
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	basalelement->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* thickness_input = basalelement->GetInput(ThicknessEnum);             _assert_(thickness_input);
+	Input* vx_input        = basalelement->GetInput(VxEnum);                    _assert_(vx_input);
+	Input* vy_input        = basalelement->GetInput(VyEnum);                    _assert_(vy_input);
+	Input* adjointx_input  = basalelement->GetInput(AdjointxEnum);              _assert_(adjointx_input);
+	Input* adjointy_input  = basalelement->GetInput(AdjointyEnum);              _assert_(adjointy_input);
+	Input* rheologyb_input = basalelement->GetInput(MaterialsRheologyBbarEnum); _assert_(rheologyb_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		thickness_input->GetInputValue(&thickness,gauss);
+		vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+		vy_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
+		adjointx_input->GetInputDerivativeValue(&dadjx[0],xyz_list,gauss);
+		adjointy_input->GetInputDerivativeValue(&dadjy[0],xyz_list,gauss);
+
+		basalelement->dViscositydBSSA(&dmudB,dim,xyz_list,gauss,vx_input,vy_input);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctionsP1(basis,gauss);
+
+		/*Build gradient vector (actually -dJ/dB): */
+		for(int i=0;i<numvertices;i++){
+			ge[i]+=-dmudB*thickness*(
+						(2*dvx[0]+dvy[1])*2*dadjx[0]+(dvx[1]+dvy[0])*(dadjx[1]+dadjy[0])+(2*dvy[1]+dvx[0])*2*dadjy[1]
+						)*Jdet*gauss->weight*basis[i];
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+}/*}}}*/
+void AdjointHorizAnalysis::GradientJBbarHO(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*WARNING: We use SSA as an estimate for now*/
+	this->GradientJBbarSSA(element,gradient,control_index);
+}/*}}}*/
+void AdjointHorizAnalysis::GradientJBbarFS(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+	/*WARNING: We use SSA as an estimate for now*/
+	this->GradientJBbarSSA(element,gradient,control_index);
+}/*}}}*/
+void AdjointHorizAnalysis::GradientJDSSA(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*Intermediaries*/
+	int      domaintype,dim;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			dim          = 2;
+			break;
+		case Domain2DverticalEnum:
+			if(!element->IsOnBase()) return;
+			basalelement = element->SpawnBasalElement();
+			dim          = 1;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return;
+			basalelement = element->SpawnBasalElement();
+			dim          = 2;
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Intermediaries*/
+	IssmDouble Jdet,weight;
+	IssmDouble thickness,dmudD;
+	IssmDouble dvx[3],dvy[3],dadjx[3],dadjy[3]; 
+	IssmDouble *xyz_list= NULL;
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = basalelement->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Retrieve all inputs we will be needing: */
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	basalelement->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* thickness_input = basalelement->GetInput(ThicknessEnum);             _assert_(thickness_input);
+	Input* vx_input        = basalelement->GetInput(VxEnum);                    _assert_(vx_input);
+	Input* vy_input        = basalelement->GetInput(VyEnum);                    _assert_(vy_input);
+	Input* adjointx_input  = basalelement->GetInput(AdjointxEnum);              _assert_(adjointx_input);
+	Input* adjointy_input  = basalelement->GetInput(AdjointyEnum);              _assert_(adjointy_input);
+	Input* rheologyb_input = basalelement->GetInput(MaterialsRheologyBbarEnum); _assert_(rheologyb_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		thickness_input->GetInputValue(&thickness,gauss);
+		vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+		vy_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
+		adjointx_input->GetInputDerivativeValue(&dadjx[0],xyz_list,gauss);
+		adjointy_input->GetInputDerivativeValue(&dadjy[0],xyz_list,gauss);
+
+		basalelement->dViscositydDSSA(&dmudD,dim,xyz_list,gauss,vx_input,vy_input);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctionsP1(basis,gauss);
+
+		for(int i=0;i<numvertices;i++){
+			ge[i]+=-dmudD*thickness*(
+						(2*dvx[0]+dvy[1])*2*dadjx[0]+(dvx[1]+dvy[0])*(dadjx[1]+dadjy[0])+(2*dvy[1]+dvx[0])*2*dadjy[1]
+						)*Jdet*gauss->weight*basis[i];
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+}/*}}}*/
 void AdjointHorizAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 	int approximation;
Index: issm/trunk/src/c/analyses/AdjointHorizAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/AdjointHorizAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/AdjointHorizAnalysis.h	(revision 18301)
@@ -33,4 +33,14 @@
 		ElementVector* CreatePVectorFS(Element* element);
 		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void GradientJDragGradient(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void GradientJBGradient(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void GradientJDragSSA(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void GradientJDragHO(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void GradientJDragFS(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void GradientJBbarSSA(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void GradientJBbarHO(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void GradientJBbarFS(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void GradientJDSSA(Element* element,Vector<IssmDouble>* gradient,int control_index);
 		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
 		void UpdateConstraints(FemModel* femmodel);
Index: issm/trunk/src/c/analyses/Analysis.h
===================================================================
--- issm/trunk/src/c/analyses/Analysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/Analysis.h	(revision 18301)
@@ -40,4 +40,5 @@
 		virtual ElementVector* CreatePVector(Element* element)=0;
 		virtual void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element)=0;
+		virtual void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index)=0;
 		virtual void InputUpdateFromSolution(IssmDouble* solution,Element* element)=0;
 		virtual void UpdateConstraints(FemModel* femmodel)=0;
Index: issm/trunk/src/c/analyses/Balancethickness2Analysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/Balancethickness2Analysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/Balancethickness2Analysis.cpp	(revision 18301)
@@ -72,5 +72,6 @@
 
 	/*Initialize Element vector and other vectors*/
-	ElementMatrix* Ke  = element->NewElementMatrix();
+	ElementMatrix* Ke     = element->NewElementMatrix();
+	IssmDouble*    dbasis = xNew<IssmDouble>(2*numnodes);
 
 	/*Retrieve all inputs and parameters*/
@@ -81,6 +82,4 @@
 	for(int ig=gauss->begin();ig<gauss->end();ig++){
 		gauss->GaussPoint(ig);
-
-		IssmDouble* dbasis=xNew<IssmDouble>(2*numnodes);
 		element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
 		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
@@ -95,4 +94,5 @@
 	/*Clean up and return*/
 	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(dbasis);
 	delete gauss;
 	return Ke;
@@ -183,5 +183,5 @@
 		element->NodalFunctions(basis,gauss);
 
-		for(int i=0;i<numnodes;i++) pe->values[i] += - Jdet*gauss->weight*thickness*(vx*normal[0] + vy*normal[1])*basis[i];
+		for(int i=0;i<numnodes;i++) pe->values[i] += Jdet*gauss->weight*thickness*(vx*normal[0] + vy*normal[1])*basis[i];
 	}
 
@@ -196,7 +196,11 @@
 	   _error_("not implemented yet");
 }/*}}}*/
+void Balancethickness2Analysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
 void Balancethickness2Analysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
 	/*Intermediaries */
+	int         Hinterpolation;
 	IssmDouble  vx,vy,vbar,nux,nuy,normdphi,dphi[2];
 	IssmDouble* xyz_list = NULL;
@@ -232,7 +236,12 @@
 	Input* nuy_input       = element->GetInput(BalancethicknessNuyEnum);   _assert_(nuy_input);
 
+	switch(element->GetElementType()){
+		case P1Enum: Hinterpolation = P0Enum; break;
+		default:     _error_("not implemented");
+	}
+
 	Gauss* gauss=element->NewGauss();
-	for (int iv=0;iv<numvertices;iv++){
-		gauss->GaussVertex(iv);
+	for (int iv=0;iv<1;iv++){
+		gauss->GaussNode(Hinterpolation,iv);//P0 Only for now
 
 		vx_input->GetInputValue(&vx,gauss);
@@ -250,7 +259,7 @@
 		vy_list[iv]        = -1./thickness_list[iv] * dphi[1];
 	}
-	element->AddInput(ThicknessEnum,thickness_list,P1Enum);
-	element->AddInput(VxEnum,vx_list,P1Enum);
-	element->AddInput(VyEnum,vy_list,P1Enum);
+	element->AddInput(ThicknessEnum,thickness_list,Hinterpolation);
+	element->AddInput(VxEnum,vx_list,Hinterpolation);
+	element->AddInput(VyEnum,vy_list,Hinterpolation);
 
 	/*Clean up and return*/
Index: issm/trunk/src/c/analyses/Balancethickness2Analysis.h
===================================================================
--- issm/trunk/src/c/analyses/Balancethickness2Analysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/Balancethickness2Analysis.h	(revision 18301)
@@ -29,4 +29,5 @@
 		ElementVector* CreatePVectorBoundary(Element* element);
 		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
 		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
 		void UpdateConstraints(FemModel* femmodel);
Index: issm/trunk/src/c/analyses/BalancethicknessAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/BalancethicknessAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/BalancethicknessAnalysis.cpp	(revision 18301)
@@ -41,5 +41,5 @@
 	iomodel->FetchDataToInput(elements,VxEnum);
 	iomodel->FetchDataToInput(elements,VyEnum);
-	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsGroundediceMeltingRateEnum);
 	iomodel->FetchDataToInput(elements,SurfaceforcingsMassBalanceEnum);
 	iomodel->FetchDataToInput(elements,BalancethicknessThickeningRateEnum);
@@ -354,5 +354,5 @@
 	/*Retrieve all inputs and parameters*/
 	element->GetVerticesCoordinates(&xyz_list);
-	Input* mb_input   = element->GetInput(BasalforcingsMeltingRateEnum);       _assert_(mb_input);
+	Input* mb_input   = element->GetInput(BasalforcingsGroundediceMeltingRateEnum);       _assert_(mb_input);
 	Input* ms_input   = element->GetInput(SurfaceforcingsMassBalanceEnum);     _assert_(ms_input);
 	Input* dhdt_input = element->GetInput(BalancethicknessThickeningRateEnum); _assert_(dhdt_input);
@@ -395,5 +395,5 @@
 	/*Retrieve all inputs and parameters*/
 	element->GetVerticesCoordinates(&xyz_list);
-	Input* mb_input   = element->GetInput(BasalforcingsMeltingRateEnum);       _assert_(mb_input);
+	Input* mb_input   = element->GetInput(BasalforcingsGroundediceMeltingRateEnum);       _assert_(mb_input);
 	Input* ms_input   = element->GetInput(SurfaceforcingsMassBalanceEnum);     _assert_(ms_input);
 	Input* dhdt_input = element->GetInput(BalancethicknessThickeningRateEnum); _assert_(dhdt_input);
@@ -479,4 +479,120 @@
 	   _error_("not implemented yet");
 }/*}}}*/
+void BalancethicknessAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	/* WARNING: this gradient is valid for Soft balance thickness only */
+
+	/*If on water, grad = 0: */
+	if(!element->IsIceInElement()) return;
+
+	/*Intermediaries*/
+	IssmDouble Jdet,weight;
+	IssmDouble thickness,thicknessobs,dH[3],dp[3];
+	IssmDouble  vx,vy,vel,dvx[2],dvy[2],dhdt,basal_melting,surface_mass_balance;
+	IssmDouble *xyz_list= NULL;
+
+	/*Get list of cost functions*/
+	int *responses = NULL;
+	int  num_responses,resp,solution;
+	element->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	element->FindParam(&responses,NULL,InversionCostFunctionsEnum);
+	element->FindParam(&solution,SolutionTypeEnum);
+	if(solution!=BalancethicknessSoftSolutionEnum) _error_("not implemented yet");
+	if(control_type!=ThicknessEnum)                _error_("Control "<<EnumToStringx(control_type)<<" not supported");
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
+	IssmDouble* dbasis        = xNew<IssmDouble>(2*numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Retrieve all inputs we will be needing: */
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* thickness_input            = element->GetInput(ThicknessEnum);                           _assert_(thickness_input);
+	Input* thicknessobs_input         = element->GetInput(InversionThicknessObsEnum);               _assert_(thicknessobs_input);
+	Input* weights_input              = element->GetInput(InversionCostFunctionsCoefficientsEnum);  _assert_(weights_input);
+	Input* vx_input                   = element->GetInput(VxEnum);                                  _assert_(vx_input);
+	Input* vy_input                   = element->GetInput(VyEnum);                                  _assert_(vy_input);
+	Input* surface_mass_balance_input = element->GetInput(SurfaceforcingsMassBalanceEnum);          _assert_(surface_mass_balance_input);
+	Input* basal_melting_input        = element->GetInput(BasalforcingsGroundediceMeltingRateEnum); _assert_(basal_melting_input);
+	Input* dhdt_input                 = element->GetInput(BalancethicknessThickeningRateEnum);      _assert_(dhdt_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		thickness_input->GetInputValue(&thickness, gauss);
+		thickness_input->GetInputDerivativeValue(&dH[0],xyz_list,gauss);
+		thicknessobs_input->GetInputValue(&thicknessobs, gauss);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctionsP1(basis,gauss);
+		element->NodalFunctionsP1Derivatives(dbasis,xyz_list,gauss);
+
+		/*Deal with first part (partial derivative a J with respect to k)*/
+		for(resp=0;resp<num_responses;resp++){
+
+			weights_input->GetInputValue(&weight,gauss,responses[resp]);
+
+			switch(responses[resp]){
+				case ThicknessAbsMisfitEnum:
+					for(int i=0;i<numvertices;i++) ge[i]+= (thicknessobs-thickness)*weight*Jdet*gauss->weight*basis[i];
+					break;
+				case ThicknessAbsGradientEnum:
+					for(int i=0;i<numvertices;i++) ge[i]+= - weight*dH[0]*dbasis[0*numvertices+i]*Jdet*gauss->weight;
+					for(int i=0;i<numvertices;i++) ge[i]+= - weight*dH[1]*dbasis[1*numvertices+i]*Jdet*gauss->weight;
+					break;
+				case ThicknessAlongGradientEnum:
+					vx_input->GetInputValue(&vx,gauss);
+					vy_input->GetInputValue(&vy,gauss);
+					vel = sqrt(vx*vx+vy*vy);
+					vx  = vx/(vel+1.e-9);
+					vy  = vy/(vel+1.e-9);
+					for(int i=0;i<numvertices;i++) ge[i]+= - weight*(dH[0]*vx+dH[1]*vy)*(dbasis[0*numvertices+i]*vx+dbasis[1*numvertices+i]*vy)*Jdet*gauss->weight;
+					break;
+				case ThicknessAcrossGradientEnum:
+					vx_input->GetInputValue(&vx,gauss);
+					vy_input->GetInputValue(&vy,gauss);
+					vel = sqrt(vx*vx+vy*vy);
+					vx  = vx/(vel+1.e-9);
+					vy  = vy/(vel+1.e-9);
+					for(int i=0;i<numvertices;i++) ge[i]+= - weight*(dH[0]*(-vy)+dH[1]*vx)*(dbasis[0*numvertices+i]*(-vy)+dbasis[1*numvertices+i]*vx)*Jdet*gauss->weight;
+					break;
+				case BalancethicknessMisfitEnum:
+					surface_mass_balance_input->GetInputValue(&surface_mass_balance,gauss);
+					basal_melting_input->GetInputValue(&basal_melting,gauss);
+					dhdt_input->GetInputValue(&dhdt,gauss);
+					vx_input->GetInputValue(&vx,gauss);
+					vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+					vy_input->GetInputValue(&vy,gauss);
+					vy_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
+					for(int i=0;i<numvertices;i++){
+						ge[i]+= - weight*Jdet*gauss->weight*(
+							(vx*dH[0]+vy*dH[1] + thickness*(dvx[0]+dvy[1]))*(vx*dbasis[0*numvertices+i]+ vy*dbasis[1*numvertices+i] + basis[i]*(dvx[0]+dvy[1]))
+							-(surface_mass_balance-basal_melting-dhdt)*(vx*dbasis[0*numvertices+i]+ vy*dbasis[1*numvertices+i] + basis[i]*(dvx[0]+dvy[1]))
+							);
+					}
+					break;
+				default:
+					_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+			}
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	xDelete<int>(responses);
+	delete gauss;
+
+
+}/*}}}*/
 void BalancethicknessAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
Index: issm/trunk/src/c/analyses/BalancethicknessAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/BalancethicknessAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/BalancethicknessAnalysis.h	(revision 18301)
@@ -33,4 +33,5 @@
 		void GetBprime(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
 		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
 		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
 		void UpdateConstraints(FemModel* femmodel);
Index: issm/trunk/src/c/analyses/BalancethicknessSoftAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/BalancethicknessSoftAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/BalancethicknessSoftAnalysis.cpp	(revision 18301)
@@ -45,4 +45,7 @@
 	   _error_("not implemented yet");
 }/*}}}*/
+void BalancethicknessSoftAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
 void BalancethicknessSoftAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 	_error_("not implemented yet");
Index: issm/trunk/src/c/analyses/BalancethicknessSoftAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/BalancethicknessSoftAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/BalancethicknessSoftAnalysis.h	(revision 18301)
@@ -27,4 +27,5 @@
 		ElementVector* CreatePVector(Element* element);
 		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
 		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
 		void UpdateConstraints(FemModel* femmodel);
Index: issm/trunk/src/c/analyses/BalancevelocityAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/BalancevelocityAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/BalancevelocityAnalysis.cpp	(revision 18301)
@@ -29,5 +29,5 @@
 	iomodel->FetchDataToInput(elements,VxEnum);
 	iomodel->FetchDataToInput(elements,VyEnum);
-	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsGroundediceMeltingRateEnum);
 	iomodel->FetchDataToInput(elements,SurfaceforcingsMassBalanceEnum);
 	iomodel->FetchDataToInput(elements,BalancethicknessThickeningRateEnum);
@@ -183,8 +183,8 @@
 	/*Retrieve all inputs and parameters*/
 	basalelement->GetVerticesCoordinates(&xyz_list);
-	Input* ms_input   = basalelement->GetInput(SurfaceforcingsMassBalanceEnum);     _assert_(ms_input);
-	Input* mb_input   = basalelement->GetInput(BasalforcingsMeltingRateEnum);       _assert_(mb_input);
-	Input* dhdt_input = basalelement->GetInput(BalancethicknessThickeningRateEnum); _assert_(dhdt_input);
-	Input* H_input    = basalelement->GetInput(ThicknessEnum);                      _assert_(H_input);
+	Input* ms_input   = basalelement->GetInput(SurfaceforcingsMassBalanceEnum);          _assert_(ms_input);
+	Input* mb_input   = basalelement->GetInput(BasalforcingsGroundediceMeltingRateEnum); _assert_(mb_input);
+	Input* dhdt_input = basalelement->GetInput(BalancethicknessThickeningRateEnum);      _assert_(dhdt_input);
+	Input* H_input    = basalelement->GetInput(ThicknessEnum);                           _assert_(H_input);
 	IssmDouble h = basalelement->CharacteristicLength();
 
@@ -241,4 +241,7 @@
 	   _error_("not implemented yet");
 }/*}}}*/
+void BalancevelocityAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
 void BalancevelocityAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
Index: issm/trunk/src/c/analyses/BalancevelocityAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/BalancevelocityAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/BalancevelocityAnalysis.h	(revision 18301)
@@ -27,4 +27,5 @@
 		ElementVector* CreatePVector(Element* element);
 		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
 		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
 		void UpdateConstraints(FemModel* femmodel);
Index: issm/trunk/src/c/analyses/DamageEvolutionAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/DamageEvolutionAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/DamageEvolutionAnalysis.cpp	(revision 18301)
@@ -23,4 +23,5 @@
 	parameters->AddObject(iomodel->CopyConstantObject(DamageMaxiterEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(DamageMaxDamageEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(DamageElementinterpEnum));
 
 	/*Requested outputs*/
@@ -31,7 +32,7 @@
 
 	/*Retrieve law dependent parameters: */
-	char* law  = NULL;
+	int law;
 	iomodel->Constant(&law,DamageLawEnum);
-	if (strcmp(law,"pralong")==0){
+	if (law>0){
 		parameters->AddObject(iomodel->CopyConstantObject(DamageC1Enum));
 		parameters->AddObject(iomodel->CopyConstantObject(DamageC2Enum));
@@ -42,10 +43,11 @@
 		parameters->AddObject(iomodel->CopyConstantObject(DamageEquivStressEnum));
 	}
-	xDelete<char>(law);
 
 }/*}}}*/
 void DamageEvolutionAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
 
-	int finiteelement = P1Enum;
+	int finiteelement;
+
+	iomodel->Constant(&finiteelement,DamageElementinterpEnum);
 
 	/*Update elements: */
@@ -67,13 +69,10 @@
 	iomodel->FetchDataToInput(elements,PressureEnum);
 
-	bool dakota_analysis;
-	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
-	if(dakota_analysis){
-		elements->InputDuplicate(DamageDEnum, QmuDamageDEnum);
-	}
 }/*}}}*/
 void DamageEvolutionAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
 
-	int finiteelement = P1Enum;
+	int finiteelement;
+
+	iomodel->Constant(&finiteelement,DamageElementinterpEnum);
 
 	if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(1,MeshVertexonbaseEnum);
@@ -83,7 +82,6 @@
 void DamageEvolutionAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
 
-	int stabilization;
-	int finiteelement = P1Enum;
-	iomodel->Constant(&stabilization,DamageStabilizationEnum);
+	int finiteelement;
+	iomodel->Constant(&finiteelement,DamageElementinterpEnum);
 
 	IoModelToConstraintsx(constraints,iomodel,DamageSpcdamageEnum,DamageEvolutionAnalysisEnum,finiteelement);
@@ -263,5 +261,5 @@
 
 	/*Intermediaries*/
-	int      domaintype;
+	int      domaintype,damagelaw;
 	Element* basalelement;
 	IssmDouble  Jdet,dt;
@@ -282,4 +280,5 @@
 	}
 
+
 	/*Fetch number of nodes and dof for this finite element*/
 	int numnodes = basalelement->GetNumberOfNodes();
@@ -292,5 +291,11 @@
 	basalelement->GetVerticesCoordinates(&xyz_list);
 	basalelement->FindParam(&dt,TimesteppingTimeStepEnum);
-	this->CreateDamageFInput(basalelement);
+	basalelement->FindParam(&damagelaw,DamageLawEnum);
+	if(damagelaw==1 | damagelaw==2){
+		this->CreateDamageFInputPralong(basalelement);
+	}
+	else if(damagelaw==3){
+		this->CreateDamageFInputExp(basalelement);
+	}
 	Input* damaged_input = basalelement->GetInput(DamageDEnum); _assert_(damaged_input);
 	Input* damagef_input = basalelement->GetInput(DamageFEnum); _assert_(damagef_input);
@@ -380,4 +385,7 @@
 	   _error_("not implemented yet");
 }/*}}}*/
+void DamageEvolutionAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
 void DamageEvolutionAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
@@ -434,5 +442,5 @@
 
 /*Intermediaries*/
-void DamageEvolutionAnalysis::CreateDamageFInput(Element* element){/*{{{*/
+void DamageEvolutionAnalysis::CreateDamageFInputPralong(Element* element){/*{{{*/
 
 	/*Intermediaries */
@@ -441,9 +449,9 @@
 	IssmDouble J2s,Chi,Psi,PosPsi,NegPsi;
 	IssmDouble damage,tau_xx,tau_xy,tau_yy;
-	int equivstress,domaintype;
+	int equivstress,domaintype,damagelaw;
 
 	/*Fetch number of vertices and allocate output*/
-	int numvertices = element->GetNumberOfVertices();
-	IssmDouble* f   = xNew<IssmDouble>(numvertices);
+	int numnodes = element->GetNumberOfNodes();
+	IssmDouble* f   = xNew<IssmDouble>(numnodes);
 
 	/*retrieve parameters:*/
@@ -454,4 +462,5 @@
 	element->FindParam(&stress_threshold,DamageStressThresholdEnum);
 	element->FindParam(&domaintype,DomainTypeEnum);
+	element->FindParam(&damagelaw,DamageLawEnum);
 
 	/*Compute stress tensor: */
@@ -470,6 +479,4 @@
 	}
 
-
-
 	/*retrieve the desired type of equivalent stress*/
 	element->FindParam(&equivstress,DamageEquivStressEnum);
@@ -477,6 +484,6 @@
 	/*Calculate damage evolution source term: */
 	Gauss* gauss=element->NewGauss();
-	for (int iv=0;iv<numvertices;iv++){
-		gauss->GaussVertex(iv);
+	for (int i=0;i<numnodes;i++){
+		gauss->GaussNode(element->GetElementType(),i);
 		
 		damage_input->GetInputValue(&damage,gauss);
@@ -502,12 +509,19 @@
 		}
 		Psi=Chi-stress_threshold;
-		PosPsi=max(Psi,0.);
 		NegPsi=max(-Chi,0.); /* healing only for compressive stresses */
 
-		f[iv]= c1*(pow(PosPsi,c2) - healing*pow(NegPsi,c2))*pow((1.-damage),-c3);
+		if(damagelaw==1){
+			PosPsi=max(Psi,0.);
+			f[i]= c1*(pow(PosPsi,c2) - healing*pow(NegPsi,c2))*pow((1./(1.-damage)),c3);
+		}
+		else if(damagelaw==2){
+			PosPsi=max(Psi,1.);
+			f[i]= c1*(pow(log10(PosPsi),c2) - healing*pow(NegPsi,c2))*pow((1./(1.-damage)),c3);
+		}
+		else _error_("damage law not supported");
 	}
 
 	/*Add input*/
-	element->AddInput(DamageFEnum,f,P1Enum);
+	element->AddInput(DamageFEnum,f,element->GetElementType());
 	
 	/*Clean up and return*/
@@ -515,2 +529,73 @@
 	delete gauss;
 }/*}}}*/
+void DamageEvolutionAnalysis::CreateDamageFInputExp(Element* element){/*{{{*/
+
+	/*Intermediaries */
+	IssmDouble epsf,stress_threshold,eps0;
+	IssmDouble damage,B,n,epseff;
+	IssmDouble eps_xx,eps_yy,eps_xy,eps1,eps2,epstmp;
+	int domaintype,damagelaw;
+
+	/*Fetch number of vertices and allocate output*/
+	int numnodes = element->GetNumberOfNodes();
+	IssmDouble* f   = xNew<IssmDouble>(numnodes);
+
+	/*retrieve parameters:*/
+	element->FindParam(&epsf,DamageC1Enum);
+	element->FindParam(&stress_threshold,DamageStressThresholdEnum);
+	element->FindParam(&domaintype,DomainTypeEnum);
+	element->FindParam(&damagelaw,DamageLawEnum);
+
+	/*Compute stress tensor: */
+	element->ComputeStrainRate();
+
+	/*retrieve what we need: */
+	Input* eps_xx_input  = element->GetInput(StrainRatexxEnum);     _assert_(eps_xx_input);
+	Input* eps_xy_input  = element->GetInput(StrainRatexyEnum);     _assert_(eps_xy_input);
+	Input* eps_yy_input  = element->GetInput(StrainRateyyEnum);     _assert_(eps_yy_input);
+	Input*  n_input=element->GetInput(MaterialsRheologyNEnum); _assert_(n_input);
+	Input* damage_input = NULL;
+	Input* B_input = NULL;
+	if(domaintype==Domain2DhorizontalEnum){
+		damage_input = element->GetInput(DamageDbarEnum); 	_assert_(damage_input);
+		B_input=element->GetInput(MaterialsRheologyBbarEnum); _assert_(B_input);
+	}
+	else{
+		damage_input = element->GetInput(DamageDEnum);   _assert_(damage_input);
+		B_input=element->GetInput(MaterialsRheologyBEnum); _assert_(B_input);
+	}
+
+	/*Calculate damage evolution source term: */
+	Gauss* gauss=element->NewGauss();
+	for (int i=0;i<numnodes;i++){
+		gauss->GaussNode(element->GetElementType(),i);
+		
+		eps_xx_input->GetInputValue(&eps_xx,gauss);
+		eps_xy_input->GetInputValue(&eps_xy,gauss);
+		eps_yy_input->GetInputValue(&eps_yy,gauss);
+		B_input->GetInputValue(&B,gauss);
+		n_input->GetInputValue(&n,gauss);
+		damage_input->GetInputValue(&damage,gauss);
+	
+		/*Calculate principal effective strain rates*/
+		eps1=(eps_xx+eps_yy)/2.+sqrt(pow((eps_xx-eps_yy)/2.,2)+pow(eps_xy,2));
+		eps2=(eps_xx+eps_yy)/2.-sqrt(pow((eps_xx-eps_yy)/2.,2)+pow(eps_xy,2));
+		if(fabs(eps2)>fabs(eps1)){epstmp=eps2; eps2=eps1; eps1=epstmp;}
+
+		/*Calculate effective strain rate and threshold strain rate*/
+		epseff=1./sqrt(2.)*sqrt(eps1*eps1-eps1*eps2+eps2*eps2);
+		eps0=pow(stress_threshold/B,n);
+
+		if(epseff>eps0){
+			f[i]=1.-pow(eps0/epseff,1./n)*exp(-(epseff-eps0)/(epsf-eps0))-damage;
+		}
+		else f[i]=0;
+	}
+
+	/*Add input*/
+	element->AddInput(DamageFEnum,f,element->GetElementType());
+	
+	/*Clean up and return*/
+	xDelete<IssmDouble>(f);
+	delete gauss;
+}/*}}}*/
Index: issm/trunk/src/c/analyses/DamageEvolutionAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/DamageEvolutionAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/DamageEvolutionAnalysis.h	(revision 18301)
@@ -29,9 +29,11 @@
 		void GetBprime(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
 		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
 		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
 		void UpdateConstraints(FemModel* femmodel);
 
 		/*Intermediaries*/
-		void CreateDamageFInput(Element* element);
+		void CreateDamageFInputPralong(Element* element);
+		void CreateDamageFInputExp(Element* element);
 };
 #endif
Index: issm/trunk/src/c/analyses/DepthAverageAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/DepthAverageAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/DepthAverageAnalysis.cpp	(revision 18301)
@@ -160,4 +160,7 @@
 	   _error_("not implemented yet");
 }/*}}}*/
+void DepthAverageAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
 void DepthAverageAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
Index: issm/trunk/src/c/analyses/DepthAverageAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/DepthAverageAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/DepthAverageAnalysis.h	(revision 18301)
@@ -28,4 +28,5 @@
 		void GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
 		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
 		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
 		void UpdateConstraints(FemModel* femmodel);
Index: issm/trunk/src/c/analyses/EnthalpyAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/EnthalpyAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/EnthalpyAnalysis.cpp	(revision 18301)
@@ -71,5 +71,5 @@
 	iomodel->FetchDataToInput(elements,BasalforcingsGeothermalfluxEnum);
 	iomodel->FetchDataToInput(elements,WatercolumnEnum);
-	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsGroundediceMeltingRateEnum);
 	iomodel->FetchDataToInput(elements,VxEnum);
 	iomodel->FetchDataToInput(elements,VyEnum);
@@ -78,11 +78,4 @@
 	InputUpdateFromConstantx(elements,0.,VyMeshEnum);
 	InputUpdateFromConstantx(elements,0.,VzMeshEnum);
-	if(dakota_analysis){
-		elements->InputDuplicate(TemperatureEnum,QmuTemperatureEnum);
-		elements->InputDuplicate(BasalforcingsMeltingRateEnum,QmuMeltingEnum);
-		elements->InputDuplicate(VxMeshEnum,QmuVxMeshEnum);
-		elements->InputDuplicate(VxMeshEnum,QmuVyMeshEnum);
-		elements->InputDuplicate(VxMeshEnum,QmuVzMeshEnum);
-	}
 	if(islevelset){
 		iomodel->FetchDataToInput(elements,IceMaskNodeActivationEnum);
@@ -779,4 +772,7 @@
 void EnthalpyAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 	element->GetSolutionFromInputsOneDof(solution,EnthalpyEnum);
+}/*}}}*/
+void EnthalpyAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
 }/*}}}*/
 void EnthalpyAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
@@ -962,5 +958,5 @@
 	element->GetInputListOnVertices(pressure,PressureEnum);
 	element->GetInputListOnVertices(watercolumn,WatercolumnEnum);
-	element->GetInputListOnVertices(basalmeltingrate,BasalforcingsMeltingRateEnum);
+	element->GetInputListOnVertices(basalmeltingrate,BasalforcingsGroundediceMeltingRateEnum);
 
 	Gauss* gauss=element->NewGauss();
@@ -1042,5 +1038,5 @@
 	element->AddInput(EnthalpyEnum,enthalpy,P1Enum);
 	element->AddInput(WatercolumnEnum,watercolumn,P1Enum);
-	element->AddInput(BasalforcingsMeltingRateEnum,basalmeltingrate,P1Enum);
+	element->AddInput(BasalforcingsGroundediceMeltingRateEnum,basalmeltingrate,P1Enum);
 
 	/*Clean up and return*/
Index: issm/trunk/src/c/analyses/EnthalpyAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/EnthalpyAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/EnthalpyAnalysis.h	(revision 18301)
@@ -35,4 +35,5 @@
 		void GetBAdvecprime(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
 		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
 		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
 		void UpdateConstraints(FemModel* femmodel);
Index: issm/trunk/src/c/analyses/EnumToAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/EnumToAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/EnumToAnalysis.cpp	(revision 18301)
@@ -95,4 +95,7 @@
 		case ThermalAnalysisEnum : return new ThermalAnalysis();
 		#endif
+		#ifdef _HAVE_UZAWAPRESSURE_
+		case UzawaPressureAnalysisEnum : return new UzawaPressureAnalysis();
+		#endif
 		#ifdef _HAVE_GIA_
 		case GiaAnalysisEnum : return new GiaAnalysis();
Index: issm/trunk/src/c/analyses/EnumToAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/EnumToAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/EnumToAnalysis.h	(revision 18301)
@@ -22,4 +22,5 @@
 		ElementVector* CreatePVector(Element* element);
 		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
 		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
 		void UpdateConstraints(FemModel* femmodel);
Index: issm/trunk/src/c/analyses/ExtrapolationAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/ExtrapolationAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/ExtrapolationAnalysis.cpp	(revision 18301)
@@ -240,4 +240,7 @@
 	_error_("not implemented yet");
 }/*}}}*/
+void ExtrapolationAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
 void ExtrapolationAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
Index: issm/trunk/src/c/analyses/ExtrapolationAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/ExtrapolationAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/ExtrapolationAnalysis.h	(revision 18301)
@@ -26,5 +26,6 @@
 	ElementMatrix* CreateKMatrix(Element* element);
 	ElementVector* CreatePVector(Element* element);
-	void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
 	void InputUpdateFromSolution(IssmDouble* solution,Element* element);
 	void UpdateConstraints(FemModel* femmodel);
Index: issm/trunk/src/c/analyses/ExtrudeFromBaseAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/ExtrudeFromBaseAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/ExtrudeFromBaseAnalysis.cpp	(revision 18301)
@@ -222,4 +222,7 @@
 	   _error_("not implemented yet");
 }/*}}}*/
+void ExtrudeFromBaseAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
 void ExtrudeFromBaseAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
Index: issm/trunk/src/c/analyses/ExtrudeFromBaseAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/ExtrudeFromBaseAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/ExtrudeFromBaseAnalysis.h	(revision 18301)
@@ -31,4 +31,5 @@
 		void GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
 		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
 		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
 		void UpdateConstraints(FemModel* femmodel);
Index: issm/trunk/src/c/analyses/ExtrudeFromTopAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/ExtrudeFromTopAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/ExtrudeFromTopAnalysis.cpp	(revision 18301)
@@ -222,4 +222,7 @@
 	   _error_("not implemented yet");
 }/*}}}*/
+void ExtrudeFromTopAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
 void ExtrudeFromTopAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
Index: issm/trunk/src/c/analyses/ExtrudeFromTopAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/ExtrudeFromTopAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/ExtrudeFromTopAnalysis.h	(revision 18301)
@@ -31,4 +31,5 @@
 		void GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
 		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
 		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
 		void UpdateConstraints(FemModel* femmodel);
Index: issm/trunk/src/c/analyses/FreeSurfaceBaseAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/FreeSurfaceBaseAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/FreeSurfaceBaseAnalysis.cpp	(revision 18301)
@@ -31,6 +31,6 @@
 	iomodel->FetchDataToInput(elements,SurfaceEnum);
 	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
-	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
-	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateCorrectionEnum,0.);
+	iomodel->FetchDataToInput(elements,BasalforcingsGroundediceMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsFloatingiceMeltingRateEnum);
 	iomodel->FetchDataToInput(elements,VxEnum);
 	iomodel->FetchDataToInput(elements,VyEnum);
@@ -232,5 +232,5 @@
 	int         domaintype,dim;
 	IssmDouble  Jdet,dt;
-	IssmDouble  mb,mb_correction,bed,vz;
+	IssmDouble  gmb,fmb,mb,bed,phi,vz;
 	Element*    basalelement = NULL;
 	IssmDouble *xyz_list  = NULL;
@@ -266,7 +266,8 @@
 	basalelement->GetVerticesCoordinates(&xyz_list);
 	basalelement->FindParam(&dt,TimesteppingTimeStepEnum);
-	Input* mb_input            = basalelement->GetInput(BasalforcingsMeltingRateEnum);   _assert_(mb_input);
-	Input* mb_correction_input = basalelement->GetInput(BasalforcingsMeltingRateCorrectionEnum);
-	Input* base_input           = basalelement->GetInput(BaseEnum);                        _assert_(base_input);
+	Input* groundedice_input   = basalelement->GetInput(MaskGroundediceLevelsetEnum);              _assert_(groundedice_input);
+	Input* gmb_input           = basalelement->GetInput(BasalforcingsGroundediceMeltingRateEnum);  _assert_(gmb_input);
+	Input* fmb_input           = basalelement->GetInput(BasalforcingsFloatingiceMeltingRateEnum);  _assert_(fmb_input);
+	Input* base_input          = basalelement->GetInput(BaseEnum);                                 _assert_(base_input);
 	Input* vz_input      = NULL;
 	switch(dim){
@@ -276,5 +277,4 @@
 	}
 
-	/*Initialize mb_correction to 0, do not forget!:*/
 	/* Start  looping on the number of gaussian points: */
 	Gauss* gauss=basalelement->NewGauss(2);
@@ -286,12 +286,12 @@
 
 		vz_input->GetInputValue(&vz,gauss);
-		mb_input->GetInputValue(&mb,gauss);
+		gmb_input->GetInputValue(&gmb,gauss);
+		fmb_input->GetInputValue(&fmb,gauss);
 		base_input->GetInputValue(&bed,gauss);
-		if(mb_correction_input)
-		 mb_correction_input->GetInputValue(&mb_correction,gauss);
-		else
-		 mb_correction=0.;
-
-		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(bed+dt*(mb-mb_correction) + dt*vz)*basis[i];
+		groundedice_input->GetInputValue(&phi,gauss);
+		if(phi>0) mb=gmb;
+		else mb=fmb;
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(bed+dt*(mb) + dt*vz)*basis[i];
 	}
 
@@ -363,4 +363,7 @@
 void FreeSurfaceBaseAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 	   _error_("not implemented yet");
+}/*}}}*/
+void FreeSurfaceBaseAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
 }/*}}}*/
 void FreeSurfaceBaseAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
Index: issm/trunk/src/c/analyses/FreeSurfaceBaseAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/FreeSurfaceBaseAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/FreeSurfaceBaseAnalysis.h	(revision 18301)
@@ -29,4 +29,5 @@
 		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);
Index: issm/trunk/src/c/analyses/FreeSurfaceTopAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/FreeSurfaceTopAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/FreeSurfaceTopAnalysis.cpp	(revision 18301)
@@ -367,4 +367,7 @@
 	   _error_("not implemented yet");
 }/*}}}*/
+void FreeSurfaceTopAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
 void FreeSurfaceTopAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
Index: issm/trunk/src/c/analyses/FreeSurfaceTopAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/FreeSurfaceTopAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/FreeSurfaceTopAnalysis.h	(revision 18301)
@@ -29,4 +29,5 @@
 		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);
Index: issm/trunk/src/c/analyses/GiaAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/GiaAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/GiaAnalysis.cpp	(revision 18301)
@@ -57,4 +57,7 @@
 	   _error_("not implemented yet");
 }/*}}}*/
+void GiaAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
 void GiaAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 	_error_("not implemented yet");
Index: issm/trunk/src/c/analyses/GiaAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/GiaAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/GiaAnalysis.h	(revision 18301)
@@ -27,4 +27,5 @@
 		ElementVector* CreatePVector(Element* element);
 		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
 		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
 		void UpdateConstraints(FemModel* femmodel);
Index: issm/trunk/src/c/analyses/HydrologyDCEfficientAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/HydrologyDCEfficientAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/HydrologyDCEfficientAnalysis.cpp	(revision 18301)
@@ -316,4 +316,7 @@
 void HydrologyDCEfficientAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 	element->GetSolutionFromInputsOneDof(solution,EplHeadEnum);
+}/*}}}*/
+void HydrologyDCEfficientAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
 }/*}}}*/
 void HydrologyDCEfficientAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
@@ -556,5 +559,5 @@
 				if(EPL_N<0.0)EPL_N=0.0;
 				/*Get then the square of the gradient of EPL heads*/
-				EPLgrad2 = (epl_slopeX[i]*epl_slopeX[i]+epl_slopeY[i]*epl_slopeY[i]);
+				EPLgrad2 = (epl_slopeX[i]+epl_slopeY[i])*(epl_slopeX[i]+epl_slopeY[i]);
 				
 				/*And proceed to the real thing*/
Index: issm/trunk/src/c/analyses/HydrologyDCEfficientAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/HydrologyDCEfficientAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/HydrologyDCEfficientAnalysis.h	(revision 18301)
@@ -28,4 +28,5 @@
 		ElementVector* CreatePVector(Element* element);
 		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
 		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
 		void UpdateConstraints(FemModel* femmodel);
Index: issm/trunk/src/c/analyses/HydrologyDCInefficientAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/HydrologyDCInefficientAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/HydrologyDCInefficientAnalysis.cpp	(revision 18301)
@@ -84,5 +84,5 @@
 	iomodel->FetchDataToInput(elements,BaseEnum);
 	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
-	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsGroundediceMeltingRateEnum);
 	iomodel->FetchDataToInput(elements,HydrologydcBasalMoulinInputEnum);
 	iomodel->FetchDataToInput(elements,SedimentHeadEnum);
@@ -307,6 +307,6 @@
 	Input* thickness_input   = basalelement->GetInput(ThicknessEnum);
 	Input* base_input        = basalelement->GetInput(BaseEnum);
-	Input* water_input       = basalelement->GetInput(BasalforcingsMeltingRateEnum);    _assert_(water_input);
-	if(dt!= 0.){old_wh_input = basalelement->GetInput(SedimentHeadOldEnum);             _assert_(old_wh_input);}
+	Input* water_input       = basalelement->GetInput(BasalforcingsGroundediceMeltingRateEnum); _assert_(water_input);
+	if(dt!= 0.){old_wh_input = basalelement->GetInput(SedimentHeadOldEnum);                     _assert_(old_wh_input);}
 
 	IssmDouble sediment_storing    = SedimentStoring(basalelement);
@@ -393,4 +393,7 @@
 	element->GetSolutionFromInputsOneDof(solution,SedimentHeadEnum);
 }/*}}}*/
+void HydrologyDCInefficientAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
 void HydrologyDCInefficientAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
@@ -601,5 +604,7 @@
 		sed_trans_input->GetInputValue(&sediment_transmitivity,gauss);
 		element->FindParam(&leakage,HydrologydcLeakageFactorEnum);
+		
 		transfer=(sediment_transmitivity)/(sediment_thickness*leakage);
+		
 		/* if(epl_head>sed_head){ */
 		/* 	h_max=GetHydrologyDCInefficientHmax(element,gauss,thickness_input,base_input); */
@@ -616,4 +621,5 @@
 		/* 	//transfer=(sediment_storing*sediment_transmitivity)/(sediment_thickness*leakage); */
 		/* } */
+		
 		break;
 	default:
Index: issm/trunk/src/c/analyses/HydrologyDCInefficientAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/HydrologyDCInefficientAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/HydrologyDCInefficientAnalysis.h	(revision 18301)
@@ -28,4 +28,5 @@
 		ElementVector* CreatePVector(Element* element);
 		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
 		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
 		void UpdateConstraints(FemModel* femmodel);
Index: issm/trunk/src/c/analyses/HydrologyShreveAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/HydrologyShreveAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/HydrologyShreveAnalysis.cpp	(revision 18301)
@@ -50,5 +50,5 @@
 	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
 	iomodel->FetchDataToInput(elements,MaskGroundediceLevelsetEnum);
-	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsGroundediceMeltingRateEnum);
 	iomodel->FetchDataToInput(elements,WatercolumnEnum);
 
@@ -205,6 +205,6 @@
 	element->GetVerticesCoordinates(&xyz_list);
 	element->FindParam(&dt,TimesteppingTimeStepEnum);
-	Input* mb_input   = element->GetInput(BasalforcingsMeltingRateEnum); _assert_(mb_input);
-	Input* oldw_input = element->GetInput(WaterColumnOldEnum);           _assert_(oldw_input);
+	Input* mb_input   = element->GetInput(BasalforcingsGroundediceMeltingRateEnum); _assert_(mb_input);
+	Input* oldw_input = element->GetInput(WaterColumnOldEnum);                      _assert_(oldw_input);
 
 	/*Initialize mb_correction to 0, do not forget!:*/
@@ -292,4 +292,7 @@
 	element->GetSolutionFromInputsOneDof(solution,WatercolumnEnum);
 }/*}}}*/
+void HydrologyShreveAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
 void HydrologyShreveAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
Index: issm/trunk/src/c/analyses/HydrologyShreveAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/HydrologyShreveAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/HydrologyShreveAnalysis.h	(revision 18301)
@@ -27,4 +27,5 @@
 		ElementVector* CreatePVector(Element* element);
 		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
 		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
 		void UpdateConstraints(FemModel* femmodel);
Index: issm/trunk/src/c/analyses/L2ProjectionBaseAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/L2ProjectionBaseAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/L2ProjectionBaseAnalysis.cpp	(revision 18301)
@@ -199,4 +199,7 @@
 	   _error_("not implemented yet");
 }/*}}}*/
+void L2ProjectionBaseAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
 void L2ProjectionBaseAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
Index: issm/trunk/src/c/analyses/L2ProjectionBaseAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/L2ProjectionBaseAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/L2ProjectionBaseAnalysis.h	(revision 18301)
@@ -27,4 +27,5 @@
 		ElementVector* CreatePVector(Element* element);
 		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
 		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
 		void UpdateConstraints(FemModel* femmodel);
Index: issm/trunk/src/c/analyses/L2ProjectionEPLAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/L2ProjectionEPLAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/L2ProjectionEPLAnalysis.cpp	(revision 18301)
@@ -229,4 +229,7 @@
 	   _error_("not implemented yet");
 }/*}}}*/
+void L2ProjectionEPLAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
 void L2ProjectionEPLAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 	int inputenum,domaintype;
Index: issm/trunk/src/c/analyses/L2ProjectionEPLAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/L2ProjectionEPLAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/L2ProjectionEPLAnalysis.h	(revision 18301)
@@ -27,4 +27,5 @@
 		ElementVector* CreatePVector(Element* element);
 		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
 		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
 		void UpdateConstraints(FemModel* femmodel);
Index: issm/trunk/src/c/analyses/LevelsetAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/LevelsetAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/LevelsetAnalysis.cpp	(revision 18301)
@@ -89,11 +89,17 @@
 ElementMatrix* LevelsetAnalysis::CreateKMatrix(Element* element){/*{{{*/
 
+	if(!element->IsOnBase()) return NULL;
 	_error_("not implemented yet");
 }/*}}}*/
 ElementVector* LevelsetAnalysis::CreatePVector(Element* element){/*{{{*/
+	
+	if(!element->IsOnBase()) return NULL;
 	_error_("not implemented yet");
 }/*}}}*/
 void LevelsetAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 	_error_("not implemented yet");
+}/*}}}*/
+void LevelsetAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
 }/*}}}*/
 void LevelsetAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
Index: issm/trunk/src/c/analyses/LevelsetAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/LevelsetAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/LevelsetAnalysis.h	(revision 18301)
@@ -27,4 +27,5 @@
 		ElementVector* CreatePVector(Element* element);
 		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
 		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
 		void UpdateConstraints(FemModel* femmodel);
Index: issm/trunk/src/c/analyses/LsfReinitializationAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/LsfReinitializationAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/LsfReinitializationAnalysis.cpp	(revision 18301)
@@ -283,4 +283,7 @@
 	xDelete<int>(doflist);
 
+}/*}}}*/
+void LsfReinitializationAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
 }/*}}}*/
 void LsfReinitializationAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
Index: issm/trunk/src/c/analyses/LsfReinitializationAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/LsfReinitializationAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/LsfReinitializationAnalysis.h	(revision 18301)
@@ -26,5 +26,6 @@
 	ElementMatrix* CreateKMatrix(Element* element);
 	ElementVector* CreatePVector(Element* element);
-	void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
 	void InputUpdateFromSolution(IssmDouble* solution,Element* element);
 	void UpdateConstraints(FemModel* femmodel);
Index: issm/trunk/src/c/analyses/MasstransportAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/MasstransportAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/MasstransportAnalysis.cpp	(revision 18301)
@@ -64,6 +64,6 @@
 	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
 	iomodel->FetchDataToInput(elements,MaskGroundediceLevelsetEnum);
-	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
-	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateCorrectionEnum,0.);
+	iomodel->FetchDataToInput(elements,BasalforcingsGroundediceMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsFloatingiceMeltingRateEnum);
 	iomodel->FetchDataToInput(elements,VxEnum);
 	iomodel->FetchDataToInput(elements,VyEnum);
@@ -71,12 +71,4 @@
 	if(stabilization==3){
 		iomodel->FetchDataToInput(elements,MasstransportSpcthicknessEnum); //for DG, we need the spc in the element
-	}
-
-	if(dakota_analysis){
-		elements->InputDuplicate(BaseEnum,QmuBaseEnum);
-		elements->InputDuplicate(ThicknessEnum,QmuThicknessEnum);
-		elements->InputDuplicate(SurfaceEnum,QmuSurfaceEnum);
-		elements->InputDuplicate(MaskIceLevelsetEnum,QmuMaskIceLevelsetEnum);
-		if(isgroundingline) elements->InputDuplicate(MaskGroundediceLevelsetEnum,QmuMaskGroundediceLevelsetEnum);
 	}
 
@@ -115,4 +107,15 @@
 		case SMBhenningEnum:
 			iomodel->FetchDataToInput(elements,SurfaceforcingsSmbrefEnum,0.);
+			break;
+		case SMBcomponentsEnum:
+			iomodel->FetchDataToInput(elements,SurfaceforcingsAccumulationEnum,0.);
+			iomodel->FetchDataToInput(elements,SurfaceforcingsEvaporationEnum,0.);
+			iomodel->FetchDataToInput(elements,SurfaceforcingsRunoffEnum,0.);
+			break;
+		case SMBmeltcomponentsEnum:
+			iomodel->FetchDataToInput(elements,SurfaceforcingsAccumulationEnum,0.);
+			iomodel->FetchDataToInput(elements,SurfaceforcingsEvaporationEnum,0.);
+			iomodel->FetchDataToInput(elements,SurfaceforcingsMeltEnum,0.);
+			iomodel->FetchDataToInput(elements,SurfaceforcingsRefreezeEnum,0.);
 			break;
 		default:
@@ -513,5 +516,5 @@
 	/*Intermediaries */
 	IssmDouble  Jdet,dt;
-	IssmDouble  ms,mb,mb_correction=0.,thickness;
+	IssmDouble  ms,mb,gmb,fmb,thickness,phi;
 	IssmDouble* xyz_list = NULL;
 
@@ -526,10 +529,10 @@
 	element->GetVerticesCoordinates(&xyz_list);
 	element->FindParam(&dt,TimesteppingTimeStepEnum);
-	Input* mb_correction_input = element->GetInput(BasalforcingsMeltingRateCorrectionEnum);
-	Input* mb_input            = element->GetInput(BasalforcingsMeltingRateEnum);     _assert_(mb_input);
-	Input* ms_input            = element->GetInput(SurfaceforcingsMassBalanceEnum);   _assert_(ms_input);
-	Input* thickness_input     = element->GetInput(ThicknessEnum);                    _assert_(thickness_input);
-
-	/*Initialize mb_correction to 0, do not forget!:*/
+	Input* gmb_input           = element->GetInput(BasalforcingsGroundediceMeltingRateEnum);  _assert_(gmb_input);
+	Input* fmb_input           = element->GetInput(BasalforcingsFloatingiceMeltingRateEnum);  _assert_(fmb_input);
+	Input* groundedice_input   = element->GetInput(MaskGroundediceLevelsetEnum);              _assert_(groundedice_input);
+	Input* ms_input            = element->GetInput(SurfaceforcingsMassBalanceEnum);           _assert_(ms_input);
+	Input* thickness_input     = element->GetInput(ThicknessEnum);                            _assert_(thickness_input);
+
 	/* Start  looping on the number of gaussian points: */
 	Gauss* gauss=element->NewGauss(2);
@@ -541,10 +544,12 @@
 
 		ms_input->GetInputValue(&ms,gauss);
-		mb_input->GetInputValue(&mb,gauss);
+		gmb_input->GetInputValue(&gmb,gauss);
+		fmb_input->GetInputValue(&fmb,gauss);
+		groundedice_input->GetInputValue(&phi,gauss);
 		thickness_input->GetInputValue(&thickness,gauss);
-		if(mb_correction_input)
-		 mb_correction_input->GetInputValue(&mb_correction,gauss);
-
-		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(thickness+dt*(ms-mb-mb_correction))*basis[i];
+		if(phi>0.) mb=gmb;
+		else mb=fmb;
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(thickness+dt*(ms-mb))*basis[i];
 	}
 
@@ -562,5 +567,5 @@
 	/*Intermediaries */
 	IssmDouble  Jdet,dt;
-	IssmDouble  ms,mb,mb_correction=0.,thickness;
+	IssmDouble  ms,mb,gmb,fmb,thickness,phi;
 	IssmDouble* xyz_list = NULL;
 
@@ -575,10 +580,10 @@
 	element->GetVerticesCoordinates(&xyz_list);
 	element->FindParam(&dt,TimesteppingTimeStepEnum);
-	Input* mb_correction_input = element->GetInput(BasalforcingsMeltingRateCorrectionEnum);
-	Input* mb_input            = element->GetInput(BasalforcingsMeltingRateEnum);     _assert_(mb_input);
-	Input* ms_input            = element->GetInput(SurfaceforcingsMassBalanceEnum);   _assert_(ms_input);
-	Input* thickness_input     = element->GetInput(ThicknessEnum);                    _assert_(thickness_input);
-
-	/*Initialize mb_correction to 0, do not forget!:*/
+	Input* gmb_input           = element->GetInput(BasalforcingsGroundediceMeltingRateEnum); _assert_(gmb_input);
+	Input* fmb_input           = element->GetInput(BasalforcingsFloatingiceMeltingRateEnum); _assert_(fmb_input);
+	Input* ms_input            = element->GetInput(SurfaceforcingsMassBalanceEnum);          _assert_(ms_input);
+	Input* groundedice_input   = element->GetInput(MaskGroundediceLevelsetEnum);             _assert_(groundedice_input);
+	Input* thickness_input     = element->GetInput(ThicknessEnum);                           _assert_(thickness_input);
+
 	/* Start  looping on the number of gaussian points: */
 	Gauss* gauss=element->NewGauss(2);
@@ -590,10 +595,12 @@
 
 		ms_input->GetInputValue(&ms,gauss);
-		mb_input->GetInputValue(&mb,gauss);
+		gmb_input->GetInputValue(&gmb,gauss);
+		fmb_input->GetInputValue(&fmb,gauss);
+		groundedice_input->GetInputValue(&phi,gauss);
 		thickness_input->GetInputValue(&thickness,gauss);
-		if(mb_correction_input)
-		 mb_correction_input->GetInputValue(&mb_correction,gauss);
-
-		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(thickness+dt*(ms-mb-mb_correction))*basis[i];
+		if(phi>0) mb=gmb;
+		else mb=fmb;
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(thickness+dt*(ms-mb))*basis[i];
 	}
 
@@ -664,4 +671,7 @@
 	   _error_("not implemented yet");
 }/*}}}*/
+void MasstransportAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
 void MasstransportAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
Index: issm/trunk/src/c/analyses/MasstransportAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/MasstransportAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/MasstransportAnalysis.h	(revision 18301)
@@ -33,4 +33,5 @@
 		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);
Index: issm/trunk/src/c/analyses/MeltingAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/MeltingAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/MeltingAnalysis.cpp	(revision 18301)
@@ -43,5 +43,5 @@
 	iomodel->FetchDataToInput(elements,MaterialsRheologyBEnum);
 	iomodel->FetchDataToInput(elements,MaterialsRheologyNEnum);
-	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsGroundediceMeltingRateEnum);
 	iomodel->FetchDataToInput(elements,PressureEnum);
 	
@@ -151,6 +151,9 @@
 	   _error_("not implemented yet");
 }/*}}}*/
+void MeltingAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
 void MeltingAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
-	element->InputUpdateFromSolutionOneDof(solution,BasalforcingsMeltingRateEnum);
+	element->InputUpdateFromSolutionOneDof(solution,BasalforcingsGroundediceMeltingRateEnum);
 }/*}}}*/
 void MeltingAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
Index: issm/trunk/src/c/analyses/MeltingAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/MeltingAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/MeltingAnalysis.h	(revision 18301)
@@ -27,4 +27,5 @@
 		ElementVector* CreatePVector(Element* element);
 		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
 		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
 		void UpdateConstraints(FemModel* femmodel);
Index: issm/trunk/src/c/analyses/MeshdeformationAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/MeshdeformationAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/MeshdeformationAnalysis.cpp	(revision 18301)
@@ -45,4 +45,7 @@
 	   _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");
Index: issm/trunk/src/c/analyses/MeshdeformationAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/MeshdeformationAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/MeshdeformationAnalysis.h	(revision 18301)
@@ -27,4 +27,5 @@
 		ElementVector* CreatePVector(Element* element);
 		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
 		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
 		void UpdateConstraints(FemModel* femmodel);
Index: issm/trunk/src/c/analyses/SmoothedSurfaceSlopeXAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/SmoothedSurfaceSlopeXAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/SmoothedSurfaceSlopeXAnalysis.cpp	(revision 18301)
@@ -172,4 +172,7 @@
 	   _error_("not implemented yet");
 }/*}}}*/
+void SmoothedSurfaceSlopeXAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
 void SmoothedSurfaceSlopeXAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 	element->InputUpdateFromSolutionOneDof(solution,SurfaceSlopeXEnum);
Index: issm/trunk/src/c/analyses/SmoothedSurfaceSlopeXAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/SmoothedSurfaceSlopeXAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/SmoothedSurfaceSlopeXAnalysis.h	(revision 18301)
@@ -27,4 +27,5 @@
 		ElementVector* CreatePVector(Element* element);
 		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
 		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
 		void UpdateConstraints(FemModel* femmodel);
Index: issm/trunk/src/c/analyses/SmoothedSurfaceSlopeYAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/SmoothedSurfaceSlopeYAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/SmoothedSurfaceSlopeYAnalysis.cpp	(revision 18301)
@@ -171,4 +171,7 @@
 	   _error_("not implemented yet");
 }/*}}}*/
+void SmoothedSurfaceSlopeYAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
 void SmoothedSurfaceSlopeYAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 	element->InputUpdateFromSolutionOneDof(solution,SurfaceSlopeYEnum);
Index: issm/trunk/src/c/analyses/SmoothedSurfaceSlopeYAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/SmoothedSurfaceSlopeYAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/SmoothedSurfaceSlopeYAnalysis.h	(revision 18301)
@@ -27,4 +27,5 @@
 		ElementVector* CreatePVector(Element* element);
 		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
 		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
 		void UpdateConstraints(FemModel* femmodel);
Index: issm/trunk/src/c/analyses/StressbalanceAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/StressbalanceAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/StressbalanceAnalysis.cpp	(revision 18301)
@@ -7,5 +7,6 @@
 #include "../cores/cores.h"
 
-//#define FSANALYTICAL 21
+//#define FSANALYTICAL 12
+//#define LATERALFRICTION 1
 
 /*Model processing*/
@@ -89,4 +90,5 @@
 	int     numoutputs;
 	char**  requestedoutputs = NULL;
+	int     materials_type;
 
 	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsSIAEnum));
@@ -108,9 +110,16 @@
 	parameters->AddObject(iomodel->CopyConstantObject(FrictionLawEnum));
 
-	/*XTH parameters*/
+	/*XTH LATH parameters*/
 	iomodel->Constant(&fe_FS,FlowequationFeFSEnum);
-	if(fe_FS==XTaylorHoodEnum){
+	if(fe_FS==XTaylorHoodEnum || fe_FS==LATaylorHoodEnum){
 		parameters->AddObject(iomodel->CopyConstantObject(AugmentedLagrangianREnum));
+		parameters->AddObject(iomodel->CopyConstantObject(AugmentedLagrangianRlambdaEnum));
 		parameters->AddObject(iomodel->CopyConstantObject(AugmentedLagrangianThetaEnum));
+	}
+
+	iomodel->Constant(&materials_type,MaterialsEnum);
+	if(materials_type==MatdamageiceEnum){
+		parameters->AddObject(iomodel->CopyConstantObject(DamageC1Enum));
+		parameters->AddObject(iomodel->CopyConstantObject(DamageStressThresholdEnum));
 	}
 
@@ -125,5 +134,5 @@
 
 	/*Intermediaries*/
-	int    materials_type,finiteelement;
+	int    materials_type,finiteelement,fe_FS;
 	int    approximation,frictionlaw;
 	int*   finiteelement_list=NULL;
@@ -212,9 +221,10 @@
 	iomodel->FetchDataToInput(elements,MaterialsRheologyNEnum);
 	iomodel->FetchDataToInput(elements,VxEnum,0.);
-	if(dakota_analysis)elements->InputDuplicate(VxEnum,QmuVxEnum);
 	iomodel->FetchDataToInput(elements,VyEnum,0.);
-	if(dakota_analysis)elements->InputDuplicate(VyEnum,QmuVyEnum);
 	iomodel->FetchDataToInput(elements,LoadingforceXEnum);
 	iomodel->FetchDataToInput(elements,LoadingforceYEnum);
+	#ifdef LATERALFRICTION
+	iomodel->FetchDataToInput(elements,MeshVertexonboundaryEnum);
+	#endif
 	if(isdamage)iomodel->FetchDataToInput(elements,DamageDEnum);
 
@@ -227,13 +237,17 @@
 		iomodel->FetchDataToInput(elements,LoadingforceZEnum);
 		iomodel->FetchDataToInput(elements,VzEnum,0.);
-		if(dakota_analysis)elements->InputDuplicate(VzEnum,QmuVzEnum);
 	}
 	if(isFS){
 		iomodel->FetchDataToInput(elements,PressureEnum,0.);
-		iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum,0.);
-		if(dakota_analysis)elements->InputDuplicate(PressureEnum,QmuPressureEnum);
+		iomodel->FetchDataToInput(elements,BasalforcingsFloatingiceMeltingRateEnum,0.);
 	}
 	if(islevelset){
 		iomodel->FetchDataToInput(elements,IceMaskNodeActivationEnum);
+	}
+	/*LATH parameters*/
+	iomodel->Constant(&fe_FS,FlowequationFeFSEnum);
+	if(fe_FS==LATaylorHoodEnum){
+		iomodel->FetchDataToInput(elements,PressureEnum,0.);
+		InputUpdateFromConstantx(elements,0.,SigmaNNEnum);
 	}
 
@@ -414,11 +428,13 @@
 			/*Deduce velocity interpolation from finite element*/
 			switch(finiteelement){
-				case P1P1Enum          : finiteelement = P1Enum;       break;
-				case P1P1GLSEnum       : finiteelement = P1Enum;       break;
-				case MINIcondensedEnum : finiteelement = P1bubbleEnum; break;
-				case MINIEnum          : finiteelement = P1bubbleEnum; break;
-				case TaylorHoodEnum    : finiteelement = P2Enum;       break;
-				case XTaylorHoodEnum   : finiteelement = P2Enum;       break;
-				case OneLayerP4zEnum   : finiteelement = P2xP4Enum;    break;
+				case P1P1Enum            : finiteelement = P1Enum;       break;
+				case P1P1GLSEnum         : finiteelement = P1Enum;       break;
+				case MINIcondensedEnum   : finiteelement = P1bubbleEnum; break;
+				case MINIEnum            : finiteelement = P1bubbleEnum; break;
+				case TaylorHoodEnum      : finiteelement = P2Enum;       break;
+				case XTaylorHoodEnum     : finiteelement = P2Enum;       break;
+				case LATaylorHoodEnum    : finiteelement = P2Enum;       break;
+				case OneLayerP4zEnum     : finiteelement = P2xP4Enum;    break;
+				case CrouzeixRaviartEnum : finiteelement = P2bubbleEnum; break;
 				default: _error_("finite element "<<EnumToStringx(finiteelement)<<" not supported");
 			}
@@ -494,4 +510,14 @@
 							if(reCast<int,IssmDouble>(vertices_type[i])==NoneApproximationEnum){
 								constraints->AddObject(new SpcStatic(count+1,iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+i+1,0,g*rho_ice*(surface[i]-z[i])/FSreconditioning,StressbalanceAnalysisEnum));
+								count++;
+							}
+						}
+					}
+					break;
+				case P2bubbleEnum:
+					for(i=0;i<iomodel->numberofvertices;i++){
+						if(iomodel->my_vertices[i]){
+							if(reCast<int,IssmDouble>(vertices_type[i])==NoneApproximationEnum){
+								constraints->AddObject(new SpcStatic(count+1,iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberofelements+iomodel->numberoffaces+i+1,0,g*rho_ice*(surface[i]-z[i])/FSreconditioning,StressbalanceAnalysisEnum));
 								count++;
 							}
@@ -856,4 +882,6 @@
 		if (fe_FS==XTaylorHoodEnum)
 		 solutionsequence_la_theta(femmodel);
+		else if (fe_FS==LATaylorHoodEnum)
+		 solutionsequence_la(femmodel);
 		else if(newton>0)
 		 solutionsequence_newton(femmodel);
@@ -1039,4 +1067,7 @@
 	xDelete<IssmDouble>(values);
 	xDelete<int>(doflist);
+}/*}}}*/
+void StressbalanceAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
 }/*}}}*/
 void StressbalanceAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
@@ -1191,5 +1222,11 @@
 	ElementMatrix* Ke1=CreateKMatrixSSAViscous(basalelement);
 	ElementMatrix* Ke2=CreateKMatrixSSAFriction(basalelement);
+	#ifdef LATERALFRICTION
+	ElementMatrix* Ke3=CreateKMatrixSSALateralFriction(basalelement);
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2,Ke3);
+	delete Ke3;
+	#else
 	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+	#endif
 
 	/*clean-up and return*/
@@ -1279,4 +1316,70 @@
 	delete friction;
 	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(D);
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixSSALateralFriction(Element* element){/*{{{*/
+
+	/*Return if element is inactive*/
+	if(!element->IsIceInElement()) return NULL;
+
+	/*If no boundary, return NULL*/
+	if(!element->IsFaceOnBoundary()) return NULL;
+
+	/*Intermediaries*/
+	IssmDouble  alpha2;
+	IssmDouble  Jdet;
+	int         domaintype;
+	IssmDouble  icefront;
+	IssmDouble *xyz_list          = NULL;
+	IssmDouble *xyz_list_boundary = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	if(domaintype==Domain2DverticalEnum) return NULL; //not supported yet
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int dim      = 2;
+	int numnodes = element->GetNumberOfNodes();
+	int numdof   = numnodes*dim;
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke = element->NewElementMatrix(SSAApproximationEnum);
+	IssmDouble*    B  = xNew<IssmDouble>(dim*numdof);
+	IssmDouble*    D  = xNewZeroInit<IssmDouble>(dim*dim);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GetLevelCoordinates(&xyz_list_boundary,xyz_list,MeshVertexonboundaryEnum,1.);
+	Input* icelevelset_input = element->GetInput(MaskIceLevelsetEnum); _assert_(icelevelset_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(xyz_list,xyz_list_boundary,3);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		this->GetBSSAFriction(B,element,dim,xyz_list,gauss);
+		element->JacobianDeterminantSurface(&Jdet,xyz_list_boundary,gauss);
+		icelevelset_input->GetInputValue(&icefront, gauss);
+		if(icefront==0.)
+		 alpha2=0.;
+		else
+		 alpha2=2.e+12;
+		for(int i=0;i<dim;i++) D[i*dim+i]=alpha2*gauss->weight*Jdet;
+
+		TripleMultiply(B,dim,numdof,1,
+					D,dim,dim,0,
+					B,dim,numdof,0,
+					&Ke->values[0],1);
+	}
+
+	/*Transform Coordinate System*/
+	if(dim==2) element->TransformStiffnessMatrixCoord(Ke,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(xyz_list_boundary);
 	xDelete<IssmDouble>(B);
 	xDelete<IssmDouble>(D);
@@ -2838,4 +2941,6 @@
 	if(fe_FS==XTaylorHoodEnum)
 	 Ke1=CreateKMatrixFSViscousXTH(element);
+	else if(fe_FS==LATaylorHoodEnum)
+	 Ke1=CreateKMatrixFSViscousLATH(element);
 	else
 	 Ke1=CreateKMatrixFSViscous(element);
@@ -2849,4 +2954,134 @@
 	delete Ke2;
 	delete Ke3;
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixFSViscousLATH(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	int         i,dim,epssize;
+	IssmDouble  r,rl,Jdet,viscosity,DU,DUl;
+	IssmDouble	normal[3];
+	IssmDouble *xyz_list = NULL;
+	IssmDouble *xyz_list_base = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+	element->FindParam(&r,AugmentedLagrangianREnum);
+	if(dim==2) epssize = 3;
+	else       epssize = 6;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumnodes = element->GetNumberOfNodes(P1Enum);
+	int lnumnodes = element->GetNumberOfNodes(P2Enum);
+	int numdof    = vnumnodes*dim;
+	int pnumdof   = pnumnodes;
+	int lnumdof   = lnumnodes;
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes);
+	if(dim==2) for(i=0;i<vnumnodes;i++) cs_list[i] = XYEnum;
+	else       for(i=0;i<vnumnodes;i++) cs_list[i] = XYZEnum;
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke       = element->NewElementMatrix(FSvelocityEnum);
+	IssmDouble*    B        = xNew<IssmDouble>(epssize*numdof);
+	IssmDouble*    Bprime   = xNew<IssmDouble>(epssize*numdof);
+	IssmDouble*    BtBUzawa = xNewZeroInit<IssmDouble>(numdof*pnumdof);
+	IssmDouble*    BU       = xNew<IssmDouble>(pnumdof);
+	IssmDouble*    BprimeU  = xNew<IssmDouble>(numdof);
+	IssmDouble*    D        = xNewZeroInit<IssmDouble>(epssize*epssize);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	Input* vx_input = element->GetInput(VxEnum);     _assert_(vx_input);
+	Input* vy_input = element->GetInput(VyEnum);     _assert_(vy_input);
+	Input* vz_input = NULL;
+	if(dim==3){vz_input = element->GetInput(VzEnum); _assert_(vz_input);}
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss = element->NewGauss(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		this->GetBFSvel(B,element,dim,xyz_list,gauss);
+		this->GetBFSprimevel(Bprime,element,dim,xyz_list,gauss);
+
+		element->ViscosityFS(&viscosity,dim,xyz_list,gauss,vx_input,vy_input,vz_input);
+		for(i=0;i<epssize;i++)   D[i*epssize+i] = 2*viscosity*gauss->weight*Jdet;
+
+		TripleMultiply(B,epssize,numdof,1,
+					D,epssize,epssize,0,
+					Bprime,epssize,numdof,0,
+					&Ke->values[0],1);
+
+		this->GetBFSUzawa(BU,element,dim,xyz_list,gauss);
+		this->GetBFSprimeUzawa(BprimeU,element,dim,xyz_list,gauss);
+
+		DU = gauss->weight*Jdet*sqrt(r);
+
+		TripleMultiply(BU,1,pnumdof,1,
+					&DU,1,1,0,
+					BprimeU,1,numdof,0,
+					BtBUzawa,1);
+	}
+
+	if(element->IsOnBase()){ 
+		element->FindParam(&rl,AugmentedLagrangianRlambdaEnum);
+		element->GetVerticesCoordinatesBase(&xyz_list_base);
+		element->NormalBase(&normal[0],xyz_list_base);
+
+		IssmDouble* Dlambda  = xNewZeroInit<IssmDouble>(dim*dim);
+		IssmDouble* C        = xNewZeroInit<IssmDouble>(dim*lnumdof);
+		IssmDouble* Cprime   = xNewZeroInit<IssmDouble>(dim*numdof);
+		IssmDouble* CtCUzawa = xNewZeroInit<IssmDouble>(numdof*lnumdof);
+
+		delete gauss;
+		gauss = element->NewGaussBase(5);
+		for(int ig=gauss->begin();ig<gauss->end();ig++){
+			gauss->GaussPoint(ig);
+
+			element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+			this->GetCFS(C,element,dim,xyz_list,gauss);
+			this->GetCFSprime(Cprime,element,dim,xyz_list,gauss);
+			for(i=0;i<dim;i++) Dlambda[i*dim+i] = gauss->weight*Jdet*sqrt(normal[i]*normal[i])*sqrt(rl);
+			TripleMultiply(C,dim,lnumdof,1,
+						Dlambda,dim,dim,0,
+						Cprime,dim,numdof,0,
+						CtCUzawa,1);
+		}
+
+		/*The sigma naugmentation should not be transformed*/
+		MatrixMultiply(CtCUzawa,lnumdof,numdof,1,
+					CtCUzawa,lnumdof,numdof,0,
+					&Ke->values[0],1);
+
+		/*Delete base part*/
+		xDelete<IssmDouble>(Dlambda);
+		xDelete<IssmDouble>(C);
+		xDelete<IssmDouble>(Cprime);
+		xDelete<IssmDouble>(CtCUzawa);
+		xDelete<IssmDouble>(xyz_list_base);
+	}
+
+	/*Transform Coordinate System*/
+	element->TransformStiffnessMatrixCoord(Ke,cs_list);
+
+	/*The pressure augmentation should not be transformed*/
+	MatrixMultiply(BtBUzawa,pnumdof,numdof,1,
+				BtBUzawa,pnumdof,numdof,0,
+				&Ke->values[0],1);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(D);
+	xDelete<IssmDouble>(Bprime);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(BprimeU);
+	xDelete<IssmDouble>(BU);
+	xDelete<IssmDouble>(BtBUzawa);
+	xDelete<int>(cs_list);
 	return Ke;
 }/*}}}*/
@@ -3072,4 +3307,5 @@
 	IssmDouble  x_coord,y_coord,z_coord;
 	IssmDouble *xyz_list_base = NULL;
+	IssmDouble *xyz_list      = NULL;
 	Gauss*      gauss         = NULL;
 
@@ -3084,9 +3320,10 @@
 	/*Initialize Element matrix and vectors*/
 	ElementMatrix* Ke = element->NewElementMatrix(FSvelocityEnum);
-	IssmDouble*    B  = xNew<IssmDouble>((dim-1)*numdof);
-	IssmDouble*    D  = xNewZeroInit<IssmDouble>((dim-1)*(dim-1));
+	IssmDouble*    B  = xNew<IssmDouble>(dim*numdof);
+	IssmDouble*    D  = xNewZeroInit<IssmDouble>(dim*dim);
 
 	/*Retrieve all inputs and parameters*/
 	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	element->GetVerticesCoordinates(&xyz_list);
 	Input* vx_input         = element->GetInput(VxEnum);      _assert_(vx_input);
 	Input* vy_input         = element->GetInput(VyEnum);      _assert_(vy_input);
@@ -3108,9 +3345,9 @@
 		this->GetBFSFriction(B,element,dim,xyz_list_base,gauss);
 		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
-		for(int i=0;i<dim-1;i++) D[i*(dim-1)+i] = alpha2*gauss->weight*Jdet; //taub_x = -alpha2 v_x (same for y)
-
-		TripleMultiply(B,dim-1,numdof,1,
-					D,dim-1,dim-1,0,
-					B,dim-1,numdof,0,
+		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);
 	}
@@ -3120,4 +3357,5 @@
 	/*Clean up and return*/
 	delete gauss;
+	xDelete<IssmDouble>(xyz_list);
 	xDelete<IssmDouble>(xyz_list_base);
 	xDelete<IssmDouble>(B);
@@ -3126,4 +3364,19 @@
 }/*}}}*/
 ElementVector* StressbalanceAnalysis::CreatePVectorFS(Element* element){/*{{{*/
+
+	ElementVector* pe = NULL;
+
+	ElementVector* pe1=CreatePVectorFSViscous(element);
+	ElementVector* pe2=CreatePVectorFSFriction(element);
+	ElementVector* pe3=CreatePVectorFSStress(element);
+	pe =new ElementVector(pe1,pe2,pe3);
+	delete pe1;
+	delete pe2;
+	delete pe3;
+
+	/*clean-up and return*/
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorFSViscous(Element* element){/*{{{*/
 
 	int         i,dim,fe_FS;
@@ -3191,4 +3444,121 @@
 		return pe3;
 	}
+	else if(fe_FS==LATaylorHoodEnum){
+		ElementVector* pe2=CreatePVectorFSViscousLATH(element);
+		ElementVector* pe3 = new ElementVector(pe,pe2);
+		delete pe;
+		delete pe2;
+		return pe3;
+	}
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorFSFriction(Element* element){/*{{{*/
+
+	if(!element->IsOnBase()) return NULL;
+
+	/*Intermediaries*/
+	int         dim;
+	IssmDouble  alpha2,Jdet;
+	IssmDouble  bed_normal[3];
+	IssmDouble *xyz_list_base = NULL;
+	Gauss*      gauss         = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+
+	/*Initialize Element matrix and vectors*/
+	ElementVector* pe = element->NewElementVector(FSvelocityEnum);
+	IssmDouble*    vbasis = xNew<IssmDouble>(vnumnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	Input*  alpha2_input=element->GetInput(FrictionCoefficientEnum); _assert_(alpha2_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=element->NewGaussBase(3);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		alpha2_input->GetInputValue(&alpha2, gauss);
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		element->NodalFunctionsVelocity(vbasis,gauss);
+		element->NormalBase(&bed_normal[0],xyz_list_base);
+
+		for(int i=0;i<vnumnodes;i++){
+			pe->values[i*dim+0] += - alpha2*gauss->weight*Jdet*vbasis[i]*bed_normal[1];
+			pe->values[i*dim+1] += alpha2*gauss->weight*Jdet*vbasis[i]*bed_normal[0];
+			if(dim==3){
+				pe->values[i*dim+2]+= alpha2*gauss->weight*Jdet*vbasis[i];
+			}
+		}
+
+	}
+
+	/*DO NOT Transform Coordinate System: this stiffness matrix is already expressed in tangential coordinates*/
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list_base);
+	xDelete<IssmDouble>(vbasis);
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorFSStress(Element* element){/*{{{*/
+
+	if(!element->IsOnBase()) return NULL;
+
+	/*Intermediaries*/
+	int         dim;
+	IssmDouble  sigmann,sigmant,Jdet,bedslope,beta;
+	IssmDouble *xyz_list_base = NULL;
+	Gauss*      gauss         = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+
+	/*Initialize Element matrix and vectors*/
+	ElementVector* pe = element->NewElementVector(FSvelocityEnum);
+	IssmDouble*    vbasis = xNew<IssmDouble>(vnumnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	Input*  sigmann_input=element->GetInput(VzEnum); _assert_(sigmann_input);
+	Input*  sigmant_input=element->GetInput(TemperatureEnum); _assert_(sigmant_input);
+	Input*  bedslope_input=element->GetInput(BedSlopeXEnum);     _assert_(bedslope_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=element->NewGaussBase(3);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		sigmann_input->GetInputValue(&sigmann, gauss);
+		sigmant_input->GetInputValue(&sigmant, gauss);
+		bedslope_input->GetInputValue(&bedslope, gauss);
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		element->NodalFunctionsVelocity(vbasis,gauss);
+
+		beta=sqrt(1+bedslope*bedslope);
+		for(int i=0;i<vnumnodes;i++){
+			pe->values[i*dim+0] += - (1./beta)*(-bedslope*sigmann + sigmant)*gauss->weight*Jdet*vbasis[i];
+			pe->values[i*dim+1] += - (1./beta)*(sigmann + bedslope*sigmant)*gauss->weight*Jdet*vbasis[i];
+			if(dim==3){
+				//pe->values[i*dim+2]+= alpha2*gauss->weight*Jdet*vbasis[i];
+				_error_("3d not supported yet");
+			}
+		}
+
+	}
+
+	/*DO NOT Transform Coordinate System: this stiffness matrix is already expressed in tangential coordinates*/
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list_base);
+	xDelete<IssmDouble>(vbasis);
 	return pe;
 }/*}}}*/
@@ -3223,6 +3593,6 @@
 	/*Initialize Element matrix and vectors*/
 	ElementMatrix* Ke = element->NewElementMatrix(FSvelocityEnum);
-	IssmDouble*    B  = xNew<IssmDouble>((dim-1)*numdof);
-	IssmDouble*    D  = xNewZeroInit<IssmDouble>((dim-1)*(dim-1));
+	IssmDouble*    B  = xNew<IssmDouble>(dim*numdof);
+	IssmDouble*    D  = xNewZeroInit<IssmDouble>(dim*dim);
 
 	/*Retrieve all inputs and parameters*/
@@ -3260,9 +3630,9 @@
 		this->GetBFSFriction(B,element,dim,xyz_list_base,gauss);
 		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
-		for(int i=0;i<dim-1;i++) D[i*(dim-1)+i] = alpha2*gauss->weight*Jdet; //taub_x = -alpha2 v_x (same for y)
-
-		TripleMultiply(B,dim-1,numdof,1,
-					D,dim-1,dim-1,0,
-					B,dim-1,numdof,0,
+		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);
 	}
@@ -3298,4 +3668,17 @@
 		delete pe4;
 	}
+	else if(fe_FS==LATaylorHoodEnum){
+		ElementVector* pe1=CreatePVectorFSViscous(element);
+		ElementVector* pe2=CreatePVectorFSShelf(element);
+		ElementVector* pe3=CreatePVectorFSFront(element);
+		ElementVector* petemp =new ElementVector(pe1,pe2,pe3);
+		ElementVector* pe4=CreatePVectorFSViscousLATH(element);
+		pe = new ElementVector(petemp,pe4);
+		delete pe1;
+		delete pe2;
+		delete pe3;
+		delete petemp;
+		delete pe4;
+	}
 	else{
 		ElementVector* pe1=CreatePVectorFSViscous(element);
@@ -3311,5 +3694,4 @@
 	return pe;
 }/*}}}*/
-#endif
 ElementVector* StressbalanceAnalysis::CreatePVectorFSViscous(Element* element){/*{{{*/
 
@@ -3381,4 +3763,5 @@
 	return pe;
 }/*}}}*/
+#endif
 ElementVector* StressbalanceAnalysis::CreatePVectorFSViscousXTH(Element* element){/*{{{*/
 
@@ -3553,4 +3936,87 @@
 	return pe;
 }/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorFSViscousLATH(Element* element){/*{{{*/
+
+	int         i,dim;
+	IssmDouble  Jdet,r,pressure;
+	IssmDouble  bed_normal[3];
+	IssmDouble *xyz_list      = NULL;
+	IssmDouble *xyz_list_base = NULL;
+	Gauss*      gauss         = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(numnodes);
+	if(dim==2) for(i=0;i<numnodes;i++) cs_list[i] = XYEnum;
+	else       for(i=0;i<numnodes;i++) cs_list[i] = XYZEnum;
+
+	/*Initialize vectors*/
+	ElementVector* pe      = element->NewElementVector(FSvelocityEnum);
+	IssmDouble*    dbasis  = xNew<IssmDouble>(3*numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->FindParam(&r,AugmentedLagrangianREnum);
+	element->GetVerticesCoordinates(&xyz_list);
+
+	/*Get pressure and sigmann*/
+	Input* pressure_input=element->GetInput(PressureEnum); _assert_(pressure_input);
+	Input* sigmann_input =element->GetInput(SigmaNNEnum);  _assert_(sigmann_input);
+
+	gauss=element->NewGauss(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		
+		pressure_input->GetInputValue(&pressure, gauss);
+		element->NodalFunctionsDerivativesVelocity(dbasis,xyz_list,gauss);
+
+		for(i=0;i<numnodes;i++){
+			pe->values[i*dim+0] += pressure*gauss->weight*Jdet*dbasis[0*numnodes+i];
+			pe->values[i*dim+1] += pressure*gauss->weight*Jdet*dbasis[1*numnodes+i];
+			if(dim==3) pe->values[i*dim+2]+= pressure*gauss->weight*Jdet*dbasis[2*numnodes+i];
+		}
+	}
+
+	if(element->IsOnBase()){ 
+		IssmDouble   sigmann;
+		IssmDouble*  vbasis = xNew<IssmDouble>(numnodes);
+
+		element->GetVerticesCoordinatesBase(&xyz_list_base);
+		element->NormalBase(&bed_normal[0],xyz_list_base);
+
+		delete gauss;
+		gauss=element->NewGaussBase(5);
+		for(int ig=gauss->begin();ig<gauss->end();ig++){
+			gauss->GaussPoint(ig);
+
+			element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+			element->NodalFunctionsVelocity(vbasis,gauss);
+			sigmann_input->GetInputValue(&sigmann, gauss);
+
+			for(i=0;i<numnodes;i++){
+				pe->values[i*dim+0] += + sigmann*bed_normal[0]*gauss->weight*Jdet*vbasis[i];
+				pe->values[i*dim+1] += + sigmann*bed_normal[1]*gauss->weight*Jdet*vbasis[i];
+				if(dim==3) pe->values[i*dim+2] += + sigmann*bed_normal[2]*gauss->weight*Jdet*vbasis[i];
+			}
+		}
+		xDelete<IssmDouble>(xyz_list_base);
+		xDelete<IssmDouble>(vbasis);
+	}
+
+	/*Transform coordinate system*/
+	//element->TransformLoadVectorCoord(pe,cs_list); Do not transform augmentation
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<int>(cs_list);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(dbasis);
+	return pe;
+}/*}}}*/
 ElementVector* StressbalanceAnalysis::CreatePVectorFSShelf(Element* element){/*{{{*/
 
@@ -3615,5 +4081,5 @@
 	element->FindParam(&shelf_dampening,StressbalanceShelfDampeningEnum);
 	if(shelf_dampening) {
-		Input*      mb_input=element->GetInput(BasalforcingsMeltingRateEnum); _assert_(mb_input);
+		Input*      mb_input=element->GetInput(BasalforcingsFloatingiceMeltingRateEnum); _assert_(mb_input);
 		IssmDouble dt,mb,normal_b;
 		element->FindParam(&dt,TimesteppingTimeStepEnum);
@@ -3941,4 +4407,189 @@
 	xDelete<IssmDouble>(pbasis);
 }/*}}}*/
+void StressbalanceAnalysis::GetBFSvel(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[Bv1 Bv2 ... Bp1 Bp2 ...] where Bvi is of size 3*NDOF3. 
+	 * For node i, Bvi can be expressed in the actual coordinate system
+	 * by: 	   Bvi=[ dphi/dx          0        ]
+	 *					 [   0           dphi/dy     ]
+	 *					 [ 1/2*dphi/dy    1/2*dphi/dx]
+	 *
+	 *
+	 *	In 3d:
+	 *     	   Bvi=[ dh/dx          0             0      ]
+	 *					[   0           dh/dy           0      ]
+	 *					[   0             0           dh/dz    ]
+	 *					[ 1/2*dh/dy    1/2*dh/dx        0      ]
+	 *					[ 1/2*dh/dz       0         1/2*dh/dx  ]
+	 *					[   0          1/2*dh/dz    1/2*dh/dy  ]
+	 *
+	 *	where phi is the finiteelement function for node i.
+	 *	Same thing for Bb except the last column that does not exist.
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* vdbasis=xNew<IssmDouble>(dim*vnumnodes);
+	element->NodalFunctionsDerivativesVelocity(vdbasis,xyz_list,gauss);
+
+	/*Build B: */
+	if(dim==2){
+		for(int i=0;i<vnumnodes;i++){
+			B[(dim*vnumnodes)*0+dim*i+0] = vdbasis[0*vnumnodes+i];
+			B[(dim*vnumnodes)*0+dim*i+1] = 0.;
+			B[(dim*vnumnodes)*1+dim*i+0] = 0.;
+			B[(dim*vnumnodes)*1+dim*i+1] = vdbasis[1*vnumnodes+i];
+			B[(dim*vnumnodes)*2+dim*i+0] = .5*vdbasis[1*vnumnodes+i];
+			B[(dim*vnumnodes)*2+dim*i+1] = .5*vdbasis[0*vnumnodes+i];
+		}
+	}
+	else{
+		for(int i=0;i<vnumnodes;i++){
+			B[(dim*vnumnodes)*0+dim*i+0] = vdbasis[0*vnumnodes+i];
+			B[(dim*vnumnodes)*0+dim*i+1] = 0.;
+			B[(dim*vnumnodes)*0+dim*i+2] = 0.;
+			B[(dim*vnumnodes)*1+dim*i+0] = 0.;
+			B[(dim*vnumnodes)*1+dim*i+1] = vdbasis[1*vnumnodes+i];
+			B[(dim*vnumnodes)*1+dim*i+2] = 0.;
+			B[(dim*vnumnodes)*2+dim*i+0] = 0.;
+			B[(dim*vnumnodes)*2+dim*i+1] = 0.;
+			B[(dim*vnumnodes)*2+dim*i+2] = vdbasis[2*vnumnodes+i];
+			B[(dim*vnumnodes)*3+dim*i+0] = .5*vdbasis[1*vnumnodes+i];
+			B[(dim*vnumnodes)*3+dim*i+1] = .5*vdbasis[0*vnumnodes+i];
+			B[(dim*vnumnodes)*3+dim*i+2] = 0.;
+			B[(dim*vnumnodes)*4+dim*i+0] = .5*vdbasis[2*vnumnodes+i];
+			B[(dim*vnumnodes)*4+dim*i+1] = 0.;
+			B[(dim*vnumnodes)*4+dim*i+2] = .5*vdbasis[0*vnumnodes+i];
+			B[(dim*vnumnodes)*5+dim*i+0] = 0.;
+			B[(dim*vnumnodes)*5+dim*i+1] = .5*vdbasis[2*vnumnodes+i];
+			B[(dim*vnumnodes)*5+dim*i+2] = .5*vdbasis[1*vnumnodes+i];
+		}
+	}
+
+	/*Clean up*/
+	xDelete<IssmDouble>(vdbasis);
+}/*}}}*/
+void StressbalanceAnalysis::GetBFSprimevel(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*	Compute B'  matrix. B'=[B1' B2' B3' B4' B5' B6' Bb'] where Bi' is of size 3*NDOF2. 
+	 *	For node i, Bi' can be expressed in the actual coordinate system
+	 *	by: 
+	 *			Bvi' = [  dphi/dx     0     ]
+	 *					 [     0      dphi/dy ]
+	 *					 [  dphi/dy   dphi/dx ]
+	 *
+	 *	In 3d
+	 *     	   Bvi=[ dh/dx     0        0    ]
+	 *					[   0      dh/dy      0    ]
+	 *					[   0        0      dh/dz  ]
+	 *					[ dh/dy    dh/dx      0    ]
+	 *					[ dh/dz      0      dh/dx  ]
+	 *					[   0      dh/dz    dh/dy  ]
+	 *	where phi is the finiteelement function for node i.
+	 *	In 3d:
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* vdbasis=xNew<IssmDouble>(dim*vnumnodes);
+	element->NodalFunctionsDerivativesVelocity(vdbasis,xyz_list,gauss);
+
+	/*Build B_prime: */
+	if(dim==2){
+		for(int i=0;i<vnumnodes;i++){
+			Bprime[(dim*vnumnodes)*0+dim*i+0] = vdbasis[0*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*0+dim*i+1] = 0.;
+			Bprime[(dim*vnumnodes)*1+dim*i+0] = 0.;
+			Bprime[(dim*vnumnodes)*1+dim*i+1] = vdbasis[1*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*2+dim*i+0] = vdbasis[1*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*2+dim*i+1] = vdbasis[0*vnumnodes+i];
+		}
+	}
+	else{
+		for(int i=0;i<vnumnodes;i++){
+			Bprime[(dim*vnumnodes)*0+dim*i+0] = vdbasis[0*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*0+dim*i+1] = 0.;
+			Bprime[(dim*vnumnodes)*0+dim*i+2] = 0.;
+			Bprime[(dim*vnumnodes)*1+dim*i+0] = 0.;
+			Bprime[(dim*vnumnodes)*1+dim*i+1] = vdbasis[1*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*1+dim*i+2] = 0.;
+			Bprime[(dim*vnumnodes)*2+dim*i+0] = 0.;
+			Bprime[(dim*vnumnodes)*2+dim*i+1] = 0.;
+			Bprime[(dim*vnumnodes)*2+dim*i+2] = vdbasis[2*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*3+dim*i+0] = vdbasis[1*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*3+dim*i+1] = vdbasis[0*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*3+dim*i+2] = 0.;
+			Bprime[(dim*vnumnodes)*4+dim*i+0] = vdbasis[2*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*4+dim*i+1] = 0.;
+			Bprime[(dim*vnumnodes)*4+dim*i+2] = vdbasis[0*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*5+dim*i+0] = 0.;
+			Bprime[(dim*vnumnodes)*5+dim*i+1] = vdbasis[2*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*5+dim*i+2] = vdbasis[1*vnumnodes+i];
+		}
+	}
+
+	/*Clean up*/
+	xDelete<IssmDouble>(vdbasis);
+}/*}}}*/
+void StressbalanceAnalysis::GetBFSUzawa(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[Bp1 Bp2 ...] where Bpi=phi_pi. 
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int pnumnodes;
+	if(dim==2) pnumnodes=3;
+	else pnumnodes=6;
+	//int pnumnodes = element->NumberofNodes(P1Enum);
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* basis =xNew<IssmDouble>(pnumnodes);
+	element->NodalFunctionsP1(basis,gauss);
+
+	/*Build B: */
+	for(int i=0;i<pnumnodes;i++){
+		B[i] = basis[i];
+	}
+
+	/*Clean up*/
+	xDelete<IssmDouble>(basis);
+}/*}}}*/
+void StressbalanceAnalysis::GetBFSprimeUzawa(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*	Compute B'  matrix. B'=[B1' B2' B3' B4' B5' B6'] where Bi' is of size 3*NDOF2. 
+	 *	For node i, Bi' can be expressed in the actual coordinate system
+	 *	by: 
+	 *			Bvi' = [  dphi/dx   dphi/dy ]
+	 *
+	 *	In 3d
+	 *     	   Bvi=[ dh/dx   dh/dy    dh/dz  ]
+	 *	where phi is the finiteelement function for node i.
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* vdbasis=xNew<IssmDouble>(dim*vnumnodes);
+	element->NodalFunctionsDerivativesVelocity(vdbasis,xyz_list,gauss);
+
+	/*Build B_prime: */
+	if(dim==2){
+		for(int i=0;i<vnumnodes;i++){
+			Bprime[dim*i+0] = vdbasis[0*vnumnodes+i];
+			Bprime[dim*i+1] = vdbasis[1*vnumnodes+i];
+		}
+	}
+	else{
+		for(int i=0;i<vnumnodes;i++){
+			Bprime[dim*i+0] = vdbasis[0*vnumnodes+i];
+			Bprime[dim*i+1] = vdbasis[1*vnumnodes+i];
+			Bprime[dim*i+2] = vdbasis[2*vnumnodes+i];
+		}
+	}
+
+	/*Clean up*/
+	xDelete<IssmDouble>(vdbasis);
+}/*}}}*/
 void StressbalanceAnalysis::GetBFSFriction(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/* Compute L  matrix. L=[L1 L2 L3] where Li is square and of size numdof. 
@@ -3972,18 +4623,96 @@
 			B[(vnumdof+pnumdof)*1+3*i+1] = vbasis[i];
 			B[(vnumdof+pnumdof)*1+3*i+2] = 0.;
+
+			B[(vnumdof+pnumdof)*2+3*i+0] = 0.;
+			B[(vnumdof+pnumdof)*2+3*i+1] = 0.;
+			B[(vnumdof+pnumdof)*2+3*i+2] = vbasis[i];
 		}
 		for(int i=0;i<pnumnodes;i++){
 			B[(vnumdof+pnumdof)*0+i+vnumdof+0] = 0.;
 			B[(vnumdof+pnumdof)*1+i+vnumdof+0] = 0.;
+			B[(vnumdof+pnumdof)*2+i+vnumdof+0] = 0.;
 		}
 	}
 	else{
 		for(int i=0;i<vnumnodes;i++){
-			B[2*i+0] = vbasis[i];
-			B[2*i+1] = 0.;
+			B[(vnumdof+pnumdof)*0+2*i+0] = vbasis[i];
+			B[(vnumdof+pnumdof)*0+2*i+1] = 0.;
+
+			B[(vnumdof+pnumdof)*1+2*i+0] = 0.;
+			B[(vnumdof+pnumdof)*1+2*i+1] = vbasis[i];
 		}
 
 		for(int i=0;i<pnumnodes;i++){
-			B[i+vnumdof+0] = 0.;
+			B[(vnumdof+pnumdof)*0+i+vnumdof+0] = 0.;
+			B[(vnumdof+pnumdof)*1+i+vnumdof+0] = 0.;
+		}
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(vbasis);
+}/*}}}*/
+void StressbalanceAnalysis::GetCFS(IssmDouble* C,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute C  matrix. C=[Cp1 Cp2 ...] where:
+	 *     Cpi=[phi phi]. 
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int lnumnodes = element->GetNumberOfNodes(P2Enum);
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* basis =xNew<IssmDouble>(lnumnodes);
+	element->NodalFunctionsP2(basis,gauss);
+
+	/*Build B: */
+	for(int i=0;i<lnumnodes;i++){
+		C[lnumnodes*0+i] = basis[i];
+		C[lnumnodes*1+i] = basis[i];
+	}
+
+	/*Clean up*/
+	xDelete<IssmDouble>(basis);
+}/*}}}*/
+void StressbalanceAnalysis::GetCFSprime(IssmDouble* Cprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*	Compute C'  matrix. C'=[C1' C2' ...] 
+	 *			Ci' = [  phi  0  ]
+	 *			      [   0  phi ]
+	 *
+	 *	In 3d
+	 *			Ci' = [  phi  0   0  ]
+	 *			      [   0  phi  0  ]
+	 *			      [   0   0  phi ]
+	 *	where phi is the finiteelement function for node i.
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+	int vnumdof   = vnumnodes*dim;
+
+	IssmDouble* vbasis=xNew<IssmDouble>(vnumnodes);
+	element->NodalFunctionsVelocity(vbasis,gauss);
+
+	/*Build B: */
+	if(dim==3){
+		for(int i=0;i<vnumnodes;i++){
+			Cprime[vnumdof*0+3*i+0] = vbasis[i];
+			Cprime[vnumdof*0+3*i+1] = 0.;
+			Cprime[vnumdof*0+3*i+2] = 0.;
+
+			Cprime[vnumdof*1+3*i+0] = 0.;
+			Cprime[vnumdof*1+3*i+1] = vbasis[i];
+			Cprime[vnumdof*1+3*i+2] = 0.;
+
+			Cprime[vnumdof*2+3*i+0] = 0.;
+			Cprime[vnumdof*2+3*i+1] = 0.;
+			Cprime[vnumdof*2+3*i+2] = vbasis[i];
+		}
+	}
+	else{
+		for(int i=0;i<vnumnodes;i++){
+			Cprime[vnumdof*0+2*i+0] = vbasis[i];
+			Cprime[vnumdof*0+2*i+1] = 0.;
+
+			Cprime[vnumdof*1+2*i+0] = 0.;
+			Cprime[vnumdof*1+2*i+1] = vbasis[i];
 		}
 	}
@@ -4046,5 +4775,5 @@
 	/*Add value to global vector*/
 	solution->SetValues(vnumdof,vdoflist,vvalues,INS_VAL);
-	solution->SetValues(pnumdof,pdoflist,pvalues,INS_VAL);
+	if(pnumdof>0) solution->SetValues(pnumdof,pdoflist,pvalues,INS_VAL);
 
 	/*Free ressources:*/
@@ -4203,5 +4932,5 @@
 	element->InputChangeName(VxEnum,VxPicardEnum);
 	element->InputChangeName(VyEnum,VyPicardEnum);
-	element->InputChangeName(PressureEnum,PressurePicardEnum);
+	if(pnumdof>0) element->InputChangeName(PressureEnum,PressurePicardEnum);
 	if(dim==3) element->InputChangeName(VzEnum,VzPicardEnum);
 
@@ -4210,5 +4939,5 @@
 	element->AddInput(VyEnum,      vy,      element->VelocityInterpolation());
 	element->AddInput(VelEnum,     vel,     element->VelocityInterpolation());
-	element->AddInput(PressureEnum,pressure,element->PressureInterpolation());
+	if(pnumdof>0) element->AddInput(PressureEnum,pressure,element->PressureInterpolation());
 	if(dim==3) element->AddInput(VzEnum,vz, element->VelocityInterpolation());
 
@@ -4407,4 +5136,7 @@
 		else{
 			_assert_(tnumnodes==4);
+			d_zz = xNew<IssmDouble>(tnumnodes);
+			d_xz = xNew<IssmDouble>(tnumnodes);
+			d_yz = xNew<IssmDouble>(tnumnodes);
 			Matrix4x4Solve(&d_xx[0],Ke,pe_xx);
 			Matrix4x4Solve(&d_yy[0],Ke,pe_yy);
@@ -4457,5 +5189,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);}
 
@@ -4492,4 +5224,9 @@
 		IssmDouble* tau_xz = NULL;
 		IssmDouble* tau_yz = NULL;
+		if(dim==3){
+			tau_zz = xNew<IssmDouble>(tnumnodes);
+			tau_xz = xNew<IssmDouble>(tnumnodes);
+			tau_yz = xNew<IssmDouble>(tnumnodes);
+		}
 		Gauss* gauss = element->NewGauss();
 		for(int ig=0;ig<tnumnodes;ig++){
@@ -5811,5 +6548,5 @@
 
 	int num_dof=2;
-	IssmDouble L1L2l3[3];
+	IssmDouble basis[3];
 
 	/*Cast gauss to GaussPenta*/
@@ -5817,27 +6554,27 @@
 	GaussPenta* gauss = dynamic_cast<GaussPenta*>(gauss_in);
 
-	/*Get L1L2l3 in actual coordinate system: */
-	L1L2l3[0]=gauss->coord1*(1-gauss->coord4)/2.0;
-	L1L2l3[1]=gauss->coord2*(1-gauss->coord4)/2.0;
-	L1L2l3[2]=gauss->coord3*(1-gauss->coord4)/2.0;
+	/*Get basis in actual coordinate system: */
+	basis[0]=gauss->coord1*(1-gauss->coord4)/2.0;
+	basis[1]=gauss->coord2*(1-gauss->coord4)/2.0;
+	basis[2]=gauss->coord3*(1-gauss->coord4)/2.0;
 
 	/*Build LFS: */
 	for(int i=0;i<3;i++){
-		LFS[num_dof*3*0+num_dof*i+0] = L1L2l3[i];
+		LFS[num_dof*3*0+num_dof*i+0] = basis[i];
 		LFS[num_dof*3*0+num_dof*i+1] = 0;
 		LFS[num_dof*3*1+num_dof*i+0] = 0;
-		LFS[num_dof*3*1+num_dof*i+1] = L1L2l3[i];
-		LFS[num_dof*3*2+num_dof*i+0] = L1L2l3[i];
+		LFS[num_dof*3*1+num_dof*i+1] = basis[i];
+		LFS[num_dof*3*2+num_dof*i+0] = basis[i];
 		LFS[num_dof*3*2+num_dof*i+1] = 0;
 		LFS[num_dof*3*3+num_dof*i+0] = 0;
-		LFS[num_dof*3*3+num_dof*i+1] = L1L2l3[i];
-		LFS[num_dof*3*4+num_dof*i+0] = L1L2l3[i];
+		LFS[num_dof*3*3+num_dof*i+1] = basis[i];
+		LFS[num_dof*3*4+num_dof*i+0] = basis[i];
 		LFS[num_dof*3*4+num_dof*i+1] = 0;
 		LFS[num_dof*3*5+num_dof*i+0] = 0;
-		LFS[num_dof*3*5+num_dof*i+1] = L1L2l3[i];
-		LFS[num_dof*3*6+num_dof*i+0] = L1L2l3[i];
+		LFS[num_dof*3*5+num_dof*i+1] = basis[i];
+		LFS[num_dof*3*6+num_dof*i+0] = basis[i];
 		LFS[num_dof*3*6+num_dof*i+1] = 0;
 		LFS[num_dof*3*7+num_dof*i+0] = 0;
-		LFS[num_dof*3*7+num_dof*i+1] = L1L2l3[i];
+		LFS[num_dof*3*7+num_dof*i+1] = basis[i];
 	}
 }/*}}}*/
@@ -5859,5 +6596,5 @@
 	int num_dof_vel=3*7;
 	int num_dof_total=3*7+1*6;
-	IssmDouble L1L2l3[3];
+	IssmDouble basis[3];
 	IssmDouble dbasis[3][6];
 
@@ -5866,8 +6603,8 @@
 	GaussPenta* gauss = dynamic_cast<GaussPenta*>(gauss_in);
 
-	/*Get L1L2l3 in actual coordinate system: */
-	L1L2l3[0]=gauss->coord1*(1-gauss->coord4)/2.0;
-	L1L2l3[1]=gauss->coord2*(1-gauss->coord4)/2.0;
-	L1L2l3[2]=gauss->coord3*(1-gauss->coord4)/2.0;
+	/*Get basis in actual coordinate system: */
+	basis[0]=gauss->coord1*(1-gauss->coord4)/2.0;
+	basis[1]=gauss->coord2*(1-gauss->coord4)/2.0;
+	basis[2]=gauss->coord3*(1-gauss->coord4)/2.0;
 
 	element->NodalFunctionsP1Derivatives(&dbasis[0][0],xyz_list,gauss);
@@ -5875,16 +6612,16 @@
 	/*Build LprimeFS: */
 	for(int i=0;i<3;i++){
-		LprimeFS[num_dof_total*0+num_dof*i+0] = L1L2l3[i];
+		LprimeFS[num_dof_total*0+num_dof*i+0] = basis[i];
 		LprimeFS[num_dof_total*0+num_dof*i+1] = 0.;
 		LprimeFS[num_dof_total*0+num_dof*i+2] = 0.;
 		LprimeFS[num_dof_total*1+num_dof*i+0] = 0.;
-		LprimeFS[num_dof_total*1+num_dof*i+1] = L1L2l3[i];
+		LprimeFS[num_dof_total*1+num_dof*i+1] = basis[i];
 		LprimeFS[num_dof_total*1+num_dof*i+2] = 0.;
 		LprimeFS[num_dof_total*2+num_dof*i+0] = 0.;
 		LprimeFS[num_dof_total*2+num_dof*i+1] = 0.;
-		LprimeFS[num_dof_total*2+num_dof*i+2] = L1L2l3[i];
+		LprimeFS[num_dof_total*2+num_dof*i+2] = basis[i];
 		LprimeFS[num_dof_total*3+num_dof*i+0] = 0.;
 		LprimeFS[num_dof_total*3+num_dof*i+1] = 0.;
-		LprimeFS[num_dof_total*3+num_dof*i+2] = L1L2l3[i];
+		LprimeFS[num_dof_total*3+num_dof*i+2] = basis[i];
 		LprimeFS[num_dof_total*4+num_dof*i+0] = 0.;
 		LprimeFS[num_dof_total*4+num_dof*i+1] = 0.;
@@ -5933,6 +6670,6 @@
 		LprimeFS[num_dof_total*4+num_dof_vel+i] = 0.;
 		LprimeFS[num_dof_total*5+num_dof_vel+i] = 0.;
-		LprimeFS[num_dof_total*6+num_dof_vel+i] = L1L2l3[i];
-		LprimeFS[num_dof_total*7+num_dof_vel+i] = L1L2l3[i];
+		LprimeFS[num_dof_total*6+num_dof_vel+i] = basis[i];
+		LprimeFS[num_dof_total*7+num_dof_vel+i] = basis[i];
 	}
 	for(int i=3;i<6;i++){
@@ -5959,5 +6696,5 @@
 
 	int num_dof=3;
-	IssmDouble L1L2l3[3];
+	IssmDouble basis[3];
 
 	/*Cast gauss to GaussPenta*/
@@ -5965,23 +6702,23 @@
 	GaussPenta* gauss = dynamic_cast<GaussPenta*>(gauss_in);
 
-	/*Get L1L2l3 in actual coordinate system: */
-	L1L2l3[0]=gauss->coord1*(1-gauss->coord4)/2.0;
-	L1L2l3[1]=gauss->coord2*(1-gauss->coord4)/2.0;
-	L1L2l3[2]=gauss->coord3*(1-gauss->coord4)/2.0;
+	/*Get basis in actual coordinate system: */
+	basis[0]=gauss->coord1*(1-gauss->coord4)/2.0;
+	basis[1]=gauss->coord2*(1-gauss->coord4)/2.0;
+	basis[2]=gauss->coord3*(1-gauss->coord4)/2.0;
 
 	/*Build LFS: */
 	for(int i=0;i<3;i++){
-		LFS[num_dof*3*0+num_dof*i+0] = L1L2l3[i];
+		LFS[num_dof*3*0+num_dof*i+0] = basis[i];
 		LFS[num_dof*3*0+num_dof*i+1] = 0.;
 		LFS[num_dof*3*0+num_dof*i+2] = 0.;
 		LFS[num_dof*3*1+num_dof*i+0] = 0.;
-		LFS[num_dof*3*1+num_dof*i+1] = L1L2l3[i];
+		LFS[num_dof*3*1+num_dof*i+1] = basis[i];
 		LFS[num_dof*3*1+num_dof*i+2] = 0.;
 		LFS[num_dof*3*2+num_dof*i+0] = 0.;
 		LFS[num_dof*3*2+num_dof*i+1] = 0.;
-		LFS[num_dof*3*2+num_dof*i+2] = L1L2l3[i];
+		LFS[num_dof*3*2+num_dof*i+2] = basis[i];
 		LFS[num_dof*3*3+num_dof*i+0] = 0.;
 		LFS[num_dof*3*3+num_dof*i+1] = 0.;
-		LFS[num_dof*3*3+num_dof*i+2] = L1L2l3[i];
+		LFS[num_dof*3*3+num_dof*i+2] = basis[i];
 	}
 }/*}}}*/
@@ -5997,5 +6734,5 @@
 	 */
 	int num_dof=2;
-	IssmDouble L1L2l3[3];
+	IssmDouble basis[3];
 
 	/*Cast gauss to GaussPenta*/
@@ -6003,19 +6740,19 @@
 	GaussPenta* gauss = dynamic_cast<GaussPenta*>(gauss_in);
 
-	/*Get L1L2l3 in actual coordinate system: */
-	L1L2l3[0]=gauss->coord1*(1-gauss->coord4)/2.0;
-	L1L2l3[1]=gauss->coord2*(1-gauss->coord4)/2.0;
-	L1L2l3[2]=gauss->coord3*(1-gauss->coord4)/2.0;
+	/*Get basis in actual coordinate system: */
+	basis[0]=gauss->coord1*(1-gauss->coord4)/2.0;
+	basis[1]=gauss->coord2*(1-gauss->coord4)/2.0;
+	basis[2]=gauss->coord3*(1-gauss->coord4)/2.0;
 
 	/*Build LprimeFS: */
 	for(int i=0;i<3;i++){
-		LprimeFS[num_dof*3*0+num_dof*i+0] = L1L2l3[i];
+		LprimeFS[num_dof*3*0+num_dof*i+0] = basis[i];
 		LprimeFS[num_dof*3*0+num_dof*i+1] = 0.;
 		LprimeFS[num_dof*3*1+num_dof*i+0] = 0.;
-		LprimeFS[num_dof*3*1+num_dof*i+1] = L1L2l3[i];
-		LprimeFS[num_dof*3*2+num_dof*i+0] = L1L2l3[i];
+		LprimeFS[num_dof*3*1+num_dof*i+1] = basis[i];
+		LprimeFS[num_dof*3*2+num_dof*i+0] = basis[i];
 		LprimeFS[num_dof*3*2+num_dof*i+1] = 0.;
 		LprimeFS[num_dof*3*3+num_dof*i+0] = 0.;
-		LprimeFS[num_dof*3*3+num_dof*i+1] = L1L2l3[i];
+		LprimeFS[num_dof*3*3+num_dof*i+1] = basis[i];
 	}
 }/*}}}*/
Index: issm/trunk/src/c/analyses/StressbalanceAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/StressbalanceAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/StressbalanceAnalysis.h	(revision 18301)
@@ -27,4 +27,5 @@
 		ElementVector* CreatePVector(Element* element);
 		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
 		void GetSolutionFromInputsHoriz(Vector<IssmDouble>* solution,Element* element);
 		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
@@ -36,4 +37,5 @@
 		ElementMatrix* CreateKMatrixSSAViscous(Element* element);
 		ElementMatrix* CreateKMatrixSSAFriction(Element* element);
+		ElementMatrix* CreateKMatrixSSALateralFriction(Element* element);
 		ElementVector* CreatePVectorSSA(Element* element);
 		ElementVector* CreatePVectorSSADrivingStress(Element* element);
@@ -67,4 +69,5 @@
 		ElementMatrix* CreateJacobianMatrixFS(Element* element);
 		ElementMatrix* CreateKMatrixFS(Element* element);
+		ElementMatrix* CreateKMatrixFSViscousLATH(Element* element);
 		ElementMatrix* CreateKMatrixFSViscousXTH(Element* element);
 		ElementMatrix* CreateKMatrixFSViscous(Element* element);
@@ -73,10 +76,19 @@
 		ElementVector* CreatePVectorFS(Element* element);
 		ElementVector* CreatePVectorFSViscous(Element* element);
+		ElementVector* CreatePVectorFSViscousLATH(Element* element);
 		ElementVector* CreatePVectorFSViscousXTH(Element* element);
 		ElementVector* CreatePVectorFSShelf(Element* element);
 		ElementVector* CreatePVectorFSFront(Element* element);
+		ElementVector* CreatePVectorFSFriction(Element* element);
+		ElementVector* CreatePVectorFSStress(Element* element);
 		void GetBFS(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
 		void GetBFSprime(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void GetBFSvel(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void GetBFSprimevel(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
 		void GetBFSFriction(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void GetBFSUzawa(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void GetBFSprimeUzawa(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void GetCFS(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void GetCFSprime(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
 		void GetSolutionFromInputsFS(Vector<IssmDouble>* solution,Element* element);
 		void InputUpdateFromSolutionFS(IssmDouble* solution,Element* element);
Index: issm/trunk/src/c/analyses/StressbalanceSIAAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/StressbalanceSIAAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/StressbalanceSIAAnalysis.cpp	(revision 18301)
@@ -40,4 +40,5 @@
 	iomodel->FetchDataToInput(elements,ThicknessEnum);
 	iomodel->FetchDataToInput(elements,FrictionCoefficientEnum);
+	iomodel->FetchDataToInput(elements,MaskGroundediceLevelsetEnum);
 	if(islevelset){
 		iomodel->FetchDataToInput(elements,IceMaskNodeActivationEnum);
@@ -493,4 +494,7 @@
 	xDelete<IssmDouble>(values);
 }/*}}}*/
+void StressbalanceSIAAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
 void StressbalanceSIAAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
Index: issm/trunk/src/c/analyses/StressbalanceSIAAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/StressbalanceSIAAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/StressbalanceSIAAnalysis.h	(revision 18301)
@@ -31,4 +31,5 @@
 		ElementVector* CreatePVector3D(Element* element);
 		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
 		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
 		void UpdateConstraints(FemModel* femmodel);
Index: issm/trunk/src/c/analyses/StressbalanceVerticalAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/StressbalanceVerticalAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/StressbalanceVerticalAnalysis.cpp	(revision 18301)
@@ -38,5 +38,6 @@
 		iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
 	}
-	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsGroundediceMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsFloatingiceMeltingRateEnum);
 	iomodel->FetchDataToInput(elements,VxEnum,0.);
 	iomodel->FetchDataToInput(elements,VyEnum,0.);
@@ -278,5 +279,6 @@
 	IssmDouble *xyz_list_base = NULL;
 	IssmDouble  Jdet,slope[3];
-	IssmDouble  vx,vy,vz=0.,dbdx,dbdy,basalmeltingvalue;
+	IssmDouble  vx,vy,vz=0.,dbdx,dbdy;
+	IssmDouble  gmb,fmb,phi,basalmeltingvalue;
 
 	if(!element->IsOnBase()) return NULL;
@@ -293,8 +295,10 @@
 	element->GetVerticesCoordinatesBase(&xyz_list_base);
 	element->GetInputValue(&approximation,ApproximationEnum);
-	Input* base_input=element->GetInput(BaseEnum);                                _assert_(base_input);
-	Input* basal_melting_input=element->GetInput(BasalforcingsMeltingRateEnum); _assert_(basal_melting_input);
-	Input* vx_input=element->GetInput(VxEnum);                                  _assert_(vx_input);
-	Input* vy_input=element->GetInput(VyEnum);                                  _assert_(vy_input);
+	Input* base_input=element->GetInput(BaseEnum);                                               _assert_(base_input);
+	Input* groundedice_input=element->GetInput(MaskGroundediceLevelsetEnum);                     _assert_(groundedice_input);
+	Input* groundedice_melting_input=element->GetInput(BasalforcingsGroundediceMeltingRateEnum); _assert_(groundedice_melting_input);
+	Input* floatingice_melting_input=element->GetInput(BasalforcingsFloatingiceMeltingRateEnum); _assert_(floatingice_melting_input);
+	Input* vx_input=element->GetInput(VxEnum);                                                   _assert_(vx_input);
+	Input* vy_input=element->GetInput(VyEnum);                                                   _assert_(vy_input);
 	Input* vzFS_input=NULL;
 	if(approximation==HOFSApproximationEnum || approximation==SSAFSApproximationEnum){
@@ -307,5 +311,7 @@
 		gauss->GaussPoint(ig);
 
-		basal_melting_input->GetInputValue(&basalmeltingvalue,gauss);
+		groundedice_melting_input->GetInputValue(&gmb,gauss);
+		floatingice_melting_input->GetInputValue(&fmb,gauss);
+		groundedice_input->GetInputValue(&phi,gauss);
 		base_input->GetInputDerivativeValue(&slope[0],xyz_list,gauss);
 		vx_input->GetInputValue(&vx,gauss);
@@ -316,4 +322,6 @@
 		dbdx=slope[0];
 		dbdy=slope[1];
+		if(phi>0.) basalmeltingvalue=gmb;
+		else basalmeltingvalue=fmb;
 
 		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
@@ -356,4 +364,7 @@
 void StressbalanceVerticalAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 	element->GetSolutionFromInputsOneDof(solution,VzEnum);
+}/*}}}*/
+void StressbalanceVerticalAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
 }/*}}}*/
 void StressbalanceVerticalAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
Index: issm/trunk/src/c/analyses/StressbalanceVerticalAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/StressbalanceVerticalAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/StressbalanceVerticalAnalysis.h	(revision 18301)
@@ -33,4 +33,5 @@
 		void GetBprime(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
 		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
 		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
 		void UpdateConstraints(FemModel* femmodel);
Index: issm/trunk/src/c/analyses/ThermalAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/ThermalAnalysis.cpp	(revision 18081)
+++ issm/trunk/src/c/analyses/ThermalAnalysis.cpp	(revision 18301)
@@ -75,11 +75,4 @@
 	InputUpdateFromConstantx(elements,0.,VyMeshEnum);
 	InputUpdateFromConstantx(elements,0.,VzMeshEnum);
-	if(dakota_analysis){
-		elements->InputDuplicate(TemperatureEnum,QmuTemperatureEnum);
-		elements->InputDuplicate(BasalforcingsMeltingRateEnum,QmuMeltingEnum);
-		elements->InputDuplicate(VxMeshEnum,QmuVxMeshEnum);
-		elements->InputDuplicate(VxMeshEnum,QmuVyMeshEnum);
-		elements->InputDuplicate(VxMeshEnum,QmuVzMeshEnum);
-	}
 	if(islevelset){
 		iomodel->FetchDataToInput(elements,IceMaskNodeActivationEnum);
@@ -653,4 +646,7 @@
 	/*Clean-up*/
 	xDelete<IssmDouble>(dbasis);
+}/*}}}*/
+void ThermalAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
 }/*}}}*/
 void ThermalAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
Index: issm/trunk/src/c/analyses/ThermalAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/ThermalAnalysis.h	(revision 18081)
+++ issm/trunk/src/c/analyses/ThermalAnalysis.h	(revision 18301)
@@ -35,4 +35,5 @@
 		void GetBAdvecprime(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
 		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
 		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
 		void UpdateConstraints(FemModel* femmodel);
Index: issm/trunk/src/c/analyses/UzawaPressureAnalysis.cpp
===================================================================
--- issm/trunk/src/c/analyses/UzawaPressureAnalysis.cpp	(revision 18301)
+++ issm/trunk/src/c/analyses/UzawaPressureAnalysis.cpp	(revision 18301)
@@ -0,0 +1,277 @@
+#include "./UzawaPressureAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+int  UzawaPressureAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void UzawaPressureAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+
+	parameters->AddObject(iomodel->CopyConstantObject(AugmentedLagrangianRhopEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(AugmentedLagrangianRholambdaEnum));
+}/*}}}*/
+void UzawaPressureAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*Update elements: */
+	int finiteelement = P1Enum;
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,finiteelement);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,VxEnum,0.);
+	iomodel->FetchDataToInput(elements,VyEnum,0.);
+	if(iomodel->domaintype==Domain3DEnum) iomodel->FetchDataToInput(elements,VzEnum,0.);
+	iomodel->FetchDataToInput(elements,PressureEnum,0.);
+	InputUpdateFromConstantx(elements,0.,SigmaNNEnum);
+}/*}}}*/
+void UzawaPressureAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	int finiteelement = P1Enum;
+	::CreateNodes(nodes,iomodel,UzawaPressureAnalysisEnum,finiteelement);
+}/*}}}*/
+void UzawaPressureAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+	return;
+}/*}}}*/
+void UzawaPressureAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+	return;
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           UzawaPressureAnalysis::Core(FemModel* femmodel){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+ElementVector* UzawaPressureAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* UzawaPressureAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* UzawaPressureAnalysis::CreateKMatrix(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble  D_scalar,Jdet;
+	IssmDouble *xyz_list = NULL;
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke   = element->NewElementMatrix();
+	IssmDouble*    M    = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+
+	Gauss* gauss = element->NewGauss(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		this->GetM(M,element,gauss);
+		D_scalar=gauss->weight*Jdet;
+		TripleMultiply(M,1,numnodes,1,
+					&D_scalar,1,1,0,
+					M,1,numnodes,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(M);
+	return Ke;
+}/*}}}*/
+ElementVector* UzawaPressureAnalysis::CreatePVector(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	int          dim;
+	IssmDouble   Jdet,rhop,divu;
+	IssmDouble   *xyz_list = NULL;
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Retrieve all inputs and parameters*/
+	element->FindParam(&dim,DomainDimensionEnum);
+	element->FindParam(&rhop,AugmentedLagrangianRhopEnum);
+	element->GetVerticesCoordinates(&xyz_list);
+
+	/*Initialize Element matrix and vectors*/
+	ElementVector* pe    = element->NewElementVector();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+	IssmDouble*    dvx   = xNew<IssmDouble>(dim);
+	IssmDouble*    dvy   = xNew<IssmDouble>(dim);
+	IssmDouble*    dvz   = xNew<IssmDouble>(dim);
+
+	Input* vx_input=element->GetInput(VxEnum);     _assert_(vx_input);
+	Input* vy_input=element->GetInput(VyEnum);     _assert_(vy_input);
+	Input* vz_input = NULL;
+	if(dim==3){vz_input=element->GetInput(VzEnum); _assert_(vz_input);}
+
+	Gauss* gauss = element->NewGauss(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis, gauss);
+		vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+		vy_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
+		if(dim==3){
+			vz_input->GetInputDerivativeValue(&dvz[0],xyz_list,gauss);
+		}
+
+		divu=dvx[0]+dvy[1];
+		if (dim==3) divu=divu+dvz[2];
+
+		for(int i=0;i<numnodes;i++){
+			pe->values[i] += - rhop * divu * Jdet * gauss->weight * basis[i];
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(dvx);
+	xDelete<IssmDouble>(dvy);
+	xDelete<IssmDouble>(dvz);
+	return pe;
+}/*}}}*/
+void UzawaPressureAnalysis::GetM(IssmDouble* M,Element* element,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. M=[M1 M2 M3] */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	element->NodalFunctions(basis,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		M[i] = basis[i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(basis);
+}/*}}}*/
+void UzawaPressureAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+void UzawaPressureAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void UzawaPressureAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+
+	int        dim;
+	int        *doflist       = NULL;
+	IssmDouble rholambda,un,vx,vy,vz,sigmann;
+	IssmDouble *xyz_list_base = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes      = element->GetNumberOfNodes();
+	int numnodessigma = element->GetNumberOfNodes(P2Enum);
+
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch dof list and allocate solution vector*/
+	element->GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble* values        = xNew<IssmDouble>(numnodes);
+	IssmDouble* valueslambda  = xNewZeroInit<IssmDouble>(numnodessigma);
+	IssmDouble* pressure      = xNew<IssmDouble>(numnodes);
+	Input* sigmann_input      = element->GetInput(SigmaNNEnum); _assert_(sigmann_input);
+	Input* vx_input           = element->GetInput(VxEnum);      _assert_(vx_input);
+	Input* vy_input           = element->GetInput(VyEnum);      _assert_(vy_input);
+	Input* vz_input           = NULL;
+	if(dim==3){vz_input       = element->GetInput(VzEnum);      _assert_(vz_input);}
+	element->GetInputListOnNodes(&pressure[0],PressureEnum);
+
+	/*Update pressure enum first*/
+	for(int i=0;i<numnodes;i++){
+		values[i]  = pressure[i] + solution[doflist[i]];
+	}
+	element->AddInput(PressureEnum,values,element->GetElementType());
+
+	/*Now compute sigmann if on base*/
+	if(element->IsOnBase()){ 
+		if(dim==3) _error_("not implemented yet");
+
+		int baselist[3];
+		int onbase=0;
+		IssmDouble  Jdet;
+		IssmDouble bed_normal[3];
+		IssmDouble  Jlambda[3][3]  = {0.0};
+		IssmDouble  Cuk[3]         = {0.0};
+		IssmDouble  deltalambda[3] = {0.0};
+		IssmDouble* vertexonbase  = xNew<IssmDouble>(numnodessigma);
+		Input* vertexonbase_input = element->GetInput(MeshVertexonbaseEnum); _assert_(vertexonbase_input);
+		Gauss* gauss = element->NewGauss();
+
+		IssmDouble* basis = xNewZeroInit<IssmDouble>(numnodessigma);
+		element->GetVerticesCoordinatesBase(&xyz_list_base);
+		element->NormalBase(&bed_normal[0],xyz_list_base);
+		element->FindParam(&rholambda,AugmentedLagrangianRholambdaEnum);
+
+		for(int i=0;i<numnodessigma;i++){
+			gauss->GaussNode(P2Enum,i);
+			vertexonbase_input->GetInputValue(&vertexonbase[i], gauss);
+			if(vertexonbase[i]==1){ 
+				baselist[onbase]=i;
+				onbase += 1;
+			}
+		}
+		if(onbase!=3) _error_("basal nodes of element not found");
+
+		delete gauss;
+		gauss = element->NewGaussBase(3);
+		for(int ig=gauss->begin();ig<gauss->end();ig++){
+			gauss->GaussPoint(ig);
+
+			/*Compute Jlambda*/
+			element->NodalFunctionsP2(basis,gauss);
+			element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+			for(int i=0;i<3;i++){
+				for(int j=0;j<3;j++){
+					Jlambda[i][j] += Jdet*gauss->weight*basis[baselist[i]]*basis[baselist[j]];
+				}
+			}
+
+			/*Compute rho_lambd C u^k*/
+			vx_input->GetInputValue(&vx, gauss);
+			vy_input->GetInputValue(&vy, gauss);
+			un=bed_normal[0]*vx + bed_normal[1]*vy;
+			for(int i=0;i<3;i++) Cuk[i] += - un*rholambda*Jdet*gauss->weight*basis[baselist[i]];
+		}
+
+		/*Now update sigmann*/
+		Matrix3x3Solve(&deltalambda[0],&Jlambda[0][0],&Cuk[0]);
+		delete gauss;
+		gauss = element->NewGauss();
+		for(int i=0;i<3;i++){
+			gauss->GaussNode(P2Enum,baselist[i]);
+			sigmann_input->GetInputValue(&sigmann, gauss);
+			valueslambda[baselist[i]] = sigmann + deltalambda[i];
+		}
+
+		delete gauss;
+		xDelete<IssmDouble>(vertexonbase);
+		xDelete<IssmDouble>(xyz_list_base);
+		xDelete<IssmDouble>(basis);
+	}
+	element->AddInput(SigmaNNEnum,valueslambda,P2Enum);
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(values);
+	xDelete<IssmDouble>(valueslambda);
+	xDelete<IssmDouble>(pressure);
+	xDelete<int>(doflist);
+}/*}}}*/
+void UzawaPressureAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/*Default, do nothing*/
+	return;
+}/*}}}*/
Index: issm/trunk/src/c/analyses/UzawaPressureAnalysis.h
===================================================================
--- issm/trunk/src/c/analyses/UzawaPressureAnalysis.h	(revision 18301)
+++ issm/trunk/src/c/analyses/UzawaPressureAnalysis.h	(revision 18301)
@@ -0,0 +1,34 @@
+/*! \file UzawaPressureAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _UzawaPressureAnalysis_
+#define _UzawaPressureAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class UzawaPressureAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+
+		/*Finite element Analysis*/
+		void           Core(FemModel* femmodel);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		void GetM(IssmDouble* M,Element* element,Gauss* gauss);
+		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void UpdateConstraints(FemModel* femmodel);
+};
+#endif
Index: issm/trunk/src/c/analyses/analyses.h
===================================================================
--- issm/trunk/src/c/analyses/analyses.h	(revision 18081)
+++ issm/trunk/src/c/analyses/analyses.h	(revision 18301)
@@ -37,4 +37,5 @@
 #include "./StressbalanceSIAAnalysis.h"
 #include "./StressbalanceVerticalAnalysis.h"
+#include "./UzawaPressureAnalysis.h"
 #include "./L2ProjectionBaseAnalysis.h"
 #include "./L2ProjectionEPLAnalysis.h"
Index: issm/trunk/src/c/bamg/AdjacentTriangle.cpp
===================================================================
--- issm/trunk/src/c/bamg/AdjacentTriangle.cpp	(revision 18081)
+++ issm/trunk/src/c/bamg/AdjacentTriangle.cpp	(revision 18301)
@@ -13,42 +13,34 @@
 
 	/*Methods*/
-	/*FUNCTION AdjacentTriangle::Locked {{{*/
-	int  AdjacentTriangle::Locked() const {
+	int  AdjacentTriangle::Locked() const {/*{{{*/
 		return t->AdjEdgeIndex[a] & 4;
 	}
 	/*}}}*/
-	/*FUNCTION AdjacentTriangle::GetAllFlag_UnSwap {{{*/
-	int  AdjacentTriangle::GetAllFlag_UnSwap() const {
+	int  AdjacentTriangle::GetAllFlag_UnSwap() const {/*{{{*/
 		// take all flag except MarkUnSwap
 		return t->AdjEdgeIndex[a] & 1012;
 	}
 	/*}}}*/
-	/*FUNCTION AdjacentTriangle::SetLock {{{*/
-	void AdjacentTriangle::SetLock(){
+	void AdjacentTriangle::SetLock(){/*{{{*/
 		t->SetLocked(a);
 	}
 	/*}}}*/
-	/*FUNCTION AdjacentTriangle::Adj {{{*/
-	AdjacentTriangle AdjacentTriangle::Adj() const {
+	AdjacentTriangle AdjacentTriangle::Adj() const {/*{{{*/
 		return  t->Adj(a);
 	}
 	/*}}}*/
-	/*FUNCTION AdjacentTriangle::EdgeVertex {{{*/
-	BamgVertex* AdjacentTriangle::EdgeVertex(const int & i) const {
+	BamgVertex* AdjacentTriangle::EdgeVertex(const int & i) const {/*{{{*/
 		return t->vertices[VerticesOfTriangularEdge[a][i]];
 	}
 	/*}}}*/
-	/*FUNCTION AdjacentTriangle::det {{{*/
-	Icoor2 & AdjacentTriangle::det() const {
+	Icoor2 & AdjacentTriangle::det() const {/*{{{*/
 		return t->det;
 	}
 	/*}}}*/
-	/*FUNCTION AdjacentTriangle::swap {{{*/
-	int AdjacentTriangle::swap(){
+	int AdjacentTriangle::swap(){/*{{{*/
 		return  t->swap(a);
 	}
 	/*}}}*/
-	/*FUNCTION AdjacentTriangle::SetAdj2 {{{*/
-	void AdjacentTriangle::SetAdj2(const AdjacentTriangle & ta, int l  ){
+	void AdjacentTriangle::SetAdj2(const AdjacentTriangle & ta, int l  ){/*{{{*/
 		//set Adjacent Triangle of a triangle
 		if(t) {
Index: issm/trunk/src/c/bamg/BamgGeom.cpp
===================================================================
--- issm/trunk/src/c/bamg/BamgGeom.cpp	(revision 18081)
+++ issm/trunk/src/c/bamg/BamgGeom.cpp	(revision 18301)
@@ -3,6 +3,5 @@
 
 /*Constructors/Destructors*/
-/*FUNCTION BamgGeom::BamgGeom(){{{*/
-BamgGeom::BamgGeom(){
+BamgGeom::BamgGeom(){/*{{{*/
 
 	this->VerticesSize[0]=0,          this->VerticesSize[1]=0;          this->Vertices=NULL;
@@ -17,6 +16,5 @@
 }
 /*}}}*/
-/*FUNCTION BamgGeom::~BamgGeom(){{{*/
-BamgGeom::~BamgGeom(){
+BamgGeom::~BamgGeom(){/*{{{*/
 
 	xDelete<double>(this->Vertices);
Index: issm/trunk/src/c/bamg/BamgMesh.cpp
===================================================================
--- issm/trunk/src/c/bamg/BamgMesh.cpp	(revision 18081)
+++ issm/trunk/src/c/bamg/BamgMesh.cpp	(revision 18301)
@@ -3,6 +3,5 @@
 
 /*Constructors/Destructors*/
-/*FUNCTION BamgMesh::BamgMesh(){{{*/
-BamgMesh::BamgMesh(){
+BamgMesh::BamgMesh(){/*{{{*/
 
 	this->VerticesSize[0]=0,                  this->VerticesSize[1]=0;                 this->Vertices=NULL;
@@ -28,6 +27,5 @@
 }
 /*}}}*/
-/*FUNCTION BamgMesh::~BamgMesh(){{{*/
-BamgMesh::~BamgMesh(){
+BamgMesh::~BamgMesh(){/*{{{*/
 
 	xDelete<double>(this->Vertices);
Index: issm/trunk/src/c/bamg/BamgOpts.cpp
===================================================================
--- issm/trunk/src/c/bamg/BamgOpts.cpp	(revision 18081)
+++ issm/trunk/src/c/bamg/BamgOpts.cpp	(revision 18301)
@@ -3,6 +3,5 @@
 
 /*Constructors/Destructors*/
-/*FUNCTION BamgOpts::BamgOpts() {{{*/
-BamgOpts::BamgOpts(){
+BamgOpts::BamgOpts(){/*{{{*/
 
 	this->anisomax=0;
@@ -39,6 +38,5 @@
 }
 /*}}}*/
-/*FUNCTION BamgOpts::~BamgOpts() {{{*/
-BamgOpts::~BamgOpts(){
+BamgOpts::~BamgOpts(){/*{{{*/
 
 	xDelete<double>(this->hminVertices);
@@ -53,6 +51,5 @@
 
 /*Methods*/
-/*FUNCTION BamgOpts::Check{{{*/
-void BamgOpts::Check(void){
+void BamgOpts::Check(void){/*{{{*/
 
 	int i;
Index: issm/trunk/src/c/bamg/BamgQuadtree.cpp
===================================================================
--- issm/trunk/src/c/bamg/BamgQuadtree.cpp	(revision 18081)
+++ issm/trunk/src/c/bamg/BamgQuadtree.cpp	(revision 18301)
@@ -98,6 +98,5 @@
 
 	/*Constructors/Destructors*/
-	/*FUNCTION BamgQuadtree::BamgQuadtree(){{{*/
-	BamgQuadtree::BamgQuadtree(){
+	BamgQuadtree::BamgQuadtree(){/*{{{*/
 
 		/*Number of boxes and vertices*/
@@ -113,6 +112,5 @@
 		}
 	/*}}}*/
-	/*FUNCTION BamgQuadtree::BamgQuadtree(Mesh * t,long nbv){{{*/
-	BamgQuadtree::BamgQuadtree(Mesh * t,long nbv){ 
+	BamgQuadtree::BamgQuadtree(Mesh * t,long nbv){ /*{{{*/
 
 		/*Number of boxes and vertices*/
@@ -135,6 +133,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION BamgQuadtree::~BamgQuadtree(){{{*/
-	BamgQuadtree::~BamgQuadtree() {
+	BamgQuadtree::~BamgQuadtree() {/*{{{*/
 		delete boxcontainer;
 		root=NULL;
@@ -143,6 +140,5 @@
 
 	/*Methods*/
-	/*FUNCTION BamgQuadtree::Add{{{*/
-	void  BamgQuadtree::Add(BamgVertex &w){
+	void  BamgQuadtree::Add(BamgVertex &w){/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, BamgQuadtree.cpp/Add)*/
 		BamgQuadtreeBox** pb=NULL;
@@ -232,6 +228,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION BamgQuadtree::NearestVertex{{{*/
-	BamgVertex*  BamgQuadtree::NearestVertex(Icoor1 i,Icoor1 j) {
+	BamgVertex*  BamgQuadtree::NearestVertex(Icoor1 i,Icoor1 j) {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, BamgQuadtree.cpp/NearestVertex)*/
 
@@ -391,6 +386,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION BamgQuadtree::NewBamgQuadtreeBox {{{*/
-	BamgQuadtree::BamgQuadtreeBox* BamgQuadtree::NewBamgQuadtreeBox(void){
+	BamgQuadtree::BamgQuadtreeBox* BamgQuadtree::NewBamgQuadtreeBox(void){/*{{{*/
 
 		/*Output*/
@@ -414,6 +408,5 @@
 		return newbox;
 	}/*}}}*/
-	/*FUNCTION BamgQuadtree::ToClose {{{*/
-	BamgVertex*   BamgQuadtree::ToClose(BamgVertex & v,double seuil,Icoor1 hx,Icoor1 hy){
+	BamgVertex*   BamgQuadtree::ToClose(BamgVertex & v,double seuil,Icoor1 hx,Icoor1 hy){/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, BamgQuadtree.cpp/ToClose)*/
 
Index: issm/trunk/src/c/bamg/BamgVertex.cpp
===================================================================
--- issm/trunk/src/c/bamg/BamgVertex.cpp	(revision 18081)
+++ issm/trunk/src/c/bamg/BamgVertex.cpp	(revision 18301)
@@ -11,7 +11,5 @@
 
 	/*Methods*/
-	/*FUNCTION BamgVertex::Echo {{{*/
-
-	void BamgVertex::Echo(void){
+	void BamgVertex::Echo(void){/*{{{*/
 
 		_printf_("Vertex:\n");
@@ -24,11 +22,9 @@
 	}
 	/*}}}*/
-	/*FUNCTION BamgVertex::GetReferenceNumber{{{*/
-	int  BamgVertex::GetReferenceNumber() const { 
+	int  BamgVertex::GetReferenceNumber() const { /*{{{*/
 		return ReferenceNumber;
 	}
 	/*}}}*/
-	/*FUNCTION BamgVertex::MetricFromHessian{{{*/
-	void BamgVertex::MetricFromHessian(const double Hxx,const double Hyx, const double Hyy,const double smin,const double smax,const double s,double err,BamgOpts* bamgopts){
+	void BamgVertex::MetricFromHessian(const double Hxx,const double Hyx, const double Hyy,const double smin,const double smax,const double s,double err,BamgOpts* bamgopts){/*{{{*/
 		/*Compute Metric from Hessian*/
 
@@ -108,6 +104,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION BamgVertex::Optim {{{*/
-	long BamgVertex::Optim(int i,int koption){ 
+	long BamgVertex::Optim(int i,int koption){ /*{{{*/
 		long ret=0;
 		if ( t && (IndexInTriangle >= 0 ) && (IndexInTriangle <3) ){
@@ -121,6 +116,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION BamgVertex::Smoothing{{{*/
-	double  BamgVertex::Smoothing(Mesh &Th,const Mesh &BTh,Triangle* &tstart ,double omega){
+	double  BamgVertex::Smoothing(Mesh &Th,const Mesh &BTh,Triangle* &tstart ,double omega){/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Smoothing)*/
 
@@ -227,6 +221,5 @@
 
 	/*Intermediary*/
-	/*FUNCTION QuadQuality{{{*/
-	double QuadQuality(const BamgVertex & a,const BamgVertex &b,const BamgVertex &c,const BamgVertex &d) {
+	double QuadQuality(const BamgVertex & a,const BamgVertex &b,const BamgVertex &c,const BamgVertex &d) {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshQuad.cpp/QuadQuality)*/
 
Index: issm/trunk/src/c/bamg/CrackedEdge.cpp
===================================================================
--- issm/trunk/src/c/bamg/CrackedEdge.cpp	(revision 18081)
+++ issm/trunk/src/c/bamg/CrackedEdge.cpp	(revision 18301)
@@ -9,6 +9,5 @@
 
 	/*Constructors/Destructors*/
-	/*FUNCTION CrackedEdge() {{{*/
-	CrackedEdge::CrackedEdge() {
+	CrackedEdge::CrackedEdge() {/*{{{*/
 		a=NULL;
 		b=NULL;
Index: issm/trunk/src/c/bamg/Curve.cpp
===================================================================
--- issm/trunk/src/c/bamg/Curve.cpp	(revision 18081)
+++ issm/trunk/src/c/bamg/Curve.cpp	(revision 18301)
@@ -10,6 +10,5 @@
 
 	/*Constructors/Destructors*/
-	/*FUNCTION Curve::Curve(){{{*/
-	Curve::Curve(){
+	Curve::Curve(){/*{{{*/
 		FirstEdge=NULL;
 		LastEdge=NULL;
@@ -20,6 +19,5 @@
 
 	/*Methods*/
-	/*FUNCTION Curve::Set {{{*/
-	void Curve::Set(const Curve & rec,const Geometry & Gh ,Geometry & GhNew){
+	void Curve::Set(const Curve & rec,const Geometry & Gh ,Geometry & GhNew){/*{{{*/
 		*this = rec;
 		FirstEdge = GhNew.edges + Gh.GetId(FirstEdge);    
Index: issm/trunk/src/c/bamg/Direction.cpp
===================================================================
--- issm/trunk/src/c/bamg/Direction.cpp	(revision 18081)
+++ issm/trunk/src/c/bamg/Direction.cpp	(revision 18301)
@@ -9,11 +9,9 @@
 
 	/*Constructors/Destructors*/
-	/*FUNCTION Direction() {{{*/
-	Direction::Direction():
+	Direction::Direction():/*{{{*/
 		dir(MaxICoor){
 
 	}/*}}}*/
-	/*FUNCTION Direction(Icoor1 i,Icoor1 j) {{{*/
-	Direction::Direction(Icoor1 i,Icoor1 j) {
+	Direction::Direction(Icoor1 i,Icoor1 j) {/*{{{*/
 		Icoor2 n2 = 2*(Abs(i)+Abs(j));  
 		Icoor2 r  = MaxICoor* (Icoor2) i;
@@ -23,6 +21,5 @@
 
 	/*Methods*/
-	/*FUNCTION Direction::direction{{{*/
-	int Direction::direction(Icoor1 i,Icoor1 j) {
+	int Direction::direction(Icoor1 i,Icoor1 j) {/*{{{*/
 		int r =1; 
 		if (dir!= MaxICoor) {
Index: issm/trunk/src/c/bamg/Edge.cpp
===================================================================
--- issm/trunk/src/c/bamg/Edge.cpp	(revision 18081)
+++ issm/trunk/src/c/bamg/Edge.cpp	(revision 18301)
@@ -14,6 +14,5 @@
 
 	/*Methods*/
-	/*FUNCTION Edge::Set {{{*/
-	void Edge::Set(const Mesh & Th ,long i,Mesh & ThNew){ 
+	void Edge::Set(const Mesh & Th ,long i,Mesh & ThNew){ /*{{{*/
 		*this = Th.edges[i];
 		v[0] = ThNew.vertices + Th.GetId(v[0]);    
@@ -25,6 +24,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Edge::Echo {{{*/
-	void Edge::Echo(void){ 
+	void Edge::Echo(void){ /*{{{*/
 		_printf_("Edge:\n");
 		_printf_("   pointers towards two vertices: " << v[0] << " " << v[1] << "\n");
@@ -34,6 +32,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Edge::Renumbering{{{*/
-	void Edge::Renumbering(BamgVertex *vb,BamgVertex *ve, long *renu){
+	void Edge::Renumbering(BamgVertex *vb,BamgVertex *ve, long *renu){/*{{{*/
 
 		if (v[0] >=vb && v[0] <ve) v[0] = vb + renu[v[0]-vb];
@@ -42,6 +39,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Edge::Intersection{{{*/
-	int Edge::Intersection(const  Edge & e){ 
+	int Edge::Intersection(const  Edge & e){ /*{{{*/
 
 		/*some shecks*/
Index: issm/trunk/src/c/bamg/EigenMetric.cpp
===================================================================
--- issm/trunk/src/c/bamg/EigenMetric.cpp	(revision 18081)
+++ issm/trunk/src/c/bamg/EigenMetric.cpp	(revision 18301)
@@ -10,6 +10,5 @@
 
 	/*Constructor*/
-	/*FUNCTION EigenMetric::EigenMetric(const Metric M){{{*/
-	EigenMetric::EigenMetric(const Metric& M){
+	EigenMetric::EigenMetric(const Metric& M){/*{{{*/
 		/*From a metric (a11,a21,a22), get eigen values lambda1 and lambda2 and one eigen vector v*/
 
@@ -89,20 +88,16 @@
 	}
 	/*}}}*/
-	/*FUNCTION EigenMetric::EigenMetric(double r1,double r2,const D2 vp1){{{*/
-	EigenMetric::EigenMetric(double r1,double r2,const D2& vp1): lambda1(r1),lambda2(r2),v(vp1){
+	EigenMetric::EigenMetric(double r1,double r2,const D2& vp1): lambda1(r1),lambda2(r2),v(vp1){/*{{{*/
 
 	}/*}}}*/
 
 	/*Methods*/
-	/*FUNCTION EigenMetric::Abs{{{*/
-	void   EigenMetric::Abs(){
+	void   EigenMetric::Abs(){/*{{{*/
 		lambda1=bamg::Abs(lambda1),lambda2=bamg::Abs(lambda2);
 	}/*}}}*/
-	/*FUNCTION EigenMetric::Aniso2{{{*/
-	double EigenMetric::Aniso2() const  { 
+	double EigenMetric::Aniso2() const  { /*{{{*/
 		return lmax()/lmin();
 	}/*}}}*/
-	/*FUNCTION EigenMetric::Echo {{{*/
-	void EigenMetric::Echo(void){
+	void EigenMetric::Echo(void){/*{{{*/
 
 		_printf_("EigenMetric:\n");
@@ -115,40 +110,31 @@
 	}
 	/*}}}*/
-	/*FUNCTION EigenMetric::hmin{{{*/
-	double EigenMetric::hmin() const {
+	double EigenMetric::hmin() const {/*{{{*/
 		return sqrt(1/bamg::Max3(lambda1,lambda2,1e-30));
 	}/*}}}*/
-	/*FUNCTION EigenMetric::hmax{{{*/
-	double EigenMetric::hmax() const {
+	double EigenMetric::hmax() const {/*{{{*/
 		return sqrt(1/bamg::Max(bamg::Min(lambda1,lambda2),1e-30));
 	}/*}}}*/
-	/*FUNCTION EigenMetric::lmax{{{*/
-	double EigenMetric::lmax() const {
+	double EigenMetric::lmax() const {/*{{{*/
 		return bamg::Max3(lambda1,lambda2,1e-30);
 	}/*}}}*/
-	/*FUNCTION EigenMetric::lmin{{{*/
-	double EigenMetric::lmin() const {
+	double EigenMetric::lmin() const {/*{{{*/
 		return bamg::Max(bamg::Min(lambda1,lambda2),1e-30);
 	}/*}}}*/
-	/*FUNCTION EigenMetric::Min{{{*/
-	void   EigenMetric::Min(double a) { 
+	void   EigenMetric::Min(double a) { /*{{{*/
 		lambda1=bamg::Min(a,lambda1); lambda2=bamg::Min(a,lambda2) ;
 	}/*}}}*/
-	/*FUNCTION EigenMetric::Max{{{*/
-	void   EigenMetric::Max(double a) { 
+	void   EigenMetric::Max(double a) { /*{{{*/
 		//change eigen values
 		lambda1=bamg::Max(a,lambda1); lambda2=bamg::Max(a,lambda2) ;
 	}/*}}}*/
-	/*FUNCTION EigenMetric::Minh{{{*/
-	void   EigenMetric::Minh(double h) {
+	void   EigenMetric::Minh(double h) {/*{{{*/
 		Min(1.0/(h*h));
 	}/*}}}*/
-	/*FUNCTION EigenMetric::Maxh{{{*/
-	void   EigenMetric::Maxh(double h) {
+	void   EigenMetric::Maxh(double h) {/*{{{*/
 		//Call Max function
 		Max(1.0/(h*h));
 	}/*}}}*/
-	/*FUNCTION EigenMetric::pow{{{*/
-	void   EigenMetric::pow(double p){
+	void   EigenMetric::pow(double p){/*{{{*/
 		lambda1=::pow(lambda1,p);lambda2=::pow(lambda2,p);
 	}/*}}}*/
Index: issm/trunk/src/c/bamg/GeomEdge.cpp
===================================================================
--- issm/trunk/src/c/bamg/GeomEdge.cpp	(revision 18081)
+++ issm/trunk/src/c/bamg/GeomEdge.cpp	(revision 18301)
@@ -15,10 +15,8 @@
 
 	/*Methods*/
-	/*FUNCTION GeomEdge::Cracked{{{*/
-	int    GeomEdge::Cracked() const  {
+	int    GeomEdge::Cracked() const  {/*{{{*/
 		return type &1;  
 	}/*}}}*/
-	/*FUNCTION GeomEdge::F{{{*/
-	R2 GeomEdge::F(double theta) const{
+	R2 GeomEdge::F(double theta) const{/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/F)*/
 		// parametrization of the curve edge
@@ -62,10 +60,8 @@
 	  }
 	/*}}}*/
-	/*FUNCTION GeomEdge::Mark{{{*/
-	int    GeomEdge::Mark()    const  {
+	int    GeomEdge::Mark()    const  {/*{{{*/
 		return type &16; 
 	}/*}}}*/
-	/*FUNCTION GeomEdge::R1tg{{{*/
-	double GeomEdge::R1tg(double theta,R2 & t) const{
+	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
@@ -138,10 +134,8 @@
 	}
 	/*}}}*/
-	/*FUNCTION GeomEdge::Required{{{*/
-	int    GeomEdge::Required()       {
+	int    GeomEdge::Required()       {/*{{{*/
 		return type &64; 
 	}/*}}}*/
-	/*FUNCTION GeomEdge::Set {{{*/
-	void GeomEdge::Set(const GeomEdge & rec,const Geometry & Gh ,Geometry & GhNew){ 
+	void GeomEdge::Set(const GeomEdge & rec,const Geometry & Gh ,Geometry & GhNew){ /*{{{*/
 		*this = rec;
 		v[0] = GhNew.vertices + Gh.GetId(v[0]);    
@@ -151,34 +145,26 @@
 	}
 	/*}}}*/
-	/*FUNCTION GeomEdge::SetCracked{{{*/
-	void   GeomEdge::SetCracked()     { 
+	void   GeomEdge::SetCracked()     { /*{{{*/
 		type |= 1;/*=>1st digit to 1*/
 	}/*}}}*/
-	/*FUNCTION GeomEdge::SetTgA{{{*/
-	void   GeomEdge::SetTgA()         { 
+	void   GeomEdge::SetTgA()         { /*{{{*/
 		type |=4; /*=>2d digit to 1*/
 	}/*}}}*/
-	/*FUNCTION GeomEdge::SetTgB{{{*/
-	void   GeomEdge::SetTgB()         { 
+	void   GeomEdge::SetTgB()         { /*{{{*/
 		type |=8; /*=> 3d digit to 1*/
 	}/*}}}*/
-	/*FUNCTION GeomEdge::SetMark{{{*/
-	void   GeomEdge::SetMark()        { 
+	void   GeomEdge::SetMark()        { /*{{{*/
 		type |=16;/*=> 4th digiy to 1*/
 	}/*}}}*/
-	/*FUNCTION GeomEdge::SetUnMark{{{*/
-	void   GeomEdge::SetUnMark()      { 
+	void   GeomEdge::SetUnMark()      { /*{{{*/
 		type &= 1007 /* 1023-16 = 000111110111 => 4th digit to 0*/;
 	}/*}}}*/
-	/*FUNCTION GeomEdge::SetRequired{{{*/
-	void   GeomEdge::SetRequired()    { 
+	void   GeomEdge::SetRequired()    { /*{{{*/
 		type |= 64;/*=>6th digit to 1*/ 
 	}/*}}}*/
-	/*FUNCTION GeomEdge::TgA{{{*/
-	int    GeomEdge::TgA()     const  {
+	int    GeomEdge::TgA()     const  {/*{{{*/
 		return type &4;  
 	}/*}}}*/
-	/*FUNCTION GeomEdge::TgB{{{*/
-	int    GeomEdge::TgB()     const  {
+	int    GeomEdge::TgB()     const  {/*{{{*/
 		return type &8;  
 	}/*}}}*/
Index: issm/trunk/src/c/bamg/GeomSubDomain.cpp
===================================================================
--- issm/trunk/src/c/bamg/GeomSubDomain.cpp	(revision 18081)
+++ issm/trunk/src/c/bamg/GeomSubDomain.cpp	(revision 18301)
@@ -12,6 +12,5 @@
 
 	/*Methods*/
-	/*FUNCTION GeomSubDomain::Set {{{*/
-	void GeomSubDomain::Set(const GeomSubDomain & rec,const Geometry & Gh ,const Geometry & GhNew){
+	void GeomSubDomain::Set(const GeomSubDomain & rec,const Geometry & Gh ,const Geometry & GhNew){/*{{{*/
 		*this = rec;
 		edge = Gh.GetId(edge) + GhNew.edges;
Index: issm/trunk/src/c/bamg/GeomVertex.cpp
===================================================================
--- issm/trunk/src/c/bamg/GeomVertex.cpp	(revision 18081)
+++ issm/trunk/src/c/bamg/GeomVertex.cpp	(revision 18301)
@@ -13,22 +13,18 @@
 
 	/*Methods*/
-	/*FUNCTION GeomVertex::Corner {{{*/
-	int  GeomVertex::Corner() const {
+	int  GeomVertex::Corner() const {/*{{{*/
 		return type & 4;
 	}
 	/*}}}*/
-	/*FUNCTION GeomVertex::Required {{{*/
-	int  GeomVertex::Required()const {
+	int  GeomVertex::Required()const {/*{{{*/
 		// a corner is required
 		return type & 6;
 	}
 	/*}}}*/
-	/*FUNCTION GeomVertex::SetCorner {{{*/
-	void GeomVertex::SetCorner(){
+	void GeomVertex::SetCorner(){/*{{{*/
 		type |= 4;
 	}
 	/*}}}*/
-	/*FUNCTION GeomVertex::SetRequired {{{*/
-	void GeomVertex::SetRequired(){
+	void GeomVertex::SetRequired(){/*{{{*/
 		type |= 2;
 	}
Index: issm/trunk/src/c/bamg/Geometry.cpp
===================================================================
--- issm/trunk/src/c/bamg/Geometry.cpp	(revision 18081)
+++ issm/trunk/src/c/bamg/Geometry.cpp	(revision 18301)
@@ -12,11 +12,9 @@
 
 	/*Constructors/Destructors*/
-	/*FUNCTION Geometry::Geometry(){{{*/
-	Geometry::Geometry(){
+	Geometry::Geometry(){/*{{{*/
 		Init();
 	}
 	/*}}}*/
-	/*FUNCTION Geometry::Geometry(BamgGeom* bamggeom, BamgOpts* bamgopts){{{*/
-	Geometry::Geometry(BamgGeom* bamggeom, BamgOpts* bamgopts){
+	Geometry::Geometry(BamgGeom* bamggeom, BamgOpts* bamgopts){/*{{{*/
 		Init();
 		ReadGeometry(bamggeom,bamgopts);
@@ -24,6 +22,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Geometry::Geometry(const Geometry & Gh) (COPY operator){{{*/
-	Geometry::Geometry(const Geometry & Gh) {
+	Geometry::Geometry(const Geometry & Gh) {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/Geometry)*/
 
@@ -44,6 +41,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Geometry::~Geometry(){{{*/
-	Geometry::~Geometry() {
+	Geometry::~Geometry() {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/~Geometry)*/
 		if(NbRef>0){   _printf_("Trying to delete geometry and NbRef>0, probably due to an error"); return;}
@@ -58,6 +54,5 @@
 
 	/*IO*/
-	/*FUNCTION Geometry::ReadGeometry{{{*/
-	void Geometry::ReadGeometry(BamgGeom* bamggeom,BamgOpts* bamgopts){
+	void Geometry::ReadGeometry(BamgGeom* bamggeom,BamgOpts* bamgopts){/*{{{*/
 
 		int verbose;
@@ -277,6 +272,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Geometry::WriteGeometry{{{*/
-	void Geometry::WriteGeometry(BamgGeom* bamggeom, BamgOpts* bamgopts){
+	void Geometry::WriteGeometry(BamgGeom* bamggeom, BamgOpts* bamgopts){/*{{{*/
 
 		int verbose;
@@ -394,6 +388,5 @@
 
 	/*Methods*/
-	/*FUNCTION Geometry::Echo {{{*/
-	void Geometry::Echo(void){
+	void Geometry::Echo(void){/*{{{*/
 
 		_printf_("Geometry:\n");
@@ -415,6 +408,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Geometry::Init{{{*/
-	void Geometry::Init(void){
+	void Geometry::Init(void){/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/EmptyGeometry)*/
 
@@ -432,6 +424,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Geometry::MinimalHmin{{{*/
-	double Geometry::MinimalHmin() {
+	double Geometry::MinimalHmin() {/*{{{*/
 		/* coeffIcoor = (2^30-1)/D
 		 * We cannot go beyond hmin = D/2^30 because of the quadtree
@@ -439,30 +430,23 @@
 		return 2.0/coefIcoor;
 	}/*}}}*/
-	/*FUNCTION Geometry::MaximalHmax{{{*/
-	double Geometry::MaximalHmax() {
+	double Geometry::MaximalHmax() {/*{{{*/
 		return Max(pmax.x-pmin.x,pmax.y-pmin.y);
 	}/*}}}*/
-	/*FUNCTION Geometry::GetId(const GeomVertex &t){{{*/
-	long Geometry::GetId(const GeomVertex & t) const  {
+	long Geometry::GetId(const GeomVertex & t) const  {/*{{{*/
 		return &t - vertices;
 	}/*}}}*/
-	/*FUNCTION Geometry::GetId(const GeomVertex * t){{{*/
-	long Geometry::GetId(const GeomVertex * t) const  {
+	long Geometry::GetId(const GeomVertex * t) const  {/*{{{*/
 		return t - vertices;
 	}/*}}}*/
-	/*FUNCTION Geometry::GetId(const GeomEdge & t){{{*/
-	long Geometry::GetId(const GeomEdge & t) const  {
+	long Geometry::GetId(const GeomEdge & t) const  {/*{{{*/
 		return &t - edges;
 	}/*}}}*/
-	/*FUNCTION Geometry::GetId(const GeomEdge * t){{{*/
-	long Geometry::GetId(const GeomEdge * t) const  {
+	long Geometry::GetId(const GeomEdge * t) const  {/*{{{*/
 		return t - edges;
 	}/*}}}*/
-	/*FUNCTION Geometry::GetId(const Curve * c){{{*/
-	long Geometry::GetId(const Curve * c) const  {
+	long Geometry::GetId(const Curve * c) const  {/*{{{*/
 		return c - curves;
 	}/*}}}*/
-	/*FUNCTION Geometry::PostRead{{{*/
-	void Geometry::PostRead(){
+	void Geometry::PostRead(){/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/AfterRead)*/
 
@@ -785,6 +769,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Geometry::ProjectOnCurve {{{*/
-	GeomEdge* Geometry::ProjectOnCurve(const Edge &e,double s,BamgVertex &V,VertexOnGeom &GV) const {
+	GeomEdge* Geometry::ProjectOnCurve(const Edge &e,double s,BamgVertex &V,VertexOnGeom &GV) const {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/ProjectOnCurve)*/
 		/*Add a vertex on an existing geometrical edge according to the metrics of the two vertices constituting the edge*/
@@ -918,6 +901,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Geometry::R2ToI2{{{*/
-	I2 Geometry::R2ToI2(const R2 & P) const {
+	I2 Geometry::R2ToI2(const R2 & P) const {/*{{{*/
 		/*coefIcoor is the coefficient used for integer coordinates:
 		 *                       (x-pmin.x)
@@ -931,6 +913,5 @@
 		return  I2( (Icoor1) (coefIcoor*(P.x-pmin.x)) ,(Icoor1) (coefIcoor*(P.y-pmin.y)) );
 	}/*}}}*/
-	/*FUNCTION Geometry::UnMarkEdges{{{*/
-	void Geometry::UnMarkEdges() {
+	void Geometry::UnMarkEdges() {/*{{{*/
 		for (int i=0;i<nbe;i++) edges[i].SetUnMark();
 	}/*}}}*/
Index: issm/trunk/src/c/bamg/ListofIntersectionTriangles.cpp
===================================================================
--- issm/trunk/src/c/bamg/ListofIntersectionTriangles.cpp	(revision 18081)
+++ issm/trunk/src/c/bamg/ListofIntersectionTriangles.cpp	(revision 18301)
@@ -11,12 +11,10 @@
 
 	/*Constructors Destructors*/
-	/*FUNCTION ListofIntersectionTriangles::ListofIntersectionTriangles{{{*/
-	ListofIntersectionTriangles::ListofIntersectionTriangles(int n,int m)
+	ListofIntersectionTriangles::ListofIntersectionTriangles(int n,int m)/*{{{*/
 	  : MaxSize(n), Size(0), len(-1),state(-1),lIntTria(new IntersectionTriangles[n]) ,
 	  NbSeg(0), MaxNbSeg(m), lSegsI(new SegInterpolation[m]){
 	  }
 	/*}}}*/
-	/*FUNCTION ListofIntersectionTriangles::~ListofIntersectionTriangles{{{*/
-	ListofIntersectionTriangles::~ListofIntersectionTriangles(){
+	ListofIntersectionTriangles::~ListofIntersectionTriangles(){/*{{{*/
 		if (lIntTria) delete [] lIntTria,lIntTria=0;
 		if (lSegsI) delete [] lSegsI,lSegsI=0;
@@ -25,6 +23,5 @@
 
 	/*Methods*/
-	/*FUNCTION ListofIntersectionTriangles::Init{{{*/
-	void ListofIntersectionTriangles::Init(void){
+	void ListofIntersectionTriangles::Init(void){/*{{{*/
 		state=0;
 		len=0;
@@ -32,6 +29,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION ListofIntersectionTriangles::Length{{{*/
-	double  ListofIntersectionTriangles::Length(){
+	double  ListofIntersectionTriangles::Length(){/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Length)*/
 
@@ -79,6 +75,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION ListofIntersectionTriangles::NewItem(Triangle * tt,double d0,double d1,double d2) {{{*/
-	int  ListofIntersectionTriangles::NewItem(Triangle * tt,double d0,double d1,double d2) { 
+	int  ListofIntersectionTriangles::NewItem(Triangle * tt,double d0,double d1,double d2) { /*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/NewItem)*/
 
@@ -107,6 +102,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION ListofIntersectionTriangles::NewItem(R2 A,const Metric & mm){{{*/
-	int ListofIntersectionTriangles::NewItem(R2 A,const Metric & mm) {
+	int ListofIntersectionTriangles::NewItem(R2 A,const Metric & mm) {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/NewItem)*/
 
@@ -123,6 +117,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION ListofIntersectionTriangles::NewPoints{{{*/
-	long ListofIntersectionTriangles::NewPoints(BamgVertex* vertices,long &nbv,long maxnbv){
+	long ListofIntersectionTriangles::NewPoints(BamgVertex* vertices,long &nbv,long maxnbv){/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/NewPoints)*/
 
@@ -180,6 +173,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION ListofIntersectionTriangles::ReShape{{{*/
-	void ListofIntersectionTriangles::ReShape(){ 
+	void ListofIntersectionTriangles::ReShape(){ /*{{{*/
 
 		int newsize = MaxSize*2;
@@ -196,6 +188,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION ListofIntersectionTriangles::SplitEdge{{{*/
-	void ListofIntersectionTriangles::SplitEdge(const Mesh & Bh, const R2 &A,const R2  &B,int nbegin) {
+	void ListofIntersectionTriangles::SplitEdge(const Mesh & Bh, const R2 &A,const R2  &B,int nbegin) {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ListofIntersectionTriangles)*/
 
Index: issm/trunk/src/c/bamg/Mesh.cpp
===================================================================
--- issm/trunk/src/c/bamg/Mesh.cpp	(revision 18081)
+++ issm/trunk/src/c/bamg/Mesh.cpp	(revision 18301)
@@ -13,6 +13,5 @@
 
 	/*Constructors/Destructors*/
-	/*FUNCTION Mesh::Mesh(BamgGeom* bamggeom,BamgMesh* bamgmesh, BamgOpts* bamgopts){{{*/
-	Mesh::Mesh(BamgGeom* bamggeom,BamgMesh* bamgmesh, BamgOpts* bamgopts):Gh(*(new Geometry())),BTh(*this){ 
+	Mesh::Mesh(BamgGeom* bamggeom,BamgMesh* bamgmesh, BamgOpts* bamgopts):Gh(*(new Geometry())),BTh(*this){ /*{{{*/
 
 		/*Initialize fields*/
@@ -43,6 +42,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::Mesh(int* index,double* x,double* y,int nods,int nels){{{*/
-	Mesh::Mesh(int* index,double* x,double* y,int nods,int nels):Gh(*(new Geometry())),BTh(*this){
+	Mesh::Mesh(int* index,double* x,double* y,int nods,int nels):Gh(*(new Geometry())),BTh(*this){/*{{{*/
 
 		Init(0);
@@ -52,11 +50,9 @@
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::Mesh(double* x,double* y,int nods){{{*/
-	Mesh::Mesh(double* x,double* y,int nods):Gh(*(new Geometry())),BTh(*this){
+	Mesh::Mesh(double* x,double* y,int nods):Gh(*(new Geometry())),BTh(*this){/*{{{*/
 		Triangulate(x,y,nods);
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::Mesh(const Mesh & Tho,const int *flag ,const int *bb){{{*/
-	Mesh::Mesh(const Mesh & Tho,const int *flag ,const int *bb,BamgOpts* bamgopts) : Gh(*(new Geometry())), BTh(*this) {
+	Mesh::Mesh(const Mesh & Tho,const int *flag ,const int *bb,BamgOpts* bamgopts) : Gh(*(new Geometry())), BTh(*this) {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Triangles)*/
 
@@ -156,6 +152,5 @@
 	  }
 	/*}}}*/
-	/*FUNCTION Mesh::Mesh(Mesh & Th,Geometry * pGh,Mesh * pBth,long maxnbv_in) COPY{{{*/
-	Mesh::Mesh(Mesh & Th,Geometry * pGh,Mesh * pBth,long maxnbv_in)
+	Mesh::Mesh(Mesh & Th,Geometry * pGh,Mesh * pBth,long maxnbv_in)/*{{{*/
 	  : Gh(*(pGh?pGh:&Th.Gh)), BTh(*(pBth?pBth:this)) {
 		  /*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Triangles)*/
@@ -219,18 +214,15 @@
 	  }
 	/*}}}*/
-	/*FUNCTION Mesh::Mesh(long maxnbv,Mesh & BT,BamgOpts* bamgopts,int keepBackVertices){{{*/
-	Mesh::Mesh(long imaxnbv,Mesh & BT,BamgOpts* bamgopts,int keepBackVertices) :Gh(BT.Gh),BTh(BT) {
+	Mesh::Mesh(long imaxnbv,Mesh & BT,BamgOpts* bamgopts,int keepBackVertices) :Gh(BT.Gh),BTh(BT) {/*{{{*/
 		this->Init(imaxnbv);
 		TriangulateFromGeom1(bamgopts,keepBackVertices);
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::Mesh(long maxnbv,Geometry & G,BamgOpts* bamgopts){{{*/
-	Mesh::Mesh(long imaxnbv,Geometry & G,BamgOpts* bamgopts):Gh(G),BTh(*this){
+	Mesh::Mesh(long imaxnbv,Geometry & G,BamgOpts* bamgopts):Gh(G),BTh(*this){/*{{{*/
 		Init(imaxnbv);
 		TriangulateFromGeom0(bamgopts);
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::~Mesh(){{{*/
-	Mesh::~Mesh() {
+	Mesh::~Mesh() {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Triangles)*/
 
@@ -259,6 +251,5 @@
 
 	/*IO*/
-	/*FUNCTION 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){
+	void Mesh::ReadMesh(int* index,double* x,double* y,int nods,int nels){/*{{{*/
 
 		long i1,i2,i3;
@@ -322,6 +313,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::ReadMesh(BamgMesh* bamgmesh, BamgOpts* bamgopts){{{*/
-	void Mesh::ReadMesh(BamgMesh* bamgmesh, BamgOpts* bamgopts){
+	void Mesh::ReadMesh(BamgMesh* bamgmesh, BamgOpts* bamgopts){/*{{{*/
 
 		int    verbose;
@@ -525,6 +515,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::WriteMesh {{{*/
-	void Mesh::WriteMesh(BamgMesh* bamgmesh,BamgOpts* bamgopts){
+	void Mesh::WriteMesh(BamgMesh* bamgmesh,BamgOpts* bamgopts){/*{{{*/
 
 		/*Intermediary*/
@@ -952,6 +941,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::ReadMetric{{{*/
-	void Mesh::ReadMetric(const BamgOpts* bamgopts) {
+	void Mesh::ReadMetric(const BamgOpts* bamgopts) {/*{{{*/
 
 		/*Intermediary*/
@@ -990,6 +978,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::WriteMetric{{{*/
-	void Mesh::WriteMetric(BamgOpts* bamgopts) {
+	void Mesh::WriteMetric(BamgOpts* bamgopts) {/*{{{*/
 		int i;
 		xDelete<double>(bamgopts->metric);
@@ -1002,6 +989,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::WriteIndex{{{*/
-	void Mesh::WriteIndex(int** pindex,int* pnels){
+	void Mesh::WriteIndex(int** pindex,int* pnels){/*{{{*/
 
 		/*Intermediary*/
@@ -1042,6 +1028,5 @@
 
 	/*Methods*/
-	/*FUNCTION Mesh::AddGeometryMetric{{{*/
-	void Mesh::AddGeometryMetric(BamgOpts* bamgopts){
+	void Mesh::AddGeometryMetric(BamgOpts* bamgopts){/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/IntersectGeomMetric)*/
 
@@ -1094,6 +1079,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::AddMetric{{{*/
-	void Mesh::AddMetric(BamgOpts* bamgopts){
+	void Mesh::AddMetric(BamgOpts* bamgopts){/*{{{*/
 		//  Hessiantype = 0 =>  H is computed using double L2 projection
 		//  Hessiantype = 1 =>  H is computed with green formula
@@ -1113,6 +1097,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::AddVertex{{{*/
-	void Mesh::AddVertex( BamgVertex &s,Triangle* t, Icoor2* det3) {
+	void Mesh::AddVertex( BamgVertex &s,Triangle* t, Icoor2* det3) {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Add)*/
 		// -------------------------------
@@ -1249,6 +1232,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::BoundAnisotropy{{{*/
-	void  Mesh::BoundAnisotropy(double anisomax,double hminaniso) {
+	void  Mesh::BoundAnisotropy(double anisomax,double hminaniso) {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/BoundAnisotropy)*/
 
@@ -1289,6 +1271,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::BuildGeometryFromMesh{{{*/
-	void Mesh::BuildGeometryFromMesh(BamgOpts* bamgopts){
+	void Mesh::BuildGeometryFromMesh(BamgOpts* bamgopts){/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/ConsGeometry)*/
 
@@ -1739,6 +1720,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::BuildMetric0 (double L2 projection){{{*/
-	void Mesh::BuildMetric0(BamgOpts* bamgopts){
+	void Mesh::BuildMetric0(BamgOpts* bamgopts){/*{{{*/
 
 		/*Options*/
@@ -1944,6 +1924,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::BuildMetric1 (Green formula){{{*/
-	void Mesh::BuildMetric1(BamgOpts* bamgopts){
+	void Mesh::BuildMetric1(BamgOpts* bamgopts){/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/IntersectConsMetric)*/
 
@@ -2237,6 +2216,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::CrackMesh{{{*/
-	void Mesh::CrackMesh(BamgOpts* bamgopts) {
+	void Mesh::CrackMesh(BamgOpts* bamgopts) {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/CrackMesh)*/
 
@@ -2385,6 +2363,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::Echo{{{*/
-	void Mesh::Echo(void) {
+	void Mesh::Echo(void) {/*{{{*/
 
 		int i;
@@ -2409,49 +2386,47 @@
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::ForceBoundary{{{*/
-		void Mesh::ForceBoundary() {
-			/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ForceBoundary)*/
-
-			long int verbose=2;
-			int k=0;
-			int nbfe=0,nbswp=0,Nbswap=0;
-
-			//display
-			if (verbose > 2) _printf_("   ForceBoundary  nb of edge: " << nbe << "\n");
-
-			//check that there is no triangle with 0 determinant
-			for (int t = 0; t < nbt; t++){
-				if (!triangles[t].det) k++;
-			}
-			if (k!=0) {
-				_error_("there is " << k << " triangles of mes = 0");
-			}
-
-			//Force Edges
-			AdjacentTriangle ta(0,0);
-			for (int i = 0; i < nbe; i++){
-
-				//Force edge i
-				nbswp =  ForceEdge(edges[i][0],edges[i][1],ta);
-				if (nbswp<0) k++;
-				else Nbswap += nbswp;
-
-				if (nbswp) nbfe++;
-				if ( nbswp < 0 && k < 5){
-					_error_("Missing Edge " << i << ", v0=" << GetId(edges[i][0]) << ",v1=" << GetId(edges[i][1]));
-				}
-			}
-
-			if (k!=0) {
-				_error_("There are " << k << " lost edges, the boundary might be crossing");
-			}
-			for (int j=0;j<nbv;j++){
-				Nbswap +=  vertices[j].Optim(1,0);
-			}
-			if (verbose > 3) _printf_("      number of inforced edge = " << nbfe << ", number of swap= " << Nbswap << "\n"); 
-		}
-	/*}}}*/
-	/*FUNCTION Mesh::FindSubDomain{{{*/
-	void Mesh::FindSubDomain(int OutSide) {
+	void Mesh::ForceBoundary() {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ForceBoundary)*/
+
+		long int verbose=2;
+		int k=0;
+		int nbfe=0,nbswp=0,Nbswap=0;
+
+		//display
+		if (verbose > 2) _printf_("   ForceBoundary  nb of edge: " << nbe << "\n");
+
+		//check that there is no triangle with 0 determinant
+		for (int t = 0; t < nbt; t++){
+			if (!triangles[t].det) k++;
+		}
+		if (k!=0) {
+			_error_("there is " << k << " triangles of mes = 0");
+		}
+
+		//Force Edges
+		AdjacentTriangle ta(0,0);
+		for (int i = 0; i < nbe; i++){
+
+			//Force edge i
+			nbswp =  ForceEdge(edges[i][0],edges[i][1],ta);
+			if (nbswp<0) k++;
+			else Nbswap += nbswp;
+
+			if (nbswp) nbfe++;
+			if ( nbswp < 0 && k < 5){
+				_error_("Missing Edge " << i << ", v0=" << GetId(edges[i][0]) << ",v1=" << GetId(edges[i][1]));
+			}
+		}
+
+		if (k!=0) {
+			_error_("There are " << k << " lost edges, the boundary might be crossing");
+		}
+		for (int j=0;j<nbv;j++){
+			Nbswap +=  vertices[j].Optim(1,0);
+		}
+		if (verbose > 3) _printf_("      number of inforced edge = " << nbfe << ", number of swap= " << Nbswap << "\n"); 
+	}
+	/*}}}*/
+	void Mesh::FindSubDomain(int OutSide) {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/FindSubDomain)*/
 
@@ -2695,36 +2670,29 @@
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::GetId(const Triangle & t) const{{{*/
-	long Mesh::GetId(const Triangle & t) const  { 
+	long Mesh::GetId(const Triangle & t) const  { /*{{{*/
 		return &t - triangles;
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::GetId(const Triangle * t) const{{{*/
-	long Mesh::GetId(const Triangle * t) const  { 
+	long Mesh::GetId(const Triangle * t) const  { /*{{{*/
 		return t - triangles;
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::GetId(const BamgVertex & t) const{{{*/
-	long Mesh::GetId(const BamgVertex & t) const  { 
+	long Mesh::GetId(const BamgVertex & t) const  { /*{{{*/
 		return &t - vertices;
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::GetId(const BamgVertex * t) const{{{*/
-	long Mesh::GetId(const BamgVertex * t) const  { 
+	long Mesh::GetId(const BamgVertex * t) const  { /*{{{*/
 		return t - vertices;
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::GetId(const Edge & t) const{{{*/
-	long Mesh::GetId(const Edge & t) const  { 
+	long Mesh::GetId(const Edge & t) const  { /*{{{*/
 		return &t - edges;
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::GetId(const Edge * t) const{{{*/
-	long Mesh::GetId(const Edge * t) const  { 
+	long Mesh::GetId(const Edge * t) const  { /*{{{*/
 		return t - edges;
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::Init{{{*/
-	void Mesh::Init(long maxnbv_in) {
+	void Mesh::Init(long maxnbv_in) {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/PreInit)*/
 
@@ -2774,6 +2742,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::Insert{{{*/
-	void Mesh::Insert(bool random) {
+	void Mesh::Insert(bool random) {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Insert)*/
 
@@ -2907,6 +2874,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::InsertNewPoints{{{*/
-	long Mesh::InsertNewPoints(long nbvold,long & NbTSwap,bool random) {
+	long Mesh::InsertNewPoints(long nbvold,long & NbTSwap,bool random) {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/InsertNewPoints)*/
 
@@ -2985,6 +2951,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::MakeGeomEdgeToEdge{{{*/
-	Edge** Mesh::MakeGeomEdgeToEdge() {
+	Edge** Mesh::MakeGeomEdgeToEdge() {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/MakeGeomEdgeToEdge)*/
 
@@ -3028,6 +2993,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::MakeQuadrangles{{{*/
-	void Mesh::MakeQuadrangles(double costheta){
+	void Mesh::MakeQuadrangles(double costheta){/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/MakeQuadrangles)*/
 
@@ -3070,17 +3034,14 @@
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::MakeBamgQuadtree{{{*/
-	void Mesh::MakeBamgQuadtree() {  
+	void Mesh::MakeBamgQuadtree() {  /*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/MakeBamgQuadtree)*/
 		if(!quadtree) quadtree = new BamgQuadtree(this);
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::MaxinalHmax{{{*/
-	double Mesh::MaximalHmax() {
+	double Mesh::MaximalHmax() {/*{{{*/
 		return Max(pmax.x-pmin.x,pmax.y-pmin.y);
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::MaxSubDivision{{{*/
-	void  Mesh::MaxSubDivision(double maxsubdiv) {
+	void  Mesh::MaxSubDivision(double maxsubdiv) {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/MaxSubDivision)*/
 
@@ -3135,6 +3096,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::MetricAt{{{*/
-	Metric Mesh::MetricAt(const R2 & A) const { 
+	Metric Mesh::MetricAt(const R2 & A) const { /*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/MetricAt)*/
 
@@ -3156,17 +3116,14 @@
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::MininalHmin{{{*/
-	double Mesh::MinimalHmin() {
+	double Mesh::MinimalHmin() {/*{{{*/
 		return 2.0/coefIcoor;
 	}
 	/*}}}*/
-/*FUNCTION Mesh::NearestVertex{{{*/
-BamgVertex* Mesh::NearestVertex(Icoor1 i,Icoor1 j) {
-	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/NearestVertex)*/
-	return  quadtree->NearestVertex(i,j); 
-} 
-/*}}}*/
-	/*FUNCTION Mesh::NewPoints{{{*/
-	void  Mesh::NewPoints(Mesh & Bh,BamgOpts* bamgopts,int KeepVertices){
+	BamgVertex* Mesh::NearestVertex(Icoor1 i,Icoor1 j) {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/NearestVertex)*/
+		return  quadtree->NearestVertex(i,j); 
+	} 
+	/*}}}*/
+	void  Mesh::NewPoints(Mesh & Bh,BamgOpts* bamgopts,int KeepVertices){/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/NewPoints)*/
 
@@ -3249,6 +3206,6 @@
 					lIntTria.SplitEdge(Bh,A,B);
 					lIntTria.NewPoints(vertices,nbv,maxnbv);
-				  } // end loop for each edge 
-			  }// for triangle   
+				} // end loop for each edge 
+			}// for triangle   
 
 			if (!InsertNewPoints(nbvold,NbTSwap,bamgopts->random)) break;
@@ -3281,6 +3238,5 @@
 		for(i=0;i<nbv;i++) NbSwapf += vertices[i].Optim(0);
 	}/*}}}*/
-	/*FUNCTION Mesh::ProjectOnCurve{{{*/
-	GeomEdge*   Mesh::ProjectOnCurve( Edge & BhAB, BamgVertex &  vA, BamgVertex & vB,
+	GeomEdge*   Mesh::ProjectOnCurve( Edge & BhAB, BamgVertex &  vA, BamgVertex & vB,/*{{{*/
 				double theta,BamgVertex & R,VertexOnEdge &  BR,VertexOnGeom & GR) {
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshQuad.cpp/ProjectOnCurve)*/
@@ -3343,5 +3299,5 @@
 		else{ // do the search by walking 
 			_error_("case not supported yet");
-		  }
+		}
 
 		// find the direction of walking with direction of edge and pA,PB;
@@ -3381,6 +3337,6 @@
 					BR = VertexOnEdge(&R,eee,thetab);
 					return  Gh.ProjectOnCurve(*eee,thetab,R,GR);
-				  }
-			  }
+				}
+			}
 			// we find the end 
 			if (v1 != pvB){
@@ -3402,321 +3358,319 @@
 					return  Gh.ProjectOnCurve(*eee,thetab,R,GR);
 				  }
-			  }
+			}
 			abscisse = lg*theta;
 
-		  }
+		}
 		_error_("Big bug...");
 		return 0; // just for the compiler 
 	}                  
 	/*}}}*/
-/*FUNCTION Mesh::ReconstructExistingMesh{{{*/
-void Mesh::ReconstructExistingMesh(){
-	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/FillHoleInMesh)*/
-
-	/*This routine reconstruct an existing mesh to make it CONVEX:
-	 * -all the holes are filled
-	 * -concave boundaries are filled
-	 * A convex mesh is required for a lot of operations. This is why every mesh
-	 * goes through this process.
-	 * This routine also generates mesh properties such as adjencies,...
-	 */
-
-	/*Intermediary*/
-	int verbose=0;
-
-	// generation of the integer coordinate
-
-	// find extrema coordinates of vertices pmin,pmax
-	long i;
-	if(verbose>2) _printf_("      Reconstruct mesh of " << nbv << " vertices\n"); 
-
-	//initialize orderedvertices
-	_assert_(orderedvertices);
-	for (i=0;i<nbv;i++) orderedvertices[i]=0;
-
-	//Initialize nbsubdomains
-	nbsubdomains =0;
-
-	/* generation of triangles adjacency*/
-
-	//First add existing edges
-	long kk =0;
-	SetOfEdges4* edge4= new SetOfEdges4(nbt*3,nbv);
-	for (i=0;i<nbe;i++){
-		kk=kk+(i==edge4->SortAndAdd(GetId(edges[i][0]),GetId(edges[i][1])));
-	}
-	if (kk != nbe){ 
-		_error_("There are " << kk-nbe << " double edges in the mesh");
-	}
-
-	//Add edges of all triangles in existing mesh
-	long* st = new long[nbt*3];
-	for (i=0;i<nbt*3;i++) st[i]=-1;
-	for (i=0;i<nbt;i++){
-		for (int j=0;j<3;j++){
-
-			//Add current triangle edge to edge4
-			long k =edge4->SortAndAdd(GetId(triangles[i][VerticesOfTriangularEdge[j][0]]),GetId(triangles[i][VerticesOfTriangularEdge[j][1]]));
-
-			long invisible=triangles[i].Hidden(j);
-
-			//If the edge has not been added to st, add it
-			if(st[k]==-1) st[k]=3*i+j;
-
-			//If the edge already exists, add adjacency
-			else if(st[k]>=0) {
-				_assert_(!triangles[i].TriangleAdj(j));
-				_assert_(!triangles[st[k]/3].TriangleAdj((int) (st[k]%3)));
-
-				triangles[i].SetAdj2(j,triangles+st[k]/3,(int)(st[k]%3));
-				if (invisible) triangles[i].SetHidden(j);
-				if (k<nbe)     triangles[i].SetLocked(j);
-
-				//Make st[k] negative so that it will throw an error message if it is found again
-				st[k]=-2-st[k]; 
-			}
-
-			//An edge belongs to 2 triangles
-			else {
-				_error_("The edge (" << GetId(triangles[i][VerticesOfTriangularEdge[j][0]]) << " , " << GetId(triangles[i][VerticesOfTriangularEdge[j][1]]) << ") belongs to more than 2 triangles");
-			}
-		}
-	}
-
-	//Display info if required
-	if(verbose>5) {
-		_printf_("         info of Mesh:\n");
-		_printf_("            - number of vertices    = " << nbv << " \n"); 
-		_printf_("            - number of triangles   = " << nbt << " \n"); 
-		_printf_("            - number of given edges = " << nbe << " \n"); 
-		_printf_("            - number of all edges   = " << edge4->nb() << "\n"); 
-		_printf_("            - Euler number 1 - nb of holes = " << nbt-edge4->nb()+nbv << "\n"); 
-	}
-
-	//check the consistency of edge[].adj and the geometrical required vertex
-	long k=0;
-	for (i=0;i<edge4->nb();i++){
-		if (st[i]>=0){ // edge alone 
-			if (i<nbe){
-				long i0=edge4->i(i);
-				orderedvertices[i0] = vertices+i0;
-				long i1=edge4->j(i);
-				orderedvertices[i1] = vertices+i1;
-			}
-			else {
-				k=k+1;
-				if (k<10) {
-					//print only 10 edges
-					_printf_("Lost boundary edges " << i << " : " << edge4->i(i) << " " << edge4->j(i) << "\n");
-				}
-				else if (k==10){
-					_printf_("Other lost boundary edges not shown...\n");
-				}
-			}
-		}
-	}
-	if(k) {
-		_error_(k << " boundary edges (from the geometry) are not defined as mesh edges");
-	}
-
-	/* mesh generation with boundary points*/
-	long nbvb=0;
-	for (i=0;i<nbv;i++){ 
-		vertices[i].t=0;
-		vertices[i].IndexInTriangle=0;
-		if (orderedvertices[i]) orderedvertices[nbvb++]=orderedvertices[i];
-	}
-
-	Triangle* savetriangles=triangles;
-	long savenbt=nbt;
-	long savemaxnbt=maxnbt;
-	SubDomain* savesubdomains=subdomains;
-	subdomains=0;
-
-	long  Nbtriafillhole=2*nbvb;
-	Triangle* triafillhole=new Triangle[Nbtriafillhole];
-	triangles = triafillhole;
-
-	nbt=2;
-	maxnbt= Nbtriafillhole;
-
-	//Find a vertex that is not aligned with vertices 0 and 1
-	for (i=2;det(orderedvertices[0]->i,orderedvertices[1]->i,orderedvertices[i]->i)==0;) 
-	 if  (++i>=nbvb) {
-		 _error_("ReconstructExistingMesh: All the vertices are aligned");
-	 }
-	//Move this vertex (i) to the 2d position in orderedvertices
-	Exchange(orderedvertices[2], orderedvertices[i]);
-
-	/*Reconstruct mesh beginning with 2 triangles*/
-	BamgVertex *  v0=orderedvertices[0], *v1=orderedvertices[1];
-
-	triangles[0](0) = NULL; // Infinite vertex
-	triangles[0](1) = v0;
-	triangles[0](2) = v1;
-
-	triangles[1](0) = NULL;// Infinite vertex
-	triangles[1](2) = v0;
-	triangles[1](1) = v1;
-	const int e0 = OppositeEdge[0];
-	const int e1 = NextEdge[e0];
-	const int e2 = PreviousEdge[e0];
-	triangles[0].SetAdj2(e0, &triangles[1] ,e0);
-	triangles[0].SetAdj2(e1, &triangles[1] ,e2);
-	triangles[0].SetAdj2(e2, &triangles[1] ,e1);
-
-	triangles[0].det = -1;  // boundary triangles
-	triangles[1].det = -1;  // boundary triangles
-
-	triangles[0].SetSingleVertexToTriangleConnectivity();
-	triangles[1].SetSingleVertexToTriangleConnectivity();
-
-	triangles[0].link=&triangles[1];
-	triangles[1].link=&triangles[0];
-
-	if (!quadtree) delete quadtree; //ReInitialise;
-	quadtree = new BamgQuadtree(this,0);
-	quadtree->Add(*v0);
-	quadtree->Add(*v1);
-
-	// vertices are added one by one
-	long NbSwap=0;
-	for (int icount=2; icount<nbvb; icount++) {
-		BamgVertex *vi  = orderedvertices[icount];
-		Icoor2 det3[3];
-		Triangle *tcvi = TriangleFindFromCoord(vi->i,det3);
-		quadtree->Add(*vi); 
-		AddVertex(*vi,tcvi,det3);
-		NbSwap += vi->Optim(1,1);
-	}
-
-	//enforce the boundary 
-	AdjacentTriangle ta(0,0);
-	long nbloss = 0,knbe=0;
-	for ( i = 0; i < nbe; i++){
-		if (st[i] >=0){ //edge alone => on border
-			BamgVertex &a=edges[i][0], &b=edges[i][1];
-			if (a.t && b.t){
-				knbe++;
-				if (ForceEdge(a,b,ta)<0) nbloss++;
-			}
-		}
-	}
-	if(nbloss) {
-		_error_("we lost " << nbloss << " existing edges other " << knbe);
-	}
-
-	FindSubDomain(1);
-	// remove all the hole 
-	// remove all the good sub domain
-	long krm =0;
-	for (i=0;i<nbt;i++){
-		if (triangles[i].link){ // remove triangles
-			krm++;
+	void Mesh::ReconstructExistingMesh(){/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/FillHoleInMesh)*/
+
+		/*This routine reconstruct an existing mesh to make it CONVEX:
+		 * -all the holes are filled
+		 * -concave boundaries are filled
+		 * A convex mesh is required for a lot of operations. This is why every mesh
+		 * goes through this process.
+		 * This routine also generates mesh properties such as adjencies,...
+		 */
+
+		/*Intermediary*/
+		int verbose=0;
+
+		// generation of the integer coordinate
+
+		// find extrema coordinates of vertices pmin,pmax
+		long i;
+		if(verbose>2) _printf_("      Reconstruct mesh of " << nbv << " vertices\n"); 
+
+		//initialize orderedvertices
+		_assert_(orderedvertices);
+		for (i=0;i<nbv;i++) orderedvertices[i]=0;
+
+		//Initialize nbsubdomains
+		nbsubdomains =0;
+
+		/* generation of triangles adjacency*/
+
+		//First add existing edges
+		long kk =0;
+		SetOfEdges4* edge4= new SetOfEdges4(nbt*3,nbv);
+		for (i=0;i<nbe;i++){
+			kk=kk+(i==edge4->SortAndAdd(GetId(edges[i][0]),GetId(edges[i][1])));
+		}
+		if (kk != nbe){ 
+			_error_("There are " << kk-nbe << " double edges in the mesh");
+		}
+
+		//Add edges of all triangles in existing mesh
+		long* st = new long[nbt*3];
+		for (i=0;i<nbt*3;i++) st[i]=-1;
+		for (i=0;i<nbt;i++){
 			for (int j=0;j<3;j++){
-				AdjacentTriangle ta =  triangles[i].Adj(j);
-				Triangle &tta = *(Triangle*)ta;
-				//if edge between remove and not remove 
-				if(! tta.link){ 
-					// change the link of ta;
-					int ja = ta;
-					BamgVertex *v0= ta.EdgeVertex(0);
-					BamgVertex *v1= ta.EdgeVertex(1);
-					long k =edge4->SortAndAdd(v0?GetId(v0):nbv,v1? GetId(v1):nbv);
-
-					_assert_(st[k]>=0);
-					tta.SetAdj2(ja,savetriangles + st[k] / 3,(int) (st[k]%3));
-					ta.SetLock();
+
+				//Add current triangle edge to edge4
+				long k =edge4->SortAndAdd(GetId(triangles[i][VerticesOfTriangularEdge[j][0]]),GetId(triangles[i][VerticesOfTriangularEdge[j][1]]));
+
+				long invisible=triangles[i].Hidden(j);
+
+				//If the edge has not been added to st, add it
+				if(st[k]==-1) st[k]=3*i+j;
+
+				//If the edge already exists, add adjacency
+				else if(st[k]>=0) {
+					_assert_(!triangles[i].TriangleAdj(j));
+					_assert_(!triangles[st[k]/3].TriangleAdj((int) (st[k]%3)));
+
+					triangles[i].SetAdj2(j,triangles+st[k]/3,(int)(st[k]%3));
+					if (invisible) triangles[i].SetHidden(j);
+					if (k<nbe)     triangles[i].SetLocked(j);
+
+					//Make st[k] negative so that it will throw an error message if it is found again
 					st[k]=-2-st[k]; 
 				}
-			}
-		}
-	}
-	long NbTfillHoll =0;
-	for (i=0;i<nbt;i++){
-		if (triangles[i].link) {
-			triangles[i]=Triangle((BamgVertex *) NULL,(BamgVertex *) NULL,(BamgVertex *) NULL);
-			triangles[i].color=-1;
-		}
-		else{
-			triangles[i].color= savenbt+ NbTfillHoll++;
-		}
-	}
-	_assert_(savenbt+NbTfillHoll<=savemaxnbt);
-
-	// copy of the outside triangles in saveMesh 
-	for (i=0;i<nbt;i++){
-		if(triangles[i].color>=0) {
-			savetriangles[savenbt]=triangles[i];
-			savetriangles[savenbt].link=0;
-			savenbt++;
-		}
-	}
-	// gestion of the adj
-	k =0;
-	Triangle * tmax = triangles + nbt;
-	for (i=0;i<savenbt;i++) { 
-		Triangle & ti = savetriangles[i];
-		for (int j=0;j<3;j++){
-			Triangle * ta = ti.TriangleAdj(j);
-			int aa = ti.NuEdgeTriangleAdj(j);
-			int lck = ti.Locked(j);
-			if (!ta) k++; // bug 
-			else if ( ta >= triangles && ta < tmax){
-				ta= savetriangles + ta->color;
-				ti.SetAdj2(j,ta,aa);
-				if(lck) ti.SetLocked(j);
-			}
-		}
-	}
-
-	// restore triangles;
-	nbt=savenbt;
-	maxnbt=savemaxnbt;
-	delete [] triangles;
-	delete [] subdomains;
-	triangles = savetriangles;
-	subdomains = savesubdomains;
-	if (k) {
-		_error_("number of triangles edges alone = " << k);
-	}
-	FindSubDomain();
-
-	delete edge4;
-	delete [] st;
-	for (i=0;i<nbv;i++) quadtree->Add(vertices[i]);
-
-	SetVertexFieldOn();
-
-	/*Check requirements consistency*/
-	for (i=0;i<nbe;i++){
- 	/*If the current mesh edge is on Geometry*/
-		if(edges[i].GeomEdgeHook){
-			for(int j=0;j<2;j++){
-				/*Go through the edges adjacent to current edge (if on the same curve)*/
-				if (!edges[i].adj[j]){
-					/*The edge is on Geometry and does not have 2 adjacent edges... (not on a closed curve)*/
-					/*Check that the 2 vertices are on geometry AND required*/
-					if(!edges[i][j].GeomEdgeHook->IsRequiredVertex()){
-						_printf_("ReconstructExistingMesh error message: problem with the edge number " << i+1 << ": [" << GetId(edges[i][0])+1 << " " << GetId(edges[i][1])+1 << "]\n");
-						_printf_("This edge is on geometrical edge number " << Gh.GetId(edges[i].GeomEdgeHook)+1 << "\n");
-						if (edges[i][j].GeomEdgeHook->OnGeomVertex())
-						 _printf_("the vertex number " << GetId(edges[i][j])+1 << " of this edge is a geometric BamgVertex number " << Gh.GetId(edges[i][j].GeomEdgeHook->gv)+1 << "\n");
-						else if (edges[i][j].GeomEdgeHook->OnGeomEdge())
-						 _printf_("the vertex number " << GetId(edges[i][j])+1 << " of this edge is a geometric Edge number " << Gh.GetId(edges[i][j].GeomEdgeHook->ge)+1 << "\n");
-						else
-						 _printf_("Its pointer is " << edges[i][j].GeomEdgeHook << "\n");
-
-						_printf_("This edge is on geometry and has no adjacent edge (open curve) and one of the tip is not required\n");
-						_error_("See above (might be cryptic...)");
+
+				//An edge belongs to 2 triangles
+				else {
+					_error_("The edge (" << GetId(triangles[i][VerticesOfTriangularEdge[j][0]]) << " , " << GetId(triangles[i][VerticesOfTriangularEdge[j][1]]) << ") belongs to more than 2 triangles");
+				}
+			}
+		}
+
+		//Display info if required
+		if(verbose>5) {
+			_printf_("         info of Mesh:\n");
+			_printf_("            - number of vertices    = " << nbv << " \n"); 
+			_printf_("            - number of triangles   = " << nbt << " \n"); 
+			_printf_("            - number of given edges = " << nbe << " \n"); 
+			_printf_("            - number of all edges   = " << edge4->nb() << "\n"); 
+			_printf_("            - Euler number 1 - nb of holes = " << nbt-edge4->nb()+nbv << "\n"); 
+		}
+
+		//check the consistency of edge[].adj and the geometrical required vertex
+		long k=0;
+		for (i=0;i<edge4->nb();i++){
+			if (st[i]>=0){ // edge alone 
+				if (i<nbe){
+					long i0=edge4->i(i);
+					orderedvertices[i0] = vertices+i0;
+					long i1=edge4->j(i);
+					orderedvertices[i1] = vertices+i1;
+				}
+				else {
+					k=k+1;
+					if (k<10) {
+						//print only 10 edges
+						_printf_("Lost boundary edges " << i << " : " << edge4->i(i) << " " << edge4->j(i) << "\n");
 					}
-				}
-			}
-		}
-	}
-}
-/*}}}*/
-	/*FUNCTION Mesh::TrianglesRenumberBySubDomain{{{*/
-	void Mesh::TrianglesRenumberBySubDomain(bool justcompress){
+					else if (k==10){
+						_printf_("Other lost boundary edges not shown...\n");
+					}
+				}
+			}
+		}
+		if(k) {
+			_error_(k << " boundary edges (from the geometry) are not defined as mesh edges");
+		}
+
+		/* mesh generation with boundary points*/
+		long nbvb=0;
+		for (i=0;i<nbv;i++){ 
+			vertices[i].t=0;
+			vertices[i].IndexInTriangle=0;
+			if (orderedvertices[i]) orderedvertices[nbvb++]=orderedvertices[i];
+		}
+
+		Triangle* savetriangles=triangles;
+		long savenbt=nbt;
+		long savemaxnbt=maxnbt;
+		SubDomain* savesubdomains=subdomains;
+		subdomains=0;
+
+		long  Nbtriafillhole=2*nbvb;
+		Triangle* triafillhole=new Triangle[Nbtriafillhole];
+		triangles = triafillhole;
+
+		nbt=2;
+		maxnbt= Nbtriafillhole;
+
+		//Find a vertex that is not aligned with vertices 0 and 1
+		for (i=2;det(orderedvertices[0]->i,orderedvertices[1]->i,orderedvertices[i]->i)==0;) 
+		 if  (++i>=nbvb) {
+			 _error_("ReconstructExistingMesh: All the vertices are aligned");
+		 }
+		//Move this vertex (i) to the 2d position in orderedvertices
+		Exchange(orderedvertices[2], orderedvertices[i]);
+
+		/*Reconstruct mesh beginning with 2 triangles*/
+		BamgVertex *  v0=orderedvertices[0], *v1=orderedvertices[1];
+
+		triangles[0](0) = NULL; // Infinite vertex
+		triangles[0](1) = v0;
+		triangles[0](2) = v1;
+
+		triangles[1](0) = NULL;// Infinite vertex
+		triangles[1](2) = v0;
+		triangles[1](1) = v1;
+		const int e0 = OppositeEdge[0];
+		const int e1 = NextEdge[e0];
+		const int e2 = PreviousEdge[e0];
+		triangles[0].SetAdj2(e0, &triangles[1] ,e0);
+		triangles[0].SetAdj2(e1, &triangles[1] ,e2);
+		triangles[0].SetAdj2(e2, &triangles[1] ,e1);
+
+		triangles[0].det = -1;  // boundary triangles
+		triangles[1].det = -1;  // boundary triangles
+
+		triangles[0].SetSingleVertexToTriangleConnectivity();
+		triangles[1].SetSingleVertexToTriangleConnectivity();
+
+		triangles[0].link=&triangles[1];
+		triangles[1].link=&triangles[0];
+
+		if (!quadtree) delete quadtree; //ReInitialise;
+		quadtree = new BamgQuadtree(this,0);
+		quadtree->Add(*v0);
+		quadtree->Add(*v1);
+
+		// vertices are added one by one
+		long NbSwap=0;
+		for (int icount=2; icount<nbvb; icount++) {
+			BamgVertex *vi  = orderedvertices[icount];
+			Icoor2 det3[3];
+			Triangle *tcvi = TriangleFindFromCoord(vi->i,det3);
+			quadtree->Add(*vi); 
+			AddVertex(*vi,tcvi,det3);
+			NbSwap += vi->Optim(1,1);
+		}
+
+		//enforce the boundary 
+		AdjacentTriangle ta(0,0);
+		long nbloss = 0,knbe=0;
+		for ( i = 0; i < nbe; i++){
+			if (st[i] >=0){ //edge alone => on border
+				BamgVertex &a=edges[i][0], &b=edges[i][1];
+				if (a.t && b.t){
+					knbe++;
+					if (ForceEdge(a,b,ta)<0) nbloss++;
+				}
+			}
+		}
+		if(nbloss) {
+			_error_("we lost " << nbloss << " existing edges other " << knbe);
+		}
+
+		FindSubDomain(1);
+		// remove all the hole 
+		// remove all the good sub domain
+		long krm =0;
+		for (i=0;i<nbt;i++){
+			if (triangles[i].link){ // remove triangles
+				krm++;
+				for (int j=0;j<3;j++){
+					AdjacentTriangle ta =  triangles[i].Adj(j);
+					Triangle &tta = *(Triangle*)ta;
+					//if edge between remove and not remove 
+					if(! tta.link){ 
+						// change the link of ta;
+						int ja = ta;
+						BamgVertex *v0= ta.EdgeVertex(0);
+						BamgVertex *v1= ta.EdgeVertex(1);
+						long k =edge4->SortAndAdd(v0?GetId(v0):nbv,v1? GetId(v1):nbv);
+
+						_assert_(st[k]>=0);
+						tta.SetAdj2(ja,savetriangles + st[k] / 3,(int) (st[k]%3));
+						ta.SetLock();
+						st[k]=-2-st[k]; 
+					}
+				}
+			}
+		}
+		long NbTfillHoll =0;
+		for (i=0;i<nbt;i++){
+			if (triangles[i].link) {
+				triangles[i]=Triangle((BamgVertex *) NULL,(BamgVertex *) NULL,(BamgVertex *) NULL);
+				triangles[i].color=-1;
+			}
+			else{
+				triangles[i].color= savenbt+ NbTfillHoll++;
+			}
+		}
+		_assert_(savenbt+NbTfillHoll<=savemaxnbt);
+
+		// copy of the outside triangles in saveMesh 
+		for (i=0;i<nbt;i++){
+			if(triangles[i].color>=0) {
+				savetriangles[savenbt]=triangles[i];
+				savetriangles[savenbt].link=0;
+				savenbt++;
+			}
+		}
+		// gestion of the adj
+		k =0;
+		Triangle * tmax = triangles + nbt;
+		for (i=0;i<savenbt;i++) { 
+			Triangle & ti = savetriangles[i];
+			for (int j=0;j<3;j++){
+				Triangle * ta = ti.TriangleAdj(j);
+				int aa = ti.NuEdgeTriangleAdj(j);
+				int lck = ti.Locked(j);
+				if (!ta) k++; // bug 
+				else if ( ta >= triangles && ta < tmax){
+					ta= savetriangles + ta->color;
+					ti.SetAdj2(j,ta,aa);
+					if(lck) ti.SetLocked(j);
+				}
+			}
+		}
+
+		// restore triangles;
+		nbt=savenbt;
+		maxnbt=savemaxnbt;
+		delete [] triangles;
+		delete [] subdomains;
+		triangles = savetriangles;
+		subdomains = savesubdomains;
+		if (k) {
+			_error_("number of triangles edges alone = " << k);
+		}
+		FindSubDomain();
+
+		delete edge4;
+		delete [] st;
+		for (i=0;i<nbv;i++) quadtree->Add(vertices[i]);
+
+		SetVertexFieldOn();
+
+		/*Check requirements consistency*/
+		for (i=0;i<nbe;i++){
+			/*If the current mesh edge is on Geometry*/
+			if(edges[i].GeomEdgeHook){
+				for(int j=0;j<2;j++){
+					/*Go through the edges adjacent to current edge (if on the same curve)*/
+					if (!edges[i].adj[j]){
+						/*The edge is on Geometry and does not have 2 adjacent edges... (not on a closed curve)*/
+						/*Check that the 2 vertices are on geometry AND required*/
+						if(!edges[i][j].GeomEdgeHook->IsRequiredVertex()){
+							_printf_("ReconstructExistingMesh error message: problem with the edge number " << i+1 << ": [" << GetId(edges[i][0])+1 << " " << GetId(edges[i][1])+1 << "]\n");
+							_printf_("This edge is on geometrical edge number " << Gh.GetId(edges[i].GeomEdgeHook)+1 << "\n");
+							if (edges[i][j].GeomEdgeHook->OnGeomVertex())
+							 _printf_("the vertex number " << GetId(edges[i][j])+1 << " of this edge is a geometric BamgVertex number " << Gh.GetId(edges[i][j].GeomEdgeHook->gv)+1 << "\n");
+							else if (edges[i][j].GeomEdgeHook->OnGeomEdge())
+							 _printf_("the vertex number " << GetId(edges[i][j])+1 << " of this edge is a geometric Edge number " << Gh.GetId(edges[i][j].GeomEdgeHook->ge)+1 << "\n");
+							else
+							 _printf_("Its pointer is " << edges[i][j].GeomEdgeHook << "\n");
+
+							_printf_("This edge is on geometry and has no adjacent edge (open curve) and one of the tip is not required\n");
+							_error_("See above (might be cryptic...)");
+						}
+					}
+				}
+			}
+		}
+	}
+	/*}}}*/
+	void Mesh::TrianglesRenumberBySubDomain(bool justcompress){/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ReNumberingTheTriangleBySubDomain)*/
 
@@ -3785,437 +3739,426 @@
 	}
 	/*}}}*/
-/*FUNCTION Mesh::SetIntCoor{{{*/
-void Mesh::SetIntCoor(const char * strfrom) {
-	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/SetIntCoor)*/
-
-	/*Set integer coordinate for existing vertices*/
-
-	//Get extrema coordinates of the existing vertices
-	pmin =  vertices[0].r;
-	pmax =  vertices[0].r;
-	long i;
-	for (i=0;i<nbv;i++) {
-		pmin.x = Min(pmin.x,vertices[i].r.x);
-		pmin.y = Min(pmin.y,vertices[i].r.y);
-		pmax.x = Max(pmax.x,vertices[i].r.x);
-		pmax.y = Max(pmax.y,vertices[i].r.y);
-	}
-	R2 DD = (pmax-pmin)*0.05;
-	pmin = pmin-DD;
-	pmax = pmax+DD; 
-
-	//Compute coefIcoor
-	coefIcoor= (MaxICoor)/(Max(pmax.x-pmin.x,pmax.y-pmin.y));
-	if (coefIcoor<=0){
-		_error_("coefIcoor should be positive, a problem in the geometry is likely");
-	}
-
-	// generation of integer coord  
-	for (i=0;i<nbv;i++) {
-		vertices[i].i = R2ToI2(vertices[i].r);    
-	}
-
-	// computation of the det 
-	int number_of_errors=0;
-	for (i=0;i<nbt;i++) {
-		BamgVertex & v0 = triangles[i][0];
-		BamgVertex & v1 = triangles[i][1];
-		BamgVertex & v2 = triangles[i][2];
-
-		//If this is not a boundary triangle
-		if ( &v0 && &v1 &&  &v2 ){
-
-			/*Compute determinant*/
-			triangles[i].det= det(v0,v1,v2);
-
-			/*Check that determinant is positive*/
-			if (triangles[i].det <=0){
-
-				/*increase number_of_errors and print error only for the first 20 triangles*/
-				number_of_errors++;
-				if (number_of_errors<20){
-					_printf_("Area of Triangle " << i+1 << " < 0 (det=" << triangles[i].det << ")\n");
-				}
-			}
-		}
-
-		//else, set as -1
-		else triangles[i].det=-1;
-	}
-
-	if (number_of_errors) _error_("Fatal error: some triangles have negative areas, see above");
-}
-/*}}}*/
-/*FUNCTION Mesh::SmoothingVertex{{{*/
-void Mesh::SmoothingVertex(int nbiter,double omega ) { 
-	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/SmoothingVertex)*/
-
-	long int verbose=0;
-	//  if quatree exist remove it end reconstruct
-	if (quadtree) delete quadtree;
-	quadtree=0;
-	CreateSingleVertexToTriangleConnectivity();
-	Triangle vide; // a triangle to mark the boundary vertex
-	Triangle   ** tstart= new Triangle* [nbv];
-	long i,j,k;
-	//   attention si Background == Triangle alors on ne peut pas utiliser la rechech rapide 
-	if ( this == & BTh)
-	 for ( i=0;i<nbv;i++)
-	  tstart[i]=vertices[i].t;     
-	else 
-	 for ( i=0;i<nbv;i++)
-	  tstart[i]=0;
-	for ( j=0;j<NbVerticesOnGeomVertex;j++ ) 
-	 tstart[ GetId(VerticesOnGeomVertex[j].meshvertex)]=&vide;
-	for ( k=0;k<NbVerticesOnGeomEdge;k++ ) 
-	 tstart[ GetId(VerticesOnGeomEdge[k].meshvertex)]=&vide;
-	if(verbose>2) _printf_("   SmoothingVertex: nb Iteration = " << nbiter << ", Omega=" << omega << "\n");
-	for (k=0;k<nbiter;k++)
-	  {
-		long i,NbSwap =0;
-		double delta =0;
-		for ( i=0;i<nbv;i++)
-		 if (tstart[i] != &vide) // not a boundary vertex 
-		  delta=Max(delta,vertices[i].Smoothing(*this,BTh,tstart[i],omega));
-		if (!nbq)
+	void Mesh::SetIntCoor(const char * strfrom) {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/SetIntCoor)*/
+
+		/*Set integer coordinate for existing vertices*/
+
+		//Get extrema coordinates of the existing vertices
+		pmin =  vertices[0].r;
+		pmax =  vertices[0].r;
+		long i;
+		for (i=0;i<nbv;i++) {
+			pmin.x = Min(pmin.x,vertices[i].r.x);
+			pmin.y = Min(pmin.y,vertices[i].r.y);
+			pmax.x = Max(pmax.x,vertices[i].r.x);
+			pmax.y = Max(pmax.y,vertices[i].r.y);
+		}
+		R2 DD = (pmax-pmin)*0.05;
+		pmin = pmin-DD;
+		pmax = pmax+DD; 
+
+		//Compute coefIcoor
+		coefIcoor= (MaxICoor)/(Max(pmax.x-pmin.x,pmax.y-pmin.y));
+		if (coefIcoor<=0){
+			_error_("coefIcoor should be positive, a problem in the geometry is likely");
+		}
+
+		// generation of integer coord  
+		for (i=0;i<nbv;i++) {
+			vertices[i].i = R2ToI2(vertices[i].r);    
+		}
+
+		// computation of the det 
+		int number_of_errors=0;
+		for (i=0;i<nbt;i++) {
+			BamgVertex & v0 = triangles[i][0];
+			BamgVertex & v1 = triangles[i][1];
+			BamgVertex & v2 = triangles[i][2];
+
+			//If this is not a boundary triangle
+			if ( &v0 && &v1 &&  &v2 ){
+
+				/*Compute determinant*/
+				triangles[i].det= det(v0,v1,v2);
+
+				/*Check that determinant is positive*/
+				if (triangles[i].det <=0){
+
+					/*increase number_of_errors and print error only for the first 20 triangles*/
+					number_of_errors++;
+					if (number_of_errors<20){
+						_printf_("Area of Triangle " << i+1 << " < 0 (det=" << triangles[i].det << ")\n");
+					}
+				}
+			}
+
+			//else, set as -1
+			else triangles[i].det=-1;
+		}
+
+		if (number_of_errors) _error_("Fatal error: some triangles have negative areas, see above");
+	}
+	/*}}}*/
+	void Mesh::SmoothingVertex(int nbiter,double omega ) { /*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/SmoothingVertex)*/
+
+		long int verbose=0;
+		//  if quatree exist remove it end reconstruct
+		if (quadtree) delete quadtree;
+		quadtree=0;
+		CreateSingleVertexToTriangleConnectivity();
+		Triangle vide; // a triangle to mark the boundary vertex
+		Triangle   ** tstart= new Triangle* [nbv];
+		long i,j,k;
+		//   attention si Background == Triangle alors on ne peut pas utiliser la rechech rapide 
+		if ( this == & BTh)
 		 for ( i=0;i<nbv;i++)
-		  if (tstart[i] != &vide) // not a boundary vertex 
-			NbSwap += vertices[i].Optim(1);
-		if (verbose>3) _printf_("      move max = " << pow(delta,0.5) << ", iteration = " << k << ", nb of swap = " << NbSwap << "\n");
-	  }
-
-	delete [] tstart;
-	if (quadtree) quadtree= new BamgQuadtree(this);
-}
-/*}}}*/
-/*FUNCTION Mesh::SmoothMetric{{{*/
-void Mesh::SmoothMetric(double raisonmax) { 
-	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/SmoothMetric)*/
-
-	long int verbose=0;
-
-	if(raisonmax<1.1) return;
-	if(verbose > 1) _printf_("   Mesh::SmoothMetric raisonmax = " << raisonmax << "\n");
-	CreateSingleVertexToTriangleConnectivity();
-	long i,j,kch,kk,ip;
-	long *first_np_or_next_t0 = new long[nbv];
-	long *first_np_or_next_t1 = new long[nbv];
-	long Head0 =0,Head1=-1;
-	double logseuil= log(raisonmax);
-
-	for(i=0;i<nbv-1;i++)
-	 first_np_or_next_t0[i]=i+1; 
-	first_np_or_next_t0[nbv-1]=-1;// end;
-	for(i=0;i<nbv;i++)
-	 first_np_or_next_t1[i]=-1;
-	kk=0;
-	while(Head0>=0&& kk++<100){
-		kch=0;
-		for(i=Head0;i>=0;i=first_np_or_next_t0[ip=i],first_np_or_next_t0[ip]=-1) {
-			//  pour tous les triangles autour du sommet s
-			Triangle* t= vertices[i].t;
-			if (!t){
-				_error_("!t");
-			}
-			BamgVertex & vi = vertices[i];
-			AdjacentTriangle ta(t,EdgesVertexTriangle[vertices[i].IndexInTriangle][0]);
-			BamgVertex *pvj0 = ta.EdgeVertex(0);
-			while (1) {
-				ta=Previous(Adj(ta));
-				if (vertices+i != ta.EdgeVertex(1)){
-					_error_("vertices+i != ta.EdgeVertex(1)");
-				}
-				BamgVertex & vj = *(ta.EdgeVertex(0));
-				if ( &vj ) {
-					j= &vj-vertices;
-					if (j<0 || j >= nbv){
-						_error_("j<0 || j >= nbv");
+		  tstart[i]=vertices[i].t;     
+		else 
+		 for ( i=0;i<nbv;i++)
+		  tstart[i]=0;
+		for ( j=0;j<NbVerticesOnGeomVertex;j++ ) 
+		 tstart[ GetId(VerticesOnGeomVertex[j].meshvertex)]=&vide;
+		for ( k=0;k<NbVerticesOnGeomEdge;k++ ) 
+		 tstart[ GetId(VerticesOnGeomEdge[k].meshvertex)]=&vide;
+		if(verbose>2) _printf_("   SmoothingVertex: nb Iteration = " << nbiter << ", Omega=" << omega << "\n");
+		for (k=0;k<nbiter;k++)
+		  {
+			long i,NbSwap =0;
+			double delta =0;
+			for ( i=0;i<nbv;i++)
+			 if (tstart[i] != &vide) // not a boundary vertex 
+			  delta=Max(delta,vertices[i].Smoothing(*this,BTh,tstart[i],omega));
+			if (!nbq)
+			 for ( i=0;i<nbv;i++)
+			  if (tstart[i] != &vide) // not a boundary vertex 
+				NbSwap += vertices[i].Optim(1);
+			if (verbose>3) _printf_("      move max = " << pow(delta,0.5) << ", iteration = " << k << ", nb of swap = " << NbSwap << "\n");
+		  }
+
+		delete [] tstart;
+		if (quadtree) quadtree= new BamgQuadtree(this);
+	}
+	/*}}}*/
+	void Mesh::SmoothMetric(double raisonmax) { /*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/SmoothMetric)*/
+
+		long int verbose=0;
+
+		if(raisonmax<1.1) return;
+		if(verbose > 1) _printf_("   Mesh::SmoothMetric raisonmax = " << raisonmax << "\n");
+		CreateSingleVertexToTriangleConnectivity();
+		long i,j,kch,kk,ip;
+		long *first_np_or_next_t0 = new long[nbv];
+		long *first_np_or_next_t1 = new long[nbv];
+		long Head0 =0,Head1=-1;
+		double logseuil= log(raisonmax);
+
+		for(i=0;i<nbv-1;i++)
+		 first_np_or_next_t0[i]=i+1; 
+		first_np_or_next_t0[nbv-1]=-1;// end;
+		for(i=0;i<nbv;i++)
+		 first_np_or_next_t1[i]=-1;
+		kk=0;
+		while(Head0>=0&& kk++<100){
+			kch=0;
+			for(i=Head0;i>=0;i=first_np_or_next_t0[ip=i],first_np_or_next_t0[ip]=-1) {
+				//  pour tous les triangles autour du sommet s
+				Triangle* t= vertices[i].t;
+				if (!t){
+					_error_("!t");
+				}
+				BamgVertex & vi = vertices[i];
+				AdjacentTriangle ta(t,EdgesVertexTriangle[vertices[i].IndexInTriangle][0]);
+				BamgVertex *pvj0 = ta.EdgeVertex(0);
+				while (1) {
+					ta=Previous(Adj(ta));
+					if (vertices+i != ta.EdgeVertex(1)){
+						_error_("vertices+i != ta.EdgeVertex(1)");
 					}
-					R2 Aij = (R2) vj - (R2) vi;
-					double ll =  Norme2(Aij);
-					if (0) {  
-						double hi = ll/vi.m(Aij);
-						double hj = ll/vj.m(Aij);
-						if(hi < hj)
+					BamgVertex & vj = *(ta.EdgeVertex(0));
+					if ( &vj ) {
+						j= &vj-vertices;
+						if (j<0 || j >= nbv){
+							_error_("j<0 || j >= nbv");
+						}
+						R2 Aij = (R2) vj - (R2) vi;
+						double ll =  Norme2(Aij);
+						if (0) {  
+							double hi = ll/vi.m(Aij);
+							double hj = ll/vj.m(Aij);
+							if(hi < hj)
+							  {
+								double dh=(hj-hi)/ll;
+								if (dh>logseuil) {
+									vj.m.IntersectWith(vi.m/(1 +logseuil*ll/hi));
+									if(first_np_or_next_t1[j]<0)
+									 kch++,first_np_or_next_t1[j]=Head1,Head1=j;
+								}
+							  }
+						} 
+						else
 						  {
-							double dh=(hj-hi)/ll;
-							if (dh>logseuil) {
-								vj.m.IntersectWith(vi.m/(1 +logseuil*ll/hi));
-								if(first_np_or_next_t1[j]<0)
-								 kch++,first_np_or_next_t1[j]=Head1,Head1=j;
-							}
+							double li = vi.m(Aij);
+							if( vj.m.IntersectWith(vi.m/(1 +logseuil*li)) )
+							 if(first_np_or_next_t1[j]<0) // if the metrix change 
+							  kch++,first_np_or_next_t1[j]=Head1,Head1=j;
 						  }
-					} 
-					else
-					  {
-						double li = vi.m(Aij);
-						if( vj.m.IntersectWith(vi.m/(1 +logseuil*li)) )
-						 if(first_np_or_next_t1[j]<0) // if the metrix change 
-						  kch++,first_np_or_next_t1[j]=Head1,Head1=j;
+					}
+					if  ( &vj ==  pvj0 ) break;
+				}
+			}
+			Head0 = Head1;
+			Head1 = -1;
+			Exchange(first_np_or_next_t0,first_np_or_next_t1);
+		}
+		if(verbose>2) _printf_("      number of iterations = " << kch << "\n"); 
+		delete [] first_np_or_next_t0;
+		delete [] first_np_or_next_t1;
+	}
+	/*}}}*/
+	long  Mesh::SplitInternalEdgeWithBorderVertices(){/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/SplitInternalEdgeWithBorderVertices)*/
+
+		long NbSplitEdge=0;
+		SetVertexFieldOn();  
+		long it;
+		long nbvold=nbv;
+		long int verbose=2;
+		for (it=0;it<nbt;it++){
+			Triangle &t=triangles[it];
+			if (t.link)
+			 for (int j=0;j<3;j++)
+			  if(!t.Locked(j) && !t.Hidden(j)){
+				  Triangle &tt = *t.TriangleAdj(j);
+				  if ( &tt && tt.link && it < GetId(tt)) 
+					 { // an internal edge 
+					  BamgVertex &v0 = t[VerticesOfTriangularEdge[j][0]];
+					  BamgVertex &v1 = t[VerticesOfTriangularEdge[j][1]];
+					  if (v0.GeomEdgeHook && v1.GeomEdgeHook){
+						  R2 P= ((R2) v0 + (R2) v1)*0.5;
+						  if ( nbv<maxnbv) {
+							  vertices[nbv].r = P;
+							  vertices[nbv++].m = Metric(0.5,v0.m,0.5,v1.m);
+							  vertices[nbv].ReferenceNumber=0;
+							  vertices[nbv].DirOfSearch = NoDirOfSearch ;
+						  }
+						  NbSplitEdge++;
 					  }
-				}
-				if  ( &vj ==  pvj0 ) break;
-			}
-		}
-		Head0 = Head1;
-		Head1 = -1;
-		Exchange(first_np_or_next_t0,first_np_or_next_t1);
-	}
-	if(verbose>2) _printf_("      number of iterations = " << kch << "\n"); 
-	delete [] first_np_or_next_t0;
-	delete [] first_np_or_next_t1;
-}
-/*}}}*/
-/*FUNCTION Mesh::SplitInternalEdgeWithBorderVertices{{{*/
-long  Mesh::SplitInternalEdgeWithBorderVertices(){
-	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/SplitInternalEdgeWithBorderVertices)*/
-
-	long NbSplitEdge=0;
-	SetVertexFieldOn();  
-	long it;
-	long nbvold=nbv;
-	long int verbose=2;
-	for (it=0;it<nbt;it++){
-		Triangle &t=triangles[it];
-		if (t.link)
-		 for (int j=0;j<3;j++)
-		  if(!t.Locked(j) && !t.Hidden(j)){
-			  Triangle &tt = *t.TriangleAdj(j);
-			  if ( &tt && tt.link && it < GetId(tt)) 
-				 { // an internal edge 
-				  BamgVertex &v0 = t[VerticesOfTriangularEdge[j][0]];
-				  BamgVertex &v1 = t[VerticesOfTriangularEdge[j][1]];
-				  if (v0.GeomEdgeHook && v1.GeomEdgeHook){
-					  R2 P= ((R2) v0 + (R2) v1)*0.5;
-					  if ( nbv<maxnbv) {
-						  vertices[nbv].r = P;
-						  vertices[nbv++].m = Metric(0.5,v0.m,0.5,v1.m);
-						  vertices[nbv].ReferenceNumber=0;
-						  vertices[nbv].DirOfSearch = NoDirOfSearch ;
-					  }
-					  NbSplitEdge++;
-				  }
-				 }
-		  }
-	}
-	CreateSingleVertexToTriangleConnectivity();    
-	if (nbvold!=nbv){
-		long  iv = nbvold;
-		long NbSwap = 0;
-		Icoor2 det3[3];  
-		for (int i=nbvold;i<nbv;i++) {// for all the new point
-			BamgVertex & vi = vertices[i];
-			vi.i = R2ToI2(vi.r);
-			vi.r = I2ToR2(vi.i);
-
-			// a good new point 
-			vi.ReferenceNumber=0; 
-			vi.DirOfSearch =NoDirOfSearch;
-			Triangle *tcvi = TriangleFindFromCoord(vi.i,det3);
-			if (tcvi && !tcvi->link) {
-				_printf_("problem inserting point in SplitInternalEdgeWithBorderVertices (tcvj && !tcvj->link)\n");
-			}
-
-			quadtree->Add(vi);
-			if (!tcvi || tcvi->det<0){// internal
-				_error_("!tcvi || tcvi->det < 0");
-			}
-			AddVertex(vi,tcvi,det3);
-			NbSwap += vi.Optim(1);          
-			iv++;
-		}
-		if (verbose>3) {
-			_printf_("   number of points: " << iv << "\n");
-			_printf_("   number of swap to  split internal edges with border vertices: " << NbSwap << "\n");
-			nbv = iv;
-		}
-	}
-	if (NbSplitEdge>nbv-nbvold) _printf_("WARNING: not enough vertices  to split all internal edges, we lost " << NbSplitEdge - ( nbv-nbvold) << " edges...\n");
-	if (verbose>2) _printf_("SplitInternalEdgeWithBorderVertices: Number of splited edge " << NbSplitEdge << "\n");
-
-	return  NbSplitEdge;
-}
-/*}}}*/
-/*FUNCTION Mesh::ToI2{{{*/
-I2 Mesh::R2ToI2(const R2 & P) const {
-	return  I2( (Icoor1) (coefIcoor*(P.x-pmin.x)),(Icoor1) (coefIcoor*(P.y-pmin.y)) );
-}
-/*}}}*/
-/*FUNCTION Mesh::ToR2{{{*/
-R2 Mesh::I2ToR2(const I2 & P) const {
-	return  R2( (double) P.x/coefIcoor+pmin.x, (double) P.y/coefIcoor+pmin.y);
-}
-/*}}}*/
-/*FUNCTION Mesh::TriangleFindFromCoord{{{*/
-Triangle * Mesh::TriangleFindFromCoord(const I2 & B,Icoor2 det3[3], Triangle *tstart) const {
-	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/FindTriangleContening)*/
-
-	Triangle * t=0;	
-	int j,jp,jn,jj;
-	int counter;
-
-	/*Get starting triangle. Take tsart if provided*/
-	if (tstart) t=tstart;
-
-	/*Else find the closest Triangle using the quadtree*/
-	else {
-
-		/*Check that the quadtree does exist*/
-		if (!quadtree) _error_("no starting triangle provided and no quadtree available");
-
-		/*Call NearestVertex*/
-		BamgVertex *a = quadtree->NearestVertex(B.x,B.y) ;
-
-		/*Check output (Vertex a)*/
-		if (!a)    _error_("problem while trying to find nearest vertex from a given point. No output found");
-		if (!a->t) _error_("no triangle is associated to vertex number " << GetId(a)+1 << " (orphan?)");
-		_assert_(a>=vertices && a<vertices+nbv);
-
-		/*Get starting triangle*/
-		t = a->t;
-		_assert_(t>=triangles && t<triangles+nbt);
-	}
-
-	Icoor2  detop ;
-
-	/*initialize number of test triangle*/
-	counter=0; 
-
-	/*The initial triangle might be outside*/
-	while (t->det < 0){ 
-
-		/*Get a real vertex from this triangle (k0)*/
-		int k0=(*t)(0)?(((*t)(1)?((*t)(2)?-1:2):1)):0;
-		_assert_(k0>=0);// k0 the NULL vertex
-		int k1=NextVertex[k0],k2=PreviousVertex[k0];
-		det3[k0]=det(B,(*t)[k1],(*t)[k2]);
-		det3[k1]=det3[k2]=-1;     
-		if (det3[k0] > 0) // outside B 
-		 return t; 
-		t = t->TriangleAdj(OppositeEdge[k0]);
-		counter++;
-		_assert_(counter<2);
-	}
-
-	jj=0;
-	detop = det(*(*t)(VerticesOfTriangularEdge[jj][0]),*(*t)(VerticesOfTriangularEdge[jj][1]),B);
-
-	while(t->det>0){
-
-		/*Increase counter*/
-		if (++counter>=10000) _error_("Maximum number of iteration reached (threshold = " << counter << ").");
-
-		j= OppositeVertex[jj];
-		det3[j] = detop;  //det(*b,*s1,*s2);
-		jn = NextVertex[j];
-		jp = PreviousVertex[j];
-		det3[jp]= det(*(*t)(j),*(*t)(jn),B);
-		det3[jn] = t->det-det3[j] -det3[jp];
-
-		// count the number k of  det3 <0
-		int k=0,ii[3];
-		if (det3[0] < 0 ) ii[k++]=0; 
-		if (det3[1] < 0 ) ii[k++]=1;
-		if (det3[2] < 0 ) ii[k++]=2;
-		// 0 => ok
-		// 1 => go in way 1
-		// 2 => two way go in way 1 or 2 randomly
-
-		if (k==0) break;
-		if (k==2 && BinaryRand()) Exchange(ii[0],ii[1]);
-		_assert_(k<3);
-		AdjacentTriangle t1 = t->Adj(jj=ii[0]);
-		if ((t1.det() < 0 ) && (k == 2))
-		 t1 = t->Adj(jj=ii[1]);
-		t=t1;
-		j=t1;// for optimisation we now the -det[OppositeVertex[j]];
-		detop = -det3[OppositeVertex[jj]];
-		jj = j;
-	}
-
-	if (t->det<0) // outside triangle 
-	 det3[0]=det3[1]=det3[2]=-1,det3[OppositeVertex[jj]]=detop;
-	return t;
-}
-/*}}}*/
-/*FUNCTION Mesh::TriangleIntNumbering{{{*/
-void Mesh::TriangleIntNumbering(long* renumbering){
-
-	long num=0;
-	for (int i=0;i<nbt;i++){
-		if (triangles[i].det>0) renumbering[i]=num++;
-		else renumbering[i]=-1;
-	}
-	return;   
-}
-/*}}}*/
-/*FUNCTION Mesh::TriangleReferenceList{{{*/
-long  Mesh::TriangleReferenceList(long* reft) const {
-	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ConsRefTriangle)*/
-
-	Triangle *t0,*t;
-	long k=0, num;   
-
-	//initialize all triangles as -1 (outside)
-	for (int it=0;it<nbt;it++) reft[it]=-1;
-
-	//loop over all subdomains
-	for (int i=0;i<nbsubdomains;i++){ 
-
-		//first triangle of the subdomain i
-		t=t0=subdomains[i].head;
-
-		//check that the subdomain is not empty
-		if (!t0){ _error_("At least one subdomain is empty");}
-
-		//loop
-		do{
-			k++;
-
-			//get current triangle number
-			num = GetId(t);
-
-			//check that num is in [0 nbt[
-			_assert_(num>=0 && num<nbt);
-
-			//reft of this triangle is the subdomain number
-			reft[num]=i;
-
-		} while (t0 != (t=t->link));
-		//stop when all triangles of subdomains have been tagged
-
-	}
-	return k;   
-}
-/*}}}*/
-/*FUNCTION Mesh::Triangulate{{{*/
-void Mesh::Triangulate(double* x,double* y,int nods){
-
-	int verbose=0;
-	int i;
-	Metric M1(1);
-
-	/*Initialize mesh*/
-	Init(nods);//this resets nbv to 0
-	nbv=nods;
-
-	//Vertices
-	if(verbose) _printf_("Reading vertices (" << nbv << ")\n");
-	for(i=0;i<nbv;i++){
-		vertices[i].r.x=x[i];
-		vertices[i].r.y=y[i];
-		vertices[i].ReferenceNumber=1;
-		vertices[i].DirOfSearch =NoDirOfSearch;
-		vertices[i].m=M1;
-		vertices[i].color=0;
-	}
-	maxnbt=2*maxnbv-2; // for filling The Holes and quadrilaterals 
-
-	/*Insert Vertices*/
-	Insert(true);
-}
-/*}}}*/
-	/*FUNCTION Mesh::TriangulateFromGeom0{{{*/
-	void Mesh::TriangulateFromGeom0(BamgOpts* bamgopts){
+					 }
+			  }
+		}
+		CreateSingleVertexToTriangleConnectivity();    
+		if (nbvold!=nbv){
+			long  iv = nbvold;
+			long NbSwap = 0;
+			Icoor2 det3[3];  
+			for (int i=nbvold;i<nbv;i++) {// for all the new point
+				BamgVertex & vi = vertices[i];
+				vi.i = R2ToI2(vi.r);
+				vi.r = I2ToR2(vi.i);
+
+				// a good new point 
+				vi.ReferenceNumber=0; 
+				vi.DirOfSearch =NoDirOfSearch;
+				Triangle *tcvi = TriangleFindFromCoord(vi.i,det3);
+				if (tcvi && !tcvi->link) {
+					_printf_("problem inserting point in SplitInternalEdgeWithBorderVertices (tcvj && !tcvj->link)\n");
+				}
+
+				quadtree->Add(vi);
+				if (!tcvi || tcvi->det<0){// internal
+					_error_("!tcvi || tcvi->det < 0");
+				}
+				AddVertex(vi,tcvi,det3);
+				NbSwap += vi.Optim(1);          
+				iv++;
+			}
+			if (verbose>3) {
+				_printf_("   number of points: " << iv << "\n");
+				_printf_("   number of swap to  split internal edges with border vertices: " << NbSwap << "\n");
+				nbv = iv;
+			}
+		}
+		if (NbSplitEdge>nbv-nbvold) _printf_("WARNING: not enough vertices  to split all internal edges, we lost " << NbSplitEdge - ( nbv-nbvold) << " edges...\n");
+		if (verbose>2) _printf_("SplitInternalEdgeWithBorderVertices: Number of splited edge " << NbSplitEdge << "\n");
+
+		return  NbSplitEdge;
+	}
+	/*}}}*/
+	I2 Mesh::R2ToI2(const R2 & P) const {/*{{{*/
+		return  I2( (Icoor1) (coefIcoor*(P.x-pmin.x)),(Icoor1) (coefIcoor*(P.y-pmin.y)) );
+	}
+	/*}}}*/
+	R2 Mesh::I2ToR2(const I2 & P) const {/*{{{*/
+		return  R2( (double) P.x/coefIcoor+pmin.x, (double) P.y/coefIcoor+pmin.y);
+	}
+	/*}}}*/
+	Triangle * Mesh::TriangleFindFromCoord(const I2 & B,Icoor2 det3[3], Triangle *tstart) const {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/FindTriangleContening)*/
+
+		Triangle * t=0;	
+		int j,jp,jn,jj;
+		int counter;
+
+		/*Get starting triangle. Take tsart if provided*/
+		if (tstart) t=tstart;
+
+		/*Else find the closest Triangle using the quadtree*/
+		else {
+
+			/*Check that the quadtree does exist*/
+			if (!quadtree) _error_("no starting triangle provided and no quadtree available");
+
+			/*Call NearestVertex*/
+			BamgVertex *a = quadtree->NearestVertex(B.x,B.y) ;
+
+			/*Check output (Vertex a)*/
+			if (!a)    _error_("problem while trying to find nearest vertex from a given point. No output found");
+			if (!a->t) _error_("no triangle is associated to vertex number " << GetId(a)+1 << " (orphan?)");
+			_assert_(a>=vertices && a<vertices+nbv);
+
+			/*Get starting triangle*/
+			t = a->t;
+			_assert_(t>=triangles && t<triangles+nbt);
+		}
+
+		Icoor2  detop ;
+
+		/*initialize number of test triangle*/
+		counter=0; 
+
+		/*The initial triangle might be outside*/
+		while (t->det < 0){ 
+
+			/*Get a real vertex from this triangle (k0)*/
+			int k0=(*t)(0)?(((*t)(1)?((*t)(2)?-1:2):1)):0;
+			_assert_(k0>=0);// k0 the NULL vertex
+			int k1=NextVertex[k0],k2=PreviousVertex[k0];
+			det3[k0]=det(B,(*t)[k1],(*t)[k2]);
+			det3[k1]=det3[k2]=-1;     
+			if (det3[k0] > 0) // outside B 
+			 return t; 
+			t = t->TriangleAdj(OppositeEdge[k0]);
+			counter++;
+			_assert_(counter<2);
+		}
+
+		jj=0;
+		detop = det(*(*t)(VerticesOfTriangularEdge[jj][0]),*(*t)(VerticesOfTriangularEdge[jj][1]),B);
+
+		while(t->det>0){
+
+			/*Increase counter*/
+			if (++counter>=10000) _error_("Maximum number of iteration reached (threshold = " << counter << ").");
+
+			j= OppositeVertex[jj];
+			det3[j] = detop;  //det(*b,*s1,*s2);
+			jn = NextVertex[j];
+			jp = PreviousVertex[j];
+			det3[jp]= det(*(*t)(j),*(*t)(jn),B);
+			det3[jn] = t->det-det3[j] -det3[jp];
+
+			// count the number k of  det3 <0
+			int k=0,ii[3];
+			if (det3[0] < 0 ) ii[k++]=0; 
+			if (det3[1] < 0 ) ii[k++]=1;
+			if (det3[2] < 0 ) ii[k++]=2;
+			// 0 => ok
+			// 1 => go in way 1
+			// 2 => two way go in way 1 or 2 randomly
+
+			if (k==0) break;
+			if (k==2 && BinaryRand()) Exchange(ii[0],ii[1]);
+			_assert_(k<3);
+			AdjacentTriangle t1 = t->Adj(jj=ii[0]);
+			if ((t1.det() < 0 ) && (k == 2))
+			 t1 = t->Adj(jj=ii[1]);
+			t=t1;
+			j=t1;// for optimisation we now the -det[OppositeVertex[j]];
+			detop = -det3[OppositeVertex[jj]];
+			jj = j;
+		}
+
+		if (t->det<0) // outside triangle 
+		 det3[0]=det3[1]=det3[2]=-1,det3[OppositeVertex[jj]]=detop;
+		return t;
+	}
+	/*}}}*/
+	void Mesh::TriangleIntNumbering(long* renumbering){/*{{{*/
+
+		long num=0;
+		for (int i=0;i<nbt;i++){
+			if (triangles[i].det>0) renumbering[i]=num++;
+			else renumbering[i]=-1;
+		}
+		return;   
+	}
+	/*}}}*/
+	long  Mesh::TriangleReferenceList(long* reft) const {/*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ConsRefTriangle)*/
+
+		Triangle *t0,*t;
+		long k=0, num;   
+
+		//initialize all triangles as -1 (outside)
+		for (int it=0;it<nbt;it++) reft[it]=-1;
+
+		//loop over all subdomains
+		for (int i=0;i<nbsubdomains;i++){ 
+
+			//first triangle of the subdomain i
+			t=t0=subdomains[i].head;
+
+			//check that the subdomain is not empty
+			if (!t0){ _error_("At least one subdomain is empty");}
+
+			//loop
+			do{
+				k++;
+
+				//get current triangle number
+				num = GetId(t);
+
+				//check that num is in [0 nbt[
+				_assert_(num>=0 && num<nbt);
+
+				//reft of this triangle is the subdomain number
+				reft[num]=i;
+
+			} while (t0 != (t=t->link));
+			//stop when all triangles of subdomains have been tagged
+
+		}
+		return k;   
+	}
+	/*}}}*/
+	void Mesh::Triangulate(double* x,double* y,int nods){/*{{{*/
+
+		int verbose=0;
+		int i;
+		Metric M1(1);
+
+		/*Initialize mesh*/
+		Init(nods);//this resets nbv to 0
+		nbv=nods;
+
+		//Vertices
+		if(verbose) _printf_("Reading vertices (" << nbv << ")\n");
+		for(i=0;i<nbv;i++){
+			vertices[i].r.x=x[i];
+			vertices[i].r.y=y[i];
+			vertices[i].ReferenceNumber=1;
+			vertices[i].DirOfSearch =NoDirOfSearch;
+			vertices[i].m=M1;
+			vertices[i].color=0;
+		}
+		maxnbt=2*maxnbv-2; // for filling The Holes and quadrilaterals 
+
+		/*Insert Vertices*/
+		Insert(true);
+	}
+	/*}}}*/
+	void Mesh::TriangulateFromGeom0(BamgOpts* bamgopts){/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/GeomToTriangles0)*/
 		/*Generate mesh from geometry*/
@@ -4531,6 +4474,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Mesh::TriangulateFromGeom1{{{*/
-	void Mesh::TriangulateFromGeom1(BamgOpts* bamgopts,int KeepVertices){ 
+	void Mesh::TriangulateFromGeom1(BamgOpts* bamgopts,int KeepVertices){ /*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/GeomToTriangles1)*/
 
@@ -4566,9 +4508,9 @@
 
 		/* There are 2 ways to make the loop 
-		* 1) on the geometry 
-		* 2) on the background mesh
-		*  if you do the loop on geometry, we don't have the pointeur on background,
-		*  and if you do the loop in background we have the pointeur on geometry
-		* so do the walk on  background */
+		 * 1) on the geometry 
+		 * 2) on the background mesh
+		 *  if you do the loop on geometry, we don't have the pointeur on background,
+		 *  and if you do the loop in background we have the pointeur on geometry
+		 * so do the walk on  background */
 
 		NbVerticesOnGeomVertex=0;
@@ -4861,6 +4803,5 @@
 
 	/*Intermediary*/
-	/*FUNCTION CloseBoundaryEdge{{{*/
-	AdjacentTriangle CloseBoundaryEdge(I2 A,Triangle *t, double &a,double &b) {
+	AdjacentTriangle CloseBoundaryEdge(I2 A,Triangle *t, double &a,double &b) {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/CloseBoundaryEdge)*/
 
@@ -4898,130 +4839,127 @@
 							b= IJ_IA/IJ2;
 							return edge;
-		  } 
-	}
-	/*}}}*/
-/*FUNCTION ForceEdge{{{*/
-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; 
-}
-/*}}}*/
-/*FUNCTION swap{{{*/
-void  swap(Triangle *t1,short a1, Triangle *t2,short a2, BamgVertex *s1,BamgVertex *s2,Icoor2 det1,Icoor2 det2){ 
-	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/swap)*/
-	// --------------------------------------------------------------
-	// short a2=aa[a];// les 2 numero de l arete dans les 2 triangles
-	//                               
-	//               sb                     sb    
-	//             / | \                   /   \                      !
-	//         as1/  |  \                 /a2   \                     !
-	//           /   |   \               /    t2 \                    !
-	//       s1 /t1  | t2 \s2  -->   s1 /___as2___\s2                 !
-	//          \  a1|a2  /             \   as1   /  
-	//           \   |   /               \ t1    /   
-	//            \  |  / as2             \   a1/    
-	//             \ | /                   \   /     
-	//              sa                       sa   
-	//  -------------------------------------------------------------
-	int as1 = NextEdge[a1];
-	int as2 = NextEdge[a2];
-	int ap1 = PreviousEdge[a1];
-	int ap2 = PreviousEdge[a2];
-	(*t1)(VerticesOfTriangularEdge[a1][1]) = s2 ; // avant sb
-	(*t2)(VerticesOfTriangularEdge[a2][1]) = s1  ; // avant sa
-	// mise a jour des 2 adjacences externes 
-	AdjacentTriangle taas1 = t1->Adj(as1),
-						  taas2 = t2->Adj(as2),
-						  tas1(t1,as1), tas2(t2,as2),
-						  ta1(t1,a1),ta2(t2,a2);
-	// externe haut gauche
-	taas1.SetAdj2(ta2, taas1.GetAllFlag_UnSwap());
-	// externe bas droite
-	taas2.SetAdj2(ta1, taas2.GetAllFlag_UnSwap());
-	// remove the Mark  UnMarkSwap 
-	t1->SetUnMarkUnSwap(ap1);
-	t2->SetUnMarkUnSwap(ap2);
-	// interne 
-	tas1.SetAdj2(tas2);
-
-	t1->det = det1;
-	t2->det = det2;
-
-	t1->SetSingleVertexToTriangleConnectivity();
-	t2->SetSingleVertexToTriangleConnectivity();
-} // end swap 
-/*}}}*/
-	/*FUNCTION SwapForForcingEdge{{{*/
-	int SwapForForcingEdge(BamgVertex   *  & pva ,BamgVertex  * &   pvb ,AdjacentTriangle & tt1,Icoor2 & dets1, Icoor2 & detsa,Icoor2 & detsb, int & NbSwap) {
+		} 
+	}
+	/*}}}*/
+	int ForceEdge(BamgVertex &a, BamgVertex & b,AdjacentTriangle & taret)  { /*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ForceEdge)*/
+
+		int NbSwap =0;
+		if (!a.t || !b.t){ // the 2 vertex is in a mesh
+			_error_("!a.t || !b.t");
+		}
+		int k=0;
+		taret=AdjacentTriangle(0,0); // erreur 
+
+		AdjacentTriangle tta(a.t,EdgesVertexTriangle[a.IndexInTriangle][0]);
+		BamgVertex   *v1, *v2 = tta.EdgeVertex(0),*vbegin =v2;
+		// we turn around a in the  direct direction  
+
+		Icoor2 det2 = v2 ? det(*v2,a,b): -1 , det1;
+		if(v2) // normal case 
+		 det2 = det(*v2,a,b);
+		else { // no chance infini vertex try the next
+			tta= Previous(Adj(tta));
+			v2 = tta.EdgeVertex(0);
+			vbegin =v2;
+			if (!v2){
+				_error_("!v2");
+			}
+			det2 = det(*v2,a,b);
+		}
+
+		while (v2 != &b) {
+			AdjacentTriangle tc = Previous(Adj(tta));    
+			v1 = v2; 
+			v2 = tc.EdgeVertex(0);
+			det1 = det2;
+			det2 =  v2 ? det(*v2,a,b): det2; 
+
+			if((det1 < 0) && (det2 >0)) { 
+				// try to force the edge 
+				BamgVertex * va = &a, *vb = &b;
+				tc = Previous(tc);
+				if (!v1 || !v2){
+					_error_("!v1 || !v2");
+				}
+				Icoor2 detss = 0,l=0;
+				while ((SwapForForcingEdge(  va,  vb, tc, detss, det1,det2,NbSwap)))
+				 if(l++ > 10000000) {
+					 _error_("Loop in forcing Egde, nb de swap=" << NbSwap << ", nb of try swap (" << l << ") too big");
+				 }
+				BamgVertex *aa = tc.EdgeVertex(0), *bb = tc.EdgeVertex(1);
+				if (((aa == &a ) && (bb == &b)) ||((bb ==  &a ) && (aa == &b))){
+					tc.SetLock();
+					a.Optim(1,0);
+					b.Optim(1,0);
+					taret = tc;
+					return NbSwap;
+				}
+				else 
+				  {
+					taret = tc;
+					return -2; // error  boundary is crossing
+				  }
+			}
+			tta = tc;
+			k++;
+			if (k>=2000){
+				_error_("k>=2000");
+			}
+			if ( vbegin == v2 ) return -1;// error 
+		}
+
+		tta.SetLock();
+		taret=tta;
+		a.Optim(1,0);
+		b.Optim(1,0);
+		return NbSwap; 
+	}
+	/*}}}*/
+	void  swap(Triangle *t1,short a1, Triangle *t2,short a2, BamgVertex *s1,BamgVertex *s2,Icoor2 det1,Icoor2 det2){ /*{{{*/
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/swap)*/
+		// --------------------------------------------------------------
+		// short a2=aa[a];// les 2 numero de l arete dans les 2 triangles
+		//                               
+		//               sb                     sb    
+		//             / | \                   /   \                      !
+		//         as1/  |  \                 /a2   \                     !
+		//           /   |   \               /    t2 \                    !
+		//       s1 /t1  | t2 \s2  -->   s1 /___as2___\s2                 !
+		//          \  a1|a2  /             \   as1   /  
+		//           \   |   /               \ t1    /   
+		//            \  |  / as2             \   a1/    
+		//             \ | /                   \   /     
+		//              sa                       sa   
+		//  -------------------------------------------------------------
+		int as1 = NextEdge[a1];
+		int as2 = NextEdge[a2];
+		int ap1 = PreviousEdge[a1];
+		int ap2 = PreviousEdge[a2];
+		(*t1)(VerticesOfTriangularEdge[a1][1]) = s2 ; // avant sb
+		(*t2)(VerticesOfTriangularEdge[a2][1]) = s1  ; // avant sa
+		// mise a jour des 2 adjacences externes 
+		AdjacentTriangle taas1 = t1->Adj(as1),
+							  taas2 = t2->Adj(as2),
+							  tas1(t1,as1), tas2(t2,as2),
+							  ta1(t1,a1),ta2(t2,a2);
+		// externe haut gauche
+		taas1.SetAdj2(ta2, taas1.GetAllFlag_UnSwap());
+		// externe bas droite
+		taas2.SetAdj2(ta1, taas2.GetAllFlag_UnSwap());
+		// remove the Mark  UnMarkSwap 
+		t1->SetUnMarkUnSwap(ap1);
+		t2->SetUnMarkUnSwap(ap2);
+		// interne 
+		tas1.SetAdj2(tas2);
+
+		t1->det = det1;
+		t2->det = det2;
+
+		t1->SetSingleVertexToTriangleConnectivity();
+		t2->SetSingleVertexToTriangleConnectivity();
+	} // end swap 
+	/*}}}*/
+	int SwapForForcingEdge(BamgVertex   *  & pva ,BamgVertex  * &   pvb ,AdjacentTriangle & tt1,Icoor2 & dets1, Icoor2 & detsa,Icoor2 & detsb, int & NbSwap) {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/SwapForForcingEdge)*/
 		// l'arete ta coupe l'arete pva pvb
@@ -5092,16 +5030,16 @@
 
 			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;}
+				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;}
 			}
 
@@ -5110,4 +5048,3 @@
 	}
 	/*}}}*/
-
 }
Index: issm/trunk/src/c/bamg/Metric.cpp
===================================================================
--- issm/trunk/src/c/bamg/Metric.cpp	(revision 18081)
+++ issm/trunk/src/c/bamg/Metric.cpp	(revision 18301)
@@ -13,14 +13,11 @@
 
 	/*Constructor/Destructor*/
-	/*FUNCTION Metric::Metric(double a){{{*/
-	Metric::Metric(double a): a11(1/(a*a)),a21(0),a22(1/(a*a)){
+	Metric::Metric(double a): a11(1/(a*a)),a21(0),a22(1/(a*a)){/*{{{*/
 
 	}/*}}}*/
-	/*FUNCTION Metric::Metric(double a,double b,double c){{{*/
-	Metric::Metric(double a,double b,double c) :a11(a),a21(b),a22(c){
+	Metric::Metric(double a,double b,double c) :a11(a),a21(b),a22(c){/*{{{*/
 
 	}/*}}}*/
-	/*FUNCTION Metric::Metric(const double  a[3],const  Metric& m0, const  Metric& m1,const  Metric&  m2 ){{{*/ 
-	Metric::Metric(const double  a[3],const  Metric& m0, const  Metric& m1,const  Metric& m2 ){
+	Metric::Metric(const double  a[3],const  Metric& m0, const  Metric& m1,const  Metric& m2 ){/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/Metric)*/
 
@@ -42,6 +39,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Metric::Metric(double  a,const  Metric& ma, double  b,const  Metric& mb){{{*/
-	Metric::Metric(double  a,const  Metric& ma, double  b,const  Metric& mb) { 
+	Metric::Metric(double  a,const  Metric& ma, double  b,const  Metric& mb) { /*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/EigenMetric)*/
 
@@ -64,10 +60,8 @@
 
 	/*Methods*/
-	/*FUNCTION Metric::det{{{*/
-	double Metric::det() const {
+	double Metric::det() const {/*{{{*/
 		return a11*a22-a21*a21;
 	}  /*}}}*/
-	/*FUNCTION Metric::Echo {{{*/
-	void Metric::Echo(void){
+	void Metric::Echo(void){/*{{{*/
 
 		_printf_("Metric:\n");
@@ -77,6 +71,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Metric::IntersectWith{{{*/
-	int Metric::IntersectWith(const Metric& M2) {
+	int Metric::IntersectWith(const Metric& M2) {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/IntersectWith)*/
 
@@ -130,12 +123,10 @@
 	}
 	/*}}}*/
-	/*FUNCTION Metric::mul{{{*/
-	R2     Metric::mul(const R2 x)const {
+	R2     Metric::mul(const R2 x)const {/*{{{*/
 		return R2(a11*x.x+a21*x.y,a21*x.x+a22*x.y);
 	}/*}}}*/
 
 	/*Intermediary*/
-	/*FUNCTION LengthInterpole{{{*/
-	double LengthInterpole(const Metric& Ma,const  Metric& Mb, R2 AB) {
+	double LengthInterpole(const Metric& Ma,const  Metric& Mb, R2 AB) {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/LengthInterpole)*/
 
@@ -204,6 +195,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION SimultaneousMatrixReduction{{{*/
-	void SimultaneousMatrixReduction( Metric M1,  Metric M2, D2xD2 &V) {
+	void SimultaneousMatrixReduction( Metric M1,  Metric M2, D2xD2 &V) {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/ReductionSimultanee)*/
 
@@ -307,6 +297,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION abscisseInterpole{{{*/
-	double abscisseInterpole(const Metric& Ma,const  Metric& Mb, R2 AB,double s,int optim) { 
+	double abscisseInterpole(const Metric& Ma,const  Metric& Mb, R2 AB,double s,int optim) { /*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/abscisseInterpole)*/
 
Index: issm/trunk/src/c/bamg/SetOfE4.cpp
===================================================================
--- issm/trunk/src/c/bamg/SetOfE4.cpp	(revision 18081)
+++ issm/trunk/src/c/bamg/SetOfE4.cpp	(revision 18301)
@@ -5,6 +5,5 @@
 
 	/*Constructor*/
-	/*FUNCTION  SetOfEdges4::SetOfEdges4(long mmx,long nnx){{{*/
-	SetOfEdges4::SetOfEdges4(long mmx,long nnx){
+	SetOfEdges4::SetOfEdges4(long mmx,long nnx){/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, SetOfEdges4.cpp/SetOfEdges4)*/
 
@@ -26,6 +25,5 @@
 
 	/*Methods*/ 
-	/*FUNCTION  SetOfEdges4::add{{{*/
-	long SetOfEdges4::add(long ii,long jj) {
+	long SetOfEdges4::add(long ii,long jj) {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, SetOfEdges4.cpp/add)*/
 
@@ -61,6 +59,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION  SetOfEdges4::find {{{*/
-	long SetOfEdges4::find(long ii,long jj) { 
+	long SetOfEdges4::find(long ii,long jj) { /*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, SetOfEdges4.cpp/find)*/
 
@@ -88,26 +85,21 @@
 	}
 	/*}}}*/
-	/*FUNCTION  SetOfEdges4::i{{{*/
-	long SetOfEdges4::i(long k){
+	long SetOfEdges4::i(long k){/*{{{*/
 		return Edges[k].i;
 	}
 	/*}}}*/
-	/*FUNCTION  SetOfEdges4::j{{{*/
-	long SetOfEdges4::j(long k){
+	long SetOfEdges4::j(long k){/*{{{*/
 		return Edges[k].j;
 	}
 	/*}}}*/
-	/*FUNCTION  SetOfEdges4::nb{{{*/
-	long SetOfEdges4::nb(){
+	long SetOfEdges4::nb(){/*{{{*/
 		return NbOfEdges;
 	}
 	/*}}}*/
-	/*FUNCTION  SetOfEdges4::SortAndAdd{{{*/
-	long SetOfEdges4::SortAndAdd (long ii,long jj) {
+	long SetOfEdges4::SortAndAdd (long ii,long jj) {/*{{{*/
 		return ii <=jj ? add (ii,jj)  : add (jj,ii) ;
 	}
 	/*}}}*/
-	/*FUNCTION  SetOfEdges4::SortAndFind{{{*/
-	long SetOfEdges4::SortAndFind (long ii,long jj) {
+	long SetOfEdges4::SortAndFind (long ii,long jj) {/*{{{*/
 		return ii <=jj ? find (ii,jj)  : find (jj,ii) ;
 	}
Index: issm/trunk/src/c/bamg/SubDomain.cpp
===================================================================
--- issm/trunk/src/c/bamg/SubDomain.cpp	(revision 18081)
+++ issm/trunk/src/c/bamg/SubDomain.cpp	(revision 18301)
@@ -12,6 +12,5 @@
 
 	/*Methods*/
-	/*FUNCTION SubDomain::Set {{{*/
-	void SubDomain::Set(const Mesh & Th ,long i,Mesh & ThNew){
+	void SubDomain::Set(const Mesh & Th ,long i,Mesh & ThNew){/*{{{*/
 		*this = Th.subdomains[i];
 		if( head-Th.triangles<0 || head-Th.triangles>=Th.nbt){
Index: issm/trunk/src/c/bamg/Triangle.cpp
===================================================================
--- issm/trunk/src/c/bamg/Triangle.cpp	(revision 18081)
+++ issm/trunk/src/c/bamg/Triangle.cpp	(revision 18301)
@@ -11,11 +11,9 @@
 
 	/*Constructors/Destructors*/
-	/*FUNCTION Triangle(){{{*/
-	Triangle::Triangle(void){
-
-	}
-	/*}}}*/
-	/*FUNCTION Triangle(Mesh *Th,long i,long j,long k) {{{*/
-	Triangle::Triangle(Mesh *Th,long i,long j,long k) {
+	Triangle::Triangle(void){/*{{{*/
+
+	}
+	/*}}}*/
+	Triangle::Triangle(Mesh *Th,long i,long j,long k) {/*{{{*/
 		BamgVertex *v=Th->vertices;
 		long nbv = Th->nbv;
@@ -34,6 +32,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Triangle(BamgVertex *v0,BamgVertex *v1,BamgVertex *v2) {{{*/
-	Triangle::Triangle(BamgVertex *v0,BamgVertex *v1,BamgVertex *v2){
+	Triangle::Triangle(BamgVertex *v0,BamgVertex *v1,BamgVertex *v2){/*{{{*/
 		vertices[0]=v0;
 		vertices[1]=v1;
@@ -49,10 +46,8 @@
 
 	/*Methods*/
-	/*FUNCTION Triangle::Adj{{{*/
-	AdjacentTriangle Triangle::Adj(int i)  const {
+	AdjacentTriangle Triangle::Adj(int i)  const {/*{{{*/
 		return AdjacentTriangle(adj[i],AdjEdgeIndex[i]&3);
 	};/*}}}*/
-	/*FUNCTION Triangle::Length{{{*/
-	double Triangle::Length() const{
+	double Triangle::Length() const{/*{{{*/
 
 		double l;
@@ -75,6 +70,5 @@
 		return l;
 	};/*}}}*/
-	/*FUNCTION Triangle::Echo {{{*/
-	void Triangle::Echo(void){
+	void Triangle::Echo(void){/*{{{*/
 
 		int i;
@@ -106,23 +100,18 @@
 	}
 	/*}}}*/
-	/*FUNCTION Triangle::GetAllflag{{{*/
-	int    Triangle::GetAllflag(int a){
+	int    Triangle::GetAllflag(int a){/*{{{*/
 		return AdjEdgeIndex[a] & 1020;
 	}/*}}}*/
-	/*FUNCTION Triangle::Hidden{{{*/
-	int    Triangle::Hidden(int a)const {
+	int    Triangle::Hidden(int a)const {/*{{{*/
 		return AdjEdgeIndex[a]&16;
 	} /*}}}*/
-	/*FUNCTION Triangle::Locked{{{*/
-	int    Triangle::Locked(int a)const {
+	int    Triangle::Locked(int a)const {/*{{{*/
 		return AdjEdgeIndex[a]&4;
 	} /*}}}*/
-	/*FUNCTION Triangle::NuEdgeTriangleAdj{{{*/
-	short  Triangle::NuEdgeTriangleAdj(int i) const {
+	short  Triangle::NuEdgeTriangleAdj(int i) const {/*{{{*/
 		/*Number of the  adjacent edge in adj tria (make sure it is between 0 and 2*/
 		return AdjEdgeIndex[i&3]&3;
 	}/*}}}*/
-	/*FUNCTION Triangle::Optim{{{*/
-	long  Triangle::Optim(short i,int koption) {
+	long  Triangle::Optim(short i,int koption) {/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Optim)*/
 
@@ -156,6 +145,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Triangle::Quadrangle {{{*/
-	Triangle* Triangle::Quadrangle(BamgVertex * & v0,BamgVertex * & v1,BamgVertex * & v2,BamgVertex * & v3) const{
+	Triangle* Triangle::Quadrangle(BamgVertex * & v0,BamgVertex * & v1,BamgVertex * & v2,BamgVertex * & v3) const{/*{{{*/
 		// return the other triangle of the quad if a quad or 0 if not a quat
 		Triangle * t =0;
@@ -177,6 +165,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Triangle::QualityQuad {{{*/
-	double   Triangle::QualityQuad(int a,int option) const{
+	double   Triangle::QualityQuad(int a,int option) const{/*{{{*/
 		double q;
 		if (!link || AdjEdgeIndex[a] &4)
@@ -200,6 +187,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Triangle::Renumbering(Triangle *tb,Triangle *te, long *renu){{{*/
-	void  Triangle::Renumbering(Triangle *tb,Triangle *te, long *renu){
+	void  Triangle::Renumbering(Triangle *tb,Triangle *te, long *renu){/*{{{*/
 
 		if (link  >=tb && link  <te) link  = tb + renu[link -tb];
@@ -208,12 +194,10 @@
 		if (adj[2] >=tb && adj[2] <te) adj[2] = tb + renu[adj[2]-tb];    
 	}/*}}}*/
-	/*FUNCTION Triangle::Renumbering(BamgVertex *vb,BamgVertex *ve, long *renu){{{*/
-	void Triangle::Renumbering(BamgVertex *vb,BamgVertex *ve, long *renu){
+	void Triangle::Renumbering(BamgVertex *vb,BamgVertex *ve, long *renu){/*{{{*/
 		if (vertices[0] >=vb && vertices[0] <ve) vertices[0] = vb + renu[vertices[0]-vb];
 		if (vertices[1] >=vb && vertices[1] <ve) vertices[1] = vb + renu[vertices[1]-vb];
 		if (vertices[2] >=vb && vertices[2] <ve) vertices[2] = vb + renu[vertices[2]-vb];    
 	}/*}}}*/
-	/*FUNCTION Triangle::Set {{{*/
-	void Triangle::Set(const Triangle & rec,const Mesh & Th ,Mesh & ThNew){ 
+	void Triangle::Set(const Triangle & rec,const Mesh & Th ,Mesh & ThNew){ /*{{{*/
 		*this = rec;
 		if ( vertices[0] ) vertices[0] = ThNew.vertices +  Th.GetId(vertices[0]);
@@ -227,6 +211,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Triangle::SetAdjAdj{{{*/
-	void Triangle::SetAdjAdj(short a){
+	void Triangle::SetAdjAdj(short a){/*{{{*/
 		// Copy all the mark 
 		a &= 3;
@@ -239,6 +222,5 @@
 		}
 	}/*}}}*/
-	/*FUNCTION Triangle::SetAdj2{{{*/
-	void Triangle::SetAdj2(short a,Triangle *t,short aat){
+	void Triangle::SetAdj2(short a,Triangle *t,short aat){/*{{{*/
 		/*For current triangle:
 		 * - a is the index of the edge were the adjency is set (in [0 2])
@@ -252,6 +234,5 @@
 		}
 	}/*}}}*/
-	/*FUNCTION Triangle::SetHidden{{{*/
-	void Triangle::SetHidden(int a){
+	void Triangle::SetHidden(int a){/*{{{*/
 		//Get Adjacent Triangle number a
 		Triangle* t = adj[a];
@@ -261,6 +242,5 @@
 		AdjEdgeIndex[a] |= 16;
 	}/*}}}*/
-	/*FUNCTION Triangle::SetLocked{{{*/
-	void Triangle::SetLocked(int a){
+	void Triangle::SetLocked(int a){/*{{{*/
 		//mark the edge as on Boundary
 		Triangle * t = adj[a];
@@ -268,24 +248,20 @@
 		AdjEdgeIndex[a] |= 4;
 	}/*}}}*/
-	/*FUNCTION Triangle::SetMarkUnSwap{{{*/
-	void Triangle::SetMarkUnSwap(int a){
+	void Triangle::SetMarkUnSwap(int a){/*{{{*/
 		Triangle * t = adj[a];
 		t->AdjEdgeIndex[AdjEdgeIndex[a] & 3] |=8;
 		AdjEdgeIndex[a] |=8 ;
 	}/*}}}*/
-	/*FUNCTION Triangle::SetSingleVertexToTriangleConnectivity{{{*/
-	void Triangle::SetSingleVertexToTriangleConnectivity() { 
+	void Triangle::SetSingleVertexToTriangleConnectivity() { /*{{{*/
 		if (vertices[0]) (vertices[0]->t=this,vertices[0]->IndexInTriangle=0);
 		if (vertices[1]) (vertices[1]->t=this,vertices[1]->IndexInTriangle=1);
 		if (vertices[2]) (vertices[2]->t=this,vertices[2]->IndexInTriangle=2);
 	}/*}}}*/
-	/*FUNCTION Triangle::SetUnMarkUnSwap{{{*/
-	void Triangle::SetUnMarkUnSwap(int a){ 
+	void Triangle::SetUnMarkUnSwap(int a){ /*{{{*/
 		Triangle * t = adj[a];
 		t->AdjEdgeIndex[AdjEdgeIndex[a] & 3] &=55; // 23 + 32 
 		AdjEdgeIndex[a] &=55 ;
 	}/*}}}*/
-	/*FUNCTION Triangle::swap{{{*/
-	int Triangle::swap(short a,int koption){
+	int Triangle::swap(short a,int koption){/*{{{*/
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/swap)*/
 
@@ -400,6 +376,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION Triangle::TriangleAdj{{{*/
-	Triangle* Triangle::TriangleAdj(int i) const {
+	Triangle* Triangle::TriangleAdj(int i) const {/*{{{*/
 		return adj[i&3];
 	}/*}}}*/
Index: issm/trunk/src/c/bamg/VertexOnEdge.cpp
===================================================================
--- issm/trunk/src/c/bamg/VertexOnEdge.cpp	(revision 18081)
+++ issm/trunk/src/c/bamg/VertexOnEdge.cpp	(revision 18301)
@@ -10,12 +10,10 @@
 
 	/*Methods*/
-	/*FUNCTION VertexOnEdge::Set {{{*/
-	void VertexOnEdge::Set(const Mesh & Th ,long i,Mesh & ThNew){
+	void VertexOnEdge::Set(const Mesh & Th ,long i,Mesh & ThNew){/*{{{*/
 		*this = Th.VertexOnBThEdge[i];  
 		v = ThNew.vertices + Th.GetId(v);
 	}
 	/*}}}*/
-	/*FUNCTION VertexOnEdge::SetOnBTh{{{*/
-	void VertexOnEdge::SetOnBTh(){
+	void VertexOnEdge::SetOnBTh(){/*{{{*/
 		v->BackgroundEdgeHook=this;
 		v->IndexInTriangle=IsVertexOnEdge;  
Index: issm/trunk/src/c/bamg/VertexOnGeom.cpp
===================================================================
--- issm/trunk/src/c/bamg/VertexOnGeom.cpp	(revision 18081)
+++ issm/trunk/src/c/bamg/VertexOnGeom.cpp	(revision 18301)
@@ -11,6 +11,5 @@
 
 	/*Constructors/Destructors*/
-	/*FUNCTION VertexOnGeom::VertexOnGeom(){{{*/
-	VertexOnGeom::VertexOnGeom(){
+	VertexOnGeom::VertexOnGeom(){/*{{{*/
 		meshvertex=NULL;
 		curvilincoord=0;
@@ -18,6 +17,5 @@
 	} 
 	/*}}}*/
-	/*FUNCTION VertexOnGeom::VertexOnGeom(BamgVertex & m,GeomVertex &g){{{*/
-	VertexOnGeom::VertexOnGeom(BamgVertex & m,GeomVertex &g){
+	VertexOnGeom::VertexOnGeom(BamgVertex & m,GeomVertex &g){/*{{{*/
 		meshvertex=&m;
 		curvilincoord=-1;
@@ -25,6 +23,5 @@
 	}
 	/*}}}*/
-	/*FUNCTION VertexOnGeom::VertexOnGeom(BamgVertex & m,GeomEdge &g,double s){{{*/
-	VertexOnGeom::VertexOnGeom(BamgVertex & m,GeomEdge &g,double s){
+	VertexOnGeom::VertexOnGeom(BamgVertex & m,GeomEdge &g,double s){/*{{{*/
 		meshvertex=&m;
 		curvilincoord=s;
@@ -34,6 +31,5 @@
 
 	/*Methods*/
-	/*FUNCTION VertexOnGeom::Set {{{*/
-	void VertexOnGeom::Set(const VertexOnGeom & rec,const Mesh & Th ,Mesh & ThNew){
+	void VertexOnGeom::Set(const VertexOnGeom & rec,const Mesh & Th ,Mesh & ThNew){/*{{{*/
 		*this = rec;  
 		meshvertex = ThNew.vertices + Th.GetId(meshvertex);
@@ -47,21 +43,17 @@
 	}
 	/*}}}*/
-	/*FUNCTION VertexOnGeom::OnGeomVertex{{{*/
-	int VertexOnGeom::OnGeomVertex()const{
+	int VertexOnGeom::OnGeomVertex()const{/*{{{*/
 		return this? curvilincoord <0 :0;
 	}
 	/*}}}*/
-	/*FUNCTION VertexOnGeom::OnGeomEdge{{{*/
-	int VertexOnGeom::OnGeomEdge() const{
+	int VertexOnGeom::OnGeomEdge() const{/*{{{*/
 		return this? curvilincoord >=0 :0;
 	}
 	/*}}}*/
-	/*FUNCTION VertexOnGeom::IsRequiredVertex{{{*/
-	int VertexOnGeom::IsRequiredVertex() {
+	int VertexOnGeom::IsRequiredVertex() {/*{{{*/
 		return this? ((curvilincoord<0 ? (gv?gv->Required():0):0 )) : 0;
 	}
 	/*}}}*/
-	/*FUNCTION VertexOnGeom::SetOn{{{*/
-	void VertexOnGeom::SetOn(){
+	void VertexOnGeom::SetOn(){/*{{{*/
 		meshvertex->GeomEdgeHook=this;
 		meshvertex->IndexInTriangle=IsVertexOnGeom;
Index: issm/trunk/src/c/bamg/VertexOnVertex.cpp
===================================================================
--- issm/trunk/src/c/bamg/VertexOnVertex.cpp	(revision 18081)
+++ issm/trunk/src/c/bamg/VertexOnVertex.cpp	(revision 18301)
@@ -10,23 +10,19 @@
 
 	/*Constructors/Destructors*/
-	/*FUNCTION VertexOnVertex::VertexOnVertex(){{{*/
-	VertexOnVertex::VertexOnVertex() {
+	VertexOnVertex::VertexOnVertex() {/*{{{*/
 		v=NULL;
 		bv=NULL;
 	};/*}}}*/
-	/*FUNCTION VertexOnVertex::VertexOnVertex(BamgVertex * w,BamgVertex *bw){{{*/
-	VertexOnVertex::VertexOnVertex(BamgVertex * w,BamgVertex *bw) :v(w),bv(bw){
+	VertexOnVertex::VertexOnVertex(BamgVertex * w,BamgVertex *bw) :v(w),bv(bw){/*{{{*/
 
 	}/*}}}*/
 
 	/*Methods*/
-	/*FUNCTION VertexOnVertex::Set{{{*/
-	void VertexOnVertex::Set(const Mesh &Th ,long i,Mesh &ThNew) { 
+	void VertexOnVertex::Set(const Mesh &Th ,long i,Mesh &ThNew) { /*{{{*/
 		*this = Th.VertexOnBThVertex[i];  
 		v     = ThNew.vertices + Th.GetId(v);
 	}
 	/*}}}*/
-	/*FUNCTION VertexOnVertex::SetOnBTh{{{*/
-	void VertexOnVertex::SetOnBTh(){
+	void VertexOnVertex::SetOnBTh(){/*{{{*/
 		v->BackgroundVertexHook=bv;v->IndexInTriangle=IsVertexOnVertex;
 	}/*}}}*/
Index: issm/trunk/src/c/classes/Constraints/Constraints.cpp
===================================================================
--- issm/trunk/src/c/classes/Constraints/Constraints.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Constraints/Constraints.cpp	(revision 18301)
@@ -19,6 +19,5 @@
 
 /*Numerics: */
-/*FUNCTION Constraints::NumberOfConstraints{{{*/
-int Constraints::NumberOfConstraints(void){
+int Constraints::NumberOfConstraints(void){/*{{{*/
 
 	int localconstraints;
Index: issm/trunk/src/c/classes/Constraints/Constraints.h
===================================================================
--- issm/trunk/src/c/classes/Constraints/Constraints.h	(revision 18081)
+++ issm/trunk/src/c/classes/Constraints/Constraints.h	(revision 18301)
@@ -16,12 +16,10 @@
 
 		/*Object constructors and destructor*/
-		/*FUNCTION Constraints::Constraints(){{{*/
-		Constraints(){
+		Constraints(){/*{{{*/
 			enum_type=ConstraintsEnum;
 			return;
 		}
 		/*}}}*/
-		/*FUNCTION Constraints::~Constraints(){{{*/
-		~Constraints(){
+		~Constraints(){/*{{{*/
 			return;
 		}
Index: issm/trunk/src/c/classes/Constraints/SpcDynamic.cpp
===================================================================
--- issm/trunk/src/c/classes/Constraints/SpcDynamic.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Constraints/SpcDynamic.cpp	(revision 18301)
@@ -14,11 +14,9 @@
 
 /*SpcDynamic constructors and destructor*/
-/*FUNCTION SpcDynamic::SpcDynamic(){{{*/
-SpcDynamic::SpcDynamic(){
+SpcDynamic::SpcDynamic(){/*{{{*/
 	return;
 }
 /*}}}*/
-/*FUNCTION SpcDynamic::SpcDynamic(int spc_sid,int spc_nodeid,...){{{*/
-SpcDynamic::SpcDynamic(int spc_sid,int spc_nodeid, int spc_dof,int spc_analysis_type){
+SpcDynamic::SpcDynamic(int spc_sid,int spc_nodeid, int spc_dof,int spc_analysis_type){/*{{{*/
 
 	sid=spc_sid;
@@ -32,6 +30,5 @@
 }
 /*}}}*/
-/*FUNCTION SpcDynamic::~SpcDynamic{{{*/
-SpcDynamic::~SpcDynamic(){
+SpcDynamic::~SpcDynamic(){/*{{{*/
 	return;
 }
@@ -39,6 +36,5 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION SpcDynamic::Echo {{{*/
-void SpcDynamic::Echo(void){
+void SpcDynamic::Echo(void){/*{{{*/
 
 	_printf_("SpcDynamic:\n");
@@ -52,6 +48,5 @@
 }
 /*}}}*/
-/*FUNCTION SpcDynamic::DeepEcho {{{*/
-void SpcDynamic::DeepEcho(void){
+void SpcDynamic::DeepEcho(void){/*{{{*/
 
 	this->Echo();
@@ -59,9 +54,7 @@
 }		
 /*}}}*/
-/*FUNCTION SpcDynamic::Id {{{*/
-int    SpcDynamic::Id(void){ return sid; }
+int SpcDynamic::Id(void){ return sid; }/*{{{*/
 /*}}}*/
-/*FUNCTION SpcDynamic::ObjectEnum{{{*/
-int SpcDynamic::ObjectEnum(void){
+int SpcDynamic::ObjectEnum(void){/*{{{*/
 
 	return SpcDynamicEnum;
@@ -69,19 +62,26 @@
 }
 /*}}}*/
-/*FUNCTION SpcDynamic::copy {{{*/
-Object* SpcDynamic::copy() {
-	return new SpcDynamic(*this); 
+Object* SpcDynamic::copy() {/*{{{*/
+
+	SpcDynamic* spcdyn = new SpcDynamic(*this); 
+
+	spcdyn->sid=this->sid;
+	spcdyn->nodeid=this->nodeid;
+	spcdyn->dof=this->dof;
+	spcdyn->value=this->value;
+	spcdyn->analysis_type=this->analysis_type;
+	spcdyn->isset=this->isset;
+
+	return (Object*) spcdyn;
 }
 /*}}}*/
 
 /*Constraint virtual functions definitions: */
-/*FUNCTION SpcDynamic::InAnalysis{{{*/
-bool SpcDynamic::InAnalysis(int in_analysis_type){
+bool SpcDynamic::InAnalysis(int in_analysis_type){/*{{{*/
 	if (in_analysis_type==this->analysis_type) return true;
 	else return false;
 }
 /*}}}*/
-/*FUNCTION SpcDynamic::ConstrainNode{{{*/
-void SpcDynamic::ConstrainNode(Nodes* nodes,Parameters* parameters){
+void SpcDynamic::ConstrainNode(Nodes* nodes,Parameters* parameters){/*{{{*/
 
 	Node* node=NULL;
@@ -100,17 +100,14 @@
 
 /*SpcDynamic functions*/
-/*FUNCTION SpcDynamic::GetDof {{{*/
-int SpcDynamic::GetDof(){
+int SpcDynamic::GetDof(){/*{{{*/
 	return dof;
 }
 /*}}}*/
-/*FUNCTION SpcDynamic::GetNodeId {{{*/
-int   SpcDynamic::GetNodeId(){
+int   SpcDynamic::GetNodeId(){/*{{{*/
 
 	return nodeid;
 }
 /*}}}*/
-/*FUNCTION SpcDynamic::GetValue {{{*/
-IssmDouble SpcDynamic::GetValue(){
+IssmDouble SpcDynamic::GetValue(){/*{{{*/
 	_assert_(this->isset);
 	_assert_(!xIsNan<IssmDouble>(value));
@@ -118,6 +115,5 @@
 }
 /*}}}*/
-/*FUNCTION SpcDynamic::SetDynamicConstraint {{{*/
-void SpcDynamic::SetDynamicConstraint(Nodes* nodes,IssmDouble* yg_serial){
+void SpcDynamic::SetDynamicConstraint(Nodes* nodes,IssmDouble* yg_serial){/*{{{*/
 
 	int pos;
Index: issm/trunk/src/c/classes/Constraints/SpcStatic.cpp
===================================================================
--- issm/trunk/src/c/classes/Constraints/SpcStatic.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Constraints/SpcStatic.cpp	(revision 18301)
@@ -14,11 +14,9 @@
 
 /*SpcStatic constructors and destructor*/
-/*FUNCTION SpcStatic::SpcStatic(){{{*/
-SpcStatic::SpcStatic(){
+SpcStatic::SpcStatic(){/*{{{*/
 	return;
 }
 /*}}}*/
-/*FUNCTION SpcStatic::SpcStatic(int spc_sid,int spc_nodeid,...){{{*/
-SpcStatic::SpcStatic(int spc_sid,int spc_nodeid, int spc_dof,IssmDouble spc_value,int spc_analysis_type){
+SpcStatic::SpcStatic(int spc_sid,int spc_nodeid, int spc_dof,IssmDouble spc_value,int spc_analysis_type){/*{{{*/
 
 	sid           = spc_sid;
@@ -31,6 +29,5 @@
 }
 /*}}}*/
-/*FUNCTION SpcStatic::~SpcStatic{{{*/
-SpcStatic::~SpcStatic(){
+SpcStatic::~SpcStatic(){/*{{{*/
 	return;
 }
@@ -38,6 +35,5 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION SpcStatic::Echo {{{*/
-void SpcStatic::Echo(void){
+void SpcStatic::Echo(void){/*{{{*/
 
 	_printf_("SpcStatic:\n");
@@ -50,6 +46,5 @@
 }
 /*}}}*/
-/*FUNCTION SpcStatic::DeepEcho {{{*/
-void SpcStatic::DeepEcho(void){
+void SpcStatic::DeepEcho(void){/*{{{*/
 
 	_printf_("SpcStatic:\n");
@@ -62,9 +57,7 @@
 }		
 /*}}}*/
-/*FUNCTION SpcStatic::Id {{{*/
-int    SpcStatic::Id(void){ return sid; }
+int SpcStatic::Id(void){ return sid; }/*{{{*/
 /*}}}*/
-/*FUNCTION SpcStatic::ObjectEnum{{{*/
-int SpcStatic::ObjectEnum(void){
+int SpcStatic::ObjectEnum(void){/*{{{*/
 
 	return SpcStaticEnum;
@@ -72,19 +65,25 @@
 }
 /*}}}*/
-/*FUNCTION SpcStatic::copy {{{*/
-Object* SpcStatic::copy() {
-	return new SpcStatic(*this); 
+Object* SpcStatic::copy() {/*{{{*/
+	
+	SpcStatic* spcstat = new SpcStatic(*this); 
+
+	spcstat->sid=this->sid;
+	spcstat->nodeid=this->nodeid;
+	spcstat->dof=this->dof;
+	spcstat->value=this->value;
+	spcstat->analysis_type=this->analysis_type;
+
+	return (Object*) spcstat;
 }
 /*}}}*/
 
 /*Constraint virtual functions definitions: */
-/*FUNCTION SpcStatic::InAnalysis{{{*/
-bool SpcStatic::InAnalysis(int in_analysis_type){
+bool SpcStatic::InAnalysis(int in_analysis_type){/*{{{*/
 	if (in_analysis_type==this->analysis_type) return true;
 	else return false;
 }
 /*}}}*/
-/*FUNCTION SpcStatic::ConstrainNode{{{*/
-void SpcStatic::ConstrainNode(Nodes* nodes,Parameters* parameters){
+void SpcStatic::ConstrainNode(Nodes* nodes,Parameters* parameters){/*{{{*/
 
 	Node* node=NULL;
@@ -101,17 +100,14 @@
 
 /*SpcStatic functions*/
-/*FUNCTION SpcStatic::GetDof {{{*/
-int SpcStatic::GetDof(){
+int SpcStatic::GetDof(){/*{{{*/
 	return dof;
 }
 /*}}}*/
-/*FUNCTION SpcStatic::GetNodeId {{{*/
-int   SpcStatic::GetNodeId(){
+int   SpcStatic::GetNodeId(){/*{{{*/
 
 	return nodeid;
 }
 /*}}}*/
-/*FUNCTION SpcStatic::GetValue {{{*/
-IssmDouble SpcStatic::GetValue(){
+IssmDouble SpcStatic::GetValue(){/*{{{*/
 	_assert_(!xIsNan<IssmDouble>(value));
 	return value;
Index: issm/trunk/src/c/classes/Constraints/SpcTransient.cpp
===================================================================
--- issm/trunk/src/c/classes/Constraints/SpcTransient.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Constraints/SpcTransient.cpp	(revision 18301)
@@ -14,6 +14,5 @@
 
 /*SpcTransient constructors and destructor*/
-/*FUNCTION SpcTransient::SpcTransient(){{{*/
-SpcTransient::SpcTransient(){
+SpcTransient::SpcTransient(){/*{{{*/
 	sid=-1;
 	nodeid=-1;
@@ -26,6 +25,5 @@
 }
 /*}}}*/
-/*FUNCTION SpcTransient::SpcTransient(int spc_sid,int spc_nodeid,...){{{*/
-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_sid,int spc_nodeid, int spc_dof,int spc_nsteps, IssmDouble* spc_times, IssmDouble* spc_values,int spc_analysis_type){/*{{{*/
 
 	sid=spc_sid;
@@ -43,6 +41,5 @@
 }
 /*}}}*/
-/*FUNCTION SpcTransient::~SpcTransient{{{*/
-SpcTransient::~SpcTransient(){
+SpcTransient::~SpcTransient(){/*{{{*/
 	xDelete<IssmDouble>(times);
 	xDelete<IssmDouble>(values);
@@ -52,6 +49,5 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION SpcTransient::Echo {{{*/
-void SpcTransient::Echo(void){
+void SpcTransient::Echo(void){/*{{{*/
 
 	int i;
@@ -69,14 +65,11 @@
 }
 /*}}}*/
-/*FUNCTION SpcTransient::DeepEcho {{{*/
-void SpcTransient::DeepEcho(void){
+void SpcTransient::DeepEcho(void){/*{{{*/
 	this->Echo();
 }		
 /*}}}*/
-/*FUNCTION SpcTransient::Id {{{*/
-int    SpcTransient::Id(void){ return sid; }
+int    SpcTransient::Id(void){ return sid; }/*{{{*/
 /*}}}*/
-/*FUNCTION SpcTransient::ObjectEnum{{{*/
-int SpcTransient::ObjectEnum(void){
+int SpcTransient::ObjectEnum(void){/*{{{*/
 
 	return SpcTransientEnum;
@@ -84,6 +77,5 @@
 }
 /*}}}*/
-/*FUNCTION SpcTransient::copy {{{*/
-Object* SpcTransient::copy() {
+Object* SpcTransient::copy() {/*{{{*/
 	return new SpcTransient(sid,nodeid,dof,nsteps,times,values,analysis_type);
 }
@@ -91,6 +83,5 @@
 
 /*Constraint virtual functions definitions:*/
-/*FUNCTION SpcTransient::InAnalysis{{{*/
-bool SpcTransient::InAnalysis(int in_analysis_type){
+bool SpcTransient::InAnalysis(int in_analysis_type){/*{{{*/
 
 	if (in_analysis_type==this->analysis_type) return true;
@@ -98,6 +89,5 @@
 }
 /*}}}*/
-/*FUNCTION SpcTransient::ConstrainNode{{{*/
-void SpcTransient::ConstrainNode(Nodes* nodes,Parameters* parameters){
+void SpcTransient::ConstrainNode(Nodes* nodes,Parameters* parameters){/*{{{*/
 
 	Node       *node  = NULL;
@@ -149,17 +139,14 @@
 
 /*SpcTransient functions*/
-/*FUNCTION SpcTransient::GetDof {{{*/
-int SpcTransient::GetDof(){
+int SpcTransient::GetDof(){/*{{{*/
 	return dof;
 }
 /*}}}*/
-/*FUNCTION SpcTransient::GetNodeId {{{*/
-int   SpcTransient::GetNodeId(){
+int   SpcTransient::GetNodeId(){/*{{{*/
 
 	return nodeid;
 }
 /*}}}*/
-/*FUNCTION SpcTransient::GetValue {{{*/
-IssmDouble SpcTransient::GetValue(){
+IssmDouble SpcTransient::GetValue(){/*{{{*/
 	return values[0];
 }
Index: issm/trunk/src/c/classes/Contour.h
===================================================================
--- issm/trunk/src/c/classes/Contour.h	(revision 18081)
+++ issm/trunk/src/c/classes/Contour.h	(revision 18301)
@@ -24,6 +24,5 @@
 
 		/*Contour constructors, destructors :*/
-		/*FUNCTION Contour() {{{*/
-		Contour(){
+		Contour(){/*{{{*/
 			this->id     = 0;
 			this->nods   = 0;
@@ -33,6 +32,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Contour(int pid, int nods, doubletype* x, doubletype* y,bool closed) {{{*/
-		Contour(int pid,int pnods, doubletype* px, doubletype* py,bool pclosed){
+		Contour(int pid,int pnods, doubletype* px, doubletype* py,bool pclosed){/*{{{*/
 
 			this->id     = pid;
@@ -47,6 +45,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION ~Contour() {{{*/
-		~Contour(){
+		~Contour(){/*{{{*/
 			xDelete<doubletype>(this->x);
 			xDelete<doubletype>(this->y);
@@ -55,6 +52,5 @@
 
 		/*Object virtual function resolutoin: */
-		/*FUNCTION Echo(){{{*/
-		void Echo(void){
+		void Echo(void){/*{{{*/
 			_printf_(" Contour: " << id << "\n");
 			_printf_("    nods: " << nods << "\n");
@@ -68,22 +64,21 @@
 		}
 		/*}}}*/
-		/*FUNCTION DeepEcho(){{{*/
-		void DeepEcho(void){
+		void DeepEcho(void){/*{{{*/
 			this->Echo();
 		}
 		/*}}}*/
-		/*FUNCTION Id(){{{*/
-		int Id(void){
+		int Id(void){/*{{{*/
 			return id;
 		}
 		/*}}}*/
-		/*FUNCTION ObjectEnum{{{*/
-		int ObjectEnum(void){
+		int ObjectEnum(void){/*{{{*/
 			return ContourEnum;
 		}
 		/*}}}*/
-		/*FUNCTION copy {{{*/
-		Object* copy() {
-			return new Contour(*this); 
+		Object* copy() {/*{{{*/
+
+			Contour* contour = new Contour(this->id,this->nods,this->x,this->y,this->closed);
+
+			return (Object*) contour;
 		}
 		/*}}}*/
Index: issm/trunk/src/c/classes/Contours.cpp
===================================================================
--- issm/trunk/src/c/classes/Contours.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Contours.cpp	(revision 18301)
@@ -19,12 +19,10 @@
 
 /*Object constructors and destructor*/
-/*FUNCTION Contours::Contours(){{{*/
-Contours::Contours(){
+Contours::Contours(){/*{{{*/
 	enum_type=ContoursEnum;
 	return;
 }
 /*}}}*/
-/*FUNCTION Contours::~Contours(){{{*/
-Contours::~Contours(){
+Contours::~Contours(){/*{{{*/
 	return;
 }
Index: issm/trunk/src/c/classes/DependentObject.cpp
===================================================================
--- issm/trunk/src/c/classes/DependentObject.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/DependentObject.cpp	(revision 18301)
@@ -14,6 +14,5 @@
 
 /*DependentObject constructors and destructor*/
-/*FUNCTION DependentObject::DependentObject(){{{*/
-DependentObject::DependentObject(){
+DependentObject::DependentObject(){/*{{{*/
 	this->name=NULL;
 	this->type=0;
@@ -21,6 +20,5 @@
 }
 /*}}}*/
-/*FUNCTION DependentObject::DependentObject(int in_name, int in_type, int in_index){{{*/
-DependentObject::DependentObject(char* in_name, int in_type,int in_index){
+DependentObject::DependentObject(char* in_name, int in_type,int in_index){/*{{{*/
 
 	this->name=xNew<char>(strlen(in_name)+1); xMemCpy<char>(this->name,in_name,strlen(in_name)+1);
@@ -32,6 +30,5 @@
 }
 /*}}}*/
-/*FUNCTION DependentObject::~DependentObject() {{{*/
-DependentObject::~DependentObject(){ //destructor
+DependentObject::~DependentObject(){ //destructor/*{{{*/
 	xDelete<char>(this->name);
 }
@@ -39,6 +36,5 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION DependentObject::Echo{{{*/
-void DependentObject::Echo(void){
+void DependentObject::Echo(void){/*{{{*/
 
 	_printf_("DependentObject:\n");
@@ -53,14 +49,11 @@
 }
 /*}}}*/
-/*FUNCTION DependentObject::DeepEcho{{{*/
-void DependentObject::DeepEcho(void){
+void DependentObject::DeepEcho(void){/*{{{*/
 	this->Echo();
 }
 /*}}}*/
-/*FUNCTION DependentObject::Id{{{*/
-int    DependentObject::Id(void){ return -1; }
+int    DependentObject::Id(void){ return -1; }/*{{{*/
 /*}}}*/
-/*FUNCTION DependentObject::ObjectEnum{{{*/
-int DependentObject::ObjectEnum(void){
+int DependentObject::ObjectEnum(void){/*{{{*/
 
 	return DependentObjectEnum;
@@ -68,12 +61,10 @@
 }
 /*}}}*/
-/*FUNCTION DependentObject::copy{{{*/
-Object* DependentObject::copy(void) { 
+Object* DependentObject::copy(void) { /*{{{*/
 	return new DependentObject(name,type,index);
 } /*}}}*/
 
 /*DependentObject methods: */
-/*FUNCTION DependentObject::NumDependents{{{*/
-int  DependentObject::NumDependents(void){
+int  DependentObject::NumDependents(void){/*{{{*/
 
 	/*Branch according to the type of variable: */
@@ -87,6 +78,5 @@
 }
 /*}}}*/
-/*FUNCTION DependentObject::Responsex{{{*/
-void  DependentObject::Responsex(IssmDouble* poutput_value,FemModel* femmodel){
+void  DependentObject::Responsex(IssmDouble* poutput_value,FemModel* femmodel){/*{{{*/
 
 	/*Is this some special type of response for which we need to go in the output definitions? :*/
Index: issm/trunk/src/c/classes/DofIndexing.cpp
===================================================================
--- issm/trunk/src/c/classes/DofIndexing.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/DofIndexing.cpp	(revision 18301)
@@ -20,6 +20,5 @@
 
 /*DofIndexing constructors and destructor*/
-/*FUNCTION DofIndexing::DofIndexing(){{{*/
-DofIndexing::DofIndexing(){
+DofIndexing::DofIndexing(){/*{{{*/
 
 	this->gsize    = UNDEF;
@@ -38,6 +37,5 @@
 }
 /*}}}*/
-/*FUNCTION DofIndexing::DofIndexing(int gsize){{{*/
-DofIndexing::DofIndexing(int in_gsize){
+DofIndexing::DofIndexing(int in_gsize){/*{{{*/
 
 	this->Init(in_gsize,NULL);
@@ -45,6 +43,5 @@
 }
 /*}}}*/
-/*FUNCTION DofIndexing::DofIndexing(DofIndexing* in)  -> copy{{{*/
-DofIndexing::DofIndexing(DofIndexing* in){ //copy constructor
+DofIndexing::DofIndexing(DofIndexing* in){ //copy constructor/*{{{*/
 
 	this->gsize  = in->gsize;
@@ -58,5 +55,10 @@
 		this->s_set=xNew<bool>(this->gsize);
 		this->svalues=xNew<IssmDouble>(this->gsize);
-		if(in->doftype)this->doftype=xNew<int>(this->gsize); 
+		if(in->doftype){
+			this->doftype=xNew<int>(this->gsize); 
+		}
+		else{
+			this->doftype=NULL;
+		}
 		this->gdoflist=xNew<int>(this->gsize); 
 	}
@@ -68,6 +70,6 @@
 		this->gdoflist = NULL;
 	}
-	if(this->fsize>0 && this->fsize!=UNDEF)this->fdoflist=xNew<int>(this->fsize); else this->fdoflist=NULL;
-	if(this->ssize>0 && this->ssize!=UNDEF)this->sdoflist=xNew<int>(this->ssize); else this->sdoflist=NULL;
+	if(this->fsize>0)this->fdoflist=xNew<int>(this->fsize); else this->fdoflist=NULL;
+	if(this->ssize>0)this->sdoflist=xNew<int>(this->ssize); else this->sdoflist=NULL;
 
 	if(this->gsize>0){
@@ -78,24 +80,72 @@
 		memcpy(this->gdoflist,in->gdoflist,this->gsize*sizeof(int));
 	}
-	if(this->fsize>0 && this->fsize!=UNDEF)memcpy(this->fdoflist,in->fdoflist,this->fsize*sizeof(int));
-	if(this->ssize>0 && this->ssize!=UNDEF)memcpy(this->sdoflist,in->sdoflist,this->ssize*sizeof(int));
-
-}
-/*}}}*/
-/*FUNCTION DofIndexing::~DofIndexing() {{{*/
-DofIndexing::~DofIndexing(){ //destructor
-
-	xDelete<bool>(f_set); 
-	xDelete<bool>(s_set); 
-	xDelete<IssmDouble>(svalues);
-	xDelete<int>(doftype); 
-	xDelete<int>(gdoflist);
-	xDelete<int>(fdoflist);
-	xDelete<int>(sdoflist);
-
-}
-/*}}}*/
-/*FUNCTION DofIndexing::Init{{{*/
-void DofIndexing::Init(int in_gsize,int* in_doftype){
+	if(this->fsize>0)memcpy(this->fdoflist,in->fdoflist,this->fsize*sizeof(int));
+	if(this->ssize>0)memcpy(this->sdoflist,in->sdoflist,this->ssize*sizeof(int));
+
+}
+/*}}}*/
+DofIndexing::~DofIndexing(){ //destructor/*{{{*/
+
+	if(this->f_set) xDelete<bool>(f_set); 
+	if(this->s_set) xDelete<bool>(s_set); 
+	if(this->svalues) xDelete<IssmDouble>(svalues);
+	if(this->doftype) xDelete<int>(doftype); 
+	if(this->gdoflist) xDelete<int>(gdoflist);
+	if(this->fdoflist) xDelete<int>(fdoflist);
+	if(this->sdoflist) xDelete<int>(sdoflist);
+
+}
+/*}}}*/
+DofIndexing DofIndexing::operator=( const DofIndexing& in ){/*{{{*/
+
+	this->copy(in);
+
+	return this;
+}
+/*}}}*/
+void DofIndexing::copy(const DofIndexing& in ){/*{{{*/
+
+	this->gsize  = in.gsize;
+	this->fsize  = in.fsize;
+	this->ssize  = in.ssize;
+	this->clone  = in.clone;
+	this->active = in.active;
+
+	if(this->gsize>0){
+		this->f_set=xNew<bool>(this->gsize);
+		this->s_set=xNew<bool>(this->gsize);
+		this->svalues=xNew<IssmDouble>(this->gsize);
+		if(in.doftype){
+			this->doftype=xNew<int>(this->gsize);
+		}
+		else{
+			this->doftype=NULL;
+		}
+		this->gdoflist=xNew<int>(this->gsize);
+	}
+	else{
+		this->f_set    = NULL;
+		this->s_set    = NULL;
+		this->svalues  = NULL;
+		this->doftype  = NULL;
+		this->gdoflist = NULL;
+	}
+	if(this->fsize>0)this->fdoflist=xNew<int>(this->fsize); else this->fdoflist=NULL;
+	if(this->ssize>0)this->sdoflist=xNew<int>(this->ssize); else this->sdoflist=NULL;
+
+	if(this->gsize>0){
+		memcpy(this->f_set,in.f_set,this->gsize*sizeof(bool));
+		memcpy(this->s_set,in.s_set,this->gsize*sizeof(bool));
+		xMemCpy<IssmDouble>(this->svalues,in.svalues,this->gsize);
+		if(this->doftype)memcpy(this->doftype,in.doftype,this->gsize*sizeof(int));
+		memcpy(this->gdoflist,in.gdoflist,this->gsize*sizeof(int));
+	}
+	if(this->fsize>0)memcpy(this->fdoflist,in.fdoflist,this->fsize*sizeof(int));
+	if(this->ssize>0)memcpy(this->sdoflist,in.sdoflist,this->ssize*sizeof(int));
+
+	return;
+}
+/*}}}*/
+void DofIndexing::Init(int in_gsize,int* in_doftype){/*{{{*/
 
 	this->gsize = in_gsize;
@@ -106,11 +156,11 @@
 	/*memory allocation */
 	if(this->gsize>0){
-		this->f_set    = xNew<bool>(this->gsize);
-		this->s_set    = xNew<bool>(this->gsize);
-		this->svalues  = xNew<IssmDouble>(this->gsize);
-		this->gdoflist = xNew<int>(this->gsize);
-
-		if(in_doftype)
-		 this->doftype = xNew<int>(this->gsize);
+		this->f_set    = xNew<bool>((unsigned int)in_gsize);
+		this->s_set    = xNew<bool>((unsigned int)in_gsize);
+		this->svalues  = xNew<IssmDouble>((unsigned int)in_gsize);
+		this->gdoflist = xNew<int>((unsigned int)in_gsize);
+
+		if(in_doftype) this->doftype = xNew<int>((unsigned int)in_gsize);
+		else this->doftype = NULL;
 	}
 
@@ -122,11 +172,9 @@
 		this->gdoflist[i] = UNDEF;
 
-		if(this->doftype)
-		 this->doftype[i]=in_doftype[i];
-	}
-}
-/*}}}*/
-/*FUNCTION DofIndexing::InitSet{{{*/
-void DofIndexing::InitSet(int setenum){
+		if(this->doftype) this->doftype[i]=in_doftype[i];
+	}
+}
+/*}}}*/
+void DofIndexing::InitSet(int setenum){/*{{{*/
 
 	int i;
@@ -162,6 +210,5 @@
 
 /*Some of the Object functionality: */
-/*FUNCTION DofIndexing::Echo{{{*/
-void DofIndexing::Echo(void){
+void DofIndexing::Echo(void){/*{{{*/
 
 	_printf_("DofIndexing:\n");
@@ -173,6 +220,5 @@
 }
 /*}}}*/
-/*FUNCTION DofIndexing::DeepEcho{{{*/
-void DofIndexing::DeepEcho(void){
+void DofIndexing::DeepEcho(void){/*{{{*/
 
 	int i;
@@ -224,6 +270,5 @@
 }		
 /*}}}*/
-/*FUNCTION DofIndexing::Deactivate{{{*/
-void DofIndexing::Deactivate(void){
+void DofIndexing::Deactivate(void){/*{{{*/
 	this->active = false;
 
@@ -237,6 +282,5 @@
 }
 /*}}}*/
-/*FUNCTION DofIndexing::Activate{{{*/
-void DofIndexing::Activate(void){
+void DofIndexing::Activate(void){/*{{{*/
 	this->active = true;
 
Index: issm/trunk/src/c/classes/DofIndexing.h
===================================================================
--- issm/trunk/src/c/classes/DofIndexing.h	(revision 18081)
+++ issm/trunk/src/c/classes/DofIndexing.h	(revision 18301)
@@ -41,9 +41,10 @@
 		DofIndexing(DofIndexing* properties);
 		~DofIndexing();
+		DofIndexing operator=(const DofIndexing& in);
 		/*}}}*/
 		/*Object like functionality: {{{*/
 		void  Echo(void); 
 		void  DeepEcho(void); 
-		void  copy(DofIndexing* properties);
+		void  copy(const DofIndexing& in);
 		/*}}}*/
 		/*DofIndexing management: {{{*/
Index: issm/trunk/src/c/classes/Elements/Element.cpp
===================================================================
--- issm/trunk/src/c/classes/Elements/Element.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Elements/Element.cpp	(revision 18301)
@@ -26,6 +26,8 @@
 	this->inputs     = NULL;
 	this->parameters = NULL;
+	this->element_type_list=NULL;
 }/*}}}*/
 Element::~Element(){/*{{{*/
+	xDelete<int>(element_type_list);
 	delete inputs;
 }
@@ -39,4 +41,195 @@
 	this->inputs->AddInput(input_in);
 }/*}}}*/
+void       Element::ComputeNewDamage(){/*{{{*/
+
+	IssmDouble *xyz_list=NULL;
+	IssmDouble  eps_xx,eps_xy,eps_yy,eps_xz,eps_yz,eps_zz,eps_eff;
+	IssmDouble  epsmin=1.e-27;
+	IssmDouble  eps_0,eps_f,sigma_0,B,D,n;
+	int         dim,counter=0;
+	IssmDouble  k1,k2,threshold=1.e-12;
+
+	/* Retrieve parameters */
+	this->GetVerticesCoordinates(&xyz_list);
+	this->ComputeStrainRate();
+	parameters->FindParam(&dim,DomainDimensionEnum);
+	parameters->FindParam(&eps_f,DamageC1Enum);
+	parameters->FindParam(&sigma_0,DamageStressThresholdEnum);
+
+	/* Retrieve inputs */
+	Input* eps_xx_input=this->GetInput(StrainRatexxEnum); _assert_(eps_xx_input);
+	Input* eps_yy_input=this->GetInput(StrainRateyyEnum); _assert_(eps_yy_input);
+	Input* eps_xy_input=this->GetInput(StrainRatexyEnum); _assert_(eps_xy_input);
+	Input* eps_xz_input=NULL;
+	Input* eps_yz_input=NULL;
+	Input* eps_zz_input=NULL;
+	if(dim==3){
+		eps_xz_input=this->GetInput(StrainRatexzEnum); _assert_(eps_xz_input);
+		eps_yz_input=this->GetInput(StrainRateyzEnum); _assert_(eps_yz_input);
+		eps_zz_input=this->GetInput(StrainRatezzEnum); _assert_(eps_zz_input);
+	}
+
+	/* Fetch number of nodes and allocate output*/
+   int numnodes = this->GetNumberOfNodes();
+   IssmDouble* newD = xNew<IssmDouble>(numnodes);
+
+	/* Retrieve domain-dependent inputs */
+	Input* n_input=this->GetInput(MaterialsRheologyNEnum); _assert_(n_input);
+   Input* damage_input = NULL;
+   Input* B_input = NULL;
+	int domaintype;
+   parameters->FindParam(&domaintype,DomainTypeEnum);
+	if(domaintype==Domain2DhorizontalEnum){
+      damage_input = this->GetInput(DamageDbarEnum);  _assert_(damage_input);
+      B_input=this->GetInput(MaterialsRheologyBbarEnum); _assert_(B_input);
+   }
+   else{
+      damage_input = this->GetInput(DamageDEnum);   _assert_(damage_input);
+      B_input=this->GetInput(MaterialsRheologyBEnum); _assert_(B_input);
+   }
+	
+	/* Start looping on the number of nodes: */
+	Gauss* gauss=this->NewGauss();
+	for (int i=0;i<numnodes;i++){
+		gauss->GaussNode(this->GetElementType(),i);
+
+		eps_xx_input->GetInputValue(&eps_xx,gauss);
+		eps_yy_input->GetInputValue(&eps_yy,gauss);
+		eps_xy_input->GetInputValue(&eps_xy,gauss);
+		if(dim==3){
+			eps_xz_input->GetInputValue(&eps_xz,gauss);
+			eps_yz_input->GetInputValue(&eps_yz,gauss);
+			eps_zz_input->GetInputValue(&eps_zz,gauss);
+		}
+		else{eps_xz=0; eps_yz=0; eps_zz=0;}
+
+		/* eps_eff^2 = exx^2 + eyy^2 + exy^2 + exz^2 + eyz^2 + exx*eyy */
+		eps_eff=sqrt(eps_xx*eps_xx+eps_yy*eps_yy+eps_xy*eps_xy+eps_xz*eps_xz+eps_yz*eps_yz+eps_xx*eps_yy+epsmin*epsmin);
+
+		B_input->GetInputValue(&B,gauss);
+      n_input->GetInputValue(&n,gauss);
+      damage_input->GetInputValue(&D,gauss);
+
+		/* Compute threshold strain rate from threshold stress */
+		eps_0=pow(sigma_0/B,n); 
+		_assert_(eps_f>eps_0);
+
+		/* Compute kappa (k) from pre-existing level of damage, using Newton-Raphson */
+		/* provide a reasonable initial guess */
+		if(D==0){
+			k1=eps_0;
+		}
+		else{
+			k1=exp(n*eps_0/(eps_f-eps_0)-n*log(1.-D)+log(eps_0)); /* initial guess */
+		}
+	
+		counter=0;
+		while(true){
+      	/*Newton step k2=k1-f(k1)/f'(k1) */
+			k2=k1-(k1+(eps_f-eps_0)/n*log(k1)-eps_0+(eps_f-eps_0)*(log(1.-D)-1./n*log(eps_0)))/(1.+(eps_f-eps_0)/n/k1);
+
+      	if( fabs(k2-k1)/(fabs(k2))<threshold ){
+         	break;
+      	}
+      	else{
+				k1=k2;
+      	   counter++;
+      	}
+
+      	if(counter>50) break;
+   	}
+
+		if(eps_eff>k2){
+			newD[i]=1.-pow(eps_0/eps_eff,1./n)*exp(-(eps_eff-eps_0)/(eps_f-eps_0));
+		}
+		else newD[i]=D;
+	}
+
+	/* Add new damage input to DamageEnum and NewDamageEnum */
+	this->AddInput(NewDamageEnum,newD,this->GetElementType());
+	if(domaintype==Domain2DhorizontalEnum){
+		this->AddInput(DamageDbarEnum,newD,this->GetElementType());
+	}
+	else{
+		this->AddInput(DamageDEnum,newD,this->GetElementType());
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(newD);
+	delete gauss;
+
+}/*}}}*/
+void       Element::ComputeStrainRate(){/*{{{*/
+
+	int         dim;
+	IssmDouble *xyz_list = NULL;
+	IssmDouble  epsilon[6];
+
+	/*Retrieve all inputs we will be needing: */
+	this->GetVerticesCoordinates(&xyz_list);
+	parameters->FindParam(&dim,DomainDimensionEnum);
+	Input* vx_input=this->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=this->GetInput(VyEnum); _assert_(vy_input);
+	Input* vz_input=NULL;
+	if(dim==3){vz_input=this->GetInput(VzEnum); _assert_(vz_input);}
+
+	/*Allocate arrays*/
+	int numvertices = this->GetNumberOfVertices();
+	IssmDouble* eps_xx = xNew<IssmDouble>(numvertices);
+	IssmDouble* eps_yy = xNew<IssmDouble>(numvertices);
+	IssmDouble* eps_zz = xNew<IssmDouble>(numvertices);
+	IssmDouble* eps_xy = xNew<IssmDouble>(numvertices);
+	IssmDouble* eps_xz = xNew<IssmDouble>(numvertices);
+	IssmDouble* eps_yz = xNew<IssmDouble>(numvertices);
+
+	/* Start looping on the number of vertices: */
+	Gauss* gauss=this->NewGauss();
+	for (int iv=0;iv<numvertices;iv++){
+		gauss->GaussVertex(iv);
+
+		/*Compute strain rate viscosity and pressure: */
+		if(dim==2)
+		 this->StrainRateSSA(&epsilon[0],xyz_list,gauss,vx_input,vy_input);
+		else
+		 this->StrainRateFS(&epsilon[0],xyz_list,gauss,vx_input,vy_input,vz_input);
+
+		if(dim==2){
+			 /* epsilon=[exx,eyy,exy];*/
+			eps_xx[iv]=epsilon[0]; 
+			eps_yy[iv]=epsilon[1];
+			eps_xy[iv]=epsilon[2];
+		}
+		else{
+			/*epsilon=[exx eyy ezz exy exz eyz]*/
+			eps_xx[iv]=epsilon[0]; 
+			eps_yy[iv]=epsilon[1];
+			eps_zz[iv]=epsilon[2];
+			eps_xy[iv]=epsilon[3]; 
+			eps_xz[iv]=epsilon[4];
+			eps_yz[iv]=epsilon[5];
+		}
+	}
+
+	/*Add Stress tensor components into inputs*/
+	this->AddInput(StrainRatexxEnum,eps_xx,P1Enum);
+	this->AddInput(StrainRatexyEnum,eps_xy,P1Enum);
+	this->AddInput(StrainRatexzEnum,eps_xz,P1Enum);
+	this->AddInput(StrainRateyyEnum,eps_yy,P1Enum);
+	this->AddInput(StrainRateyzEnum,eps_yz,P1Enum);
+	this->AddInput(StrainRatezzEnum,eps_zz,P1Enum);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(eps_xx);
+	xDelete<IssmDouble>(eps_yy);
+	xDelete<IssmDouble>(eps_zz);
+	xDelete<IssmDouble>(eps_xy);
+	xDelete<IssmDouble>(eps_xz);
+	xDelete<IssmDouble>(eps_yz);
+
+}
+/*}}}*/
 void       Element::CoordinateSystemTransform(IssmDouble** ptransform,Node** nodes_list,int numnodes,int* cs_array){/*{{{*/
 
@@ -162,5 +355,8 @@
 	if(nodes){
 		int numnodes = this->GetNumberOfNodes();
-		for(int i=0;i<numnodes;i++) nodes[i]->Echo();
+		for(int i=0;i<numnodes;i++) {
+			_printf_("nodes[" << i << "] = " << nodes[i]);	
+			nodes[i]->Echo();
+		}
 	}
 	else _printf_("nodes = NULL\n");
@@ -185,4 +381,5 @@
 
 	/*Intermediaries*/
+	int        dim;
 	IssmDouble Jdet;
 	IssmDouble divergence=0.;
@@ -191,10 +388,14 @@
 
 	/*Get inputs and parameters*/
-	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);
+	this->FindParam(&dim,DomainDimensionEnum);
+	Input* vx_input = this->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input = this->GetInput(VyEnum); _assert_(vy_input);
+	Input* vz_input = NULL;
+	if(dim==3){
+		vz_input = this->GetInput(VzEnum); _assert_(vz_input);
+	}
 	this->GetVerticesCoordinates(&xyz_list);
 
-	Gauss* gauss=this->NewGaussBase(5);
+	Gauss* gauss=this->NewGauss(5);
 	for(int ig=gauss->begin();ig<gauss->end();ig++){
 		gauss->GaussPoint(ig);
@@ -204,7 +405,12 @@
 		vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
 		vy_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
-		vz_input->GetInputDerivativeValue(&dvz[0],xyz_list,gauss);
-
-		divergence += (dvx[0]+dvy[1]+dvz[2])*gauss->weight*Jdet;
+		if(dim==2){
+			divergence += (dvx[0]+dvy[1])*gauss->weight*Jdet;
+		}
+		else{
+			vz_input->GetInputDerivativeValue(&dvz[0],xyz_list,gauss);
+			divergence += (dvx[0]+dvy[1]+dvz[2])*gauss->weight*Jdet;
+		}
+
 	}
 
@@ -213,4 +419,58 @@
 	return divergence;
 }/*}}}*/
+void       Element::dViscositydBSSA(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble dmudB;
+	IssmDouble epsilon2d[3];/* epsilon=[exx,eyy,exy];    */
+	IssmDouble epsilon1d;   /* epsilon=[exx];    */
+	IssmDouble eps_eff;
+
+	 if(dim==2){
+		 /* eps_eff^2 = exx^2 + eyy^2 + exy^2 + exx*eyy*/
+		 this->StrainRateSSA(&epsilon2d[0],xyz_list,gauss,vx_input,vy_input);
+		 eps_eff = sqrt(epsilon2d[0]*epsilon2d[0] + epsilon2d[1]*epsilon2d[1] + epsilon2d[2]*epsilon2d[2] + epsilon2d[0]*epsilon2d[1]);
+	 }
+	 else{
+		 /* eps_eff^2 = 1/2 exx^2*/
+		 this->StrainRateSSA1d(&epsilon1d,xyz_list,gauss,vx_input);
+		 eps_eff = sqrt(epsilon1d*epsilon1d/2.);
+	 }
+
+	/*Get viscosity*/
+	material->GetViscosity_B(&dmudB,eps_eff);
+
+	/*Assign output pointer*/
+	*pdmudB=dmudB;
+
+}
+/*}}}*/
+void       Element::dViscositydDSSA(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble dmudB;
+	IssmDouble epsilon2d[3];/* epsilon=[exx,eyy,exy];    */
+	IssmDouble epsilon1d;   /* epsilon=[exx];    */
+	IssmDouble eps_eff;
+
+	if(dim==2){
+		/* eps_eff^2 = exx^2 + eyy^2 + exy^2 + exx*eyy*/
+		this->StrainRateSSA(&epsilon2d[0],xyz_list,gauss,vx_input,vy_input);
+		eps_eff = sqrt(epsilon2d[0]*epsilon2d[0] + epsilon2d[1]*epsilon2d[1] + epsilon2d[2]*epsilon2d[2] + epsilon2d[0]*epsilon2d[1]);
+	}
+	else{
+		/* eps_eff^2 = 1/2 exx^2*/
+		this->StrainRateSSA1d(&epsilon1d,xyz_list,gauss,vx_input);
+		eps_eff = sqrt(epsilon1d*epsilon1d/2.);
+	}
+
+	/*Get viscosity*/
+	material->GetViscosity_D(&dmudB,eps_eff);
+
+	/*Assign output pointer*/
+	*pdmudB=dmudB;
+
+}
+/*}}}*/
 void       Element::ThermalToEnthalpy(IssmDouble* penthalpy,IssmDouble temperature,IssmDouble waterfraction,IssmDouble pressure){/*{{{*/
 	matpar->ThermalToEnthalpy(penthalpy,temperature,waterfraction,pressure);
@@ -603,4 +863,20 @@
 	return z;
 }/*}}}*/
+void       Element::GradientIndexing(int* indexing,int control_index){/*{{{*/
+
+	/*Get number of controls*/
+	int num_controls;
+	parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+
+	/*Get number of vertices*/
+	int numvertices = this->GetNumberOfVertices();
+
+	/*get gradient indices*/
+	for(int i=0;i<numvertices;i++){
+		indexing[i]=num_controls*this->vertices[i]->Pid() + control_index;
+	}
+
+}
+/*}}}*/
 bool       Element::HasNodeOnBase(){/*{{{*/
 	return (this->inputs->Max(MeshVertexonbaseEnum)>0.);
@@ -749,8 +1025,12 @@
 				name==BaseEnum ||
 				name==BedEnum ||
+				name==BalancethicknessThickeningRateEnum ||
+				name==BalancethicknessApparentMassbalanceEnum ||
+				name==SigmaNNEnum ||
 				name==SurfaceSlopeXEnum ||
 				name==SurfaceSlopeYEnum ||
 				name==SurfaceforcingsMassBalanceEnum ||
-				name==BasalforcingsMeltingRateEnum ||
+				name==BasalforcingsGroundediceMeltingRateEnum ||
+				name==BasalforcingsFloatingiceMeltingRateEnum ||
 				name==BasalforcingsGeothermalfluxEnum ||
 				name==SurfaceAreaEnum||
@@ -783,19 +1063,4 @@
 				name==OldGradientEnum  ||
 				name==ConvergedEnum || 
-				name==QmuVxEnum ||
-				name==QmuVyEnum ||
-				name==QmuVzEnum ||
-				name==QmuVxMeshEnum ||
-				name==QmuVyMeshEnum ||
-				name==QmuVzMeshEnum ||
-				name==QmuPressureEnum ||
-				name==QmuBaseEnum ||
-				name==QmuThicknessEnum ||
-				name==QmuSurfaceEnum ||
-				name==QmuTemperatureEnum ||
-				name==QmuMeltingEnum ||
-				name==QmuMaskGroundediceLevelsetEnum ||
-				name==QmuMaskIceLevelsetEnum ||
-				name==QmuMaterialsRheologyBEnum ||
 				name==MaterialsRheologyBEnum ||
 				name==MaterialsRheologyBbarEnum ||
@@ -819,4 +1084,25 @@
 }
 /*}}}*/
+void       Element::LinearFloatingiceMeltingRate(){/*{{{*/
+
+	int numvertices      = this->GetNumberOfVertices();
+	IssmDouble  deepwaterel,upperwaterel,deepwatermelt;
+	IssmDouble* base     = xNew<IssmDouble>(numvertices);
+	IssmDouble* values   = xNew<IssmDouble>(numvertices);
+
+	parameters->FindParam(&deepwaterel,BasalforcingsDeepwaterElevationEnum);
+	parameters->FindParam(&upperwaterel,BasalforcingsUpperwaterElevationEnum);
+	parameters->FindParam(&deepwatermelt,BasalforcingsDeepwaterMeltingRateEnum);
+
+	this->GetInputListOnVertices(base,BaseEnum);
+	for(int i=0;i<numvertices;i++){
+		if(base[i]>upperwaterel)      values[i]=0;
+		else if (base[i]<deepwaterel) values[i]=deepwatermelt;
+		else values[i]=deepwatermelt*(base[i]-upperwaterel)/(deepwaterel-upperwaterel);
+	}
+
+	this->AddInput(BasalforcingsFloatingiceMeltingRateEnum,values,P1Enum);
+
+}/*}}}*/
 ElementVector* Element::NewElementVector(int approximation_enum){/*{{{*/
 	return new ElementVector(nodes,this->GetNumberOfNodes(),this->parameters,approximation_enum);
@@ -876,4 +1162,8 @@
 				input=this->inputs->GetInput(output_enum);
 				break;
+			case NewDamageEnum:
+				this->ComputeNewDamage();
+				input=this->inputs->GetInput(output_enum);
+				break;
 			default:
 				_error_("input "<<EnumToStringx(output_enum)<<" not found in element");
@@ -904,5 +1194,7 @@
 					break;
 				default:
-					_error_("Input of type "<<EnumToStringx(input->GetResultInterpolation())<<" not supported");
+					Gauss* gauss = this->NewGauss();
+					input->GetInputValue(&value,gauss);
+					delete gauss;
 			}
 			vector->SetValue(this->Sid(),value,INS_VAL);
Index: issm/trunk/src/c/classes/Elements/Element.h
===================================================================
--- issm/trunk/src/c/classes/Elements/Element.h	(revision 18081)
+++ issm/trunk/src/c/classes/Elements/Element.h	(revision 18301)
@@ -47,4 +47,7 @@
 		Parameters  *parameters;
 
+		int* element_type_list;
+		int  element_type;
+
 	public: 
 		/*Constructors/Destructores*/
@@ -56,8 +59,12 @@
 		/* bool       AllActive(void); */
 		/* bool       AnyActive(void); */
+		void       ComputeNewDamage();
+		void       ComputeStrainRate();
 		void       CoordinateSystemTransform(IssmDouble** ptransform,Node** nodes,int numnodes,int* cs_array);
 		void       Echo();
 		void       DeepEcho();
 		void       DeleteMaterials(void);
+		void       dViscositydBSSA(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
+		void       dViscositydDSSA(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
 		IssmDouble Divergence(void);
 		void       ThermalToEnthalpy(IssmDouble* penthalpy,IssmDouble temperature,IssmDouble waterfraction,IssmDouble pressure);
@@ -94,4 +101,5 @@
 		IssmDouble GetYcoord(IssmDouble* xyz_list,Gauss* gauss);
 		IssmDouble GetZcoord(IssmDouble* xyz_list,Gauss* gauss);
+		void       GradientIndexing(int* indexing,int control_index);
 		bool       HasNodeOnBase();
 		bool       HasNodeOnSurface();
@@ -107,4 +115,5 @@
 		bool	     IsInput(int name);
 		bool       IsFloating(); 
+		void       LinearFloatingiceMeltingRate(); 
 		ElementVector*  NewElementVector(int approximation_enum=NoneApproximationEnum);
 		ElementMatrix*  NewElementMatrix(int approximation_enum=NoneApproximationEnum);
@@ -156,4 +165,5 @@
 		virtual void       Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters)=0;
 		virtual void       SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Materials* materials,Parameters* parameters)=0;
+		virtual void       ResetHooks()=0;
 		virtual void   ElementSizes(IssmDouble* phx,IssmDouble* phy,IssmDouble* phz)=0;
 
@@ -162,4 +172,5 @@
 		virtual void   NodalFunctions(IssmDouble* basis,Gauss* gauss)=0;
 		virtual void   NodalFunctionsP1(IssmDouble* basis,Gauss* gauss)=0;
+		virtual void   NodalFunctionsP2(IssmDouble* basis,Gauss* gauss)=0;
 		virtual void   NodalFunctionsVelocity(IssmDouble* basis, Gauss* gauss)=0;
 		virtual void   NodalFunctionsPressure(IssmDouble* basis, Gauss* gauss)=0;
@@ -184,4 +195,5 @@
 		virtual int    GetNodeIndex(Node* node)=0;
 		virtual int    GetNumberOfNodes(void)=0;
+		virtual int    GetNumberOfNodes(int enum_type)=0;
 		virtual int    GetNumberOfVertices(void)=0;
 
@@ -202,6 +214,4 @@
 		virtual void   ComputeSigmaNN(void)=0;
 		virtual void   ComputeBasalStress(Vector<IssmDouble>* sigma_b)=0;
-		virtual void   ComputeStrainRate()=0;
-		virtual void   ComputeStrainRate(Vector<IssmDouble>* eps)=0;
 		virtual void   ComputeStressTensor(void)=0;
 		virtual void   ComputeDeviatoricStressTensor(void)=0;
@@ -228,5 +238,4 @@
 		virtual void   PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm)=0;
 		virtual void   Delta18oParameterization(void)=0;
-		virtual void   SmbGradients(void)=0;
 	   virtual Element*   SpawnBasalElement(void)=0;
 		virtual Element*   SpawnTopElement(void)=0;
@@ -247,17 +256,7 @@
 		virtual void   ZeroLevelsetCoordinates(IssmDouble** pxyz_zero,IssmDouble* xyz_list,int levelsetenum)=0;
 		virtual void   GetIcefrontCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum)=0;
+		virtual void   GetLevelCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum,IssmDouble level)=0;
 
 		virtual void   AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part)=0;
-		virtual void   MinVel(IssmDouble* pminvel)=0;
-		virtual void   MaxVel(IssmDouble* pmaxvel)=0;
-		virtual void   MinVx(IssmDouble* pminvx)=0;
-		virtual void   MaxVx(IssmDouble* pmaxvx)=0;
-		virtual void   MaxAbsVx(IssmDouble* pmaxabsvx)=0;
-		virtual void   MinVy(IssmDouble* pminvy)=0;
-		virtual void   MaxVy(IssmDouble* pmaxvy)=0;
-		virtual void   MaxAbsVy(IssmDouble* pmaxabsvy)=0;
-		virtual void   MinVz(IssmDouble* pminvz)=0;
-		virtual void   MaxVz(IssmDouble* pmaxvz)=0;
-		virtual void   MaxAbsVz(IssmDouble* pmaxabsvz)=0;
 		virtual IssmDouble MassFlux(IssmDouble* segment)=0;
 		virtual IssmDouble MassFlux(IssmDouble x1,IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id)=0;
@@ -275,8 +274,5 @@
 		#endif
 
-		virtual void   Gradj(Vector<IssmDouble>* gradient,int control_type,int control_index)=0;
-		virtual void   ControlInputGetGradient(Vector<IssmDouble>* gradient,int enum_type,int control_index)=0;
 		virtual void   ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index)=0;
-		virtual void   ControlInputScaleGradient(int enum_type, IssmDouble scale)=0;
 		virtual void   ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum)=0;
 		virtual void   GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data)=0;
Index: issm/trunk/src/c/classes/Elements/ElementHook.cpp
===================================================================
--- issm/trunk/src/c/classes/Elements/ElementHook.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Elements/ElementHook.cpp	(revision 18301)
@@ -27,10 +27,10 @@
 ElementHook::~ElementHook(){/*{{{*/
 
-	int i;
-
-	for(i=0;i<this->numanalyses;i++){
-		if (this->hnodes[i]) delete this->hnodes[i];
+	if(this->hnodes){
+		for(int i=0;i<this->numanalyses;i++){
+			if(this->hnodes[i]) delete this->hnodes[i]; 
+		}
+		delete [] this->hnodes;
 	}
-	delete [] this->hnodes;
 	delete hvertices;
 	delete hmaterial;
@@ -76,5 +76,5 @@
 
 void ElementHook::SetHookNodes(int* node_ids,int numnodes,int analysis_counter){/*{{{*/
-	this->hnodes[analysis_counter]= new Hook(node_ids,numnodes);
+	if(this->hnodes) this->hnodes[analysis_counter]= new Hook(node_ids,numnodes);
 }
 /*}}}*/
Index: issm/trunk/src/c/classes/Elements/Elements.cpp
===================================================================
--- issm/trunk/src/c/classes/Elements/Elements.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Elements/Elements.cpp	(revision 18301)
@@ -62,4 +62,18 @@
 }
 /*}}}*/
+void Elements::ResetHooks(){/*{{{*/
+
+	vector<Object*>::iterator object;
+	Element* element=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		element=dynamic_cast<Element*>((*object));
+		element->ResetHooks();
+
+	}
+
+}
+/*}}}*/
 int  Elements::MaxNumNodes(void){/*{{{*/
 
Index: issm/trunk/src/c/classes/Elements/Elements.h
===================================================================
--- issm/trunk/src/c/classes/Elements/Elements.h	(revision 18081)
+++ issm/trunk/src/c/classes/Elements/Elements.h	(revision 18301)
@@ -27,4 +27,5 @@
 		int    MaxNumNodes(void);
 		void   SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
+		void   ResetHooks();
 		int    NumberOfElements(void);
 		void   InputDuplicate(int input_enum,int output_enum);
Index: issm/trunk/src/c/classes/Elements/Penta.cpp
===================================================================
--- issm/trunk/src/c/classes/Elements/Penta.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Elements/Penta.cpp	(revision 18301)
@@ -25,6 +25,5 @@
 /*}}}*/
 Penta::Penta(int penta_id, int penta_sid, int index, IoModel* iomodel,int nummodels)/*{{{*/
-	:PentaRef(nummodels)
-	,ElementHook(nummodels,index+1,NUMVERTICES,iomodel){
+	:ElementHook(nummodels,index+1,NUMVERTICES,iomodel){
 
 	int penta_elements_ids[2];
@@ -35,6 +34,6 @@
 
 	/*id: */
-	this->id=penta_id;
-	this->sid=penta_sid;
+	this->id  = penta_id;
+	this->sid = penta_sid;
 
 	/*Build neighbors list*/
@@ -57,4 +56,7 @@
 	this->matpar            = NULL;
 	this->verticalneighbors = NULL;
+
+	/*Only allocate pointer*/
+	this->element_type_list=xNew<int>(nummodels);
 }
 /*}}}*/
@@ -62,5 +64,4 @@
 
 	int i;
-
 	Penta* penta=NULL;
 
@@ -68,37 +69,56 @@
 
 	//deal with PentaRef mother class
-	penta->element_type_list=xNew<int>(this->numanalyses);
-	for(i=0;i<this->numanalyses;i++) penta->element_type_list[i]=this->element_type_list[i];
-
-	//deal with ElementHook
-	penta->numanalyses=this->numanalyses;
-	penta->hnodes=new Hook*[penta->numanalyses];
-	for(i=0;i<penta->numanalyses;i++)penta->hnodes[i]=(Hook*)this->hnodes[i]->copy();
-	penta->hvertices=(Hook*)this->hvertices->copy();
-	penta->hmaterial=(Hook*)this->hmaterial->copy();
-	penta->hmatpar=(Hook*)this->hmatpar->copy();
-	penta->hneighbors=(Hook*)this->hneighbors->copy();
-
-	/*deal with Penta  copy fields: */
-	penta->id=this->id;
-	penta->sid=this->sid;
-	if(this->inputs){
-		penta->inputs=(Inputs*)this->inputs->Copy();
-	}
-	else{
-		penta->inputs=new Inputs();
-	}
+	int nanalyses = this->numanalyses;
+	if(nanalyses > 0){
+		penta->element_type_list=xNew<int>(nanalyses);
+		for(i=0;i<nanalyses;i++) {
+			if (this->element_type_list[i]) penta->element_type_list[i]=this->element_type_list[i];
+			else penta->element_type_list[i] = 0;
+		}
+	}
+	else penta->element_type_list = NULL;
+	penta->element_type=this->element_type;
+	penta->numanalyses=nanalyses;
+
+	//deal with ElementHook mother class
+	if (this->hnodes){
+		penta->hnodes=xNew<Hook*>(penta->numanalyses);
+		for(i=0;i<penta->numanalyses;i++){
+			if (this->hnodes[i]) penta->hnodes[i] = (Hook*)(this->hnodes[i]->copy());
+			else penta->hnodes[i] = NULL;
+		}
+	}
+	else penta->hnodes = NULL;
+
+	penta->hvertices = (Hook*)this->hvertices->copy();
+	penta->hmaterial = (Hook*)this->hmaterial->copy();
+	penta->hmatpar   = (Hook*)this->hmatpar->copy();
+	if (this->hneighbors) penta->hneighbors = (Hook*)(this->hneighbors->copy());
+	else penta->hneighbors = NULL;
+
+	/*deal with Tria fields: */
+	penta->id  = this->id;
+	penta->sid = this->sid;
+	if(this->inputs) penta->inputs = (Inputs*)(this->inputs->Copy());
+	else penta->inputs=new Inputs();
+
 	/*point parameters: */
 	penta->parameters=this->parameters;
 
 	/*recover objects: */
-	penta->nodes=xNew<Node*>(6); //we cannot rely on an analysis_counter to tell us which analysis_type we are running, so we just copy the nodes.
-	for(i=0;i<6;i++)penta->nodes[i]=this->nodes[i];
-	penta->vertices=(Vertex**)penta->hvertices->deliverp();
-	penta->material=(Material*)penta->hmaterial->delivers();
-	penta->matpar=(Matpar*)penta->hmatpar->delivers();
-	penta->verticalneighbors=(Penta**)penta->hneighbors->deliverp();
+	if (this->nodes) {
+		unsigned int num_nodes = 6;
+		penta->nodes = xNew<Node*>(num_nodes); //we cannot rely on an analysis_counter to tell us which analysis_type we are running, so we just copy the nodes.
+		for(i=0;i<num_nodes;i++) if(this->nodes[i]) penta->nodes[i]=this->nodes[i]; else penta->nodes[i] = NULL;
+	}
+	else penta->nodes = NULL;
+
+	penta->vertices = (Vertex**)this->hvertices->deliverp();
+	penta->material = (Material*)this->hmaterial->delivers();
+	penta->matpar   = (Matpar*)this->hmatpar->delivers();
+	penta->verticalneighbors = (Penta**)this->hneighbors->deliverp();
 
 	return penta;
+
 }
 /*}}}*/
@@ -223,52 +243,4 @@
 }
 /*}}}*/
-void       Penta::ComputeStrainRate(){/*{{{*/
-
-	IssmDouble      xyz_list[NUMVERTICES][3];
-	IssmDouble      epsilon[6]; /* epsilon=[exx,eyy,exy];*/
-	IssmDouble      eps_xx[NUMVERTICES];
-	IssmDouble		 eps_yy[NUMVERTICES];
-	IssmDouble		 eps_zz[NUMVERTICES];
-	IssmDouble      eps_xy[NUMVERTICES];
-	IssmDouble		 eps_xz[NUMVERTICES];
-	IssmDouble		 eps_yz[NUMVERTICES];
-	GaussPenta*     gauss=NULL;
-
-	/* Get node coordinates and dof list: */
-	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-
-	/*Retrieve all inputs we will be needing: */
-	Input* vx_input=inputs->GetInput(VxEnum);             _assert_(vx_input);
-	Input* vy_input=inputs->GetInput(VyEnum);             _assert_(vy_input);
-	Input* vz_input=inputs->GetInput(VzEnum);             _assert_(vz_input);
-
-	/* Start looping on the number of vertices: */
-	gauss=new GaussPenta();
-	for (int iv=0;iv<NUMVERTICES;iv++){
-		gauss->GaussVertex(iv);
-
-		/*Compute strain rate viscosity and pressure: */
-		this->StrainRateFS(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
-
-		eps_xx[iv]=epsilon[0]; 
-		eps_yy[iv]=epsilon[1];
-		eps_zz[iv]=epsilon[2];
-		eps_xy[iv]=epsilon[3];
-		eps_xz[iv]=epsilon[4];
-		eps_yz[iv]=epsilon[5];
-	}
-
-	/*Add Stress tensor components into inputs*/
-	this->inputs->AddInput(new PentaInput(StrainRatexxEnum,&eps_xx[0],P1Enum));
-	this->inputs->AddInput(new PentaInput(StrainRatexyEnum,&eps_xy[0],P1Enum));
-	this->inputs->AddInput(new PentaInput(StrainRatexzEnum,&eps_xz[0],P1Enum));
-	this->inputs->AddInput(new PentaInput(StrainRateyyEnum,&eps_yy[0],P1Enum));
-	this->inputs->AddInput(new PentaInput(StrainRateyzEnum,&eps_yz[0],P1Enum));
-	this->inputs->AddInput(new PentaInput(StrainRatezzEnum,&eps_zz[0],P1Enum));
-
-	/*Clean up and return*/
-	delete gauss;
-}
-/*}}}*/
 void       Penta::ComputeStressTensor(){/*{{{*/
 
@@ -869,5 +841,5 @@
 
 	_assert_(nodes);
-	int numnodes = this->NumberofNodes();
+	int numnodes = this->NumberofNodes(this->element_type);
 
 	for(int i=0;i<numnodes;i++){
@@ -879,5 +851,9 @@
 /*}}}*/
 int        Penta::GetNumberOfNodes(void){/*{{{*/
-	return this->NumberofNodes();
+	return this->NumberofNodes(this->element_type);
+}
+/*}}}*/
+int        Penta::GetNumberOfNodes(int enum_type){/*{{{*/
+	return this->NumberofNodes(enum_type);
 }
 /*}}}*/
@@ -886,7 +862,7 @@
 }
 /*}}}*/
-Node* Penta::GetNode(int node_number){/*{{{*/
+Node*      Penta::GetNode(int node_number){/*{{{*/
 	_assert_(node_number>=0); 
-	_assert_(node_number<this->NumberofNodes()); 
+	_assert_(node_number<this->NumberofNodes(this->element_type)); 
 	return this->nodes[node_number];
 }
@@ -1169,5 +1145,5 @@
 		/*Step3: Vertically integrate A COPY of the original*/
 		if(original_input->ObjectEnum()==PentaInputEnum){
-			if(((PentaInput*)original_input)->element_type==P0Enum){
+			if(((PentaInput*)original_input)->interpolation_type==P0Enum){
 				original_input->GetInputValue(&p0top1_list[i]);
 				element_integrated_input= new  PentaInput(original_input->InstanceEnum(),p0top1_list,P1Enum);
@@ -1358,5 +1334,5 @@
 
 	/*Fetch number of nodes for this finite element*/
-	int numnodes = this->NumberofNodes();
+	int numnodes = this->NumberofNodes(this->element_type);
 
 	/*Fetch dof list and allocate solution vector*/
@@ -1512,5 +1488,5 @@
 }
 /*}}}*/
-bool   Penta::IsNodeOnShelfFromFlags(IssmDouble* flags){/*{{{*/
+bool       Penta::IsNodeOnShelfFromFlags(IssmDouble* flags){/*{{{*/
 
 	int  i;
@@ -1582,5 +1558,5 @@
 }
 /*}}}*/
-int    Penta::NodalValue(IssmDouble* pvalue, int index, int natureofdataenum){/*{{{*/
+int        Penta::NodalValue(IssmDouble* pvalue, int index, int natureofdataenum){/*{{{*/
 
 	int i;
@@ -1613,13 +1589,13 @@
 }
 /*}}}*/
-Gauss* Penta::NewGauss(void){/*{{{*/
+Gauss*     Penta::NewGauss(void){/*{{{*/
 	return new GaussPenta();
 }
 /*}}}*/
-Gauss* Penta::NewGauss(int order){/*{{{*/
+Gauss*     Penta::NewGauss(int order){/*{{{*/
 	return new GaussPenta(order,order);
 }
 /*}}}*/
-Gauss* Penta::NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order_horiz,int order_vert){/*{{{*/
+Gauss*     Penta::NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order_horiz,int order_vert){/*{{{*/
 
 	IssmDouble  area_coordinates[4][3];
@@ -1630,13 +1606,13 @@
 }
 /*}}}*/
-Gauss* Penta::NewGaussBase(int order){/*{{{*/
+Gauss*     Penta::NewGaussBase(int order){/*{{{*/
 	return new GaussPenta(0,1,2,order);
 }
 /*}}}*/
-Gauss* Penta::NewGaussLine(int vertex1,int vertex2,int order){/*{{{*/
+Gauss*     Penta::NewGaussLine(int vertex1,int vertex2,int order){/*{{{*/
 	return new GaussPenta(vertex1,vertex2,order);
 }
 /*}}}*/
-Gauss* Penta::NewGaussTop(int order){/*{{{*/
+Gauss*     Penta::NewGaussTop(int order){/*{{{*/
 	return new GaussPenta(3,4,5,order);
 }
@@ -1645,5 +1621,5 @@
 
 	_assert_(gauss->Enum()==GaussPentaEnum);
-	this->GetNodalFunctions(basis,(GaussPenta*)gauss);
+	this->GetNodalFunctions(basis,(GaussPenta*)gauss,this->element_type);
 
 }
@@ -1652,5 +1628,12 @@
 
 	_assert_(gauss->Enum()==GaussPentaEnum);
-	this->GetNodalFunctionsP1(basis,(GaussPenta*)gauss);
+	this->GetNodalFunctions(basis,(GaussPenta*)gauss,P1Enum);
+
+}
+/*}}}*/
+void       Penta::NodalFunctionsP2(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussPentaEnum);
+	this->GetNodalFunctions(basis,(GaussPenta*)gauss,P2Enum);
 
 }
@@ -1659,5 +1642,5 @@
 
 	_assert_(gauss->Enum()==GaussPentaEnum);
-	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussPenta*)gauss);
+	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussPenta*)gauss,this->element_type);
 
 }
@@ -1666,5 +1649,5 @@
 
 	_assert_(gauss->Enum()==GaussPentaEnum);
-	this->GetNodalFunctionsP1Derivatives(dbasis,xyz_list,(GaussPenta*)gauss);
+	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussPenta*)gauss,P1Enum);
 
 }
@@ -1673,5 +1656,5 @@
 
 	_assert_(gauss->Enum()==GaussPentaEnum);
-	this->GetNodalFunctionsMINIDerivatives(dbasis,xyz_list,(GaussPenta*)gauss);
+	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussPenta*)gauss,P1bubbleEnum);
 
 }
@@ -1946,4 +1929,22 @@
 }
 /*}}}*/
+void       Penta::ResetHooks(){/*{{{*/
+
+	this->nodes=NULL;
+	this->vertices=NULL;
+	this->material=NULL;
+	this->matpar=NULL;
+	this->verticalneighbors=NULL;
+	this->parameters=NULL;
+
+	//deal with ElementHook mother class
+	for(int i=0;i<this->numanalyses;i++) if(this->hnodes[i]) this->hnodes[i]->reset();
+	this->hvertices->reset();
+	this->hmaterial->reset();
+	this->hmatpar->reset();
+	if(this->hneighbors) this->hneighbors->reset();
+
+}
+/*}}}*/
 void       Penta::SetTemporaryElementType(int element_type_in){/*{{{*/
 	this->element_type=element_type_in;
@@ -2003,49 +2004,4 @@
 }
 /*}}}*/
-void       Penta::SmbGradients(void){/*{{{*/
-
-	int i;
-
-	// input
-   IssmDouble h[NUMVERTICES];					// ice thickness (m)		
-	IssmDouble s[NUMVERTICES];					// surface elevation (m)
-	IssmDouble b_pos[NUMVERTICES];				// Hs-SMB relation parameter
-	IssmDouble b_neg[NUMVERTICES];				// Hs-SMB relation paremeter
-	IssmDouble Href[NUMVERTICES];					// reference elevation from which deviations are used to calculate the SMB adjustment
-	IssmDouble Smbref[NUMVERTICES];				// reference SMB to which deviations are added
-   IssmDouble rho_water;                   // density of fresh water
-	IssmDouble rho_ice;                     // density of ice
-
-	// output
-	IssmDouble smb[NUMVERTICES];					// surface mass balance (m/yr ice)
-
-	/*Recover SmbGradients*/
-	GetInputListOnVertices(&Href[0],SurfaceforcingsHrefEnum);
-	GetInputListOnVertices(&Smbref[0],SurfaceforcingsSmbrefEnum);
-	GetInputListOnVertices(&b_pos[0],SurfaceforcingsBPosEnum);
-	GetInputListOnVertices(&b_neg[0],SurfaceforcingsBNegEnum);
-
-   /*Recover surface elevatio at vertices: */
-	GetInputListOnVertices(&h[0],ThicknessEnum);
-	GetInputListOnVertices(&s[0],SurfaceEnum);
-
-   /*Get material parameters :*/
-   rho_ice=matpar->GetRhoIce();
-   rho_water=matpar->GetRhoFreshwater();
-
-   // loop over all vertices
- for(i=0;i<NUMVERTICES;i++){
-     if(Smbref[i]>0){
-		  smb[i]=Smbref[i]+b_pos[i]*(s[i]-Href[i]);
-	  }
-	  else{
-		  smb[i]=Smbref[i]+b_neg[i]*(s[i]-Href[i]);
-	  }
-	  smb[i]=smb[i]/rho_ice;      // SMB in m/y ice		
-	}  //end of the loop over the vertices
-	  /*Update inputs*/
-	  this->inputs->AddInput(new PentaInput(SurfaceforcingsMassBalanceEnum,&smb[0],P1Enum));
-}
-/*}}}*/
 IssmDouble Penta::SurfaceArea(void){/*{{{*/
 
@@ -2096,7 +2052,7 @@
 
 	/*Get for Vx and Vy, the max of abs value: */
-	this->MaxAbsVx(&maxabsvx);
-	this->MaxAbsVy(&maxabsvy);
-	this->MaxAbsVz(&maxabsvz);
+	maxabsvx = this->inputs->MaxAbs(VxEnum);
+	maxabsvy = this->inputs->MaxAbs(VyEnum);
+	maxabsvz = this->inputs->MaxAbs(VzEnum);
 
 	/* Get node coordinates and dof list: */
@@ -2148,5 +2104,5 @@
 
 	/*Recover element type*/
-	this->SetElementType(finiteelement_type,analysis_counter);
+	this->element_type_list[analysis_counter]=finiteelement_type;
 
 	/*Recover vertices ids needed to initialize inputs*/
@@ -2277,4 +2233,27 @@
 			penta_node_ids[17]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elementtofaceconnectivity[5*index+4]+1;
 			break;
+		case P2bubbleEnum: case P2bubblecondensedEnum:
+			numnodes         = 19;
+			penta_node_ids   = xNew<int>(numnodes);
+			penta_node_ids[ 0]=iomodel->nodecounter+iomodel->elements[6*index+0];
+			penta_node_ids[ 1]=iomodel->nodecounter+iomodel->elements[6*index+1];
+			penta_node_ids[ 2]=iomodel->nodecounter+iomodel->elements[6*index+2];
+			penta_node_ids[ 3]=iomodel->nodecounter+iomodel->elements[6*index+3];
+			penta_node_ids[ 4]=iomodel->nodecounter+iomodel->elements[6*index+4];
+			penta_node_ids[ 5]=iomodel->nodecounter+iomodel->elements[6*index+5];
+			penta_node_ids[ 6]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+0]+1;
+			penta_node_ids[ 7]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+1]+1;
+			penta_node_ids[ 8]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+2]+1;
+			penta_node_ids[ 9]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+3]+1;
+			penta_node_ids[10]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+4]+1;
+			penta_node_ids[11]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+5]+1;
+			penta_node_ids[12]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+6]+1;
+			penta_node_ids[13]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+7]+1;
+			penta_node_ids[14]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+8]+1;
+			penta_node_ids[15]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elementtofaceconnectivity[5*index+2]+1;
+			penta_node_ids[16]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elementtofaceconnectivity[5*index+3]+1;
+			penta_node_ids[17]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elementtofaceconnectivity[5*index+4]+1;
+			penta_node_ids[18]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberoffaces+index+1;
+			break;
 		case P1P1Enum: case P1P1GLSEnum:
 			numnodes         = 12;
@@ -2340,4 +2319,26 @@
 			penta_node_ids[22]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberoffaces+iomodel->elements[6*index+4];
 			penta_node_ids[23]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberoffaces+iomodel->elements[6*index+5];
+			break;
+		case LATaylorHoodEnum:
+			numnodes         = 18;
+			penta_node_ids   = xNew<int>(numnodes);
+			penta_node_ids[ 0]=iomodel->nodecounter+iomodel->elements[6*index+0];
+			penta_node_ids[ 1]=iomodel->nodecounter+iomodel->elements[6*index+1];
+			penta_node_ids[ 2]=iomodel->nodecounter+iomodel->elements[6*index+2];
+			penta_node_ids[ 3]=iomodel->nodecounter+iomodel->elements[6*index+3];
+			penta_node_ids[ 4]=iomodel->nodecounter+iomodel->elements[6*index+4];
+			penta_node_ids[ 5]=iomodel->nodecounter+iomodel->elements[6*index+5];
+			penta_node_ids[ 6]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+0]+1;
+			penta_node_ids[ 7]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+1]+1;
+			penta_node_ids[ 8]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+2]+1;
+			penta_node_ids[ 9]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+3]+1;
+			penta_node_ids[10]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+4]+1;
+			penta_node_ids[11]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+5]+1;
+			penta_node_ids[12]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+6]+1;
+			penta_node_ids[13]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+7]+1;
+			penta_node_ids[14]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+8]+1;
+			penta_node_ids[15]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elementtofaceconnectivity[5*index+2]+1;
+			penta_node_ids[16]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elementtofaceconnectivity[5*index+3]+1;
+			penta_node_ids[17]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elementtofaceconnectivity[5*index+4]+1;
 			break;
 		case OneLayerP4zEnum:
@@ -2382,4 +2383,34 @@
 			penta_node_ids[35]=iomodel->nodecounter+iomodel->numberofvertices+3*iomodel->numberofedges+3*iomodel->numberoffaces+iomodel->elements[6*index+5];
 			break;
+		case CrouzeixRaviartEnum:
+			numnodes         = 25;
+			penta_node_ids   = xNew<int>(numnodes);
+			penta_node_ids[ 0]=iomodel->nodecounter+iomodel->elements[6*index+0];
+			penta_node_ids[ 1]=iomodel->nodecounter+iomodel->elements[6*index+1];
+			penta_node_ids[ 2]=iomodel->nodecounter+iomodel->elements[6*index+2];
+			penta_node_ids[ 3]=iomodel->nodecounter+iomodel->elements[6*index+3];
+			penta_node_ids[ 4]=iomodel->nodecounter+iomodel->elements[6*index+4];
+			penta_node_ids[ 5]=iomodel->nodecounter+iomodel->elements[6*index+5];
+			penta_node_ids[ 6]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+0]+1;
+			penta_node_ids[ 7]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+1]+1;
+			penta_node_ids[ 8]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+2]+1;
+			penta_node_ids[ 9]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+3]+1;
+			penta_node_ids[10]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+4]+1;
+			penta_node_ids[11]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+5]+1;
+			penta_node_ids[12]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+6]+1;
+			penta_node_ids[13]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+7]+1;
+			penta_node_ids[14]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+8]+1;
+			penta_node_ids[15]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elementtofaceconnectivity[5*index+2]+1;
+			penta_node_ids[16]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elementtofaceconnectivity[5*index+3]+1;
+			penta_node_ids[17]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elementtofaceconnectivity[5*index+4]+1;
+			penta_node_ids[18]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberoffaces+index+1;
+
+			penta_node_ids[19]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberoffaces+iomodel->numberofelements+6*index+1;
+			penta_node_ids[20]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberoffaces+iomodel->numberofelements+6*index+2;
+			penta_node_ids[21]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberoffaces+iomodel->numberofelements+6*index+3;
+			penta_node_ids[22]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberoffaces+iomodel->numberofelements+6*index+4;
+			penta_node_ids[23]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberoffaces+iomodel->numberofelements+6*index+5;
+			penta_node_ids[24]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberoffaces+iomodel->numberofelements+6*index+6;
+			break;
 		default:
 			_error_("Finite element "<<EnumToStringx(finiteelement_type)<<" not supported yet");
@@ -2445,5 +2476,5 @@
 
 	GaussPenta* gauss=new GaussPenta();
-	for(int iv=0;iv<this->NumberofNodes();iv++){
+	for(int iv=0;iv<this->NumberofNodes(this->element_type);iv++){
 		gauss->GaussNode(this->element_type,iv);
 		onbase->GetInputValue(&isonbase,gauss);
@@ -2483,5 +2514,5 @@
 /*}}}*/
 void       Penta::ValueP1DerivativesOnGauss(IssmDouble* dvalue,IssmDouble* values,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-	PentaRef::GetInputDerivativeValue(dvalue,values,xyz_list,gauss);
+	PentaRef::GetInputDerivativeValue(dvalue,values,xyz_list,gauss,P1Enum);
 }
 /*}}}*/
@@ -2521,9 +2552,9 @@
 /*}}}*/
 int        Penta::VelocityInterpolation(void){/*{{{*/
-	return PentaRef::VelocityInterpolation();
+	return PentaRef::VelocityInterpolation(this->element_type);
 }
 /*}}}*/
 int        Penta::PressureInterpolation(void){/*{{{*/
-	return PentaRef::PressureInterpolation();
+	return PentaRef::PressureInterpolation(this->element_type);
 }
 /*}}}*/
@@ -2621,40 +2652,4 @@
 }
 /*}}}*/
-void       Penta::MinVel(IssmDouble* pminvel){/*{{{*/
-
-	/*Get minimum:*/
-	IssmDouble minvel=this->inputs->Min(VelEnum);
-
-	/*Assign output pointers:*/
-	*pminvel=minvel;
-}
-/*}}}*/
-void       Penta::MinVx(IssmDouble* pminvx){/*{{{*/
-
-	/*Get minimum:*/
-	IssmDouble minvx=this->inputs->Min(VxEnum);
-
-	/*Assign output pointers:*/
-	*pminvx=minvx;
-}
-/*}}}*/
-void       Penta::MinVy(IssmDouble* pminvy){/*{{{*/
-
-	/*Get minimum:*/
-	IssmDouble minvy=this->inputs->Min(VyEnum);
-
-	/*Assign output pointers:*/
-	*pminvy=minvy;
-}
-/*}}}*/
-void       Penta::MinVz(IssmDouble* pminvz){/*{{{*/
-
-	/*Get minimum:*/
-	IssmDouble minvz=this->inputs->Min(VzEnum);
-
-	/*Assign output pointers:*/
-	*pminvz=minvz;
-}
-/*}}}*/
 IssmDouble Penta::MassFlux( IssmDouble* segment){/*{{{*/
 
@@ -2701,68 +2696,4 @@
 	/*clean up and return*/
 	return mass_flux;
-}
-/*}}}*/
-void       Penta::MaxAbsVx(IssmDouble* pmaxabsvx){/*{{{*/
-
-	/*Get maximum:*/
-	IssmDouble maxabsvx=this->inputs->MaxAbs(VxEnum);
-
-	/*Assign output pointers:*/
-	*pmaxabsvx=maxabsvx;
-}
-/*}}}*/
-void       Penta::MaxAbsVy(IssmDouble* pmaxabsvy){/*{{{*/
-
-	/*Get maximum:*/
-	IssmDouble maxabsvy=this->inputs->MaxAbs(VyEnum);
-
-	/*Assign output pointers:*/
-	*pmaxabsvy=maxabsvy;
-}
-/*}}}*/
-void       Penta::MaxAbsVz(IssmDouble* pmaxabsvz){/*{{{*/
-
-	/*Get maximum:*/
-	IssmDouble maxabsvz=this->inputs->MaxAbs(VzEnum);
-
-	/*Assign output pointers:*/
-	*pmaxabsvz=maxabsvz;
-}
-/*}}}*/
-void       Penta::MaxVel(IssmDouble* pmaxvel){/*{{{*/
-
-	/*Get maximum:*/
-	IssmDouble maxvel=this->inputs->Max(VelEnum);
-
-	/*Assign output pointers:*/
-	*pmaxvel=maxvel;
-
-}
-/*}}}*/
-void       Penta::MaxVx(IssmDouble* pmaxvx){/*{{{*/
-
-	/*Get maximum:*/
-	IssmDouble maxvx=this->inputs->Max(VxEnum);
-
-	/*Assign output pointers:*/
-	*pmaxvx=maxvx;
-}
-/*}}}*/
-void       Penta::MaxVy(IssmDouble* pmaxvy){/*{{{*/
-
-	/*Get maximum:*/
-	IssmDouble maxvy=this->inputs->Max(VyEnum);
-
-	/*Assign output pointers:*/
-	*pmaxvy=maxvy;
-}
-/*}}}*/
-void       Penta::MaxVz(IssmDouble* pmaxvz){/*{{{*/
-
-	/*Get maximum:*/
-	IssmDouble maxvz=this->inputs->Max(VzEnum);
-
-	/*Assign output pointers:*/
-	*pmaxvz=maxvz;
 }
 /*}}}*/
@@ -2833,45 +2764,4 @@
 #endif
 
-void       Penta::ControlInputGetGradient(Vector<IssmDouble>* gradient,int enum_type,int control_index){/*{{{*/
-
-	int vertexpidlist[NUMVERTICES];
-	Input* input=NULL;
-
-	if(enum_type==MaterialsRheologyBbarEnum){
-		if(!IsOnBase()) return;
-		input=(Input*)inputs->GetInput(MaterialsRheologyBEnum);
-	}
-	else if(enum_type==DamageDbarEnum){
-		if(!IsOnBase()) return;
-		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);
-	((ControlInput*)input)->GetGradient(gradient,&vertexpidlist[0]);
-
-}/*}}}*/
-void       Penta::ControlInputScaleGradient(int enum_type,IssmDouble scale){/*{{{*/
-
-	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");
-
-	((ControlInput*)input)->ScaleGradient(scale);
-}/*}}}*/
 void       Penta::ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index){/*{{{*/
 
@@ -2940,336 +2830,4 @@
 
 }/*}}}*/
-void       Penta::GradientIndexing(int* indexing,int control_index){/*{{{*/
-
-	/*Get some parameters*/
-	int num_controls;
-	parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
-
-	/*get gradient indices*/
-	for(int i=0;i<NUMVERTICES;i++){
-		indexing[i]=num_controls*this->vertices[i]->Pid() + control_index;
-	}
-
-}
-/*}}}*/
-void       Penta::Gradj(Vector<IssmDouble>* gradient,int control_type,int control_index){/*{{{*/
-	/*dJ/dalpha = ∂L/∂alpha = ∂J/∂alpha + ∂/∂alpha(KU-F)*/
-
-	int   approximation;
-	Tria* tria=NULL;
-
-	/*If on water, skip grad (=0): */
-	if(!IsIceInElement())return;
-					
-	/*First deal with ∂/∂alpha(KU-F)*/
-	switch(control_type){
-
-		case FrictionCoefficientEnum:
-			inputs->GetInputValue(&approximation,ApproximationEnum);
-			switch(approximation){
-				case SSAApproximationEnum:
-					GradjDragSSA(gradient,control_index);
-					break;
-				case HOApproximationEnum:
-					GradjDragHO(gradient,control_index);
-					break;
-				case FSApproximationEnum:
-					GradjDragFS(gradient,control_index);
-					break;
-				case NoneApproximationEnum:
-					/*Gradient is 0*/
-					break;
-				default:
-					_error_("approximation " << EnumToStringx(approximation) << " not supported yet");
-			}
-			break;
-
-		case MaterialsRheologyBbarEnum:
-			inputs->GetInputValue(&approximation,ApproximationEnum);
-			switch(approximation){
-				case SSAApproximationEnum:
-					GradjBbarSSA(gradient,control_index);
-					break;
-				case HOApproximationEnum:
-					GradjBbarHO(gradient,control_index);
-					break;
-				case FSApproximationEnum:
-					GradjBbarFS(gradient,control_index);
-					break;
-				case NoneApproximationEnum:
-					/*Gradient is 0*/
-					break;
-				default:
-					_error_("approximation " << EnumToStringx(approximation) << " not supported yet");
-			}
-			break;
-
-		default:
-			_error_("control type " << EnumToStringx(control_type) << " not supported yet: ");
-	}
-
-	/*Now deal with ∂J/∂alpha*/
-	int *responses = NULL;
-	int num_responses,resp;
-	this->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
-	this->parameters->FindParam(&responses,NULL,InversionCostFunctionsEnum);
-
-	for(resp=0;resp<num_responses;resp++) switch(responses[resp]){
-
-		case ThicknessAbsMisfitEnum:
-		case SurfaceAbsVelMisfitEnum:
-		case SurfaceRelVelMisfitEnum:
-		case SurfaceLogVelMisfitEnum:
-		case SurfaceLogVxVyMisfitEnum:
-		case SurfaceAverageVelMisfitEnum:
-			/*Nothing, J does not depends on the parameter being inverted for*/
-			break;
-		case DragCoefficientAbsGradientEnum:
-			if(IsOnBase()){
-				tria=(Tria*)SpawnTria(0,1,2);
-				tria->GradjDragGradient(gradient,control_index);
-				delete tria->material; delete tria;
-			}
-			break;
-		case RheologyBbarAbsGradientEnum:
-			if(IsOnBase()){
-				tria=(Tria*)SpawnTria(0,1,2);
-				tria->GradjBGradient(gradient,control_index);
-				delete tria->material; delete tria;
-			}
-			break;
-		default:
-			_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
-	}
-	xDelete<int>(responses);
-}
-/*}}}*/
-void       Penta::GradjDragSSA(Vector<IssmDouble>* gradient,int control_index){/*{{{*/
-
-	/*Gradient is 0 if on shelf or not on bed*/
-	if(IsFloating() || !IsOnBase()) return;
-
-	/*Spawn tria*/
-	Tria* tria=(Tria*)SpawnTria(0,1,2);
-	tria->GradjDragSSA(gradient,control_index);
-	delete tria->material; delete tria;
-
-} /*}}}*/
-void       Penta::GradjDragHO(Vector<IssmDouble>* gradient,int control_index){/*{{{*/
-
-	int        i,j;
-	int        analysis_type;
-	int        vertexpidlist[NUMVERTICES];
-	IssmDouble vx,vy,lambda,mu,alpha_complement,Jdet;
-	IssmDouble bed,thickness,Neff,drag;
-	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble xyz_list_tria[NUMVERTICES2D][3]={0.0};
-	IssmDouble dk[NDOF3]; 
-	IssmDouble grade_g[NUMVERTICES]={0.0};
-	IssmDouble grade_g_gaussian[NUMVERTICES];
-	IssmDouble basis[6];
-	Friction*  friction=NULL;
-	GaussPenta *gauss=NULL;
-
-	/*Gradient is 0 if on shelf or not on bed*/
-	if(IsFloating() || !IsOnBase()) return;
-
-	/*Retrieve all inputs and parameters*/
-	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
-	GradientIndexing(&vertexpidlist[0],control_index);
-	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
-	Input* adjointx_input=inputs->GetInput(AdjointxEnum);               _assert_(adjointx_input);
-	Input* adjointy_input=inputs->GetInput(AdjointyEnum);               _assert_(adjointy_input);
-	Input* vx_input=inputs->GetInput(VxEnum);                           _assert_(vx_input);
-	Input* vy_input=inputs->GetInput(VyEnum);                           _assert_(vy_input);
-	Input* dragcoefficient_input=inputs->GetInput(FrictionCoefficientEnum); _assert_(dragcoefficient_input);
-
-	/*Build frictoin element, needed later: */
-	friction=new Friction(this,2);
-
-	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussPenta(0,1,2,4);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-
-		GetTriaJacobianDeterminant(&Jdet, &xyz_list_tria[0][0],gauss);
-		GetNodalFunctionsP1(basis,gauss);
-
-		/*Build alpha_complement_list: */
-		friction->GetAlphaComplement(&alpha_complement,gauss);
-
-		dragcoefficient_input->GetInputValue(&drag, gauss);
-		adjointx_input->GetInputValue(&lambda, gauss);
-		adjointy_input->GetInputValue(&mu, gauss);
-		vx_input->GetInputValue(&vx,gauss);
-		vy_input->GetInputValue(&vy,gauss);
-		dragcoefficient_input->GetInputDerivativeValue(&dk[0],&xyz_list[0][0],gauss);
-
-		/*Build gradje_g_gaussian vector (actually -dJ/ddrag): */
-		for (i=0;i<NUMVERTICES;i++){
-			grade_g_gaussian[i]=-2*drag*alpha_complement*((lambda*vx+mu*vy))*Jdet*gauss->weight*basis[i];
-		}
-
-		/*Add gradje_g_gaussian vector to gradje_g: */
-		for(i=0;i<NUMVERTICES;i++){
-			_assert_(!xIsNan<IssmDouble>(grade_g[i]));
-			grade_g[i]+=grade_g_gaussian[i];
-		}
-	}
-	gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
-
-	/*Clean up and return*/
-	delete gauss;
-	delete friction;
-}
-/*}}}*/
-void       Penta::GradjDragFS(Vector<IssmDouble>* gradient,int control_index){/*{{{*/
-
-	int        i,j;
-	int        analysis_type;
-	int        vertexpidlist[NUMVERTICES];
-	IssmDouble bed,thickness,Neff;
-	IssmDouble lambda,mu,xi,Jdet,vx,vy,vz;
-	IssmDouble alpha_complement,drag;
-	IssmDouble surface_normal[3],bed_normal[3];
-	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble xyz_list_tria[NUMVERTICES2D][3]={0.0};
-	IssmDouble dk[NDOF3]; 
-	IssmDouble basis[6];
-	IssmDouble grade_g[NUMVERTICES]={0.0};
-	IssmDouble grade_g_gaussian[NUMVERTICES];
-	Friction*  friction=NULL;
-	GaussPenta* gauss=NULL;
-
-	/*Gradient is 0 if on shelf or not on bed*/
-	if(IsFloating() || !IsOnBase()) return;
-
-	/*Retrieve all inputs and parameters*/
-	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
-	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
-	GradientIndexing(&vertexpidlist[0],control_index);
-	Input* drag_input    =inputs->GetInput(FrictionCoefficientEnum); _assert_(drag_input);
-	Input* vx_input      =inputs->GetInput(VxEnum);                  _assert_(vx_input);
-	Input* vy_input      =inputs->GetInput(VyEnum);                  _assert_(vy_input);
-	Input* vz_input      =inputs->GetInput(VzEnum);                  _assert_(vz_input);
-	Input* adjointx_input=inputs->GetInput(AdjointxEnum);            _assert_(adjointx_input);
-	Input* adjointy_input=inputs->GetInput(AdjointyEnum);            _assert_(adjointy_input);
-	Input* adjointz_input=inputs->GetInput(AdjointzEnum);            _assert_(adjointz_input);
-
-	/*Build frictoin element, needed later: */
-	friction=new Friction(this,3);
-
-	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussPenta(0,1,2,4);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-
-		/*Recover alpha_complement and drag: */
-		friction->GetAlphaComplement(&alpha_complement,gauss);
-		drag_input->GetInputValue(&drag,gauss);
-
-		/*recover lambda mu and xi: */
-		adjointx_input->GetInputValue(&lambda,gauss);
-		adjointy_input->GetInputValue(&mu    ,gauss);
-		adjointz_input->GetInputValue(&xi    ,gauss);
-
-		/*recover vx vy and vz: */
-		vx_input->GetInputValue(&vx, gauss);
-		vy_input->GetInputValue(&vy, gauss);
-		vz_input->GetInputValue(&vz, gauss);
-
-		/*Get normal vector to the bed */
-		NormalTop(&surface_normal[0],&xyz_list_tria[0][0]);
-
-		bed_normal[0]=-surface_normal[0]; //Function is for upper surface, so the normal to the bed is the opposite of the result
-		bed_normal[1]=-surface_normal[1];
-		bed_normal[2]=-surface_normal[2];
-
-		/* Get Jacobian determinant: */
-		GetTriaJacobianDeterminant(&Jdet,&xyz_list_tria[0][0],gauss);
-		GetNodalFunctionsP1(basis, gauss);
-
-		/*Get k derivative: dk/dx */
-		drag_input->GetInputDerivativeValue(&dk[0],&xyz_list[0][0],gauss);
-
-		/*Build gradje_g_gaussian vector (actually -dJ/ddrag): */
-		for (i=0;i<NUMVERTICES;i++){
-			//standard gradient dJ/dki
-			grade_g_gaussian[i]=(
-						-lambda*(2*drag*alpha_complement*(vx - vz*bed_normal[0]*bed_normal[2]))
-						-mu    *(2*drag*alpha_complement*(vy - vz*bed_normal[1]*bed_normal[2]))
-						-xi    *(2*drag*alpha_complement*(-vx*bed_normal[0]*bed_normal[2]-vy*bed_normal[1]*bed_normal[2]))
-						)*Jdet*gauss->weight*basis[i]; 
-		}
-
-		/*Add gradje_g_gaussian vector to gradje_g: */
-		for( i=0; i<NUMVERTICES; i++)grade_g[i]+=grade_g_gaussian[i];
-	}
-
-	gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
-
-	delete friction;
-	delete gauss;
-}
-/*}}}*/
-void       Penta::GradjBbarSSA(Vector<IssmDouble>* gradient,int control_index){/*{{{*/
-
-	/*This element should be collapsed into a tria element at its base*/
-	if (!IsOnBase()) return; 
-
-	/*Depth Average B*/
-	this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum);
-	if(this->material->IsDamage())this->InputDepthAverageAtBase(DamageDEnum,DamageDbarEnum);
-
-	/*Collapse element to the base*/
-	Tria* tria=(Tria*)SpawnTria(0,1,2);
-	tria->GradjBSSA(gradient,control_index);
-	delete tria->material; delete tria;
-
-	/*delete Average B*/
-	this->inputs->DeleteInput(MaterialsRheologyBbarEnum);
-	this->inputs->DeleteInput(DamageDbarEnum);
-
-} /*}}}*/
-void       Penta::GradjBbarHO(Vector<IssmDouble>* gradient,int control_index){/*{{{*/
-
-	/*Gradient is computed on bed only (Bbar)*/
-	if (!IsOnBase()) return;
-
-	/*Depth Average B and D*/
-	this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum);
-	if(this->material->IsDamage())this->InputDepthAverageAtBase(DamageDEnum,DamageDbarEnum);
-
-	/*Collapse element to the base*/
-	Tria* tria=(Tria*)SpawnTria(0,1,2);
-	tria->GradjBSSA(gradient,control_index);    //We use SSA as an estimate for now
-	delete tria->material; delete tria;
-
-	/*delete Average B*/
-	this->inputs->DeleteInput(MaterialsRheologyBbarEnum);
-	this->inputs->DeleteInput(DamageDbarEnum);
-} /*}}}*/
-void       Penta::GradjBbarFS(Vector<IssmDouble>* gradient,int control_index){/*{{{*/
-
-	/*Gradient is computed on bed only (Bbar)*/
-	if (!IsOnBase()) return;
-
-	/*Depth Average B and D*/
-	this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum);
-	if(this->material->IsDamage())this->InputDepthAverageAtBase(DamageDEnum,DamageDbarEnum);
-
-	/*Collapse element to the base*/
-	Tria* tria=(Tria*)SpawnTria(0,1,2);
-	tria->GradjBSSA(gradient,control_index);    //We use SSA as an estimate for now
-	delete tria->material; delete tria;
-
-	/*delete Average B*/
-	this->inputs->DeleteInput(MaterialsRheologyBbarEnum);
-	this->inputs->DeleteInput(DamageDbarEnum);
-} /*}}}*/
 void       Penta::InputControlUpdate(IssmDouble scalar,bool save_parameter){/*{{{*/
 
@@ -3326,4 +2884,5 @@
 
 	/*Get input (either in element or material)*/
+	if(control_enum==MaterialsRheologyBbarEnum) control_enum=MaterialsRheologyBEnum;
 	Input* input=inputs->GetInput(control_enum);
 	if(!input) _error_("Input " << EnumToStringx(control_enum) << " not found in element");
@@ -3340,7 +2899,16 @@
 
 	IssmDouble  values[NUMVERTICES];
-	int     vertexpidlist[NUMVERTICES];
-	Input  *input     = NULL;
-	Input  *new_input = NULL;
+	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*/
@@ -3351,15 +2919,21 @@
 
 	/*Get values on vertices*/
-	for (int i=0;i<NUMVERTICES;i++){
+	for(int i=0;i<NUMVERTICES;i++){
 		values[i]=vector[vertexpidlist[i]];
 	}
-	new_input = new PentaInput(control_enum,values,P1Enum);
-	input=(Input*)this->inputs->GetInput(control_enum);   _assert_(input);
-
-	if (input->ObjectEnum()!=ControlInputEnum){
+	Input* new_input = new PentaInput(control_enum,values,P1Enum);
+	Input* input=(Input*)this->inputs->GetInput(control_enum);   _assert_(input);
+	if(input->ObjectEnum()!=ControlInputEnum){
 		_error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
 	}
 
 	((ControlInput*)input)->SetInput(new_input);
+
+	if(control_init==MaterialsRheologyBbarEnum){
+		this->InputExtrude(control_enum);
+	}
+	if(control_init==DamageDbarEnum){
+		this->InputExtrude(control_enum);
+	}
 }
 /*}}}*/
@@ -3538,8 +3112,5 @@
 
 	int        i,migration_style;
-	bool       oldfloating;
-	bool       floatingelement = false;
-	bool       groundedelement = false;
-	IssmDouble bed_hydro,yts,gl_melting_rate;
+	IssmDouble bed_hydro,yts;
 	IssmDouble rho_water,rho_ice,density;
 	IssmDouble h[NUMVERTICES],s[NUMVERTICES],b[NUMVERTICES],r[NUMVERTICES];
@@ -3550,5 +3121,4 @@
 	/*Recover info at the vertices: */
 	parameters->FindParam(&migration_style,GroundinglineMigrationEnum);
-	parameters->FindParam(&gl_melting_rate,GroundinglineMeltingRateEnum);
 	parameters->FindParam(&yts,ConstantsYtsEnum);
 	GetInputListOnVertices(&h[0],ThicknessEnum);
@@ -3560,5 +3130,4 @@
 	rho_ice     = matpar->GetRhoIce();
 	density     = rho_ice/rho_water;
-	oldfloating = this->IsFloating(); //figure out if the element is floating before starting to change everything
 
 	/*go through vertices, and update inputs, considering them to be PentaVertex type: */
@@ -3605,29 +3174,4 @@
 	this->InputExtrude(MaskGroundediceLevelsetEnum);
 
-	/*SubelementMigrationEnum: if one grounded, all grounded*/
-	if(migration_style==SubelementMigrationEnum || migration_style==SubelementMigration2Enum){
-		for(i=0;i<NUMVERTICES;i++){
-			if(phi[i]>0.){
-				groundedelement=true;
-				break;
-			}
-		}
-		floatingelement=!groundedelement;
-	}
-	else{
-		for(i=0;i<NUMVERTICES;i++){
-			if(phi[i]<=0.){
-				floatingelement=true;
-				break;
-			}
-		}
-	}
-
-   /*Add basal melting rate if element just ungrounded*/
-	if(!oldfloating && floatingelement==true){
-		for(i=0;i<NUMVERTICES;i++)melting[i]=gl_melting_rate/yts;
-		this->inputs->AddInput(new PentaInput(BasalforcingsMeltingRateEnum,&melting[0],P1Enum));
-	} 
-
 	/*Update inputs*/
 	this->inputs->AddInput(new PentaInput(SurfaceEnum,&s[0],P1Enum));
Index: issm/trunk/src/c/classes/Elements/Penta.h
===================================================================
--- issm/trunk/src/c/classes/Elements/Penta.h	(revision 18081)
+++ issm/trunk/src/c/classes/Elements/Penta.h	(revision 18301)
@@ -54,6 +54,4 @@
 		IssmDouble CharacteristicLength(void){_error_("not implemented yet");};
 		void   ComputeBasalStress(Vector<IssmDouble>* sigma_b);
-		void   ComputeStrainRate();
-		void   ComputeStrainRate(Vector<IssmDouble>* eps){_error_("not implemented yet");};
 		void   ComputeSigmaNN(){_error_("not implemented yet");};
 		void   ComputeStressTensor();
@@ -64,4 +62,5 @@
 		void   FSContactMigration(Vector<IssmDouble>* vertexgrounded,Vector<IssmDouble>* vertexfloating);
 		void   SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Materials* materials,Parameters* parameters);
+		void   ResetHooks();
 		void   Delta18oParameterization(void);
 		Penta* GetUpperPenta(void);
@@ -75,4 +74,5 @@
 		int    GetNodeIndex(Node* node);
 		int    GetNumberOfNodes(void);
+		int    GetNumberOfNodes(int enum_type);
 		int    GetNumberOfVertices(void);
 		void   GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution,int enum_type);
@@ -92,8 +92,8 @@
 		void   ZeroLevelsetCoordinates(IssmDouble** pxyz_zero,IssmDouble* xyz_list,int levelsetenum);
 		void   GetIcefrontCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum){_error_("not implemented yet");};
+		void   GetLevelCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum,IssmDouble level){_error_("not implemented yet");};
 		void   PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm);
 		void   ReduceMatrices(ElementMatrix* Ke,ElementVector* pe);
 		void   ResetFSBasalBoundaryCondition(void);
-		void   SmbGradients();
 		void   SetTemporaryElementType(int element_type_in);
 	   Element* SpawnBasalElement(void);
@@ -113,18 +113,7 @@
 		IssmDouble IceVolumeAboveFloatation(void);
 		IssmDouble TotalSmb(void);
-		void   MinVel(IssmDouble* pminvel);
-		void   MinVx(IssmDouble* pminvx);
-		void   MinVy(IssmDouble* pminvy);
-		void   MinVz(IssmDouble* pminvz);
 		IssmDouble MassFlux(IssmDouble* segment);
 		IssmDouble MassFlux(IssmDouble x1,IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id);
-		void   MaxAbsVx(IssmDouble* pmaxabsvx);
-		void   MaxAbsVy(IssmDouble* pmaxabsvy);
-		void   MaxAbsVz(IssmDouble* pmaxabsvz);
-		void   MaxVel(IssmDouble* pmaxvel);
 		void   ElementResponse(IssmDouble* presponse,int response_enum);
-		void   MaxVx(IssmDouble* pmaxvx);
-		void   MaxVy(IssmDouble* pmaxvy);
-		void   MaxVz(IssmDouble* pmaxvz);
 
 		#ifdef _HAVE_GIA_
@@ -132,16 +121,6 @@
 		#endif
 
-		void   GradientIndexing(int* indexing,int control_index);
-		void   Gradj(Vector<IssmDouble>* gradient,int control_type,int control_index);
-		void   GradjDragSSA(Vector<IssmDouble>* gradient,int control_index);
-		void   GradjDragHO(Vector<IssmDouble>* gradient,int control_index);
-		void   GradjDragFS(Vector<IssmDouble>* gradient,int control_index);
-		void   GradjBbarSSA(Vector<IssmDouble>* gradient,int control_index);
-		void   GradjBbarHO(Vector<IssmDouble>* gradient,int control_index);
-		void   GradjBbarFS(Vector<IssmDouble>* gradient,int control_index);
 		void   GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data);
 		void   SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index);
-		void   ControlInputGetGradient(Vector<IssmDouble>* gradient,int enum_type,int control_index);
-		void   ControlInputScaleGradient(int enum_type,IssmDouble scale);
 		void   ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index);
 		void   ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum);
@@ -186,4 +165,5 @@
 		void           NodalFunctions(IssmDouble* basis,Gauss* gauss);
 		void           NodalFunctionsP1(IssmDouble* basis,Gauss* gauss);
+		void           NodalFunctionsP2(IssmDouble* basis,Gauss* gauss);
 		void           NodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
 		void           NodalFunctionsP1Derivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
Index: issm/trunk/src/c/classes/Elements/PentaRef.cpp
===================================================================
--- issm/trunk/src/c/classes/Elements/PentaRef.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Elements/PentaRef.cpp	(revision 18301)
@@ -24,28 +24,12 @@
 #define NUMNODESP2xP1 12
 #define NUMNODESP2    18
+#define NUMNODESP2b   19
 #define NUMNODESP2xP4 30
 
 /*Object constructors and destructor*/
 PentaRef::PentaRef(){/*{{{*/
-	this->element_type_list=NULL;
-}
-/*}}}*/
-PentaRef::PentaRef(const int nummodels){/*{{{*/
-
-	/*Only allocate pointer*/
-	element_type_list=xNew<int>(nummodels);
-
 }
 /*}}}*/
 PentaRef::~PentaRef(){/*{{{*/
-	xDelete<int>(element_type_list);
-}
-/*}}}*/
-
-/*Management*/
-void PentaRef::SetElementType(int type,int type_counter){/*{{{*/
-
-	/*initialize element type*/
-	this->element_type_list[type_counter]=type;
 }
 /*}}}*/
@@ -167,12 +151,4 @@
 	/*Invert Jacobian matrix: */
 	Matrix3x3Invert(Jinv,&J[0][0]);
-}
-/*}}}*/
-void PentaRef::GetNodalFunctions(IssmDouble* basis,Gauss* gauss){/*{{{*/
-	/*This routine returns the values of the nodal functions  at the gaussian point.*/
-
-	_assert_(basis);
-	GetNodalFunctions(basis,gauss,this->element_type);
-
 }
 /*}}}*/
@@ -262,4 +238,30 @@
 			basis[16]=4.*gauss->coord3*gauss->coord1*(1.-zeta*zeta);
 			basis[17]=4.*gauss->coord1*gauss->coord2*(1.-zeta*zeta);
+			return;
+		case P2bubbleEnum: case P2bubblecondensedEnum:
+			/*Corner nodes*/
+			basis[ 0]=gauss->coord1*(2.*gauss->coord1-1.)*zeta*(zeta-1.)/2.;
+			basis[ 1]=gauss->coord2*(2.*gauss->coord2-1.)*zeta*(zeta-1.)/2.;
+			basis[ 2]=gauss->coord3*(2.*gauss->coord3-1.)*zeta*(zeta-1.)/2.;
+			basis[ 3]=gauss->coord1*(2.*gauss->coord1-1.)*zeta*(zeta+1.)/2.;
+			basis[ 4]=gauss->coord2*(2.*gauss->coord2-1.)*zeta*(zeta+1.)/2.;
+			basis[ 5]=gauss->coord3*(2.*gauss->coord3-1.)*zeta*(zeta+1.)/2.;
+			/*mid-sides of quads*/
+			basis[ 6]=gauss->coord1*(2.*gauss->coord1-1.)*(1.-zeta*zeta);
+			basis[ 7]=gauss->coord2*(2.*gauss->coord2-1.)*(1.-zeta*zeta);
+			basis[ 8]=gauss->coord3*(2.*gauss->coord3-1.)*(1.-zeta*zeta);
+			/*mid-sides of triangles*/
+			basis[ 9]=4.*gauss->coord3*gauss->coord2*zeta*(zeta-1.)/2.;
+			basis[10]=4.*gauss->coord3*gauss->coord1*zeta*(zeta-1.)/2.;
+			basis[11]=4.*gauss->coord1*gauss->coord2*zeta*(zeta-1.)/2.;
+			basis[12]=4.*gauss->coord3*gauss->coord2*zeta*(zeta+1.)/2.;
+			basis[13]=4.*gauss->coord3*gauss->coord1*zeta*(zeta+1.)/2.;
+			basis[14]=4.*gauss->coord1*gauss->coord2*zeta*(zeta+1.)/2.;
+			/*quad faces*/
+			basis[15]=4.*gauss->coord3*gauss->coord2*(1.-zeta*zeta);
+			basis[16]=4.*gauss->coord3*gauss->coord1*(1.-zeta*zeta);
+			basis[17]=4.*gauss->coord1*gauss->coord2*(1.-zeta*zeta);
+			/*bubble*/
+			basis[18]=27.*gauss->coord1*gauss->coord2*gauss->coord3*(1.+zeta)*(1.-zeta);
 			return;
 		case P2xP4Enum :
@@ -321,8 +323,4 @@
 }
 /*}}}*/
-void PentaRef::GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, Gauss* gauss){/*{{{*/
-	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss,this->element_type);
-}
-/*}}}*/
 void PentaRef::GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, Gauss* gauss,int finiteelement){/*{{{*/
 
@@ -356,8 +354,4 @@
 	/*Clean up*/
 	xDelete<IssmDouble>(dbasis_ref);
-}
-/*}}}*/
-void PentaRef::GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,Gauss* gauss){/*{{{*/
-	GetNodalFunctionsDerivativesReference(dbasis,gauss,this->element_type);
 }
 /*}}}*/
@@ -605,4 +599,86 @@
 			dbasis[NUMNODESP2*1+17] = (1.-zeta*zeta)*(-2.*SQRT3/3.*(gauss->coord1+gauss->coord2));
 			dbasis[NUMNODESP2*2+17] = -2.*zeta*4.*gauss->coord1*gauss->coord2;
+			return;
+		case P2bubbleEnum: case P2bubblecondensedEnum:
+			/*Nodal function 1*/
+			dbasis[NUMNODESP2b*0+0 ] = .5*zeta*(zeta-1.)*(-2.*gauss->coord1 + 0.5);
+			dbasis[NUMNODESP2b*1+0 ] = .5*zeta*(zeta-1.)*(-2.*SQRT3/3.*gauss->coord1 + SQRT3/6.);
+			dbasis[NUMNODESP2b*2+0 ] = .5*(2.*zeta-1.)*gauss->coord1*(2.*gauss->coord1-1.);
+			/*Nodal function 2*/
+			dbasis[NUMNODESP2b*0+1 ] = .5*zeta*(zeta-1.)*(+2.*gauss->coord2 - 0.5);
+			dbasis[NUMNODESP2b*1+1 ] = .5*zeta*(zeta-1.)*(-2.*SQRT3/3.*gauss->coord2 + SQRT3/6.);
+			dbasis[NUMNODESP2b*2+1 ] = .5*(2.*zeta-1.)*gauss->coord2*(2.*gauss->coord2-1.);
+			/*Nodal function 3*/
+			dbasis[NUMNODESP2b*0+2 ] = 0.;
+			dbasis[NUMNODESP2b*1+2 ] = .5*zeta*(zeta-1.)*(4.*SQRT3/3.*gauss->coord3 - SQRT3/3.);
+			dbasis[NUMNODESP2b*2+2 ] = .5*(2.*zeta-1.)*gauss->coord3*(2.*gauss->coord3-1.);
+			/*Nodal function 4*/
+			dbasis[NUMNODESP2b*0+3 ] = .5*zeta*(zeta+1.)*(-2.*gauss->coord1 + 0.5);
+			dbasis[NUMNODESP2b*1+3 ] = .5*zeta*(zeta+1.)*(-2.*SQRT3/3.*gauss->coord1 + SQRT3/6.);
+			dbasis[NUMNODESP2b*2+3 ] = .5*(2.*zeta+1.)*gauss->coord1*(2.*gauss->coord1-1.);
+			/*Nodal function 5*/
+			dbasis[NUMNODESP2b*0+4 ] = .5*zeta*(zeta+1.)*(+2.*gauss->coord2 - 0.5);
+			dbasis[NUMNODESP2b*1+4 ] = .5*zeta*(zeta+1.)*(-2.*SQRT3/3.*gauss->coord2 + SQRT3/6.);
+			dbasis[NUMNODESP2b*2+4 ] = .5*(2.*zeta+1.)*gauss->coord2*(2.*gauss->coord2-1.);
+			/*Nodal function 6*/
+			dbasis[NUMNODESP2b*0+5 ] = 0.;
+			dbasis[NUMNODESP2b*1+5 ] = .5*zeta*(zeta+1.)*(4.*SQRT3/3.*gauss->coord3 - SQRT3/3.);
+			dbasis[NUMNODESP2b*2+5 ] = .5*(2.*zeta+1.)*gauss->coord3*(2.*gauss->coord3-1.);
+
+			/*Nodal function 7*/
+			dbasis[NUMNODESP2b*0+6 ] = (-2.*gauss->coord1 + 0.5)*(1.-zeta*zeta);
+			dbasis[NUMNODESP2b*1+6 ] = (-2.*SQRT3/3.*gauss->coord1 + SQRT3/6.)*(1.-zeta*zeta);
+			dbasis[NUMNODESP2b*2+6 ] = -2.*zeta*gauss->coord1*(2.*gauss->coord1-1.);
+			/*Nodal function 8*/
+			dbasis[NUMNODESP2b*0+7 ] = (+2.*gauss->coord2 - 0.5)*(1.-zeta*zeta);
+			dbasis[NUMNODESP2b*1+7 ] = (-2.*SQRT3/3.*gauss->coord2 + SQRT3/6.)*(1.-zeta*zeta);
+			dbasis[NUMNODESP2b*2+7 ] = -2.*zeta*gauss->coord2*(2.*gauss->coord2-1.);
+			/*Nodal function 9*/
+			dbasis[NUMNODESP2b*0+8 ] = 0.;
+			dbasis[NUMNODESP2b*1+8 ] = (+4.*SQRT3/3.*gauss->coord3 - SQRT3/3.)*(1.-zeta*zeta);
+			dbasis[NUMNODESP2b*2+8 ] = -2.*zeta*gauss->coord3*(2.*gauss->coord3-1.);
+
+			/*Nodal function 10*/
+			dbasis[NUMNODESP2b*0+9 ] = zeta*(zeta-1.)*gauss->coord3;
+			dbasis[NUMNODESP2b*1+9 ] = .5*zeta*(zeta-1.)*(+4.*SQRT3/3.*gauss->coord2 - 2.*SQRT3/3.*gauss->coord3);
+			dbasis[NUMNODESP2b*2+9 ] = 2.*gauss->coord3*gauss->coord2*(2.*zeta-1.);
+			/*Nodal function 11*/
+			dbasis[NUMNODESP2b*0+10] = -zeta*(zeta-1.)*gauss->coord3;
+			dbasis[NUMNODESP2b*1+10] = .5*zeta*(zeta-1.)*(+4.*SQRT3/3.*gauss->coord1 - 2.*SQRT3/3.*gauss->coord3);
+			dbasis[NUMNODESP2b*2+10] = 2.*gauss->coord3*gauss->coord1*(2.*zeta-1.);
+			/*Nodal function 12*/
+			dbasis[NUMNODESP2b*0+11] = zeta*(zeta-1.)*(gauss->coord1-gauss->coord2);
+			dbasis[NUMNODESP2b*1+11] = .5*zeta*(zeta-1.)*(-2.*SQRT3/3.*(gauss->coord1+gauss->coord2));
+			dbasis[NUMNODESP2b*2+11] = 2.*gauss->coord1*gauss->coord2*(2.*zeta-1.);
+			/*Nodal function 13*/
+			dbasis[NUMNODESP2b*0+12] = zeta*(zeta+1.)*gauss->coord3;
+			dbasis[NUMNODESP2b*1+12] = .5*zeta*(zeta+1.)*(+4.*SQRT3/3.*gauss->coord2 - 2.*SQRT3/3.*gauss->coord3);
+			dbasis[NUMNODESP2b*2+12] = 2.*gauss->coord3*gauss->coord2*(2.*zeta+1.);
+			/*Nodal function 14*/
+			dbasis[NUMNODESP2b*0+13] = -zeta*(zeta+1.)*gauss->coord3;
+			dbasis[NUMNODESP2b*1+13] = .5*zeta*(zeta+1.)*(+4.*SQRT3/3.*gauss->coord1 - 2.*SQRT3/3.*gauss->coord3);
+			dbasis[NUMNODESP2b*2+13] = 2.*gauss->coord3*gauss->coord1*(2.*zeta+1.);
+			/*Nodal function 15*/
+			dbasis[NUMNODESP2b*0+14] = zeta*(zeta+1.)*(gauss->coord1-gauss->coord2);
+			dbasis[NUMNODESP2b*1+14] = .5*zeta*(zeta+1.)*(-2.*SQRT3/3.*(gauss->coord1+gauss->coord2));
+			dbasis[NUMNODESP2b*2+14] = 2.*gauss->coord1*gauss->coord2*(2.*zeta+1.);
+
+			/*Nodal function 16*/
+			dbasis[NUMNODESP2b*0+15] = 2.*gauss->coord3*(1.-zeta*zeta);
+			dbasis[NUMNODESP2b*1+15] = (1.-zeta*zeta)*(+4.*SQRT3/3.*gauss->coord2 - 2.*SQRT3/3.*gauss->coord3);
+			dbasis[NUMNODESP2b*2+15] = -2.*zeta*4.*gauss->coord3*gauss->coord2;
+			/*Nodal function 17*/
+			dbasis[NUMNODESP2b*0+16] = -2.*gauss->coord3*(1.-zeta*zeta);
+			dbasis[NUMNODESP2b*1+16] = (1.-zeta*zeta)*(+4.*SQRT3/3.*gauss->coord1 - 2.*SQRT3/3.*gauss->coord3);
+			dbasis[NUMNODESP2b*2+16] = -2.*zeta*4.*gauss->coord3*gauss->coord1;
+			/*Nodal function 18*/
+			dbasis[NUMNODESP2b*0+17] = 2.*(gauss->coord1-gauss->coord2)*(1.-zeta*zeta);
+			dbasis[NUMNODESP2b*1+17] = (1.-zeta*zeta)*(-2.*SQRT3/3.*(gauss->coord1+gauss->coord2));
+			dbasis[NUMNODESP2b*2+17] = -2.*zeta*4.*gauss->coord1*gauss->coord2;
+
+			/*Nodal function 19*/
+			dbasis[NUMNODESP2b*0+18] = 27.*(1.+zeta)*(1.-zeta)*(-.5*gauss->coord2*gauss->coord3 + .5*gauss->coord1*gauss->coord3);
+			dbasis[NUMNODESP2b*1+18] = 27.*(1.+zeta)*(1.-zeta)*SQRT3*(-1./6.*gauss->coord2*gauss->coord3 - 1./6.*gauss->coord1*gauss->coord3 +1./3.*gauss->coord1*gauss->coord2);
+			dbasis[NUMNODESP2b*2+18] = -54*gauss->coord1*gauss->coord2*gauss->coord3*zeta;
 			return;
 		case P2xP4Enum :
@@ -784,155 +860,4 @@
 }
 /*}}}*/
-void PentaRef::GetNodalFunctionsMINIDerivatives(IssmDouble* dbasismini,IssmDouble* xyz_list, Gauss* gauss){/*{{{*/
-
-	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
-	 * actual coordinate system): */
-
-	IssmDouble    dbasismini_ref[3][NUMNODESP1b];
-	IssmDouble    Jinv[3][3];
-
-	/*Get derivative values with respect to parametric coordinate system: */
-	GetNodalFunctionsMINIDerivativesReference(&dbasismini_ref[0][0], gauss); 
-
-	/*Get Jacobian invert: */
-	GetJacobianInvert(&Jinv[0][0], xyz_list, gauss);
-
-	/*Build dbasis: 
-	 *
-	 * [dhi/dx]= Jinv'*[dhi/dr]
-	 * [dhi/dy]        [dhi/ds]
-	 * [dhi/dz]        [dhi/dzeta]
-	 */
-
-	for(int i=0;i<NUMNODESP1b;i++){
-		*(dbasismini+NUMNODESP1b*0+i)=Jinv[0][0]*dbasismini_ref[0][i]+Jinv[0][1]*dbasismini_ref[1][i]+Jinv[0][2]*dbasismini_ref[2][i];
-		*(dbasismini+NUMNODESP1b*1+i)=Jinv[1][0]*dbasismini_ref[0][i]+Jinv[1][1]*dbasismini_ref[1][i]+Jinv[1][2]*dbasismini_ref[2][i];
-		*(dbasismini+NUMNODESP1b*2+i)=Jinv[2][0]*dbasismini_ref[0][i]+Jinv[2][1]*dbasismini_ref[1][i]+Jinv[2][2]*dbasismini_ref[2][i];
-	}
-
-}
-/*}}}*/
-void PentaRef::GetNodalFunctionsMINIDerivativesReference(IssmDouble* dbasis,Gauss* gauss_in){/*{{{*/
-	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
-	 * natural coordinate system) at the gaussian point. */
-
-	/*Cast gauss to GaussPenta*/
-	_assert_(gauss_in->Enum()==GaussPentaEnum);
-	GaussPenta* gauss = dynamic_cast<GaussPenta*>(gauss_in);
-
-
-	IssmDouble zeta=gauss->coord4;
-
-	/*Nodal function 1*/
-	dbasis[NUMNODESP1b*0+0]=-0.5*(1.0-zeta)/2.0;
-	dbasis[NUMNODESP1b*1+0]=-SQRT3/6.0*(1.0-zeta)/2.0;
-	dbasis[NUMNODESP1b*2+0]=-0.5*gauss->coord1;
-	/*Nodal function 2*/
-	dbasis[NUMNODESP1b*0+1]=0.5*(1.0-zeta)/2.0;
-	dbasis[NUMNODESP1b*1+1]=-SQRT3/6.0*(1.0-zeta)/2.0;
-	dbasis[NUMNODESP1b*2+1]=-0.5*gauss->coord2;
-	/*Nodal function 3*/
-	dbasis[NUMNODESP1b*0+2]=0.;
-	dbasis[NUMNODESP1b*1+2]=SQRT3/3.0*(1.0-zeta)/2.0;
-	dbasis[NUMNODESP1b*2+2]=-0.5*gauss->coord3;
-	/*Nodal function 4*/
-	dbasis[NUMNODESP1b*0+3]=-0.5*(1.0+zeta)/2.0;
-	dbasis[NUMNODESP1b*1+3]=-SQRT3/6.0*(1.0+zeta)/2.0;
-	dbasis[NUMNODESP1b*2+3]=0.5*gauss->coord1;
-	/*Nodal function 5*/
-	dbasis[NUMNODESP1b*0+4]=0.5*(1.0+zeta)/2.0;
-	dbasis[NUMNODESP1b*1+4]=-SQRT3/6.0*(1.0+zeta)/2.0;
-	dbasis[NUMNODESP1b*2+4]=0.5*gauss->coord2;
-	/*Nodal function 6*/
-	dbasis[NUMNODESP1b*0+5]=0.;
-	dbasis[NUMNODESP1b*1+5]=SQRT3/3.0*(1.0+zeta)/2.0;
-	dbasis[NUMNODESP1b*2+5]=0.5*gauss->coord3;
-	/*Nodal function 7*/
-	dbasis[NUMNODESP1b*0+6]=27.*(1.+zeta)*(1.-zeta)*(-.5*gauss->coord2*gauss->coord3 + .5*gauss->coord1*gauss->coord3);
-	dbasis[NUMNODESP1b*1+6]=27.*(1.+zeta)*(1.-zeta)*SQRT3*(-1./6.*gauss->coord2*gauss->coord3 - 1./6.*gauss->coord1*gauss->coord3 +1./3.*gauss->coord1*gauss->coord2);
-	dbasis[NUMNODESP1b*2+6]=27*gauss->coord1*gauss->coord2*gauss->coord3*(-2.0*zeta);
-}
-/*}}}*/
-void PentaRef::GetNodalFunctionsP1(IssmDouble* basis, Gauss* gauss_in){/*{{{*/
-	/*This routine returns the values of the nodal functions  at the gaussian point.*/
-
-	/*Cast gauss to GaussPenta*/
-	_assert_(gauss_in->Enum()==GaussPentaEnum);
-	GaussPenta* gauss = dynamic_cast<GaussPenta*>(gauss_in);
-
-	basis[0]=gauss->coord1*(1-gauss->coord4)/2.0;
-	basis[1]=gauss->coord2*(1-gauss->coord4)/2.0;
-	basis[2]=gauss->coord3*(1-gauss->coord4)/2.0;
-	basis[3]=gauss->coord1*(1+gauss->coord4)/2.0;
-	basis[4]=gauss->coord2*(1+gauss->coord4)/2.0;
-	basis[5]=gauss->coord3*(1+gauss->coord4)/2.0;
-
-}
-/*}}}*/
-void PentaRef::GetNodalFunctionsP1Derivatives(IssmDouble* dbasis,IssmDouble* xyz_list, Gauss* gauss){/*{{{*/
-
-	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
-	 * actual coordinate system): */
-	IssmDouble    dbasis_ref[NDOF3][NUMNODESP1];
-	IssmDouble    Jinv[NDOF3][NDOF3];
-
-	/*Get derivative values with respect to parametric coordinate system: */
-	GetNodalFunctionsP1DerivativesReference(&dbasis_ref[0][0], gauss); 
-
-	/*Get Jacobian invert: */
-	GetJacobianInvert(&Jinv[0][0], xyz_list, gauss);
-
-	/*Build dh1dh3: 
-	 *
-	 * [dhi/dx]= Jinv*[dhi/dr]
-	 * [dhi/dy]       [dhi/ds]
-	 * [dhi/dz]       [dhi/dn]
-	 */
-
-	for (int i=0;i<NUMNODESP1;i++){
-		*(dbasis+NUMNODESP1*0+i)=Jinv[0][0]*dbasis_ref[0][i]+Jinv[0][1]*dbasis_ref[1][i]+Jinv[0][2]*dbasis_ref[2][i];
-		*(dbasis+NUMNODESP1*1+i)=Jinv[1][0]*dbasis_ref[0][i]+Jinv[1][1]*dbasis_ref[1][i]+Jinv[1][2]*dbasis_ref[2][i];
-		*(dbasis+NUMNODESP1*2+i)=Jinv[2][0]*dbasis_ref[0][i]+Jinv[2][1]*dbasis_ref[1][i]+Jinv[2][2]*dbasis_ref[2][i];
-	}
-
-}
-/*}}}*/
-void PentaRef::GetNodalFunctionsP1DerivativesReference(IssmDouble* dbasis,Gauss* gauss_in){/*{{{*/
-
-	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
-	 * natural coordinate system) at the gaussian point. Those values vary along xi,eta,z */
-
-	/*Cast gauss to GaussPenta*/
-	_assert_(gauss_in->Enum()==GaussPentaEnum);
-	GaussPenta* gauss = dynamic_cast<GaussPenta*>(gauss_in);
-
-	IssmDouble zeta=gauss->coord4;
-
-	/*Nodal function 1*/
-	dbasis[NUMNODESP1*0+0]=-0.5*(1.0-zeta)/2.0;
-	dbasis[NUMNODESP1*1+0]=-SQRT3/6.0*(1.0-zeta)/2.0;
-	dbasis[NUMNODESP1*2+0]=-0.5*gauss->coord1;
-	/*Nodal function 2*/
-	dbasis[NUMNODESP1*0+1]=0.5*(1.0-zeta)/2.0;
-	dbasis[NUMNODESP1*1+1]=-SQRT3/6.0*(1.0-zeta)/2.0;
-	dbasis[NUMNODESP1*2+1]=-0.5*gauss->coord2;
-	/*Nodal function 3*/
-	dbasis[NUMNODESP1*0+2]=0.;
-	dbasis[NUMNODESP1*1+2]=SQRT3/3.0*(1.0-zeta)/2.0;
-	dbasis[NUMNODESP1*2+2]=-0.5*gauss->coord3;
-	/*Nodal function 4*/
-	dbasis[NUMNODESP1*0+3]=-0.5*(1.0+zeta)/2.0;
-	dbasis[NUMNODESP1*1+3]=-SQRT3/6.0*(1.0+zeta)/2.0;
-	dbasis[NUMNODESP1*2+3]=0.5*gauss->coord1;
-	/*Nodal function 5*/
-	dbasis[NUMNODESP1*0+4]=0.5*(1.0+zeta)/2.0;
-	dbasis[NUMNODESP1*1+4]=-SQRT3/6.0*(1.0+zeta)/2.0;
-	dbasis[NUMNODESP1*2+4]=0.5*gauss->coord2;
-	/*Nodal function 6*/
-	dbasis[NUMNODESP1*0+5]=0.;
-	dbasis[NUMNODESP1*1+5]=SQRT3/3.0*(1.0+zeta)/2.0;
-	dbasis[NUMNODESP1*2+5]=0.5*gauss->coord3;
-}
-/*}}}*/
 void PentaRef::GetQuadJacobianDeterminant(IssmDouble* Jdet,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*This routine returns the values of the nodal functions  at the gaussian point.*/
@@ -960,10 +885,4 @@
 }
 /*}}}*/
-void PentaRef::GetInputValue(IssmDouble* pvalue,IssmDouble* plist,Gauss* gauss){/*{{{*/
-
-	GetInputValue(pvalue,plist,gauss,this->element_type);
-
-}
-/*}}}*/
 void PentaRef::GetInputValue(IssmDouble* pvalue,IssmDouble* plist,Gauss* gauss,int finiteelement){/*{{{*/
 
@@ -987,5 +906,5 @@
 }
 /*}}}*/
-void PentaRef::GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, Gauss* gauss){/*{{{*/
+void PentaRef::GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, Gauss* gauss,int finiteelement){/*{{{*/
 	/*From node values of parameter p (p_list[0], p_list[1], p_list[2],
 	 * p_list[3], p_list[4] and p_list[4]), return parameter derivative value at
@@ -1004,9 +923,9 @@
 
 	/*Fetch number of nodes for this finite element*/
-	int numnodes = this->NumberofNodes();
+	int numnodes = this->NumberofNodes(finiteelement);
 
 	/*Get nodal functions derivatives*/
 	IssmDouble* dbasis=xNew<IssmDouble>(3*numnodes);
-	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss,finiteelement);
 
 	/*Calculate parameter for this Gauss point*/
@@ -1023,19 +942,20 @@
 }
 /*}}}*/
-int  PentaRef::NumberofNodes(void){/*{{{*/
-
-	return this->NumberofNodes(this->element_type);
-}
-/*}}}*/
 int  PentaRef::NumberofNodes(int finiteelement){/*{{{*/
 
 	switch(finiteelement){
+		case NoneEnum:              return 0;
 		case P0Enum:                return NUMNODESP0;
 		case P1Enum:                return NUMNODESP1;
+		case P1DGEnum:              return NUMNODESP1;
 		case P1bubbleEnum:          return NUMNODESP1b;
 		case P1bubblecondensedEnum: return NUMNODESP1b;
 		case P2Enum:                return NUMNODESP2;
+		case P2bubbleEnum:          return NUMNODESP2b;
+		case P2bubblecondensedEnum: return NUMNODESP2b;
 		case P2xP1Enum:             return NUMNODESP2xP1;
 		case P1xP2Enum:             return NUMNODESP1xP2;
+		case P2xP4Enum:             return NUMNODESP2xP4;
+		case P1xP3Enum:             return NUMNODESP1xP3;
 		case P1P1Enum:              return NUMNODESP1*2;
 		case P1P1GLSEnum:           return NUMNODESP1*2;
@@ -1043,8 +963,8 @@
 		case MINIEnum:              return NUMNODESP1b+NUMNODESP1;
 		case TaylorHoodEnum:        return NUMNODESP2+NUMNODESP1;
+		case LATaylorHoodEnum:      return NUMNODESP2;
 		case OneLayerP4zEnum:       return NUMNODESP2xP4+NUMNODESP1;
-		case P2xP4Enum:             return NUMNODESP2xP4;
-		case P1xP3Enum:             return NUMNODESP1xP3;
-		default:       _error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+		case CrouzeixRaviartEnum:   return NUMNODESP2b+NUMNODESP1;
+		default:       _error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
 	}
 
@@ -1052,14 +972,16 @@
 }
 /*}}}*/
-int  PentaRef::VelocityInterpolation(void){/*{{{*/
-
-	switch(this->element_type){
-		case P1P1Enum:          return P1Enum;
-		case P1P1GLSEnum:       return P1Enum;
-		case MINIcondensedEnum: return P1bubbleEnum;
-		case MINIEnum:          return P1bubbleEnum;
-		case TaylorHoodEnum:    return P2Enum;
-		case OneLayerP4zEnum:   return P2xP4Enum;
-		default:       _error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+int  PentaRef::VelocityInterpolation(int fe_stokes){/*{{{*/
+
+	switch(fe_stokes){
+		case P1P1Enum:           return P1Enum;
+		case P1P1GLSEnum:        return P1Enum;
+		case MINIcondensedEnum:  return P1bubbleEnum;
+		case MINIEnum:           return P1bubbleEnum;
+		case TaylorHoodEnum:     return P2Enum;
+		case LATaylorHoodEnum:   return P2Enum;
+		case OneLayerP4zEnum:    return P2xP4Enum;
+		case CrouzeixRaviartEnum:return P2bubbleEnum;
+		default:       _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
 	}
 
@@ -1067,14 +989,16 @@
 }
 /*}}}*/
-int  PentaRef::PressureInterpolation(void){/*{{{*/
-
-	switch(this->element_type){
-		case P1P1Enum:          return P1Enum;
-		case P1P1GLSEnum:       return P1Enum;
-		case MINIcondensedEnum: return P1Enum;
-		case MINIEnum:          return P1Enum;
-		case TaylorHoodEnum:    return P1Enum;
-		case OneLayerP4zEnum:   return P1Enum;
-		default:       _error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+int  PentaRef::PressureInterpolation(int fe_stokes){/*{{{*/
+
+	switch(fe_stokes){
+		case P1P1Enum:           return P1Enum;
+		case P1P1GLSEnum:        return P1Enum;
+		case MINIcondensedEnum:  return P1Enum;
+		case MINIEnum:           return P1Enum;
+		case TaylorHoodEnum:     return P1Enum;
+		case LATaylorHoodEnum:   return NoneEnum;
+		case OneLayerP4zEnum:    return P1Enum;
+		case CrouzeixRaviartEnum:return P1DGEnum;
+		default:       _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
 	}
 
@@ -1082,9 +1006,9 @@
 }
 /*}}}*/
-int  PentaRef::TensorInterpolation(void){/*{{{*/
-
-	switch(this->element_type){
+int  PentaRef::TensorInterpolation(int fe_stokes){/*{{{*/
+
+	switch(fe_stokes){
 		case XTaylorHoodEnum:    return P1DGEnum;
-		default: _error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+		default: _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
 	}
 
@@ -1147,4 +1071,14 @@
 			indices[5] = 11;
 			break;
+		case P2bubbleEnum:
+			numindices = 6;
+			indices    = xNew<int>(numindices);
+			indices[0] = 0;
+			indices[1] = 1;
+			indices[2] = 2;
+			indices[3] = 9;
+			indices[4] = 10;
+			indices[5] = 11;
+			break;
 		case P2xP4Enum:
 			numindices = 6;
@@ -1158,5 +1092,5 @@
 			break;
 		default:
-			_error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+			_error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
 	}
 
@@ -1215,5 +1149,5 @@
 			break;
 		default:
-			_error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+			_error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
 	}
 
Index: issm/trunk/src/c/classes/Elements/PentaRef.h
===================================================================
--- issm/trunk/src/c/classes/Elements/PentaRef.h	(revision 18081)
+++ issm/trunk/src/c/classes/Elements/PentaRef.h	(revision 18301)
@@ -11,26 +11,11 @@
 
 	public: 
-		int* element_type_list; //P1CG, P1DG, MINI, P2...
-		int  element_type;
-
 		PentaRef();
-		PentaRef(const int nummodels);
 		~PentaRef();
 
-		/*Management*/
-		void SetElementType(int type,int type_counter);
-
 		/*Numerics*/
-		void GetNodalFunctions(IssmDouble* basis, Gauss* gauss);
 		void GetNodalFunctions(IssmDouble* basis, Gauss* gauss,int finiteelement);
-		void GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
 		void GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss,int finiteelement);
-		void GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,Gauss* gauss);
 		void GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,Gauss* gauss,int finiteelement);
-		void GetNodalFunctionsP1(IssmDouble* l1l6, Gauss* gauss);
-		void GetNodalFunctionsP1Derivatives(IssmDouble* dh1dh6,IssmDouble* xyz_list, Gauss* gauss);
-		void GetNodalFunctionsMINIDerivatives(IssmDouble* dh1dh7,IssmDouble* xyz_list, Gauss* gauss);
-		void GetNodalFunctionsP1DerivativesReference(IssmDouble* dl1dl6,Gauss* gauss);
-		void GetNodalFunctionsMINIDerivativesReference(IssmDouble* dl1dl7,Gauss* gauss);
 		void GetQuadJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,Gauss* gauss);
 		void GetJacobian(IssmDouble* J, IssmDouble* xyz_list,Gauss* gauss);
@@ -40,15 +25,13 @@
 		void GetJacobianInvert(IssmDouble*  Jinv, IssmDouble* xyz_list,Gauss* gauss);
 		void GetLprimeFSSSA(IssmDouble* LprimeFSSSA, IssmDouble* xyz_list, Gauss* gauss);
-		void GetInputValue(IssmDouble* pvalue,IssmDouble* plist, Gauss* gauss);
 		void GetInputValue(IssmDouble* pvalue,IssmDouble* plist, Gauss* gauss,int finiteelement);
-		void GetInputDerivativeValue(IssmDouble* pvalues, IssmDouble* plist,IssmDouble* xyz_list, Gauss* gauss);
+		void GetInputDerivativeValue(IssmDouble* pvalues, IssmDouble* plist,IssmDouble* xyz_list, Gauss* gauss,int finiteelement);
 
 		void BasalNodeIndices(int* pnumindices,int** pindices,int finiteelement);
 		void SurfaceNodeIndices(int* pnumindices,int** pindices,int finiteelement);
-		int  NumberofNodes(void);
 		int  NumberofNodes(int finiteelement);
-		int  VelocityInterpolation(void);
-		int  PressureInterpolation(void);
-		int  TensorInterpolation(void);
+		int  VelocityInterpolation(int fe_stokes);
+		int  PressureInterpolation(int fe_stokes);
+		int  TensorInterpolation(int fe_stokes);
 };
 #endif
Index: issm/trunk/src/c/classes/Elements/Seg.cpp
===================================================================
--- issm/trunk/src/c/classes/Elements/Seg.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Elements/Seg.cpp	(revision 18301)
@@ -20,5 +20,5 @@
 /*Constructors/destructor/copy*/
 Seg::Seg(int seg_id, int seg_sid, int index, IoModel* iomodel,int nummodels)/*{{{*/
-		:SegRef(nummodels),ElementHook(nummodels,index+1,NUMVERTICES,iomodel){
+		:ElementHook(nummodels,index+1,NUMVERTICES,iomodel){
 
 			/*id: */
@@ -37,4 +37,7 @@
 			this->material = NULL;
 			this->matpar   = NULL;
+
+			/*Only allocate pointer*/
+			this->element_type_list=xNew<int>(nummodels);
 		}
 /*}}}*/
@@ -99,6 +102,20 @@
 	*pxyz_front=xyz_front;
 }/*}}}*/
+void       Seg::NodalFunctionsP1(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussSegEnum);
+	this->GetNodalFunctions(basis,(GaussSeg*)gauss,P1Enum);
+
+}
+/*}}}*/
+void       Seg::NodalFunctionsP2(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussSegEnum);
+	this->GetNodalFunctions(basis,(GaussSeg*)gauss,P2Enum);
+
+}
+/*}}}*/
 int        Seg::GetNumberOfNodes(void){/*{{{*/
-	return this->NumberofNodes();
+	return this->NumberofNodes(this->element_type);
 }
 /*}}}*/
@@ -116,126 +133,4 @@
 
 }/*}}}*/
-void       Seg::GradientIndexing(int* indexing,int control_index){/*{{{*/
-
-	/*Get some parameters*/
-	int num_controls;
-	parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
-
-	/*get gradient indices*/
-	for(int i=0;i<NUMVERTICES;i++){
-		indexing[i]=num_controls*this->vertices[i]->Pid() + control_index;
-	}
-
-}
-/*}}}*/
-void       Seg::GradjDragFS(Vector<IssmDouble>* gradient,int control_index){/*{{{*/
-
-	int        i;
-	int        analysis_type;
-	int        vertexpidlist[NUMVERTICES];
-	int        connectivity[NUMVERTICES];
-	IssmDouble vx,lambda,alpha_complement,drag,Jdet;
-	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble dk[NDOF2]; 
-	IssmDouble grade_g[NUMVERTICES]={0.0};
-	IssmDouble grade_g_gaussian[NUMVERTICES];
-	IssmDouble basis[3];
-	Friction*  friction=NULL;
-	GaussSeg  *gauss=NULL;
-
-	if(IsFloating())return;
-
-	/*retrive parameters: */
-	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
-	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	GradientIndexing(&vertexpidlist[0],control_index);
-	this->GetVerticesConnectivityList(&connectivity[0]);
-
-	/*Build frictoin element, needed later: */
-	friction=new Friction(this,1);
-
-	/*Retrieve all inputs we will be needing: */
-	Input* adjointx_input=inputs->GetInput(AdjointxEnum);                   _assert_(adjointx_input);
-	Input* vx_input=inputs->GetInput(VxEnum);                               _assert_(vx_input);
-	Input* dragcoefficient_input=inputs->GetInput(FrictionCoefficientEnum); _assert_(dragcoefficient_input);
-
-	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussSeg(4);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-
-		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
-		GetNodalFunctions(basis, gauss);
-
-		/*Build alpha_complement_list: */
-		friction->GetAlphaComplement(&alpha_complement,gauss);
-
-		dragcoefficient_input->GetInputValue(&drag, gauss);
-		adjointx_input->GetInputValue(&lambda, gauss);
-		vx_input->GetInputValue(&vx,gauss);
-		dragcoefficient_input->GetInputDerivativeValue(&dk[0],&xyz_list[0][0],gauss);
-
-		/*Build gradje_g_gaussian vector (actually -dJ/ddrag): */
-		for (i=0;i<NUMVERTICES;i++){
-			grade_g_gaussian[i]=-2*drag*alpha_complement*(lambda*vx)*Jdet*gauss->weight*basis[i];
-		}
-
-		/*Add gradje_g_gaussian vector to gradje_g: */
-		for(i=0;i<NUMVERTICES;i++){
-			_assert_(!xIsNan<IssmDouble>(grade_g[i]));
-			grade_g[i]+=grade_g_gaussian[i];
-		}
-	}
-	gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
-
-	/*Clean up and return*/
-	delete gauss;
-	delete friction;
-}
-/*}}}*/
-void       Seg::GradjDragGradient(Vector<IssmDouble>* gradient,int control_index){/*{{{*/
-
-	int        i;
-	int        vertexpidlist[NUMVERTICES];
-	IssmDouble Jdet,weight;
-	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble dbasis[NDOF2][NUMVERTICES];
-	IssmDouble dk[NDOF2]; 
-	IssmDouble grade_g[NUMVERTICES]={0.0};
-	GaussSeg  *gauss=NULL;
-
-	/*Retrieve all inputs we will be needing: */
-	if(IsFloating())return;
-	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	GradientIndexing(&vertexpidlist[0],control_index);
-	Input* dragcoefficient_input=inputs->GetInput(FrictionCoefficientEnum); _assert_(dragcoefficient_input);
-	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);                 _assert_(weights_input);
-
-	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussSeg(2);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-
-		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
-		GetNodalFunctionsDerivatives(&dbasis[0][0],&xyz_list[0][0],gauss);
-		weights_input->GetInputValue(&weight,gauss,DragCoefficientAbsGradientEnum);
-
-		/*Build alpha_complement_list: */
-		dragcoefficient_input->GetInputDerivativeValue(&dk[0],&xyz_list[0][0],gauss);
-
-		/*Build gradje_g_gaussian vector (actually -dJ/ddrag): */
-		for (i=0;i<NUMVERTICES;i++){
-			grade_g[i]+=-weight*Jdet*gauss->weight*dbasis[0][i]*dk[0];
-			_assert_(!xIsNan<IssmDouble>(grade_g[i]));
-		}
-	}
-	gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
-
-	/*Clean up and return*/
-	delete gauss;
-}
-/*}}}*/
 bool       Seg::IsIcefront(void){/*{{{*/
 
@@ -299,5 +194,5 @@
 
 	_assert_(gauss->Enum()==GaussSegEnum);
-	this->GetNodalFunctions(basis,(GaussSeg*)gauss);
+	this->GetNodalFunctions(basis,(GaussSeg*)gauss,this->element_type);
 
 }
@@ -306,5 +201,5 @@
 
 	_assert_(gauss->Enum()==GaussSegEnum);
-	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussSeg*)gauss);
+	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussSeg*)gauss,this->element_type);
 
 }
Index: issm/trunk/src/c/classes/Elements/Seg.h
===================================================================
--- issm/trunk/src/c/classes/Elements/Seg.h	(revision 18081)
+++ issm/trunk/src/c/classes/Elements/Seg.h	(revision 18301)
@@ -55,10 +55,9 @@
 		void        ComputeBasalStress(Vector<IssmDouble>* sigma_b){_error_("not implemented yet");};
 		void        ComputeSigmaNN(){_error_("not implemented yet");};
-		void        ComputeStrainRate(){_error_("not implemented yet");};
-		void        ComputeStrainRate(Vector<IssmDouble>* eps){_error_("not implemented yet");};
 		void        ComputeStressTensor(){_error_("not implemented yet");};
 		void        ComputeDeviatoricStressTensor(){_error_("not implemented yet");};
 		void        Configure(Elements* elements,Loads* loads,Nodes* nodesin,Vertices* verticesin,Materials* materials,Parameters* parameters){_error_("not implemented yet");};
 		void        SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Materials* materials,Parameters* parameters){_error_("not implemented yet");};
+		void        ResetHooks(){_error_("not implemented yet");};
 		void        Delta18oParameterization(void){_error_("not implemented yet");};
 		void        ElementSizes(IssmDouble* hx,IssmDouble* hy,IssmDouble* hz){_error_("not implemented yet");};
@@ -69,4 +68,5 @@
 		int         GetNodeIndex(Node* node){_error_("not implemented yet");};
 		int         GetNumberOfNodes(void);
+		int         GetNumberOfNodes(int enum_type){_error_("not implemented yet");};
 		int         GetNumberOfVertices(void);
 		void        GetVerticesCoordinates(IssmDouble** pxyz_list);
@@ -83,5 +83,6 @@
 		IssmDouble  MinEdgeLength(IssmDouble* xyz_list){_error_("not implemented yet");};
 		void        NodalFunctions(IssmDouble* basis,Gauss* gauss);
-		void        NodalFunctionsP1(IssmDouble* basis,Gauss* gauss){_error_("not implemented yet");};
+		void        NodalFunctionsP1(IssmDouble* basis,Gauss* gauss);
+		void        NodalFunctionsP2(IssmDouble* basis,Gauss* gauss);
 		void        NodalFunctionsVelocity(IssmDouble* basis,Gauss* gauss){_error_("not implemented yet");};
 		void        NodalFunctionsPressure(IssmDouble* basis,Gauss* gauss){_error_("not implemented yet");};
@@ -122,7 +123,8 @@
 		bool        IsZeroLevelset(int levelset_enum){_error_("not implemented");};
 		bool		   IsIcefront(void);
-		bool   IsFaceOnBoundary(void){_error_("not implemented yet");};
+		bool        IsFaceOnBoundary(void){_error_("not implemented yet");};
 		void        ZeroLevelsetCoordinates(IssmDouble** pxyz_zero,IssmDouble* xyz_list,int levelsetenum){_error_("not implemented");};
 		void		   GetIcefrontCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum);
+		void		   GetLevelCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum,IssmDouble level){_error_("not implemented");};
 
 		void        GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution,int enum_type){_error_("not implemented yet");};
@@ -136,5 +138,4 @@
 		void        ReduceMatrices(ElementMatrix* Ke,ElementVector* pe){_error_("not implemented yet");};
 		void        SetTemporaryElementType(int element_type_in){_error_("not implemented yet");};
-		void	      SmbGradients(){_error_("not implemented yet");};
 		IssmDouble  SurfaceArea(void){_error_("not implemented yet");};
 		void        Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finitelement){_error_("not implemented yet");};
@@ -147,18 +148,7 @@
 		IssmDouble IceVolumeAboveFloatation(void){_error_("not implemented yet");};
 		IssmDouble TotalSmb(void){_error_("not implemented yet");};
-		void       MinVel(IssmDouble* pminvel){_error_("not implemented yet");};
-		void       MinVx(IssmDouble* pminvx){_error_("not implemented yet");};
-		void       MinVy(IssmDouble* pminvy){_error_("not implemented yet");};
-		void       MinVz(IssmDouble* pminvz){_error_("not implemented yet");};
 		IssmDouble MassFlux(IssmDouble* segment){_error_("not implemented yet");};
 		IssmDouble MassFlux(IssmDouble x1,IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id){_error_("not implemented yet");}
-		void       MaxAbsVx(IssmDouble* pmaxabsvx){_error_("not implemented yet");};
-		void       MaxAbsVy(IssmDouble* pmaxabsvy){_error_("not implemented yet");};
-		void       MaxAbsVz(IssmDouble* pmaxabsvz){_error_("not implemented yet");};
 		void       ElementResponse(IssmDouble* presponse,int response_enum){_error_("not implemented yet");};
-		void       MaxVel(IssmDouble* pmaxvel){_error_("not implemented yet");};
-		void       MaxVx(IssmDouble* pmaxvx){_error_("not implemented yet");};
-		void       MaxVy(IssmDouble* pmaxvy){_error_("not implemented yet");};
-		void       MaxVz(IssmDouble* pmaxvz){_error_("not implemented yet");};
 		IssmDouble Misfit(int modelenum,int observationenum,int weightsenum){_error_("not implemented yet");};
 		IssmDouble MisfitArea(int weightsenum){_error_("not implemented yet");};
@@ -168,21 +158,6 @@
 #endif
 
-		void       GradientIndexing(int* indexing,int control_index);
-		void       Gradj(Vector<IssmDouble>* gradient,int control_type,int control_index){_error_("not implemented yet");};
-		void       GradjBGradient(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
-		void       GradjDGradient(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
-		void       GradjBSSA(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
-		void       GradjDSSA(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
-		void       GradjDragSSA(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
-		void       GradjDragFS(Vector<IssmDouble>* gradient,int control_index);
-		void       GradjDragGradient(Vector<IssmDouble>* gradient,int control_index);
-		void       GradjDhDtBalancedthickness(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
-		void       GradjVxBalancedthickness(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
-		void       GradjVyBalancedthickness(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
-		void       GradjThicknessBalancethicknessSoft(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
 		void       GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data){_error_("not implemented yet");};
 		void       SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index){_error_("not implemented yet");};
-		void       ControlInputGetGradient(Vector<IssmDouble>* gradient,int enum_type,int control_index){_error_("not implemented yet");};
-		void       ControlInputScaleGradient(int enum_type,IssmDouble scale){_error_("not implemented yet");};
 		void       ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index){_error_("not implemented yet");};
 		void       ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum){_error_("not implemented yet");};
Index: issm/trunk/src/c/classes/Elements/SegRef.cpp
===================================================================
--- issm/trunk/src/c/classes/Elements/SegRef.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Elements/SegRef.cpp	(revision 18301)
@@ -21,36 +21,11 @@
 /*Object constructors and destructor*/
 SegRef::SegRef(){/*{{{*/
-	this->element_type_list=NULL;
-}
-/*}}}*/
-SegRef::SegRef(const int nummodels){/*{{{*/
-
-	/*Only allocate pointer*/
-	element_type_list=xNew<int>(nummodels);
-
 }
 /*}}}*/
 SegRef::~SegRef(){/*{{{*/
-	xDelete<int>(element_type_list);
-}
-/*}}}*/
-
-/*Management*/
-void SegRef::SetElementType(int type,int type_counter){/*{{{*/
-
-	/*initialize element type*/
-	this->element_type_list[type_counter]=type;
 }
 /*}}}*/
 
 /*Reference Element numerics*/
-void SegRef::GetNodalFunctions(IssmDouble* basis,GaussSeg* gauss){/*{{{*/
-	/*This routine returns the values of the nodal functions  at the gaussian point.*/
-
-	_assert_(basis);
-
-	GetNodalFunctions(basis,gauss,this->element_type);
-}
-/*}}}*/
 void SegRef::GetNodalFunctions(IssmDouble* basis,GaussSeg* gauss,int finiteelement){/*{{{*/
 	/*This routine returns the values of the nodal functions  at the gaussian point.*/
@@ -74,10 +49,4 @@
 			_error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
 	}
-}
-/*}}}*/
-void SegRef::GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, GaussSeg* gauss){/*{{{*/
-
-	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss,this->element_type);
-
 }
 /*}}}*/
@@ -107,12 +76,4 @@
 	/*Clean up*/
 	xDelete<IssmDouble>(dbasis_ref);
-
-}
-/*}}}*/
-void SegRef::GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,GaussSeg* gauss){/*{{{*/
-	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
-	 * natural coordinate system) at the gaussian point. */
-
-	GetNodalFunctionsDerivativesReference(dbasis,gauss,this->element_type);
 
 }
@@ -147,5 +108,5 @@
 }
 /*}}}*/
-void SegRef::GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, GaussSeg* gauss){/*{{{*/
+void SegRef::GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, GaussSeg* gauss,int finiteelement){/*{{{*/
 
 	/*From node values of parameter p (plist[0],plist[1]), return parameter derivative value at gaussian 
@@ -160,9 +121,9 @@
 
 	/*Fetch number of nodes for this finite element*/
-	int numnodes = this->NumberofNodes();
+	int numnodes = this->NumberofNodes(finiteelement);
 
 	/*Get nodal functions derivatives*/
 	IssmDouble* dbasis=xNew<IssmDouble>(1*numnodes);
-	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss,finiteelement);
 
 	/*Calculate parameter for this Gauss point*/
@@ -175,9 +136,4 @@
 }
 /*}}}*/
-void SegRef::GetInputValue(IssmDouble* p, IssmDouble* plist, GaussSeg* gauss){/*{{{*/
-
-	GetInputValue(p,plist,gauss,this->element_type);
-}
-/*}}}*/
 void SegRef::GetInputValue(IssmDouble* p, IssmDouble* plist, GaussSeg* gauss,int finiteelement){/*{{{*/
 
@@ -230,9 +186,4 @@
 	/*Invert Jacobian matrix: */
 	*Jinv = 1./J;
-}
-/*}}}*/
-int  SegRef::NumberofNodes(void){/*{{{*/
-
-	return this->NumberofNodes(this->element_type);
 }
 /*}}}*/
@@ -243,5 +194,5 @@
 		case P1Enum:                return NUMNODESP1;
 		case P1DGEnum:              return NUMNODESP1;
-		default: _error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+		default: _error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
 	}
 
Index: issm/trunk/src/c/classes/Elements/SegRef.h
===================================================================
--- issm/trunk/src/c/classes/Elements/SegRef.h	(revision 18081)
+++ issm/trunk/src/c/classes/Elements/SegRef.h	(revision 18301)
@@ -13,27 +13,15 @@
 
 	public: 
-		int* element_type_list;
-		int  element_type;
-
 		SegRef();
-		SegRef(const int nummodels);
 		~SegRef();
 
-		/*Management*/
-		void SetElementType(int type,int type_counter);
 		void GetJacobian(IssmDouble* J, IssmDouble* xyz_list,GaussSeg* gauss);
 		void GetJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,GaussSeg* gauss);
 		void GetJacobianInvert(IssmDouble* Jinv, IssmDouble* xyz_list,GaussSeg* gauss);
-		void GetNodalFunctions(IssmDouble* basis,GaussSeg* gauss);
 		void GetNodalFunctions(IssmDouble* basis,GaussSeg* gauss,int finiteelement);
-		void GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, GaussSeg* gauss);
 		void GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, GaussSeg* gauss,int finiteelement);
-		void GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,GaussSeg* gauss);
 		void GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,GaussSeg* gauss,int finiteelement);
-		void GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, GaussSeg* gauss);
-		void GetInputValue(IssmDouble* p, IssmDouble* plist, GaussSeg* gauss);
+		void GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, GaussSeg* gauss,int finiteelement);
 		void GetInputValue(IssmDouble* p, IssmDouble* plist, GaussSeg* gauss,int finiteelement);
-
-		int  NumberofNodes(void);
 		int  NumberofNodes(int finiteelement);
 };
Index: issm/trunk/src/c/classes/Elements/Tetra.cpp
===================================================================
--- issm/trunk/src/c/classes/Elements/Tetra.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Elements/Tetra.cpp	(revision 18301)
@@ -21,5 +21,5 @@
 /*Constructors/destructor/copy*/
 Tetra::Tetra(int seg_id, int seg_sid, int index, IoModel* iomodel,int nummodels)/*{{{*/
-		:TetraRef(nummodels),ElementHook(nummodels,index+1,NUMVERTICES,iomodel){
+		:ElementHook(nummodels,index+1,NUMVERTICES,iomodel){
 
 			/*id: */
@@ -38,4 +38,7 @@
 			this->material = NULL;
 			this->matpar   = NULL;
+
+			/*Only allocate pointer*/
+			this->element_type_list=xNew<int>(nummodels);
 		}
 /*}}}*/
@@ -45,5 +48,57 @@
 /*}}}*/
 Object* Tetra::copy() {/*{{{*/
-	_error_("not implemented yet");
+
+	int i;
+	Tetra* tetra=NULL;
+
+	tetra=new Tetra();
+
+	//deal with TetraRef mother class
+	int nanalyses = this->numanalyses;
+	if(nanalyses > 0){
+		tetra->element_type_list=xNew<int>(nanalyses);
+		for(i=0;i<nanalyses;i++){
+			if (this->element_type_list[i]) tetra->element_type_list[i]=this->element_type_list[i];
+			else tetra->element_type_list[i] = 0;
+		}
+	}
+	else tetra->element_type_list = NULL;
+	tetra->element_type=this->element_type;
+	tetra->numanalyses=nanalyses;
+
+	//deal with ElementHook mother class
+	if (this->hnodes){
+		tetra->hnodes=xNew<Hook*>(tetra->numanalyses);
+		for(i=0;i<tetra->numanalyses;i++){
+			if (this->hnodes[i]) tetra->hnodes[i] = (Hook*)(this->hnodes[i]->copy());
+			else tetra->hnodes[i] = NULL;
+		}
+	}
+	else tetra->hnodes = NULL;
+
+	tetra->hvertices = (Hook*)this->hvertices->copy();
+	tetra->hmaterial = (Hook*)this->hmaterial->copy();
+	tetra->hmatpar   = (Hook*)this->hmatpar->copy();
+	tetra->hneighbors = NULL;
+
+	/*deal with Tria fields: */
+	tetra->id  = this->id;
+	tetra->sid = this->sid;
+	if(this->inputs) tetra->inputs = (Inputs*)(this->inputs->Copy());
+	else tetra->inputs=new Inputs();
+
+	/*point parameters: */
+	tetra->parameters=this->parameters;
+
+	/*recover objects: */
+	unsigned int num_nodes = 3;
+	tetra->nodes = xNew<Node*>(num_nodes); //we cannot rely on an analysis_counter to tell us which analysis_type we are running, so we just copy the nodes.
+	for(i=0;i<num_nodes;i++) if(this->nodes[i]) tetra->nodes[i]=this->nodes[i]; else tetra->nodes[i] = NULL;
+
+	tetra->vertices = (Vertex**)this->hvertices->deliverp();
+	tetra->material = (Material*)this->hmaterial->delivers();
+	tetra->matpar   = (Matpar*)this->hmatpar->delivers();
+
+	return tetra;
 }
 /*}}}*/
@@ -202,5 +257,5 @@
 
 	_assert_(nodes);
-	int numnodes = this->NumberofNodes();
+	int numnodes = this->NumberofNodes(this->element_type);
 
 	for(int i=0;i<numnodes;i++){
@@ -212,5 +267,5 @@
 /*}}}*/
 int      Tetra::GetNumberOfNodes(void){/*{{{*/
-	return this->NumberofNodes();
+	return this->NumberofNodes(this->element_type);
 }
 /*}}}*/
@@ -400,5 +455,5 @@
 
 	/*Fetch number of nodes for this finite element*/
-	int numnodes = this->NumberofNodes();
+	int numnodes = this->NumberofNodes(this->element_type);
 
 	/*Fetch dof list and allocate solution vector*/
@@ -502,5 +557,5 @@
 
 	_assert_(gauss->Enum()==GaussTetraEnum);
-	this->GetNodalFunctions(basis,(GaussTetra*)gauss);
+	this->GetNodalFunctions(basis,(GaussTetra*)gauss,this->element_type);
 
 }
@@ -530,5 +585,5 @@
 
 	_assert_(gauss->Enum()==GaussTetraEnum);
-	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussTetra*)gauss);
+	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussTetra*)gauss,this->element_type);
 
 }
@@ -661,5 +716,5 @@
 	/*For FS only: we want the CS to be tangential to the bedrock*/
 	inputs->GetInputValue(&approximation,ApproximationEnum);
-	if(IsFloating() || !HasNodeOnBase() ||  approximation!=FSApproximationEnum) return;
+	if(!HasNodeOnBase() ||  approximation!=FSApproximationEnum) return;
 
 	//printf("element number %i \n",this->id);
@@ -724,4 +779,20 @@
 }
 /*}}}*/
+void     Tetra::ResetHooks(){/*{{{*/
+
+	this->nodes=NULL;
+	this->vertices=NULL;
+	this->material=NULL;
+	this->matpar=NULL;
+	this->parameters=NULL;
+
+	//deal with ElementHook mother class
+	for(int i=0;i<this->numanalyses;i++) if(this->hnodes[i]) this->hnodes[i]->reset();
+	this->hvertices->reset();
+	this->hmaterial->reset();
+	this->hmatpar->reset();
+	if(this->hneighbors) this->hneighbors->reset();
+}
+/*}}}*/
 Element* Tetra::SpawnBasalElement(void){/*{{{*/
 
@@ -788,5 +859,5 @@
 
 	/*Recover element type*/
-	this->SetElementType(finiteelement_type,analysis_counter);
+	this->element_type_list[analysis_counter]=finiteelement_type;
 
 	/*Recover vertices ids needed to initialize inputs*/
@@ -841,4 +912,5 @@
 			break;
 		case TaylorHoodEnum:
+		case XTaylorHoodEnum:
 			numnodes        = 14;
 			tetra_node_ids  = xNew<int>(numnodes);
@@ -859,4 +931,18 @@
 			tetra_node_ids[13]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elements[4*index+3];
 			break;
+		case LATaylorHoodEnum:
+			numnodes        = 10;
+			tetra_node_ids  = xNew<int>(numnodes);
+			tetra_node_ids[0]=iomodel->nodecounter+iomodel->elements[4*index+0];
+			tetra_node_ids[1]=iomodel->nodecounter+iomodel->elements[4*index+1];
+			tetra_node_ids[2]=iomodel->nodecounter+iomodel->elements[4*index+2];
+			tetra_node_ids[3]=iomodel->nodecounter+iomodel->elements[4*index+3];
+			tetra_node_ids[4]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[6*index+0]+1;
+			tetra_node_ids[5]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[6*index+1]+1;
+			tetra_node_ids[6]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[6*index+2]+1;
+			tetra_node_ids[7]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[6*index+3]+1;
+			tetra_node_ids[8]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[6*index+4]+1;
+			tetra_node_ids[9]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[6*index+5]+1;
+			break;
 		default:
 			_error_("Finite element "<<EnumToStringx(finiteelement_type)<<" not supported yet");
@@ -871,6 +957,10 @@
 }
 /*}}}*/
+void     Tetra::ValueP1OnGauss(IssmDouble* pvalue,IssmDouble* values,Gauss* gauss){/*{{{*/
+	TetraRef::GetInputValue(pvalue,values,gauss,P1Enum);
+}
+/*}}}*/
 int      Tetra::VelocityInterpolation(void){/*{{{*/
-	return TetraRef::VelocityInterpolation();
+	return TetraRef::VelocityInterpolation(this->element_type);
 }
 /*}}}*/
@@ -892,9 +982,9 @@
 /*}}}*/
 int      Tetra::PressureInterpolation(void){/*{{{*/
-	return TetraRef::PressureInterpolation();
+	return TetraRef::PressureInterpolation(this->element_type);
 }
 /*}}}*/
 int      Tetra::TensorInterpolation(void){/*{{{*/
-	return TetraRef::TensorInterpolation();
+	return TetraRef::TensorInterpolation(this->element_type);
 }
 /*}}}*/
Index: issm/trunk/src/c/classes/Elements/Tetra.h
===================================================================
--- issm/trunk/src/c/classes/Elements/Tetra.h	(revision 18081)
+++ issm/trunk/src/c/classes/Elements/Tetra.h	(revision 18301)
@@ -55,10 +55,9 @@
 		void        ComputeBasalStress(Vector<IssmDouble>* sigma_b){_error_("not implemented yet");};
 		void        ComputeSigmaNN(){_error_("not implemented yet");};
-		void        ComputeStrainRate(){_error_("not implemented yet");};
-		void        ComputeStrainRate(Vector<IssmDouble>* eps){_error_("not implemented yet");};
 		void        ComputeStressTensor(){_error_("not implemented yet");};
 		void        ComputeDeviatoricStressTensor(){_error_("not implemented yet");};
 		void        Configure(Elements* elements,Loads* loads,Nodes* nodesin,Vertices* verticesin,Materials* materials,Parameters* parameters);
 		void        SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Materials* materials,Parameters* parameters);
+		void        ResetHooks();
 		void        Delta18oParameterization(void){_error_("not implemented yet");};
 		void        ElementSizes(IssmDouble* hx,IssmDouble* hy,IssmDouble* hz);
@@ -72,4 +71,5 @@
 		int         GetNodeIndex(Node* node);
 		int         GetNumberOfNodes(void);
+		int         GetNumberOfNodes(int enum_type){_error_("not implemented yet");};
 		int         GetNumberOfVertices(void);
 		void        GetVerticesCoordinatesBase(IssmDouble** pxyz_list);
@@ -88,4 +88,5 @@
 		void        NodalFunctions(IssmDouble* basis,Gauss* gauss);
 		void        NodalFunctionsP1(IssmDouble* basis,Gauss* gauss){_error_("not implemented yet");};
+		void        NodalFunctionsP2(IssmDouble* basis,Gauss* gauss){_error_("not implemented yet");};
 		void        NodalFunctionsVelocity(IssmDouble* basis,Gauss* gauss);
 		void        NodalFunctionsPressure(IssmDouble* basis,Gauss* gauss);
@@ -105,5 +106,5 @@
 		IssmDouble  StabilizationParameter(IssmDouble u, IssmDouble v, IssmDouble w, IssmDouble diameter, IssmDouble kappa){_error_("not implemented yet");};
 		int         PressureInterpolation(void);
-		void        ValueP1OnGauss(IssmDouble* pvalue,IssmDouble* values,Gauss* gauss){_error_("not implemented yet");};
+		void        ValueP1OnGauss(IssmDouble* pvalue,IssmDouble* values,Gauss* gauss);
 		void        ValueP1DerivativesOnGauss(IssmDouble* dvalue,IssmDouble* values,IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
 		int         VelocityInterpolation(void);
@@ -127,7 +128,8 @@
 		bool        IsZeroLevelset(int levelset_enum){_error_("not implemented");};
 		bool		   IsIcefront(void);
-		bool   IsFaceOnBoundary(void){_error_("not implemented yet");};
+		bool        IsFaceOnBoundary(void){_error_("not implemented yet");};
 		void        ZeroLevelsetCoordinates(IssmDouble** pxyz_zero,IssmDouble* xyz_list,int levelsetenum);
 		void		   GetIcefrontCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum){_error_("not implemented yet");};
+		void		   GetLevelCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum,IssmDouble level){_error_("not implemented yet");};
 		void        GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution,int enum_type){_error_("not implemented yet");};
 		void        InputDepthAverageAtBase(int enum_type,int average_enum_type){_error_("not implemented yet");};
@@ -140,5 +142,4 @@
 		void        ReduceMatrices(ElementMatrix* Ke,ElementVector* pe);
 		void        SetTemporaryElementType(int element_type_in){_error_("not implemented yet");};
-		void	      SmbGradients(){_error_("not implemented yet");};
 		IssmDouble  SurfaceArea(void){_error_("not implemented yet");};
 		void        Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finitelement);
@@ -151,18 +152,7 @@
 		IssmDouble IceVolumeAboveFloatation(void){_error_("not implemented yet");};
 		IssmDouble TotalSmb(void){_error_("not implemented yet");};
-		void       MinVel(IssmDouble* pminvel){_error_("not implemented yet");};
-		void       MinVx(IssmDouble* pminvx){_error_("not implemented yet");};
-		void       MinVy(IssmDouble* pminvy){_error_("not implemented yet");};
-		void       MinVz(IssmDouble* pminvz){_error_("not implemented yet");};
 		IssmDouble MassFlux(IssmDouble* segment){_error_("not implemented yet");};
 		IssmDouble MassFlux(IssmDouble x1,IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id){_error_("not implemented yet");}
-		void       MaxAbsVx(IssmDouble* pmaxabsvx){_error_("not implemented yet");};
-		void       MaxAbsVy(IssmDouble* pmaxabsvy){_error_("not implemented yet");};
-		void       MaxAbsVz(IssmDouble* pmaxabsvz){_error_("not implemented yet");};
 		void       ElementResponse(IssmDouble* presponse,int response_enum){_error_("not implemented yet");};
-		void       MaxVel(IssmDouble* pmaxvel){_error_("not implemented yet");};
-		void       MaxVx(IssmDouble* pmaxvx){_error_("not implemented yet");};
-		void       MaxVy(IssmDouble* pmaxvy){_error_("not implemented yet");};
-		void       MaxVz(IssmDouble* pmaxvz){_error_("not implemented yet");};
 		IssmDouble Misfit(int modelenum,int observationenum,int weightsenum){_error_("not implemented yet");};
 		IssmDouble MisfitArea(int weightsenum){_error_("not implemented yet");};
@@ -174,20 +164,6 @@
 		IssmDouble DragCoefficientAbsGradient(void){_error_("not implemented yet");};
 		void       GradientIndexing(int* indexing,int control_index){_error_("not implemented yet");};
-		void       Gradj(Vector<IssmDouble>* gradient,int control_type,int control_index){_error_("not implemented yet");};
-		void       GradjBGradient(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
-		void       GradjDGradient(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
-		void       GradjBSSA(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
-		void       GradjDSSA(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
-		void       GradjDragSSA(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
-		void       GradjDragFS(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
-		void       GradjDragGradient(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
-		void       GradjDhDtBalancedthickness(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
-		void       GradjVxBalancedthickness(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
-		void       GradjVyBalancedthickness(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
-		void       GradjThicknessBalancethicknessSoft(Vector<IssmDouble>* gradient,int control_index){_error_("not implemented yet");};
 		void       GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data){_error_("not implemented yet");};
 		void       SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index){_error_("not implemented yet");};
-		void       ControlInputGetGradient(Vector<IssmDouble>* gradient,int enum_type,int control_index){_error_("not implemented yet");};
-		void       ControlInputScaleGradient(int enum_type,IssmDouble scale){_error_("not implemented yet");};
 		void       ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index){_error_("not implemented yet");};
 		void       ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum){_error_("not implemented yet");};
Index: issm/trunk/src/c/classes/Elements/TetraRef.cpp
===================================================================
--- issm/trunk/src/c/classes/Elements/TetraRef.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Elements/TetraRef.cpp	(revision 18301)
@@ -4,5 +4,5 @@
 
 /*Headers:*/
-/*{{{*//*{{{*/
+/*{{{*/
 #ifdef HAVE_CONFIG_H
 #include <config.h>
@@ -23,38 +23,19 @@
 /*Object constructors and destructor*/
 TetraRef::TetraRef(){/*{{{*/
-	this->element_type_list=NULL;
-}
-/*}}}*/
-TetraRef::TetraRef(const int nummodels){/*{{{*/
-
-	/*Only allocate pointer*/
-	element_type_list=xNew<int>(nummodels);
-
 }
 /*}}}*/
 TetraRef::~TetraRef(){/*{{{*/
-	xDelete<int>(element_type_list);
-}
-/*}}}*/
-
-/*Management*/
-void TetraRef::SetElementType(int type,int type_counter){/*{{{*/
-
-	/*initialize element type*/
-	this->element_type_list[type_counter]=type;
 }
 /*}}}*/
 
 /*Reference Element numerics*/
-void TetraRef::GetNodalFunctions(IssmDouble* basis,GaussTetra* gauss){/*{{{*/
+void TetraRef::GetNodalFunctions(IssmDouble* basis,Gauss* gauss_in,int finiteelement){/*{{{*/
 	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
 	_assert_(basis);
-	GetNodalFunctions(basis,gauss,this->element_type);
-}
-/*}}}*/
-void TetraRef::GetNodalFunctions(IssmDouble* basis,GaussTetra* gauss,int finiteelement){/*{{{*/
-	/*This routine returns the values of the nodal functions  at the gaussian point.*/
-
-	_assert_(basis);
+
+	/*Cast gauss to GaussTetra*/
+	_assert_(gauss_in->Enum()==GaussTetraEnum);
+	GaussTetra* gauss = dynamic_cast<GaussTetra*>(gauss_in);
 
 	switch(finiteelement){
@@ -96,8 +77,4 @@
 }
 /*}}}*/
-void TetraRef::GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, GaussTetra* gauss){/*{{{*/
-	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss,this->element_type);
-}
-/*}}}*/
 void TetraRef::GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, GaussTetra* gauss,int finiteelement){/*{{{*/
 
@@ -133,12 +110,4 @@
 }
 /*}}}*/
-void TetraRef::GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,GaussTetra* gauss){/*{{{*/
-	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
-	 * natural coordinate system) at the gaussian point. */
-
-	GetNodalFunctionsDerivativesReference(dbasis,gauss,this->element_type);
-
-}
-/*}}}*/
 void TetraRef::GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,GaussTetra* gauss,int finiteelement){/*{{{*/
 	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
@@ -239,5 +208,5 @@
 }
 /*}}}*/
-void TetraRef::GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, GaussTetra* gauss){/*{{{*/
+void TetraRef::GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, GaussTetra* gauss,int finiteelement){/*{{{*/
 	/*From node values of parameter p (p_list[0], p_list[1], p_list[2],
 	 * p_list[3], p_list[4] and p_list[4]), return parameter derivative value at
@@ -256,9 +225,9 @@
 
 	/*Fetch number of nodes for this finite element*/
-	int numnodes = this->NumberofNodes();
+	int numnodes = this->NumberofNodes(finiteelement);
 
 	/*Get nodal functions derivatives*/
 	IssmDouble* dbasis=xNew<IssmDouble>(3*numnodes);
-	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss,finiteelement);
 
 	/*Calculate parameter for this Gauss point*/
@@ -274,10 +243,5 @@
 }
 /*}}}*/
-void TetraRef::GetInputValue(IssmDouble* p, IssmDouble* plist, GaussTetra* gauss){/*{{{*/
-
-	GetInputValue(p,plist,gauss,this->element_type);
-}
-/*}}}*/
-void TetraRef::GetInputValue(IssmDouble* p, IssmDouble* plist, GaussTetra* gauss,int finiteelement){/*{{{*/
+void TetraRef::GetInputValue(IssmDouble* p, IssmDouble* plist, Gauss* gauss,int finiteelement){/*{{{*/
 
 	/*Output*/
@@ -374,9 +338,4 @@
 	/*Invert Jacobian matrix: */
 	Matrix3x3Invert(Jinv,&J[0][0]);
-}
-/*}}}*/
-int  TetraRef::NumberofNodes(void){/*{{{*/
-
-	return this->NumberofNodes(this->element_type);
 }
 /*}}}*/
@@ -395,5 +354,7 @@
 		case MINIEnum:              return NUMNODESP1b+NUMNODESP1;
 		case TaylorHoodEnum:        return NUMNODESP2+NUMNODESP1;
-		default: _error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+		case LATaylorHoodEnum:      return NUMNODESP2;
+		case XTaylorHoodEnum:       return NUMNODESP2+NUMNODESP1;
+		default: _error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
 	}
 
@@ -401,7 +362,7 @@
 }
 /*}}}*/
-int  TetraRef::VelocityInterpolation(void){/*{{{*/
-
-	switch(this->element_type){
+int  TetraRef::VelocityInterpolation(int fe_stokes){/*{{{*/
+
+	switch(fe_stokes){
 		case P1P1Enum:          return P1Enum;
 		case P1P1GLSEnum:       return P1Enum;
@@ -409,5 +370,7 @@
 		case MINIEnum:          return P1bubbleEnum;
 		case TaylorHoodEnum:    return P2Enum;
-		default:       _error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+		case LATaylorHoodEnum:  return P2Enum;
+		case XTaylorHoodEnum:   return P2Enum;
+		default:       _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
 	}
 
@@ -415,7 +378,7 @@
 }
 /*}}}*/
-int TetraRef::PressureInterpolation(void){/*{{{*/
-
-	switch(this->element_type){
+int  TetraRef::PressureInterpolation(int fe_stokes){/*{{{*/
+
+	switch(fe_stokes){
 		case P1P1Enum:          return P1Enum;
 		case P1P1GLSEnum:       return P1Enum;
@@ -423,16 +386,18 @@
 		case MINIEnum:          return P1Enum;
 		case TaylorHoodEnum:    return P1Enum;
-		default:       _error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+		case LATaylorHoodEnum:  return NoneEnum;
+		case XTaylorHoodEnum:   return P1Enum;
+		default:       _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
 	}
 
 	return -1;
 }/*}}}*/
-int  TetraRef::TensorInterpolation(void){/*{{{*/
+int  TetraRef::TensorInterpolation(int fe_stokes){/*{{{*/
 	/*This routine returns the values of the nodal functions  at the gaussian point.*/
 
-	switch(this->element_type){
+	switch(fe_stokes){
 		case XTaylorHoodEnum: return P1DGEnum;
-		default: _error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
-	}
-}
-/*}}}*/
+		default: _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
+	}
+}
+/*}}}*/
Index: issm/trunk/src/c/classes/Elements/TetraRef.h
===================================================================
--- issm/trunk/src/c/classes/Elements/TetraRef.h	(revision 18081)
+++ issm/trunk/src/c/classes/Elements/TetraRef.h	(revision 18301)
@@ -13,32 +13,21 @@
 
 	public: 
-		int* element_type_list;
-		int  element_type;
-
 		TetraRef();
-		TetraRef(const int nummodels);
 		~TetraRef();
 
-		/*Management*/
-		void SetElementType(int type,int type_counter);
 		void GetJacobian(IssmDouble* J, IssmDouble* xyz_list,GaussTetra* gauss);
 		void GetJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,GaussTetra* gauss);
 		void GetJacobianDeterminantFace(IssmDouble*  Jdet, IssmDouble* xyz_list,GaussTetra* gauss);
 		void GetJacobianInvert(IssmDouble* Jinv, IssmDouble* xyz_list,GaussTetra* gauss);
-		void GetNodalFunctions(IssmDouble* basis,GaussTetra* gauss);
-		void GetNodalFunctions(IssmDouble* basis,GaussTetra* gauss,int finiteelement);
-		void GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, GaussTetra* gauss);
+		void GetNodalFunctions(IssmDouble* basis,Gauss* gauss_in,int finiteelement);
 		void GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, GaussTetra* gauss,int finiteelement);
-		void GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,GaussTetra* gauss);
 		void GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,GaussTetra* gauss,int finiteelement);
-		void GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, GaussTetra* gauss);
-		void GetInputValue(IssmDouble* p, IssmDouble* plist, GaussTetra* gauss);
-		void GetInputValue(IssmDouble* p, IssmDouble* plist, GaussTetra* gauss,int finiteelement);
+		void GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, GaussTetra* gauss,int finiteelement);
+		void GetInputValue(IssmDouble* p, IssmDouble* plist, Gauss* gauss,int finiteelement);
 
-		int  NumberofNodes(void);
 		int  NumberofNodes(int finiteelement);
-		int  VelocityInterpolation(void);
-		int  PressureInterpolation(void);
-		int  TensorInterpolation(void);
+		int  VelocityInterpolation(int fe_stokes);
+		int  PressureInterpolation(int fe_stokes);
+		int  TensorInterpolation(int fe_stokes);
 };
 #endif
Index: issm/trunk/src/c/classes/Elements/Tria.cpp
===================================================================
--- issm/trunk/src/c/classes/Elements/Tria.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Elements/Tria.cpp	(revision 18301)
@@ -25,5 +25,5 @@
 /*Constructors/destructor/copy*/
 Tria::Tria(int tria_id, int tria_sid, int index, IoModel* iomodel,int nummodels)/*{{{*/
-	:TriaRef(nummodels),ElementHook(nummodels,index+1,NUMVERTICES,iomodel){
+	:ElementHook(nummodels,index+1,NUMVERTICES,iomodel){
 
 		/*id: */
@@ -42,4 +42,10 @@
 		this->material = NULL;
 		this->matpar   = NULL;
+		if(nummodels>0){
+			this->element_type_list=xNew<int>(nummodels);
+			for(int i=0;i<nummodels;i++) this->element_type_list[i] = 0;
+		}
+		else this->element_type_list = NULL;
+
 }
 /*}}}*/
@@ -56,34 +62,52 @@
 
 	//deal with TriaRef mother class
-	tria->element_type_list=xNew<int>(this->numanalyses);
-	for(i=0;i<this->numanalyses;i++) tria->element_type_list[i]=this->element_type_list[i];
+	int nanalyses = this->numanalyses;
+	if(nanalyses > 0){
+		tria->element_type_list=xNew<int>(nanalyses);
+		for(i=0;i<nanalyses;i++){
+			if (this->element_type_list[i]) tria->element_type_list[i]=this->element_type_list[i];
+			else tria->element_type_list[i] = 0;
+		}
+	}
+	else tria->element_type_list = NULL;
+	tria->element_type=this->element_type;
+	tria->numanalyses=nanalyses;
 
 	//deal with ElementHook mother class
-	tria->numanalyses=this->numanalyses;
-	tria->hnodes=new Hook*[tria->numanalyses];
-	for(i=0;i<tria->numanalyses;i++)tria->hnodes[i]=(Hook*)this->hnodes[i]->copy();
+	if (this->hnodes){
+		tria->hnodes=xNew<Hook*>(tria->numanalyses);
+		for(i=0;i<tria->numanalyses;i++){
+			if (this->hnodes[i]) tria->hnodes[i] = (Hook*)(this->hnodes[i]->copy());
+			else tria->hnodes[i] = NULL;
+		}
+	}
+	else tria->hnodes = NULL;
+
 	tria->hvertices = (Hook*)this->hvertices->copy();
 	tria->hmaterial = (Hook*)this->hmaterial->copy();
 	tria->hmatpar   = (Hook*)this->hmatpar->copy();
+	tria->hneighbors = NULL;
 
 	/*deal with Tria fields: */
 	tria->id  = this->id;
 	tria->sid = this->sid;
-	if(this->inputs){
-		tria->inputs=(Inputs*)this->inputs->Copy();
-	}
-	else{
-		tria->inputs=new Inputs();
-	}
+	if(this->inputs) tria->inputs = (Inputs*)(this->inputs->Copy());
+	else tria->inputs=new Inputs();
+
 	/*point parameters: */
 	tria->parameters=this->parameters;
 
 	/*recover objects: */
-	tria->nodes = xNew<Node*>(3); //we cannot rely on an analysis_counter to tell us which analysis_type we are running, so we just copy the nodes.
-	for(i=0;i<3;i++)tria->nodes[i]=this->nodes[i];
-
-	tria->vertices = (Vertex**)tria->hvertices->deliverp();
-	tria->material = (Material*)tria->hmaterial->delivers();
-	tria->matpar   = (Matpar*)tria->hmatpar->delivers();
+	if (this->nodes){
+		unsigned int num_nodes = 3;
+		tria->nodes = xNew<Node*>(num_nodes); //we cannot rely on an analysis_counter to tell us which analysis_type we are running, so we just copy the nodes.
+		for(i=0;i<num_nodes;i++) if(this->nodes[i]) tria->nodes[i]=this->nodes[i]; else tria->nodes[i] = NULL;
+	}
+	else tria->nodes = NULL;
+	
+
+	tria->vertices = (Vertex**)this->hvertices->deliverp();
+	tria->material = (Material*)this->hmaterial->delivers();
+	tria->matpar   = (Matpar*)this->hmatpar->delivers();
 
 	return tria;
@@ -197,49 +221,4 @@
 }
 /*}}}*/
-void       Tria::ComputeStrainRate(){/*{{{*/
-
-	IssmDouble      xyz_list[NUMVERTICES][3];
-	IssmDouble      epsilon[6]; /* epsilon=[exx,eyy,exy];*/
-	IssmDouble      eps_xx[NUMVERTICES];
-	IssmDouble		 eps_yy[NUMVERTICES];
-	IssmDouble		 eps_zz[NUMVERTICES]={0,0,0};
-	IssmDouble      eps_xy[NUMVERTICES];
-	IssmDouble		 eps_xz[NUMVERTICES]={0,0,0};
-	IssmDouble		 eps_yz[NUMVERTICES]={0,0,0};
-	GaussTria*     gauss=NULL;
-
-	/* Get node coordinates and dof list: */
-	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-
-	/*Retrieve all inputs we will be needing: */
-	Input* vx_input=inputs->GetInput(VxEnum);             _assert_(vx_input);
-	Input* vy_input=inputs->GetInput(VyEnum);             _assert_(vy_input);
-
-	/* Start looping on the number of vertices: */
-	gauss=new GaussTria();
-	for (int iv=0;iv<NUMVERTICES;iv++){
-		gauss->GaussVertex(iv);
-
-		/*Compute strain rate viscosity and pressure: */
-		this->StrainRateSSA(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
-
-		eps_xx[iv]=epsilon[0]; 
-		eps_yy[iv]=epsilon[1];
-		eps_xy[iv]=epsilon[2];
-	}
-
-	/*Add Stress tensor components into inputs*/
-	this->inputs->AddInput(new TriaInput(StrainRatexxEnum,&eps_xx[0],P1Enum));
-	this->inputs->AddInput(new TriaInput(StrainRatexyEnum,&eps_xy[0],P1Enum));
-	this->inputs->AddInput(new TriaInput(StrainRatexzEnum,&eps_xz[0],P1Enum));
-	this->inputs->AddInput(new TriaInput(StrainRateyyEnum,&eps_yy[0],P1Enum));
-	this->inputs->AddInput(new TriaInput(StrainRateyzEnum,&eps_yz[0],P1Enum));
-	this->inputs->AddInput(new TriaInput(StrainRatezzEnum,&eps_zz[0],P1Enum));
-
-	/*Clean up and return*/
-	delete gauss;
-
-}
-/*}}}*/
 void       Tria::ComputeStressTensor(){/*{{{*/
 
@@ -351,9 +330,13 @@
 
 	/*Get Element type*/
-	this->element_type=this->element_type_list[analysis_counter];
+	if (this->element_type_list) this->element_type=this->element_type_list[analysis_counter];
 
 	/*Take care of hooking up all objects for this element, ie links the objects in the hooks to their respective 
 	 * datasets, using internal ids and offsets hidden in hooks: */
-	if(this->hnodes[analysis_counter]) this->hnodes[analysis_counter]->configure(nodesin);
+	if(this->hnodes){
+		if (this->hnodes[analysis_counter]) this->hnodes[analysis_counter]->configure(nodesin);
+		else this->hnodes[analysis_counter] = NULL;
+	}
+	else this->hnodes = NULL; 
 	this->hvertices->configure(verticesin);
 	this->hmaterial->configure(materialsin);
@@ -361,5 +344,5 @@
 
 	/*Now, go pick up the objects inside the hooks: */
-	if(this->hnodes[analysis_counter]) this->nodes=(Node**)this->hnodes[analysis_counter]->deliverp();
+	if(this->hnodes && this->hnodes[analysis_counter]) this->nodes=(Node**)this->hnodes[analysis_counter]->deliverp();
 	else this->nodes=NULL;
 	this->vertices = (Vertex**)this->hvertices->deliverp();
@@ -371,5 +354,5 @@
 
 	/*get inputs configured too: */
-	this->inputs->Configure(parameters);
+	this->inputs->Configure(this->parameters);
 
 }
@@ -889,4 +872,44 @@
 	xDelete<int>(indicesfront);
 }/*}}}*/
+void       Tria::GetLevelCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum,IssmDouble level){/*{{{*/
+
+	/* Intermediaries */
+	int i, dir,nrfrontnodes;
+	IssmDouble  levelset[NUMVERTICES];
+
+	/*Recover parameters and values*/
+	GetInputListOnVertices(&levelset[0],levelsetenum);
+
+	int* indicesfront = xNew<int>(NUMVERTICES);
+	/* Get nodes where there is no ice */
+	nrfrontnodes=0;
+	for(i=0;i<NUMVERTICES;i++){
+		if(levelset[i]==level){
+			indicesfront[nrfrontnodes]=i;
+			nrfrontnodes++;
+		}
+	}
+
+	_assert_(nrfrontnodes==2);
+
+	/* arrange order of frontnodes such that they are oriented counterclockwise */
+	if((NUMVERTICES+indicesfront[0]-indicesfront[1])%NUMVERTICES!=NUMVERTICES-1){
+		int index=indicesfront[0];
+		indicesfront[0]=indicesfront[1];
+		indicesfront[1]=index;
+	}	
+
+	IssmDouble* xyz_front = xNew<IssmDouble>(3*nrfrontnodes);
+	/* Return nodes */
+	for(i=0;i<nrfrontnodes;i++){
+		for(dir=0;dir<3;dir++){
+			xyz_front[3*i+dir]=xyz_list[3*indicesfront[i]+dir];
+		}
+	}
+
+	*pxyz_front=xyz_front;
+
+	xDelete<int>(indicesfront);
+}/*}}}*/
 int        Tria::GetNodeIndex(Node* node){/*{{{*/
 
@@ -900,5 +923,10 @@
 /*}}}*/
 int        Tria::GetNumberOfNodes(void){/*{{{*/
-	return this->NumberofNodes();
+	if (this->nodes) return this->NumberofNodes(this->element_type);
+	else return 0;
+}
+/*}}}*/
+int        Tria::GetNumberOfNodes(int enum_type){/*{{{*/
+	return this->NumberofNodes(enum_type);
 }
 /*}}}*/
@@ -921,5 +949,5 @@
 Node*      Tria::GetNode(int node_number){/*{{{*/
 	_assert_(node_number>=0); 
-	_assert_(node_number<this->NumberofNodes()); 
+	_assert_(node_number<this->NumberofNodes(this->element_type)); 
 	return this->nodes[node_number];
 
@@ -983,5 +1011,4 @@
 	}
 
-
 	/*Control Inputs*/
 	if (control_analysis && iomodel->Data(InversionControlParametersEnum)){
@@ -991,4 +1018,5 @@
 				/*yts conversion*/
 				case BalancethicknessThickeningRateEnum:
+				case BalancethicknessApparentMassbalanceEnum:
 				case VxEnum:
 				case VyEnum:
@@ -1058,5 +1086,5 @@
 
 	/*Fetch number of nodes for this finite element*/
-	int numnodes = this->NumberofNodes();
+	int numnodes = this->NumberofNodes(this->element_type);
 
 	/*Fetch dof list and allocate solution vector*/
@@ -1109,5 +1137,5 @@
 
 		/*Get number of nodes and dof list: */
-		numnodes = this->NumberofNodes();
+		numnodes = this->NumberofNodes(this->element_type);
 		values   = xNew<IssmDouble>(numnodes);
 		GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
@@ -1123,5 +1151,5 @@
 
 		/*Get number of nodes and dof list: */
-		numnodes = this->NumberofNodes();
+		numnodes = this->NumberofNodes(this->element_type);
 		values   = xNew<IssmDouble>(numnodes);
 
@@ -1452,5 +1480,19 @@
 
 	_assert_(gauss->Enum()==GaussTriaEnum);
-	this->GetNodalFunctions(basis,(GaussTria*)gauss);
+	this->GetNodalFunctions(basis,(GaussTria*)gauss,this->element_type);
+
+}
+/*}}}*/
+void       Tria::NodalFunctionsP1(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTriaEnum);
+	this->GetNodalFunctions(basis,(GaussTria*)gauss,P1Enum);
+
+}
+/*}}}*/
+void       Tria::NodalFunctionsP2(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTriaEnum);
+	this->GetNodalFunctions(basis,(GaussTria*)gauss,P2Enum);
 
 }
@@ -1459,5 +1501,12 @@
 
 	_assert_(gauss->Enum()==GaussTriaEnum);
-	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussTria*)gauss);
+	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussTria*)gauss,this->element_type);
+
+}
+/*}}}*/
+void       Tria::NodalFunctionsP1Derivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTriaEnum);
+	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussTria*)gauss,P1Enum);
 
 }
@@ -1558,13 +1607,13 @@
 /*}}}*/
 int        Tria::VelocityInterpolation(void){/*{{{*/
-	return TriaRef::VelocityInterpolation();
+	return TriaRef::VelocityInterpolation(this->element_type);
 }
 /*}}}*/
 int        Tria::PressureInterpolation(void){/*{{{*/
-	return TriaRef::PressureInterpolation();
+	return TriaRef::PressureInterpolation(this->element_type);
 }
 /*}}}*/
 int        Tria::TensorInterpolation(void){/*{{{*/
-	return TriaRef::TensorInterpolation();
+	return TriaRef::TensorInterpolation(this->element_type);
 }
 /*}}}*/
@@ -1714,52 +1763,24 @@
 }
 /*}}}*/
+void       Tria::ResetHooks(){/*{{{*/
+
+	this->nodes=NULL;
+	this->vertices=NULL;
+	this->material=NULL;
+	this->matpar=NULL;
+	this->parameters=NULL;
+
+	//deal with ElementHook mother class
+	for(int i=0;i<this->numanalyses;i++) if(this->hnodes[i]) this->hnodes[i]->reset();
+	this->hvertices->reset();
+	this->hmaterial->reset();
+	this->hmatpar->reset();
+	if(this->hneighbors) this->hneighbors->reset();
+
+}
+/*}}}*/
 void       Tria::SetClone(int* minranks){/*{{{*/
 
 	_error_("not implemented yet");
-}
-/*}}}*/
-void       Tria::SmbGradients(void){/*{{{*/
-
-	int i;
-
-	// input
-   IssmDouble h[NUMVERTICES];					// ice thickness (m)		
-	IssmDouble s[NUMVERTICES];					// surface elevation (m)
-	IssmDouble b_pos[NUMVERTICES];				// Hs-SMB relation parameter
-	IssmDouble b_neg[NUMVERTICES];				// Hs-SMB relation paremeter
-	IssmDouble Href[NUMVERTICES];					// reference elevation from which deviations are used to calculate the SMB adjustment
-	IssmDouble Smbref[NUMVERTICES];				// reference SMB to which deviations are added
-   IssmDouble rho_water;                   // density of fresh water
-	IssmDouble rho_ice;                     // density of ice
-
-	// output
-	IssmDouble smb[NUMVERTICES];					// surface mass balance (m/yr ice)
-
-	/*Recover SmbGradients*/
-	GetInputListOnVertices(&Href[0],SurfaceforcingsHrefEnum);
-	GetInputListOnVertices(&Smbref[0],SurfaceforcingsSmbrefEnum);
-	GetInputListOnVertices(&b_pos[0],SurfaceforcingsBPosEnum);
-	GetInputListOnVertices(&b_neg[0],SurfaceforcingsBNegEnum);
-
-   /*Recover surface elevatio at vertices: */
-	GetInputListOnVertices(&h[0],ThicknessEnum);
-	GetInputListOnVertices(&s[0],SurfaceEnum);
-
-   /*Get material parameters :*/
-   rho_ice=matpar->GetRhoIce();
-   rho_water=matpar->GetRhoFreshwater();
-
-   // loop over all vertices
-   for(i=0;i<NUMVERTICES;i++){
-     if(Smbref[i]>0){
-		  smb[i]=Smbref[i]+b_pos[i]*(s[i]-Href[i]);
-	  }
-	  else{
-		  smb[i]=Smbref[i]+b_neg[i]*(s[i]-Href[i]);
-	  }
-	  smb[i]=smb[i]/rho_ice;      // SMB in m/y ice		
-		}  //end of the loop over the vertices
-	  /*Update inputs*/
-	  this->inputs->AddInput(new TriaInput(SurfaceforcingsMassBalanceEnum,&smb[0],P1Enum));
 }
 /*}}}*/
@@ -1834,9 +1855,10 @@
 
 	/*Get Element type*/
-	this->element_type=this->element_type_list[analysis_counter];
+	if(this->element_type_list) this->element_type=this->element_type_list[analysis_counter];
 
 	/*Pick up nodes*/
-	if(this->hnodes[analysis_counter]) this->nodes=(Node**)this->hnodes[analysis_counter]->deliverp();
-	else this->nodes=NULL;
+	if(this->hnodes && this->hnodes[analysis_counter]){
+		this->nodes=(Node**)this->hnodes[analysis_counter]->deliverp();
+	}
 
 }
@@ -1884,6 +1906,6 @@
 
 	/*Get for Vx and Vy, the max of abs value: */
-	this->MaxAbsVx(&maxabsvx);
-	this->MaxAbsVy(&maxabsvy);
+	maxabsvx = this->inputs->MaxAbs(VxEnum);
+	maxabsvy = this->inputs->MaxAbs(VyEnum);
 
 	/* Get node coordinates and dof list: */
@@ -1920,5 +1942,5 @@
 
 	/*Recover element type*/
-	this->SetElementType(finiteelement_type,analysis_counter);
+	this->element_type_list[analysis_counter]=finiteelement_type;
 
 	/*Recover nodes ids needed to initialize the node hook.*/
@@ -1956,4 +1978,15 @@
 			tria_node_ids[5]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+2]+1;
 			break;
+		case P2bubbleEnum: case P2bubblecondensedEnum:
+			numnodes        = 7;
+			tria_node_ids   = xNew<int>(numnodes);
+			tria_node_ids[0]=iomodel->nodecounter+iomodel->elements[3*index+0];
+			tria_node_ids[1]=iomodel->nodecounter+iomodel->elements[3*index+1];
+			tria_node_ids[2]=iomodel->nodecounter+iomodel->elements[3*index+2];
+			tria_node_ids[3]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+0]+1;
+			tria_node_ids[4]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+1]+1;
+			tria_node_ids[5]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+2]+1;
+			tria_node_ids[6]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+index+1;
+			break;
 		case P1P1Enum: case P1P1GLSEnum:
 			numnodes        = 6;
@@ -1994,4 +2027,29 @@
 			tria_node_ids[8]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elements[3*index+2];
 			break;
+		case LATaylorHoodEnum:
+			numnodes        = 6;
+			tria_node_ids   = xNew<int>(numnodes);
+			tria_node_ids[0]=iomodel->nodecounter+iomodel->elements[3*index+0];
+			tria_node_ids[1]=iomodel->nodecounter+iomodel->elements[3*index+1];
+			tria_node_ids[2]=iomodel->nodecounter+iomodel->elements[3*index+2];
+			tria_node_ids[3]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+0]+1;
+			tria_node_ids[4]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+1]+1;
+			tria_node_ids[5]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+2]+1;
+			break;
+		case CrouzeixRaviartEnum:
+			numnodes        = 10;
+			tria_node_ids   = xNew<int>(numnodes);
+			tria_node_ids[0]=iomodel->nodecounter+iomodel->elements[3*index+0];
+			tria_node_ids[1]=iomodel->nodecounter+iomodel->elements[3*index+1];
+			tria_node_ids[2]=iomodel->nodecounter+iomodel->elements[3*index+2];
+			tria_node_ids[3]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+0]+1;
+			tria_node_ids[4]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+1]+1;
+			tria_node_ids[5]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+2]+1;
+			tria_node_ids[6]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+index+1;
+
+			tria_node_ids[7]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberofelements+3*index+1;
+			tria_node_ids[8]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberofelements+3*index+2;
+			tria_node_ids[9]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberofelements+3*index+3;
+			break;
 		default:
 			_error_("Finite element "<<EnumToStringx(finiteelement_type)<<" not supported yet");
@@ -2018,5 +2076,5 @@
 
 	GaussTria* gauss=new GaussTria();
-	for(int iv=0;iv<this->NumberofNodes();iv++){
+	for(int iv=0;iv<this->NumberofNodes(this->element_type);iv++){
 		gauss->GaussNode(this->element_type,iv);
 		onbase->GetInputValue(&isonbase,gauss);
@@ -2057,5 +2115,5 @@
 /*}}}*/
 void       Tria::ValueP1DerivativesOnGauss(IssmDouble* dvalue,IssmDouble* values,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-	TriaRef::GetInputDerivativeValue(dvalue,values,xyz_list,gauss);
+	TriaRef::GetInputDerivativeValue(dvalue,values,xyz_list,gauss,P1Enum);
 }
 /*}}}*/
@@ -2346,104 +2404,4 @@
 	delete gauss_2;
 	return mass_flux;
-}
-/*}}}*/
-void       Tria::MaxAbsVx(IssmDouble* pmaxabsvx){/*{{{*/
-
-	/*Get maximum:*/
-	IssmDouble maxabsvx=this->inputs->MaxAbs(VxEnum);
-
-	/*Assign output pointers:*/
-	*pmaxabsvx=maxabsvx;
-}
-/*}}}*/
-void       Tria::MaxAbsVy(IssmDouble* pmaxabsvy){/*{{{*/
-
-	/*Get maximum:*/
-	IssmDouble maxabsvy=this->inputs->MaxAbs(VyEnum);
-
-	/*Assign output pointers:*/
-	*pmaxabsvy=maxabsvy;
-}
-/*}}}*/
-void       Tria::MaxAbsVz(IssmDouble* pmaxabsvz){/*{{{*/
-
-	/*Get maximum:*/
-	IssmDouble maxabsvz=this->inputs->MaxAbs(VzEnum);
-
-	/*Assign output pointers:*/
-	*pmaxabsvz=maxabsvz;
-}
-/*}}}*/
-void       Tria::MaxVel(IssmDouble* pmaxvel){/*{{{*/
-
-	/*Get maximum:*/
-	IssmDouble maxvel=this->inputs->Max(VelEnum);
-
-	/*Assign output pointers:*/
-	*pmaxvel=maxvel;
-}
-/*}}}*/
-void       Tria::MaxVx(IssmDouble* pmaxvx){/*{{{*/
-
-	/*Get maximum:*/
-	IssmDouble maxvx=this->inputs->Max(VxEnum);
-
-	/*Assign output pointers:*/
-	*pmaxvx=maxvx;
-}
-/*}}}*/
-void       Tria::MaxVy(IssmDouble* pmaxvy){/*{{{*/
-
-	/*Get maximum:*/
-	IssmDouble maxvy=this->inputs->Max(VyEnum);
-
-	/*Assign output pointers:*/
-	*pmaxvy=maxvy;
-
-}
-/*}}}*/
-void       Tria::MaxVz(IssmDouble* pmaxvz){/*{{{*/
-
-	/*Get maximum:*/
-	IssmDouble maxvz=this->inputs->Max(VzEnum);
-
-	/*Assign output pointers:*/
-	*pmaxvz=maxvz;
-}
-/*}}}*/
-void       Tria::MinVel(IssmDouble* pminvel){/*{{{*/
-
-	/*Get minimum:*/
-	IssmDouble minvel=this->inputs->Min(VelEnum);
-
-	/*Assign output pointers:*/
-	*pminvel=minvel;
-}
-/*}}}*/
-void       Tria::MinVx(IssmDouble* pminvx){/*{{{*/
-
-	/*Get minimum:*/
-	IssmDouble minvx=this->inputs->Min(VxEnum);
-
-	/*Assign output pointers:*/
-	*pminvx=minvx;
-}
-/*}}}*/
-void       Tria::MinVy(IssmDouble* pminvy){/*{{{*/
-
-	/*Get minimum:*/
-	IssmDouble minvy=this->inputs->Min(VyEnum);
-
-	/*Assign output pointers:*/
-	*pminvy=minvy;
-}
-/*}}}*/
-void       Tria::MinVz(IssmDouble* pminvz){/*{{{*/
-
-	/*Get minimum:*/
-	IssmDouble minvz=this->inputs->Min(VzEnum);
-
-	/*Assign output pointers:*/
-	*pminvz=minvz;
 }
 /*}}}*/
@@ -2735,24 +2693,4 @@
 }
 /*}}}*/
-void       Tria::ControlInputGetGradient(Vector<IssmDouble>* gradient,int enum_type,int control_index){/*{{{*/
-
-	int vertexpidlist[NUMVERTICES];
-
-	Input* input=inputs->GetInput(enum_type);
-	if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found");
-	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
-
-	GradientIndexing(&vertexpidlist[0],control_index);
-	((ControlInput*)input)->GetGradient(gradient,&vertexpidlist[0]);
-
-}/*}}}*/
-void       Tria::ControlInputScaleGradient(int enum_type,IssmDouble scale){/*{{{*/
-
-	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");
-
-	((ControlInput*)input)->ScaleGradient(scale);
-}/*}}}*/
 void       Tria::ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index){/*{{{*/
 
@@ -2803,618 +2741,4 @@
 
 }/*}}}*/
-void       Tria::Gradj(Vector<IssmDouble>* gradient,int control_type,int control_index){/*{{{*/
-	/*dJ/dalpha = ∂L/∂alpha = ∂J/∂alpha + ∂/∂alpha(KU-F)*/
-
-	int   approximation;
-	Seg*  seg=NULL;
-
-	/*If on water, grad = 0: */
-	if(!IsIceInElement()) return;
-
-	/*First deal with ∂/∂alpha(KU-F)*/
-	switch(control_type){
-		case FrictionCoefficientEnum:
-			inputs->GetInputValue(&approximation,ApproximationEnum);
-			switch(approximation){
-				case SSAApproximationEnum:
-					GradjDragSSA(gradient,control_index);
-					break;
-				case FSApproximationEnum:
-					GradjDragFS(gradient,control_index);
-					break;
-				case NoneApproximationEnum:
-					/*Gradient is 0*/
-					break;
-				default:
-					_error_("approximation " << EnumToStringx(approximation) << " not supported yet");
-			}
-			break;
-		case MaterialsRheologyBbarEnum:
-			GradjBSSA(gradient,control_index);
-			break;
-		case DamageDbarEnum:
-			GradjDSSA(gradient,control_index);
-			break;
-		case BalancethicknessThickeningRateEnum:
-			GradjDhDtBalancedthickness(gradient,control_index);
-			break;
-		case VxEnum:
-			GradjVxBalancedthickness(gradient,control_index);
-			break;
-		case VyEnum:
-			GradjVyBalancedthickness(gradient,control_index);
-			break;
-		case ThicknessEnum:
-			GradjThicknessBalancethicknessSoft(gradient,control_index);
-			break;
-		default:
-			_error_("control type not supported yet: " << control_type);
-	}
-
-	/*Now deal with ∂J/∂alpha*/
-	int        *responses = NULL;
-	int         num_responses,resp;
-	this->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
-	this->parameters->FindParam(&responses,NULL,InversionCostFunctionsEnum);
-
-	for(resp=0;resp<num_responses;resp++) switch(responses[resp]){
-		//FIXME: the control type should be checked somewhere (with respect to what variable are we taking the gradient!)
-
-		case ThicknessAbsMisfitEnum:
-		case ThicknessAbsGradientEnum:
-		case ThicknessAlongGradientEnum:
-		case ThicknessAcrossGradientEnum:
-		case BalancethicknessMisfitEnum:
-		case SurfaceAbsVelMisfitEnum:
-		case SurfaceRelVelMisfitEnum:
-		case SurfaceLogVelMisfitEnum:
-		case SurfaceLogVxVyMisfitEnum:
-		case SurfaceAverageVelMisfitEnum:
-			/*Nothing, J does not depends on the parameter being inverted for*/
-			break;
-		case DragCoefficientAbsGradientEnum:
-			inputs->GetInputValue(&approximation,ApproximationEnum);
-			switch(approximation){
-				case SSAApproximationEnum:
-					GradjDragGradient(gradient,control_index);
-					break;
-				case FSApproximationEnum:{
-					if(IsFloating() || !IsOnBase()) return;
-					int index1,index2;
-					this->EdgeOnBaseIndices(&index1,&index2);
-					Seg* seg = SpawnSeg(index1,index2);
-					seg->GradjDragGradient(gradient,control_index);
-					seg->DeleteMaterials(); delete seg;
-					break;
-												 }
-				case NoneApproximationEnum:
-					/*Gradient is 0*/
-					break;
-				default:
-					_error_("approximation " << EnumToStringx(approximation) << " not supported yet");
-			}
-			break;
-		case RheologyBbarAbsGradientEnum:
-			GradjBGradient(gradient,control_index);
-			break;
-		default:
-			_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
-	}
-
-	xDelete<int>(responses);
-}
-/*}}}*/
-void       Tria::GradjBGradient(Vector<IssmDouble>* gradient,int control_index){/*{{{*/
-
-	int        i;
-	int        vertexpidlist[NUMVERTICES];
-	IssmDouble Jdet,weight;
-	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble dbasis[NDOF2][NUMVERTICES];
-	IssmDouble dk[NDOF2]; 
-	IssmDouble grade_g[NUMVERTICES]={0.0};
-	GaussTria  *gauss=NULL;
-
-	/*Retrieve all inputs we will be needing: */
-	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	GradientIndexing(&vertexpidlist[0],control_index);
-	Input* rheologyb_input=inputs->GetInput(MaterialsRheologyBbarEnum); _assert_(rheologyb_input);
-	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);                _assert_(weights_input);
-
-	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussTria(2);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-
-		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
-		GetNodalFunctionsDerivatives(&dbasis[0][0],&xyz_list[0][0],gauss);
-		weights_input->GetInputValue(&weight,gauss,RheologyBbarAbsGradientEnum);
-
-		/*Build alpha_complement_list: */
-		rheologyb_input->GetInputDerivativeValue(&dk[0],&xyz_list[0][0],gauss);
-
-		/*Build gradje_g_gaussian vector (actually -dJ/ddrag): */
-		for (i=0;i<NUMVERTICES;i++) grade_g[i]+=-weight*Jdet*gauss->weight*(dbasis[0][i]*dk[0]+dbasis[1][i]*dk[1]);
-	}
-	gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
-
-	/*Clean up and return*/
-	delete gauss;
-}
-/*}}}*/
-void       Tria::GradjBSSA(Vector<IssmDouble>* gradient,int control_index){/*{{{*/
-
-	/*Intermediaries*/
-	int        i;
-	int        doflist[NUMVERTICES];
-	IssmDouble vx,vy,lambda,mu,thickness,Jdet;
-	IssmDouble viscosity_complement;
-	IssmDouble dvx[NDOF2],dvy[NDOF2],dadjx[NDOF2],dadjy[NDOF2],dB[NDOF2]; 
-	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble basis[3],epsilon[3];
-	IssmDouble grad[NUMVERTICES]={0.0};
-	GaussTria *gauss = NULL;
-
-	/* Get node coordinates and dof list: */
-	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	GradientIndexing(&doflist[0],control_index);
-
-	/*Retrieve all inputs*/
-	Input* thickness_input=inputs->GetInput(ThicknessEnum);                     _assert_(thickness_input);
-	Input* vx_input=inputs->GetInput(VxEnum);                                   _assert_(vx_input);
-	Input* vy_input=inputs->GetInput(VyEnum);                                   _assert_(vy_input);
-	Input* adjointx_input=inputs->GetInput(AdjointxEnum);                       _assert_(adjointx_input);
-	Input* adjointy_input=inputs->GetInput(AdjointyEnum);                       _assert_(adjointy_input);
-	Input* rheologyb_input=inputs->GetInput(MaterialsRheologyBbarEnum); _assert_(rheologyb_input);
-
-	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussTria(4);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-
-		thickness_input->GetInputValue(&thickness,gauss);
-		rheologyb_input->GetInputDerivativeValue(&dB[0],&xyz_list[0][0],gauss);
-		vx_input->GetInputDerivativeValue(&dvx[0],&xyz_list[0][0],gauss);
-		vy_input->GetInputDerivativeValue(&dvy[0],&xyz_list[0][0],gauss);
-		adjointx_input->GetInputDerivativeValue(&dadjx[0],&xyz_list[0][0],gauss);
-		adjointy_input->GetInputDerivativeValue(&dadjy[0],&xyz_list[0][0],gauss);
-
-		this->StrainRateSSA(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
-		material->GetViscosityComplement(&viscosity_complement,&epsilon[0]);
-
-		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
-		GetNodalFunctions(basis,gauss);
-
-		/*standard gradient dJ/dki*/
-		for (i=0;i<NUMVERTICES;i++) grad[i]+=-viscosity_complement*thickness*(
-					(2*dvx[0]+dvy[1])*2*dadjx[0]+(dvx[1]+dvy[0])*(dadjx[1]+dadjy[0])+(2*dvy[1]+dvx[0])*2*dadjy[1]
-					)*Jdet*gauss->weight*basis[i];
-	}
-
-	gradient->SetValues(NUMVERTICES,doflist,grad,ADD_VAL);
-
-	/*clean-up*/
-	delete gauss;
-}
-/*}}}*/
-void       Tria::GradjDSSA(Vector<IssmDouble>* gradient,int control_index){/*{{{*/
-
-	/*Intermediaries*/
-	int        i;
-	int        doflist[NUMVERTICES];
-	IssmDouble vx,vy,lambda,mu,thickness,Jdet;
-	IssmDouble viscosity_complement;
-	IssmDouble dvx[NDOF2],dvy[NDOF2],dadjx[NDOF2],dadjy[NDOF2];
-	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble basis[3],epsilon[3];
-	IssmDouble grad[NUMVERTICES]={0.0};
-	GaussTria *gauss = NULL;
-
-	/* Get node coordinates and dof list: */
-	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	GradientIndexing(&doflist[0],control_index);
-
-	/*Retrieve all inputs*/
-	Input* thickness_input=inputs->GetInput(ThicknessEnum);                     _assert_(thickness_input);
-	Input* vx_input=inputs->GetInput(VxEnum);                                   _assert_(vx_input);
-	Input* vy_input=inputs->GetInput(VyEnum);                                   _assert_(vy_input);
-	Input* adjointx_input=inputs->GetInput(AdjointxEnum);                       _assert_(adjointx_input);
-	Input* adjointy_input=inputs->GetInput(AdjointyEnum);                       _assert_(adjointy_input);
-	if(this->material->IsDamage()){
-		Input* rheologyd_input=inputs->GetInput(DamageDbarEnum); _assert_(rheologyd_input);
-	}
-
-	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussTria(4);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-
-		thickness_input->GetInputValue(&thickness,gauss);
-		vx_input->GetInputDerivativeValue(&dvx[0],&xyz_list[0][0],gauss);
-		vy_input->GetInputDerivativeValue(&dvy[0],&xyz_list[0][0],gauss);
-		adjointx_input->GetInputDerivativeValue(&dadjx[0],&xyz_list[0][0],gauss);
-		adjointy_input->GetInputDerivativeValue(&dadjy[0],&xyz_list[0][0],gauss);
-
-		this->StrainRateSSA(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
-		material->GetViscosityDComplement(&viscosity_complement,&epsilon[0]);
-
-		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
-		GetNodalFunctions(basis,gauss);
-
-		/*standard gradient dJ/dki*/
-		for (i=0;i<NUMVERTICES;i++) grad[i]+=-viscosity_complement*thickness*(
-					(2*dvx[0]+dvy[1])*2*dadjx[0]+(dvx[1]+dvy[0])*(dadjx[1]+dadjy[0])+(2*dvy[1]+dvx[0])*2*dadjy[1]
-					)*Jdet*gauss->weight*basis[i];
-	}
-
-	gradient->SetValues(NUMVERTICES,doflist,grad,ADD_VAL);
-
-	/*clean-up*/
-	delete gauss;
-}
-/*}}}*/
-void       Tria::GradjDragSSA(Vector<IssmDouble>* gradient,int control_index){/*{{{*/
-
-	int        i;
-	int        analysis_type;
-	int        vertexpidlist[NUMVERTICES];
-	int        connectivity[NUMVERTICES];
-	IssmDouble vx,vy,lambda,mu,alpha_complement,Jdet;
-	IssmDouble bed,thickness,Neff,drag;
-	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble dk[NDOF2]; 
-	IssmDouble grade_g[NUMVERTICES]={0.0};
-	IssmDouble grade_g_gaussian[NUMVERTICES];
-	IssmDouble basis[3];
-	Friction*  friction=NULL;
-	GaussTria  *gauss=NULL;
-
-	if(IsFloating())return;
-
-	/*retrive parameters: */
-	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
-	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	GradientIndexing(&vertexpidlist[0],control_index);
-	this->GetVerticesConnectivityList(&connectivity[0]);
-
-	/*Build frictoin element, needed later: */
-	friction=new Friction(this,2);
-
-	/*Retrieve all inputs we will be needing: */
-	Input* adjointx_input=inputs->GetInput(AdjointxEnum);                   _assert_(adjointx_input);
-	Input* adjointy_input=inputs->GetInput(AdjointyEnum);                   _assert_(adjointy_input);
-	Input* vx_input=inputs->GetInput(VxEnum);                               _assert_(vx_input);
-	Input* vy_input=inputs->GetInput(VyEnum);                               _assert_(vy_input);
-	Input* dragcoefficient_input=inputs->GetInput(FrictionCoefficientEnum); _assert_(dragcoefficient_input);
-
-	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussTria(4);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-
-		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
-		GetNodalFunctions(basis, gauss);
-
-		/*Build alpha_complement_list: */
-		friction->GetAlphaComplement(&alpha_complement,gauss);
-
-		dragcoefficient_input->GetInputValue(&drag, gauss);
-		adjointx_input->GetInputValue(&lambda, gauss);
-		adjointy_input->GetInputValue(&mu, gauss);
-		vx_input->GetInputValue(&vx,gauss);
-		vy_input->GetInputValue(&vy,gauss);
-		dragcoefficient_input->GetInputDerivativeValue(&dk[0],&xyz_list[0][0],gauss);
-
-		/*Build gradje_g_gaussian vector (actually -dJ/ddrag): */
-		for (i=0;i<NUMVERTICES;i++){
-			grade_g_gaussian[i]=-2*drag*alpha_complement*((lambda*vx+mu*vy))*Jdet*gauss->weight*basis[i];
-		}
-
-		/*Add gradje_g_gaussian vector to gradje_g: */
-		for(i=0;i<NUMVERTICES;i++){
-			_assert_(!xIsNan<IssmDouble>(grade_g[i]));
-			grade_g[i]+=grade_g_gaussian[i];
-		}
-	}
-	/*Analytical gradient*/
-	//delete gauss;
-	//gauss=new GaussTria();
-	//for (int iv=0;iv<NUMVERTICES;iv++){
-	//	gauss->GaussVertex(iv);
-	//	friction->GetAlphaComplement(&alpha_complement,gauss);
-	//	dragcoefficient_input->GetInputValue(&drag, gauss);
-	//	adjointx_input->GetInputValue(&lambda, gauss);
-	//	adjointy_input->GetInputValue(&mu, gauss);
-	//	vx_input->GetInputValue(&vx,gauss);
-	//	vy_input->GetInputValue(&vy,gauss);
-	//	grade_g[iv] = -2*1.e+7*drag*alpha_complement*(lambda*vx+mu*vy)/((IssmDouble)connectivity[iv]);
-	//}
-	/*End Analytical gradient*/
-
-	gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
-
-	/*Clean up and return*/
-	delete gauss;
-	delete friction;
-}
-/*}}}*/
-void       Tria::GradjDragFS(Vector<IssmDouble>* gradient,int control_index){/*{{{*/
-
-	/*Gradient is 0 if on shelf or not on bed*/
-	if(IsFloating() || !IsOnBase()) return;
-
-	int index1,index2;
-	this->EdgeOnBaseIndices(&index1,&index2);
-	Seg* seg = SpawnSeg(index1,index2);
-	seg->GradjDragFS(gradient,control_index);
-	seg->DeleteMaterials(); delete seg;
-}
-/*}}}*/
-void       Tria::GradjDragGradient(Vector<IssmDouble>* gradient,int control_index){/*{{{*/
-
-	int        i;
-	int        vertexpidlist[NUMVERTICES];
-	IssmDouble Jdet,weight;
-	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble dbasis[NDOF2][NUMVERTICES];
-	IssmDouble dk[NDOF2]; 
-	IssmDouble grade_g[NUMVERTICES]={0.0};
-	GaussTria  *gauss=NULL;
-
-	/*Retrieve all inputs we will be needing: */
-	if(IsFloating())return;
-	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	GradientIndexing(&vertexpidlist[0],control_index);
-	Input* dragcoefficient_input=inputs->GetInput(FrictionCoefficientEnum); _assert_(dragcoefficient_input);
-	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);                 _assert_(weights_input);
-
-	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussTria(2);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-
-		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
-		GetNodalFunctionsDerivatives(&dbasis[0][0],&xyz_list[0][0],gauss);
-		weights_input->GetInputValue(&weight,gauss,DragCoefficientAbsGradientEnum);
-
-		/*Build alpha_complement_list: */
-		dragcoefficient_input->GetInputDerivativeValue(&dk[0],&xyz_list[0][0],gauss);
-
-		/*Build gradje_g_gaussian vector (actually -dJ/ddrag): */
-		for (i=0;i<NUMVERTICES;i++){
-			grade_g[i]+=-weight*Jdet*gauss->weight*(dbasis[0][i]*dk[0]+dbasis[1][i]*dk[1]);
-			_assert_(!xIsNan<IssmDouble>(grade_g[i]));
-		}
-	}
-	gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
-
-	/*Clean up and return*/
-	delete gauss;
-}
-/*}}}*/
-void       Tria::GradjDhDtBalancedthickness(Vector<IssmDouble>* gradient,int control_index){/*{{{*/
-
-	/*Intermediaries*/
-	int    vertexpidlist[NUMVERTICES];
-	IssmDouble lambda[NUMVERTICES];
-	IssmDouble gradient_g[NUMVERTICES];
-
-	/*Compute Gradient*/
-	GradientIndexing(&vertexpidlist[0],control_index);
-	GetInputListOnVertices(&lambda[0],AdjointEnum);
-	for(int i=0;i<NUMVERTICES;i++) gradient_g[i]=-lambda[i];
-
-	gradient->SetValues(NUMVERTICES,vertexpidlist,gradient_g,INS_VAL);
-}
-/*}}}*/
-void       Tria::GradjVxBalancedthickness(Vector<IssmDouble>* gradient,int control_index){/*{{{*/
-
-	/*Intermediaries*/
-	int        i;
-	int        vertexpidlist[NUMVERTICES];
-	IssmDouble thickness,Jdet;
-	IssmDouble basis[3];
-	IssmDouble Dlambda[2],dp[2];
-	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble grade_g[NUMVERTICES] = {0.0};
-	GaussTria *gauss                = NULL;
-
-	/* Get node coordinates and dof list: */
-	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	GradientIndexing(&vertexpidlist[0],control_index);
-
-	/*Retrieve all inputs we will be needing: */
-	Input* adjoint_input=inputs->GetInput(AdjointEnum);     _assert_(adjoint_input);
-	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
-
-	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussTria(2);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-
-		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
-		GetNodalFunctions(basis, gauss);
-
-		adjoint_input->GetInputDerivativeValue(&Dlambda[0],&xyz_list[0][0],gauss);
-		thickness_input->GetInputValue(&thickness, gauss);
-		thickness_input->GetInputDerivativeValue(&dp[0],&xyz_list[0][0],gauss);
-
-		for(i=0;i<NUMVERTICES;i++) grade_g[i]+=thickness*Dlambda[0]*Jdet*gauss->weight*basis[i];
-	}
-
-	gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
-
-	/*Clean up and return*/
-	delete gauss;
-}
-/*}}}*/
-void       Tria::GradjVyBalancedthickness(Vector<IssmDouble>* gradient,int control_index){/*{{{*/
-
-	/*Intermediaries*/
-	int        i;
-	int        vertexpidlist[NUMVERTICES];
-	IssmDouble thickness,Jdet;
-	IssmDouble basis[3];
-	IssmDouble Dlambda[2],dp[2];
-	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble grade_g[NUMVERTICES] = {0.0};
-	GaussTria *gauss                = NULL;
-
-	/* Get node coordinates and dof list: */
-	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	GradientIndexing(&vertexpidlist[0],control_index);
-
-	/*Retrieve all inputs we will be needing: */
-	Input* adjoint_input=inputs->GetInput(AdjointEnum);     _assert_(adjoint_input);
-	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
-
-	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussTria(2);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-
-		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
-		GetNodalFunctions(basis, gauss);
-
-		adjoint_input->GetInputDerivativeValue(&Dlambda[0],&xyz_list[0][0],gauss);
-		thickness_input->GetInputValue(&thickness, gauss);
-		thickness_input->GetInputDerivativeValue(&dp[0],&xyz_list[0][0],gauss);
-
-		for(i=0;i<NUMVERTICES;i++) grade_g[i]+=thickness*Dlambda[1]*Jdet*gauss->weight*basis[i];
-	}
-	gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
-
-	/*Clean up and return*/
-	delete gauss;
-}
-/*}}}*/
-void       Tria::GradjThicknessBalancethicknessSoft(Vector<IssmDouble>* gradient,int control_index){/*{{{*/
-
-	/*Intermediaries */
-	int         i,resp;
-	int         vertexpidlist[NUMVERTICES];
-	IssmDouble  Jdet;
-	IssmDouble  thickness,thicknessobs,weight;
-	int         num_responses;
-	IssmDouble  xyz_list[NUMVERTICES][3];
-	IssmDouble  basis[3];
-	IssmDouble  dbasis[NDOF2][NUMVERTICES];
-	IssmDouble  dH[2];
-	IssmDouble  vx,vy,vel;
-	IssmDouble  dvx[2],dvy[2];
-	IssmDouble dhdt,basal_melting,surface_mass_balance;
-	GaussTria *gauss     = NULL;
-	int       *responses = NULL;
-	IssmDouble grade_g[NUMVERTICES] = {0.0};
-
-	/* Get node coordinates and dof list: */
-	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	GradientIndexing(&vertexpidlist[0],control_index);
-
-	/*Retrieve all inputs and parameters*/
-	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	this->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
-	this->parameters->FindParam(&responses,NULL,InversionCostFunctionsEnum);
-	Input* thickness_input            = inputs->GetInput(ThicknessEnum);                          _assert_(thickness_input);
-	Input* thicknessobs_input         = inputs->GetInput(InversionThicknessObsEnum);              _assert_(thicknessobs_input);
-	Input* weights_input              = inputs->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
-	Input* vx_input                   = inputs->GetInput(VxEnum);                                 _assert_(vx_input);
-	Input* vy_input                   = inputs->GetInput(VyEnum);                                 _assert_(vy_input);
-	Input* surface_mass_balance_input = inputs->GetInput(SurfaceforcingsMassBalanceEnum);         _assert_(surface_mass_balance_input);
-	Input* basal_melting_input        = inputs->GetInput(BasalforcingsMeltingRateEnum);           _assert_(basal_melting_input);
-	Input* dhdt_input                 = inputs->GetInput(BalancethicknessThickeningRateEnum);     _assert_(dhdt_input);
-
-	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussTria(2);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-
-		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
-		GetNodalFunctions(basis, gauss);
-		GetNodalFunctionsDerivatives(&dbasis[0][0],&xyz_list[0][0],gauss);
-
-		thickness_input->GetInputValue(&thickness, gauss);
-		thickness_input->GetInputDerivativeValue(&dH[0],&xyz_list[0][0],gauss);
-		thicknessobs_input->GetInputValue(&thicknessobs, gauss);
-
-		/*Loop over all requested responses*/
-		for(resp=0;resp<num_responses;resp++){
-
-			weights_input->GetInputValue(&weight,gauss,responses[resp]);
-
-			switch(responses[resp]){
-
-				case ThicknessAbsMisfitEnum:
-					for(i=0;i<NUMVERTICES;i++) grade_g[i]+= (thicknessobs-thickness)*weight*Jdet*gauss->weight*basis[i];
-					break;
-				case ThicknessAbsGradientEnum:
-					for(i=0;i<NUMVERTICES;i++) grade_g[i]+= - weight*dH[0]*dbasis[0][i]*Jdet*gauss->weight;
-					for(i=0;i<NUMVERTICES;i++) grade_g[i]+= - weight*dH[1]*dbasis[1][i]*Jdet*gauss->weight;
-					break;
-				case ThicknessAlongGradientEnum:
-					vx_input->GetInputValue(&vx,gauss);
-					vy_input->GetInputValue(&vy,gauss);
-					vel = sqrt(vx*vx+vy*vy);
-					vx  = vx/(vel+1.e-9);
-					vy  = vy/(vel+1.e-9);
-					for(i=0;i<NUMVERTICES;i++) grade_g[i]+= - weight*(dH[0]*vx+dH[1]*vy)*(dbasis[0][i]*vx+dbasis[1][i]*vy)*Jdet*gauss->weight;
-					break;
-				case ThicknessAcrossGradientEnum:
-					vx_input->GetInputValue(&vx,gauss);
-					vy_input->GetInputValue(&vy,gauss);
-					vel = sqrt(vx*vx+vy*vy);
-					vx  = vx/(vel+1.e-9);
-					vy  = vy/(vel+1.e-9);
-					for(i=0;i<NUMVERTICES;i++) grade_g[i]+= - weight*(dH[0]*(-vy)+dH[1]*vx)*(dbasis[0][i]*(-vy)+dbasis[1][i]*vx)*Jdet*gauss->weight;
-					break;
-				case BalancethicknessMisfitEnum:
-					surface_mass_balance_input->GetInputValue(&surface_mass_balance,gauss);
-					basal_melting_input->GetInputValue(&basal_melting,gauss);
-					dhdt_input->GetInputValue(&dhdt,gauss);
-					vx_input->GetInputValue(&vx,gauss);
-					vx_input->GetInputDerivativeValue(&dvx[0],&xyz_list[0][0],gauss);
-					vy_input->GetInputValue(&vy,gauss);
-					vy_input->GetInputDerivativeValue(&dvy[0],&xyz_list[0][0],gauss);
-					for(i=0;i<NUMVERTICES;i++){
-						grade_g[i]+= - weight*Jdet*gauss->weight*(
-									(vx*dH[0]+vy*dH[1] + thickness*(dvx[0]+dvy[1]))*(vx*dbasis[0][i]+ vy*dbasis[1][i] + basis[i]*(dvx[0]+dvy[1]))
-									-(surface_mass_balance-basal_melting-dhdt)*(vx*dbasis[0][i]+ vy*dbasis[1][i] + basis[i]*(dvx[0]+dvy[1]))
-									);
-					}
-					break;
-				default:
-					_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
-			}
-		}
-	}
-
-	gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
-
-	/*Clean up and return*/
-	delete gauss;
-	xDelete<int>(responses);
-}
-/*}}}*/
-void       Tria::GradientIndexing(int* indexing,int control_index){/*{{{*/
-
-	/*Get some parameters*/
-	int num_controls;
-	parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
-
-	/*get gradient indices*/
-	for(int i=0;i<NUMVERTICES;i++){
-		indexing[i]=num_controls*this->vertices[i]->Pid() + control_index;
-	}
-
-}
-/*}}}*/
 void       Tria::GetVectorFromControlInputs(Vector<IssmDouble>* vector,int control_enum,int control_index,const char* data){/*{{{*/
 
@@ -3442,7 +2766,23 @@
 
 	IssmDouble  values[NUMVERTICES];
-	int     vertexpidlist[NUMVERTICES];
-	Input  *input     = NULL;
-	Input  *new_input = NULL;
+	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*/
@@ -3453,11 +2793,10 @@
 
 	/*Get values on vertices*/
-	for (int i=0;i<NUMVERTICES;i++){
+	for(int i=0;i<NUMVERTICES;i++){
 		values[i]=vector[vertexpidlist[i]];
 	}
-	new_input = new TriaInput(control_enum,values,P1Enum);
-
-	input=(Input*)this->inputs->GetInput(control_enum);   _assert_(input);
-	if (input->ObjectEnum()!=ControlInputEnum){
+	Input* new_input = new TriaInput(control_enum,values,P1Enum);
+	Input* input     = (Input*)this->inputs->GetInput(control_enum);   _assert_(input);
+	if(input->ObjectEnum()!=ControlInputEnum){
 		_error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
 	}
@@ -3472,5 +2811,5 @@
 
 	/*Fetch number of nodes for this finite element*/
-	int numnodes = this->NumberofNodes();
+	int numnodes = this->NumberofNodes(this->element_type);
 
 	/*Fetch dof list and allocate solution vector*/
@@ -3634,8 +2973,6 @@
 
 	int        i,migration_style;
-	bool       oldfloating;
-	bool       floatingelement = false;
 	bool       groundedelement = false;
-	IssmDouble bed_hydro,yts,gl_melting_rate;
+	IssmDouble bed_hydro,yts;
 	IssmDouble rho_water,rho_ice,density;
 	IssmDouble melting[NUMVERTICES],phi[NUMVERTICES];;
@@ -3644,5 +2981,4 @@
 	/*Recover info at the vertices: */
 	parameters->FindParam(&migration_style,GroundinglineMigrationEnum);
-	parameters->FindParam(&gl_melting_rate,GroundinglineMeltingRateEnum);
 	parameters->FindParam(&yts,ConstantsYtsEnum);
 	GetInputListOnVertices(&h[0],ThicknessEnum);
@@ -3654,5 +2990,4 @@
 	rho_ice     = matpar->GetRhoIce();
 	density     = rho_ice/rho_water;
-	oldfloating = this->IsFloating(); //figure out if element is floating before we start to change everything
 
 	if(migration_style == ContactEnum){
@@ -3667,16 +3002,4 @@
 			}
 		}
-
-		/*Add basal melting rate if element just ungrounded*/
-		for(i=0;i<NUMVERTICES;i++){
-			if(phi[i]<0.){
-				floatingelement=true;
-				break;
-			}
-		}
-		if(!oldfloating && floatingelement==true){
-			for(i=0;i<NUMVERTICES;i++) melting[i]=gl_melting_rate/yts;
-			this->inputs->AddInput(new TriaInput(BasalforcingsMeltingRateEnum,&melting[0],P1Enum));
-		} 
 
 		/*Update inputs*/
@@ -3729,30 +3052,4 @@
 	this->inputs->AddInput(new TriaInput(MaskGroundediceLevelsetEnum,&phi[0],P1Enum));
 
-	/*SubelementMigrationEnum: if one grounded, all grounded*/
-	if(migration_style==SubelementMigrationEnum || migration_style==SubelementMigration2Enum){
-		for(i=0;i<NUMVERTICES;i++){
-			if(phi[i]>0.){
-				groundedelement=true;
-				break;
-			}
-		}
-		floatingelement=!groundedelement;
-	}
-	else{
-		/*Otherwise: if one floating, all floating*/
-		for(i=0;i<NUMVERTICES;i++){
-			if(phi[i]<=0.){
-				floatingelement=true;
-				break;
-			}
-		}
-	}
-
-	/*Add basal melting rate if element just ungrounded*/
-	if(!oldfloating && floatingelement==true){
-		for(i=0;i<NUMVERTICES;i++)melting[i]=gl_melting_rate/yts;
-		this->inputs->AddInput(new TriaInput(BasalforcingsMeltingRateEnum,&melting[0],P1Enum));
-	} 
-
 	/*Update inputs*/
 	this->inputs->AddInput(new TriaInput(SurfaceEnum,&s[0],P1Enum));
Index: issm/trunk/src/c/classes/Elements/Tria.h
===================================================================
--- issm/trunk/src/c/classes/Elements/Tria.h	(revision 18081)
+++ issm/trunk/src/c/classes/Elements/Tria.h	(revision 18301)
@@ -53,6 +53,4 @@
 		void        ComputeBasalStress(Vector<IssmDouble>* sigma_b);
 		void        ComputeSigmaNN();
-		void		   ComputeStrainRate();
-		void		   ComputeStrainRate(Vector<IssmDouble>* eps){_error_("not implemented yet");};
 		void        ComputeStressTensor();
 		void        ComputeDeviatoricStressTensor();
@@ -60,4 +58,5 @@
 		void        Configure(Elements* elements,Loads* loads,Nodes* nodesin,Vertices* verticesin,Materials* materials,Parameters* parameters);
 		void        SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Materials* materials,Parameters* parameters);
+		void        ResetHooks();
 		void        Delta18oParameterization(void);
 		void        ElementSizes(IssmDouble* hx,IssmDouble* hy,IssmDouble* hz);
@@ -70,4 +69,5 @@
 		int         GetNodeIndex(Node* node);
 		int         GetNumberOfNodes(void);
+		int         GetNumberOfNodes(int enum_type);
 		int         GetNumberOfVertices(void);
 		bool        IsOnBase();
@@ -93,5 +93,4 @@
 		void        ReduceMatrices(ElementMatrix* Ke,ElementVector* pe);
 		void        ResetFSBasalBoundaryCondition(void);
-		void	      SmbGradients();
 	   Element*    SpawnBasalElement(void);
 		Element*    SpawnTopElement(void);
@@ -102,13 +101,14 @@
 		void        Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finitelement);
 		IssmDouble  TimeAdapt();
-		void   ValueP1OnGauss(IssmDouble* pvalue,IssmDouble* values,Gauss* gauss);
-		void   ValueP1DerivativesOnGauss(IssmDouble* dvalue,IssmDouble* values,IssmDouble* xyz_list,Gauss* gauss);
+		void        ValueP1OnGauss(IssmDouble* pvalue,IssmDouble* values,Gauss* gauss);
+		void        ValueP1DerivativesOnGauss(IssmDouble* dvalue,IssmDouble* values,IssmDouble* xyz_list,Gauss* gauss);
 		int         VertexConnectivity(int vertexindex);
-		void   VerticalSegmentIndices(int** pindices,int* pnumseg){_error_("not implemented yet");};
+		void        VerticalSegmentIndices(int** pindices,int* pnumseg){_error_("not implemented yet");};
 		void        ZeroLevelsetCoordinates(IssmDouble** pxyz_zero,IssmDouble* xyz_list,int levelsetenum);
-		void	    GetIcefrontCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum);
+		void	      GetIcefrontCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum);
+		void	      GetLevelCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum,IssmDouble level);
 		bool        IsZeroLevelset(int levelset_enum);
-		bool		IsIcefront(void);
-		bool		IsFaceOnBoundary(void);
+		bool	   	IsIcefront(void);
+		bool	   	IsFaceOnBoundary(void);
 
 		void       AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part);
@@ -116,18 +116,7 @@
 		IssmDouble IceVolumeAboveFloatation(void);
 		IssmDouble TotalSmb(void);
-		void       MinVel(IssmDouble* pminvel);
-		void       MinVx(IssmDouble* pminvx);
-		void       MinVy(IssmDouble* pminvy);
-		void       MinVz(IssmDouble* pminvz);
 		IssmDouble MassFlux(IssmDouble* segment);
 		IssmDouble MassFlux(IssmDouble x1,IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id);
-		void       MaxAbsVx(IssmDouble* pmaxabsvx);
-		void       MaxAbsVy(IssmDouble* pmaxabsvy);
-		void       MaxAbsVz(IssmDouble* pmaxabsvz);
 		void       ElementResponse(IssmDouble* presponse,int response_enum);
-		void       MaxVel(IssmDouble* pmaxvel);
-		void       MaxVx(IssmDouble* pmaxvx);
-		void       MaxVy(IssmDouble* pmaxvy);
-		void       MaxVz(IssmDouble* pmaxvz);
 		IssmDouble Misfit(int modelenum,int observationenum,int weightsenum);
 		IssmDouble MisfitArea(int weightsenum);
@@ -137,21 +126,6 @@
 		#endif
 
-		void       GradientIndexing(int* indexing,int control_index);
-		void       Gradj(Vector<IssmDouble>* gradient,int control_type,int control_index);
-		void       GradjBGradient(Vector<IssmDouble>* gradient,int control_index);
-		void       GradjDGradient(Vector<IssmDouble>* gradient,int control_index);
-		void       GradjBSSA(Vector<IssmDouble>* gradient,int control_index);
-		void       GradjDSSA(Vector<IssmDouble>* gradient,int control_index);
-		void       GradjDragSSA(Vector<IssmDouble>* gradient,int control_index);
-		void       GradjDragFS(Vector<IssmDouble>* gradient,int control_index);
-		void       GradjDragGradient(Vector<IssmDouble>* gradient,int control_index);
-		void       GradjDhDtBalancedthickness(Vector<IssmDouble>* gradient,int control_index);
-		void       GradjVxBalancedthickness(Vector<IssmDouble>* gradient,int control_index);
-		void       GradjVyBalancedthickness(Vector<IssmDouble>* gradient,int control_index);
-		void       GradjThicknessBalancethicknessSoft(Vector<IssmDouble>* gradient,int control_index);
 		void       GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data);
 		void       SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index);
-		void       ControlInputGetGradient(Vector<IssmDouble>* gradient,int enum_type,int control_index);
-		void       ControlInputScaleGradient(int enum_type,IssmDouble scale);
 		void       ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index);
 		void       ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum);
@@ -192,7 +166,8 @@
 		Gauss*         NewGaussTop(int order);
 		void           NodalFunctions(IssmDouble* basis,Gauss* gauss);
-		void           NodalFunctionsP1(IssmDouble* basis,Gauss* gauss){_error_("not implemented yet");};
+		void           NodalFunctionsP1(IssmDouble* basis,Gauss* gauss);
+		void           NodalFunctionsP2(IssmDouble* basis,Gauss* gauss);
 		void           NodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
-		void           NodalFunctionsP1Derivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
+		void           NodalFunctionsP1Derivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
 		void           NodalFunctionsMINIDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
 		void           NodalFunctionsDerivativesVelocity(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
Index: issm/trunk/src/c/classes/Elements/TriaRef.cpp
===================================================================
--- issm/trunk/src/c/classes/Elements/TriaRef.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Elements/TriaRef.cpp	(revision 18301)
@@ -4,5 +4,5 @@
 
 /*Headers:*/
-/*{{{*//*{{{*/
+/*{{{*/
 #ifdef HAVE_CONFIG_H
 	#include <config.h>
@@ -20,32 +20,16 @@
 #define NUMNODESP1b 4
 #define NUMNODESP2  6
+#define NUMNODESP2b 7
 
 /*Object constructors and destructor*/
 TriaRef::TriaRef(){/*{{{*/
-	this->element_type_list=NULL;
-}
-/*}}}*/
-TriaRef::TriaRef(const int nummodels){/*{{{*/
-
-	/*Only allocate pointer*/
-	element_type_list=xNew<int>(nummodels);
-
 }
 /*}}}*/
 TriaRef::~TriaRef(){/*{{{*/
-	xDelete<int>(element_type_list);
-}
-/*}}}*/
-
-/*Management*/
-void TriaRef::SetElementType(int type,int type_counter){/*{{{*/
-
-	/*initialize element type*/
-	this->element_type_list[type_counter]=type;
 }
 /*}}}*/
 
 /*Reference Element numerics*/
-void TriaRef::GetSegmentBFlux(IssmDouble* B,Gauss* gauss, int index1,int index2){/*{{{*/
+void TriaRef::GetSegmentBFlux(IssmDouble* B,Gauss* gauss, int index1,int index2,int finiteelement){/*{{{*/
 	/*Compute B  matrix. B=[phi1 phi2 -phi3 -phi4]
 	 *
@@ -56,9 +40,9 @@
 
 	/*Fetch number of nodes for this finite element*/
-	int numnodes = this->NumberofNodes();
+	int numnodes = this->NumberofNodes(finiteelement);
 
 	/*Get nodal functions*/
 	IssmDouble* basis=xNew<IssmDouble>(numnodes);
-	GetNodalFunctions(basis,gauss);
+	GetNodalFunctions(basis,gauss,finiteelement);
 
 	/*Build B for this segment*/
@@ -72,5 +56,5 @@
 }
 /*}}}*/
-void TriaRef::GetSegmentBprimeFlux(IssmDouble* Bprime,Gauss* gauss, int index1,int index2){/*{{{*/
+void TriaRef::GetSegmentBprimeFlux(IssmDouble* Bprime,Gauss* gauss, int index1,int index2,int finiteelement){/*{{{*/
 	/*Compute Bprime  matrix. Bprime=[phi1 phi2 phi3 phi4]
 	 *
@@ -81,9 +65,9 @@
 
 	/*Fetch number of nodes for this finite element*/
-	int numnodes = this->NumberofNodes();
+	int numnodes = this->NumberofNodes(finiteelement);
 
 	/*Get nodal functions*/
 	IssmDouble* basis=xNew<IssmDouble>(numnodes);
-	GetNodalFunctions(basis,gauss);
+	GetNodalFunctions(basis,gauss,finiteelement);
 
 	/*Build B'*/
@@ -155,12 +139,4 @@
 }
 /*}}}*/
-void TriaRef::GetNodalFunctions(IssmDouble* basis,Gauss* gauss){/*{{{*/
-	/*This routine returns the values of the nodal functions  at the gaussian point.*/
-
-	_assert_(basis);
-	GetNodalFunctions(basis,gauss,this->element_type);
-
-}
-/*}}}*/
 void TriaRef::GetNodalFunctions(IssmDouble* basis,Gauss* gauss_in,int finiteelement){/*{{{*/
 	/*This routine returns the values of the nodal functions  at the gaussian point.*/
@@ -173,4 +149,6 @@
 
 	switch(finiteelement){
+		case NoneEnum:
+			return;
 		case P0Enum:
 			basis[0]=1.;
@@ -199,4 +177,16 @@
 			basis[5]=4.*gauss->coord1*gauss->coord2;
 			return;
+		case P2bubbleEnum: case P2bubblecondensedEnum:
+			/*Corner nodes*/
+			basis[0]=gauss->coord1*(2.*gauss->coord1-1.);
+			basis[1]=gauss->coord2*(2.*gauss->coord2-1.);
+			basis[2]=gauss->coord3*(2.*gauss->coord3-1.);
+			/*Mid-sides*/
+			basis[3]=4.*gauss->coord3*gauss->coord2;
+			basis[4]=4.*gauss->coord3*gauss->coord1;
+			basis[5]=4.*gauss->coord1*gauss->coord2;
+			/*bubble*/
+			basis[6]=27.*gauss->coord1*gauss->coord2*gauss->coord3;
+			return;
 		default:
 			_error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
@@ -204,5 +194,5 @@
 }
 /*}}}*/
-void TriaRef::GetSegmentNodalFunctions(IssmDouble* basis,Gauss* gauss,int index1,int index2){/*{{{*/
+void TriaRef::GetSegmentNodalFunctions(IssmDouble* basis,Gauss* gauss,int index1,int index2,int finiteelement){/*{{{*/
 	/*This routine returns the values of the nodal functions  at the gaussian point.*/
 
@@ -211,11 +201,11 @@
 
 	/*Fetch number of nodes for this finite element*/
-	int numnodes = this->NumberofNodes();
+	int numnodes = this->NumberofNodes(finiteelement);
 
 	/*Get nodal functions*/
 	IssmDouble* triabasis=xNew<IssmDouble>(numnodes);
-	GetNodalFunctions(triabasis,gauss);
-
-	switch(this->element_type){
+	GetNodalFunctions(triabasis,gauss,finiteelement);
+
+	switch(finiteelement){
 		case P1Enum: case P1DGEnum:
 			basis[0]=triabasis[index1];
@@ -236,15 +226,9 @@
 			return;
 		default:
-			_error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+			_error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
 	}
 
 	/*Clean up*/
 	xDelete<IssmDouble>(triabasis);
-}
-/*}}}*/
-void TriaRef::GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, Gauss* gauss){/*{{{*/
-
-	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss,this->element_type);
-
 }
 /*}}}*/
@@ -276,12 +260,4 @@
 	/*Clean up*/
 	xDelete<IssmDouble>(dbasis_ref);
-
-}
-/*}}}*/
-void TriaRef::GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,Gauss* gauss){/*{{{*/
-	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
-	 * natural coordinate system) at the gaussian point. */
-
-	GetNodalFunctionsDerivativesReference(dbasis,gauss,this->element_type);
 
 }
@@ -348,4 +324,27 @@
 			dbasis[NUMNODESP2*1+5] = -2.*SQRT3/3.*(gauss->coord1+gauss->coord2);
 			return;
+		case P2bubbleEnum: case P2bubblecondensedEnum:
+			/*Nodal function 1*/
+			dbasis[NUMNODESP2b*0+0] = -2.*gauss->coord1 + 0.5;
+			dbasis[NUMNODESP2b*1+0] = -2.*SQRT3/3.*gauss->coord1 + SQRT3/6.;
+			/*Nodal function 2*/
+			dbasis[NUMNODESP2b*0+1] = +2.*gauss->coord2 - 0.5;
+			dbasis[NUMNODESP2b*1+1] = -2.*SQRT3/3.*gauss->coord2 + SQRT3/6.;
+			/*Nodal function 3*/
+			dbasis[NUMNODESP2b*0+2] = 0.;
+			dbasis[NUMNODESP2b*1+2] = +4.*SQRT3/3.*gauss->coord3 - SQRT3/3.;
+			/*Nodal function 4*/
+			dbasis[NUMNODESP2b*0+3] = +2.*gauss->coord3;
+			dbasis[NUMNODESP2b*1+3] = +4.*SQRT3/3.*gauss->coord2 - 2.*SQRT3/3.*gauss->coord3;
+			/*Nodal function 5*/
+			dbasis[NUMNODESP2b*0+4] = -2.*gauss->coord3;
+			dbasis[NUMNODESP2b*1+4] = +4.*SQRT3/3.*gauss->coord1 - 2.*SQRT3/3.*gauss->coord3;
+			/*Nodal function 6*/
+			dbasis[NUMNODESP2b*0+5] = 2.*(gauss->coord1-gauss->coord2);
+			dbasis[NUMNODESP2b*1+5] = -2.*SQRT3/3.*(gauss->coord1+gauss->coord2);
+			/*Nodal function 7*/
+			dbasis[NUMNODESP2b*0+6] = 27.*(-.5*gauss->coord2*gauss->coord3 + .5*gauss->coord1*gauss->coord3);
+			dbasis[NUMNODESP2b*1+6] = 27.*SQRT3*(-1./6.*gauss->coord2*gauss->coord3 - 1./6.*gauss->coord1*gauss->coord3 +1./3.*gauss->coord1*gauss->coord2);
+			return;
 		default:
 			_error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
@@ -354,5 +353,5 @@
 }
 /*}}}*/
-void TriaRef::GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, Gauss* gauss){/*{{{*/
+void TriaRef::GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, Gauss* gauss,int finiteelement){/*{{{*/
 
 	/*From node values of parameter p (plist[0],plist[1],plist[2]), return parameter derivative value at gaussian 
@@ -369,9 +368,9 @@
 
 	/*Fetch number of nodes for this finite element*/
-	int numnodes = this->NumberofNodes();
+	int numnodes = this->NumberofNodes(finiteelement);
 
 	/*Get nodal functions derivatives*/
 	IssmDouble* dbasis=xNew<IssmDouble>(2*numnodes);
-	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss,finiteelement);
 
 	/*Calculate parameter for this Gauss point*/
@@ -386,9 +385,4 @@
 }
 /*}}}*/
-void TriaRef::GetInputValue(IssmDouble* p, IssmDouble* plist, Gauss* gauss){/*{{{*/
-
-	GetInputValue(p,plist,gauss,this->element_type);
-}
-/*}}}*/
 void TriaRef::GetInputValue(IssmDouble* p, IssmDouble* plist, Gauss* gauss,int finiteelement){/*{{{*/
 
@@ -411,12 +405,8 @@
 }
 /*}}}*/
-int  TriaRef::NumberofNodes(void){/*{{{*/
-
-	return this->NumberofNodes(this->element_type);
-}
-/*}}}*/
 int  TriaRef::NumberofNodes(int finiteelement){/*{{{*/
 
 	switch(finiteelement){
+		case NoneEnum:              return 0;
 		case P0Enum:                return NUMNODESP0;
 		case P1Enum:                return NUMNODESP1;
@@ -425,4 +415,6 @@
 		case P1bubblecondensedEnum: return NUMNODESP1b;
 		case P2Enum:                return NUMNODESP2;
+		case P2bubbleEnum:          return NUMNODESP2b;
+		case P2bubblecondensedEnum: return NUMNODESP2b;
 		case P1P1Enum:              return NUMNODESP1*2;
 		case P1P1GLSEnum:           return NUMNODESP1*2;
@@ -430,6 +422,8 @@
 		case MINIEnum:              return NUMNODESP1b+NUMNODESP1;
 		case TaylorHoodEnum:        return NUMNODESP2+NUMNODESP1;
+		case LATaylorHoodEnum:      return NUMNODESP2;
 		case XTaylorHoodEnum:       return NUMNODESP2+NUMNODESP1;
-		default: _error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+		case CrouzeixRaviartEnum:   return NUMNODESP2b+NUMNODESP1;
+		default: _error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
 	}
 
@@ -437,14 +431,16 @@
 }
 /*}}}*/
-int  TriaRef::VelocityInterpolation(void){/*{{{*/
-
-	switch(this->element_type){
-		case P1P1Enum:          return P1Enum;
-		case P1P1GLSEnum:       return P1Enum;
-		case MINIcondensedEnum: return P1bubbleEnum;
-		case MINIEnum:          return P1bubbleEnum;
-		case TaylorHoodEnum:    return P2Enum;
-		case XTaylorHoodEnum:   return P2Enum;
-		default:       _error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+int  TriaRef::VelocityInterpolation(int fe_stokes){/*{{{*/
+
+	switch(fe_stokes){
+		case P1P1Enum:           return P1Enum;
+		case P1P1GLSEnum:        return P1Enum;
+		case MINIcondensedEnum:  return P1bubbleEnum;
+		case MINIEnum:           return P1bubbleEnum;
+		case TaylorHoodEnum:     return P2Enum;
+		case LATaylorHoodEnum:   return P2Enum;
+		case XTaylorHoodEnum:    return P2Enum;
+		case CrouzeixRaviartEnum:return P2bubbleEnum;
+		default:       _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
 	}
 
@@ -452,14 +448,16 @@
 }
 /*}}}*/
-int  TriaRef::PressureInterpolation(void){/*{{{*/
-
-	switch(this->element_type){
-		case P1P1Enum:          return P1Enum;
-		case P1P1GLSEnum:       return P1Enum;
-		case MINIcondensedEnum: return P1Enum;
-		case MINIEnum:          return P1Enum;
-		case TaylorHoodEnum:    return P1Enum;
-		case XTaylorHoodEnum:   return P1Enum;
-		default:       _error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+int  TriaRef::PressureInterpolation(int fe_stokes){/*{{{*/
+
+	switch(fe_stokes){
+		case P1P1Enum:            return P1Enum;
+		case P1P1GLSEnum:         return P1Enum;
+		case MINIcondensedEnum:   return P1Enum;
+		case MINIEnum:            return P1Enum;
+		case TaylorHoodEnum:      return P1Enum;
+		case LATaylorHoodEnum:    return NoneEnum;
+		case XTaylorHoodEnum:     return P1Enum;
+		case CrouzeixRaviartEnum: return P1DGEnum;
+		default:       _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
 	}
 
@@ -467,10 +465,10 @@
 }
 /*}}}*/
-int  TriaRef::TensorInterpolation(void){/*{{{*/
+int  TriaRef::TensorInterpolation(int fe_stokes){/*{{{*/
 	/*This routine returns the values of the nodal functions  at the gaussian point.*/
 
-	switch(this->element_type){
+	switch(fe_stokes){
 		case XTaylorHoodEnum: return P1DGEnum;
-		default: _error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+		default: _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
 	}
 }
@@ -527,5 +525,5 @@
 			break;
 		default:
-			_error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+			_error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
 	}
 
Index: issm/trunk/src/c/classes/Elements/TriaRef.h
===================================================================
--- issm/trunk/src/c/classes/Elements/TriaRef.h	(revision 18081)
+++ issm/trunk/src/c/classes/Elements/TriaRef.h	(revision 18301)
@@ -12,13 +12,6 @@
 
 	public: 
-		int* element_type_list; //P1CG, P1DG, MINI, P2...
-		int  element_type;
-
 		TriaRef();
-		TriaRef(const int nummodels);
 		~TriaRef();
-
-		/*Management*/
-		void SetElementType(int type,int type_counter);
 
 		/*Numerics*/
@@ -27,23 +20,18 @@
 		void GetJacobianDeterminant(IssmDouble* Jdet, IssmDouble* xyz_list,Gauss* gauss);
 		void GetJacobianInvert(IssmDouble*  Jinv, IssmDouble* xyz_list,Gauss* gauss);
-		void GetNodalFunctions(IssmDouble* basis,Gauss* gauss);
 		void GetNodalFunctions(IssmDouble* basis,Gauss* gauss,int finiteelement);
-		void GetSegmentNodalFunctions(IssmDouble* basis,Gauss* gauss, int index1,int index2);
-		void GetSegmentBFlux(IssmDouble* B,Gauss* gauss, int index1,int index2);
-		void GetSegmentBprimeFlux(IssmDouble* Bprime,Gauss* gauss, int index1,int index2);
-		void GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, Gauss* gauss);
+		void GetSegmentNodalFunctions(IssmDouble* basis,Gauss* gauss, int index1,int index2,int finiteelement);
+		void GetSegmentBFlux(IssmDouble* B,Gauss* gauss, int index1,int index2,int finiteelement);
+		void GetSegmentBprimeFlux(IssmDouble* Bprime,Gauss* gauss, int index1,int index2,int finiteelement);
 		void GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, Gauss* gauss,int finiteelement);
-		void GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,Gauss* gauss);
 		void GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,Gauss* gauss,int finiteelement);
-		void GetInputValue(IssmDouble* pp, IssmDouble* plist, Gauss* gauss);
 		void GetInputValue(IssmDouble* pp, IssmDouble* plist, Gauss* gauss,int finiteelement);
-		void GetInputDerivativeValue(IssmDouble* pp, IssmDouble* plist,IssmDouble* xyz_list, Gauss* gauss);
+		void GetInputDerivativeValue(IssmDouble* pp, IssmDouble* plist,IssmDouble* xyz_list, Gauss* gauss,int finiteelement);
 
 		void NodeOnEdgeIndices(int* pnumindices,int** pindices,int index,int finiteelement);
-		int  NumberofNodes(void);
 		int  NumberofNodes(int finiteelement);
-		int  VelocityInterpolation(void);
-		int  PressureInterpolation(void);
-		int  TensorInterpolation(void);
+		int  VelocityInterpolation(int fe_stokes);
+		int  PressureInterpolation(int fe_stokes);
+		int  TensorInterpolation(int fe_stokes);
 };
 #endif
Index: issm/trunk/src/c/classes/ExternalResults/Results.cpp
===================================================================
--- issm/trunk/src/c/classes/ExternalResults/Results.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/ExternalResults/Results.cpp	(revision 18301)
@@ -20,12 +20,10 @@
 
 /*Object constructors and destructor*/
-/*FUNCTION Results::Results(){{{*/
-Results::Results(){
+Results::Results(){/*{{{*/
 	enum_type=ResultsEnum;
 	return;
 }
 /*}}}*/
-/*FUNCTION Results::~Results(){{{*/
-Results::~Results(){
+Results::~Results(){/*{{{*/
 	return;
 }
@@ -33,6 +31,5 @@
 
 /*Object management*/
-/*FUNCTION Results::Write{{{*/
-void Results::Write(Parameters* parameters){
+void Results::Write(Parameters* parameters){/*{{{*/
 
 	FILE       *fid  = NULL;
@@ -50,6 +47,5 @@
 }
 /*}}}*/
-/*FUNCTION Results::AddResult(ExternalResult* in_result){{{*/
-int Results::AddResult(ExternalResult* in_result){
+int Results::AddResult(ExternalResult* in_result){/*{{{*/
 
 	/*First, go through dataset of inputs and check whether any input 
@@ -82,6 +78,5 @@
 }
 /*}}}*/
-/*FUNCTION Results::DeleteResult(ExternalResult* in_result){{{*/
-int Results::DeleteResult(int result_enum,int result_step){
+int Results::DeleteResult(int result_enum,int result_step){/*{{{*/
 
 	for(int i=0;i<this->Size();i++){
Index: issm/trunk/src/c/classes/FemModel.cpp
===================================================================
--- issm/trunk/src/c/classes/FemModel.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/FemModel.cpp	(revision 18301)
@@ -43,6 +43,5 @@
 
 /*Object constructors and destructor*/
-/*FUNCTION FemModel::FemModel(int argc,char** argv,ISSM_MPI_Comm incomm){{{*/
-FemModel::FemModel(int argc,char** argv,ISSM_MPI_Comm incomm){
+FemModel::FemModel(int argc,char** argv,ISSM_MPI_Comm incomm){/*{{{*/
 
 	/*configuration: */
@@ -94,6 +93,5 @@
 }
 /*}}}*/
-/*FUNCTION FemModel::FemModel(char* rootpath, char* inputfilename, char* outputfilename, char* toolkitsfilename, char* lockfilename, const int in_solution_type,const int* analyses,const int nummodels){{{*/
-FemModel::FemModel(char* rootpath, char* inputfilename, char* outputfilename, char* toolkitsfilename, char* lockfilename, const int in_solution_type,const int* analyses,const int nummodels){
+FemModel::FemModel(char* rootpath, char* inputfilename, char* outputfilename, char* toolkitsfilename, char* lockfilename, const int in_solution_type,const int* analyses,const int nummodels){/*{{{*/
 
 	/*Call InitFromFiles. This constructor is just a wrapper: */
@@ -102,6 +100,5 @@
 }
 /*}}}*/
-/*FUNCTION FemModel::~FemModel{{{*/
-FemModel::~FemModel(){
+FemModel::~FemModel(){/*{{{*/
 
 	/*Intermediary*/
@@ -109,18 +106,7 @@
 	char *outbinfilename = NULL;
 	char *lockfilename   = NULL;
-	bool  waitonlock     = false;
-
-	/*Close output file: */
-	this->parameters->FindParam(&output_fid,OutputFilePointerEnum); 
-	this->parameters->FindParam(&outbinfilename,OutputFileNameEnum); 
-	pfclose(output_fid,outbinfilename);
-
-	/*Write lock file if requested: */
-	this->parameters->FindParam(&waitonlock,SettingsWaitonlockEnum);
+
+	this->parameters->FindParam(&outbinfilename,OutputFileNameEnum);
 	this->parameters->FindParam(&lockfilename,LockFileNameEnum);
-	if(waitonlock){
-		_printf0_("write lock file:\n");
-		WriteLockFile(lockfilename);
-	}
 
 	/*Delete all the datasets: */
@@ -137,4 +123,113 @@
 	delete results;
 
+	/*Now delete: */
+	delete profiler;
+
+}
+/*}}}*/
+
+/*Object management*/
+void FemModel::Echo(void){/*{{{*/
+
+	_printf_("FemModel echo: \n");
+	_printf_("   number of fem models: " << nummodels << "\n");
+	_printf_("   analysis_type_list: \n");
+	for(int i=0;i<nummodels;i++)_printf_("     " << i << ": " << EnumToStringx(analysis_type_list[i]) << "\n");
+	_printf_("   current analysis_type: \n");
+	_printf_("     " << analysis_counter << ": " << EnumToStringx(analysis_type_list[analysis_counter]) << "\n");
+
+}
+/*}}}*/
+void FemModel::InitFromFiles(char* rootpath, char* inputfilename, char* outputfilename, char* toolkitsfilename, char* lockfilename, const int in_solution_type,const int* analyses,const int nummodels){/*{{{*/
+
+	/*intermediary*/
+	int         i;
+	int         analysis_type;
+	FILE       *IOMODEL = NULL;
+	FILE       *toolkitsoptionsfid = NULL;
+	FILE       *output_fid = NULL;
+	int         my_rank;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	/*Open input file on cpu 0: */
+	if(my_rank==0) IOMODEL = pfopen0(inputfilename ,"rb");
+
+	/*Open toolkits file: */
+	toolkitsoptionsfid=pfopen(toolkitsfilename,"r");
+
+	/*Initialize internal data: */
+	this->nummodels        = nummodels;
+	this->solution_type    = in_solution_type;
+	this->analysis_counter = nummodels-1;   //point to last analysis_type carried out.
+	this->results          = new Results(); //not initialized by CreateDataSets
+
+	/*Dynamically allocate whatever is a list of length nummodels: */
+	analysis_type_list=xNew<int>(nummodels);
+
+	/*Initialize: */
+	for(i=0;i<nummodels;i++)analysis_type_list[i]=analyses[i];
+
+	/*create datasets for all analyses*/
+	ModelProcessorx(&this->elements,&this->nodes,&this->vertices,&this->materials,&this->constraints,&this->loads,&this->parameters,IOMODEL,toolkitsoptionsfid,rootpath,this->solution_type,nummodels,analyses);
+
+	/*do the post-processing of the datasets to get an FemModel that can actually run analyses: */
+	for(i=0;i<nummodels;i++){
+
+		if(VerboseMProcessor()) _printf0_("   Processing finite element model of analysis " << EnumToStringx(analysis_type_list[i]) << ":\n");
+		analysis_type=analysis_type_list[i];
+		this->SetCurrentConfiguration(analysis_type);
+
+		if(i==0){
+			if(VerboseMProcessor()) _printf0_("      creating vertex PIDs\n");
+			VerticesDofx(vertices,parameters); //only call once, we only have one set of vertices
+		}
+
+		if(VerboseMProcessor()) _printf0_("      resolving node constraints\n");
+		SpcNodesx(nodes,constraints,parameters,analysis_type); 
+
+		if(VerboseMProcessor()) _printf0_("      creating nodal degrees of freedom\n");
+		NodesDofx(nodes,parameters,analysis_type);
+
+		if(VerboseMProcessor()) _printf0_("      configuring element and loads\n");
+		ConfigureObjectsx(elements, loads, nodes, vertices, materials,parameters);
+	}
+
+	/*Close input file and toolkits file descriptors: */
+	if(my_rank==0) pfclose(IOMODEL,inputfilename);
+	pfclose(toolkitsoptionsfid,toolkitsfilename);
+
+	/*Open output file once for all and add output file name and file descriptor to parameters*/
+	output_fid=pfopen(outputfilename,"wb");
+	this->parameters->AddObject(new StringParam(OutputFileNameEnum,outputfilename));
+	this->parameters->SetParam(output_fid,OutputFilePointerEnum);
+
+	/*Save lock file name for later: */
+	this->parameters->AddObject(new StringParam(LockFileNameEnum,lockfilename));
+
+	}
+/*}}}*/
+void FemModel::CleanUp(void){/*{{{*/
+
+	/*Intermediary*/
+	FILE *output_fid;
+	char *outbinfilename = NULL;
+	char *lockfilename   = NULL;
+	bool  waitonlock     = false;
+
+	/*Close output file: */
+	this->parameters->FindParam(&output_fid,OutputFilePointerEnum);
+	this->parameters->FindParam(&outbinfilename,OutputFileNameEnum);
+	pfclose(output_fid,outbinfilename);
+
+	/*Write lock file if requested: */
+	this->parameters->FindParam(&waitonlock,SettingsWaitonlockEnum);
+	this->parameters->FindParam(&lockfilename,LockFileNameEnum);
+	if(waitonlock){
+		_printf0_("write lock file:\n");
+		WriteLockFile(lockfilename);
+	}
+
 	/*Before we delete the profiler, report statistics for this run: */
 	profiler->Tag(Finish);  //final tagging
@@ -144,108 +239,24 @@
 	_printf0_("\n");
 	_printf0_("   Total elapsed time:"
-			<<profiler->DeltaTimeModHour(Start,Finish)<<" hrs "
-			<<profiler->DeltaTimeModMin(Start,Finish)<<" min "
-			<<profiler->DeltaTimeModSec(Start,Finish)<<" sec"
-			);
+				<<profiler->DeltaTimeModHour(Start,Finish)<<" hrs "
+				<<profiler->DeltaTimeModMin(Start,Finish)<<" min "
+				<<profiler->DeltaTimeModSec(Start,Finish)<<" sec"
+				);
 	_printf0_("\n");
-
-	/*Now delete: */
-	delete profiler;
 
 	/*Finalize PETSC for this model: */
 	#ifdef _HAVE_PETSC_
 	_printf0_("closing PETSc\n");
-	PetscFinalize(); 
+	PetscFinalize();
 	#endif
 
-}
-/*}}}*/
-
-/*Object management*/
-/*FUNCTION FemModel::Echo {{{*/
-void FemModel::Echo(void){
-
-	_printf_("FemModel echo: \n");
-	_printf_("   number of fem models: " << nummodels << "\n");
-	_printf_("   analysis_type_list: \n");
-	for(int i=0;i<nummodels;i++)_printf_("     " << i << ": " << EnumToStringx(analysis_type_list[i]) << "\n");
-	_printf_("   current analysis_type: \n");
-	_printf_("     " << analysis_counter << ": " << EnumToStringx(analysis_type_list[analysis_counter]) << "\n");
-
-}
-/*}}}*/
-/*FUNCTION FemModel::InitFromFiles(char* rootpath, char* inputfilename, char* outputfilename, char* toolkitsfilename, char* lockfilename, const int in_solution_type,const int* analyses,const int nummodels){{{*/
-void FemModel::InitFromFiles(char* rootpath, char* inputfilename, char* outputfilename, char* toolkitsfilename, char* lockfilename, const int in_solution_type,const int* analyses,const int nummodels){
-
-	/*intermediary*/
-	int         i;
-	int         analysis_type;
-	FILE       *IOMODEL = NULL;
-	FILE       *toolkitsoptionsfid = NULL;
-	FILE       *output_fid = NULL;
-	int         my_rank;
-
-	/*recover my_rank:*/
-	my_rank=IssmComm::GetRank();
-
-	/*Open input file on cpu 0: */
-	if(my_rank==0) IOMODEL = pfopen0(inputfilename ,"rb");
-
-	/*Open toolkits file: */
-	toolkitsoptionsfid=pfopen(toolkitsfilename,"r");
-
-	/*Initialize internal data: */
-	this->nummodels        = nummodels;
-	this->solution_type    = in_solution_type;
-	this->analysis_counter = nummodels-1;   //point to last analysis_type carried out.
-	this->results          = new Results(); //not initialized by CreateDataSets
-
-	/*Dynamically allocate whatever is a list of length nummodels: */
-	analysis_type_list=xNew<int>(nummodels);
-
-	/*Initialize: */
-	for(i=0;i<nummodels;i++)analysis_type_list[i]=analyses[i];
-
-	/*create datasets for all analyses*/
-	ModelProcessorx(&this->elements,&this->nodes,&this->vertices,&this->materials,&this->constraints,&this->loads,&this->parameters,IOMODEL,toolkitsoptionsfid,rootpath,this->solution_type,nummodels,analyses);
-
-	/*do the post-processing of the datasets to get an FemModel that can actually run analyses: */
-	for(i=0;i<nummodels;i++){
-
-		if(VerboseMProcessor()) _printf0_("   Processing finite element model of analysis " << EnumToStringx(analysis_type_list[i]) << ":\n");
-		analysis_type=analysis_type_list[i];
-		this->SetCurrentConfiguration(analysis_type);
-
-		if(i==0){
-			if(VerboseMProcessor()) _printf0_("      creating vertex PIDs\n");
-			VerticesDofx(vertices,parameters); //only call once, we only have one set of vertices
-		}
-
-		if(VerboseMProcessor()) _printf0_("      resolving node constraints\n");
-		SpcNodesx(nodes,constraints,parameters,analysis_type); 
-
-		if(VerboseMProcessor()) _printf0_("      creating nodal degrees of freedom\n");
-		NodesDofx(nodes,parameters,analysis_type);
-
-		if(VerboseMProcessor()) _printf0_("      configuring element and loads\n");
-		ConfigureObjectsx(elements, loads, nodes, vertices, materials,parameters);
-	}
-
-	/*Close input file and toolkits file descriptors: */
-	if(my_rank==0) pfclose(IOMODEL,inputfilename);
-	pfclose(toolkitsoptionsfid,toolkitsfilename);
-
-	/*Open output file once for all and add output file name and file descriptor to parameters*/
-	output_fid=pfopen(outputfilename,"wb");
-	this->parameters->AddObject(new StringParam(OutputFileNameEnum,outputfilename));
-	this->parameters->SetParam(output_fid,OutputFilePointerEnum);
-
-	/*Save lock file name for later: */
-	this->parameters->AddObject(new StringParam(LockFileNameEnum,lockfilename));
-
-	}
-/*}}}*/
-/*FUNCTION FemModel::SetStaticComm {{{*/
-void FemModel::SetStaticComm(void){
+
+	/*Clean up*/
+	xDelete<char>(outbinfilename);
+	xDelete<char>(lockfilename);
+
+}
+/*}}}*/
+void FemModel::SetStaticComm(void){/*{{{*/
 
 	/*This routine sets the global communicator variable hidden inside the IssmComm 
@@ -255,6 +266,5 @@
 }
 /*}}}*/
-/*FUNCTION FemModel::SetCurrentConfiguration(int configuration_type,int analysis_type){{{*/
-void FemModel::SetCurrentConfiguration(int configuration_type,int analysis_type){
+void FemModel::SetCurrentConfiguration(int configuration_type,int analysis_type){/*{{{*/
 
 	/*Use configuration_type to setup the analysis counter, the configurations of objects etc ... but use 
@@ -290,11 +300,9 @@
 }
 /*}}}*/
-/*FUNCTION FemModel::SetCurrentConfiguration(int configuration_type){{{*/
-void FemModel::SetCurrentConfiguration(int configuration_type){
+void FemModel::SetCurrentConfiguration(int configuration_type){/*{{{*/
 	this->SetCurrentConfiguration(configuration_type,configuration_type);
 }
 /*}}}*/
-/*FUNCTION FemModel::Solve {{{*/
-void FemModel::Solve(void){
+void FemModel::Solve(void){/*{{{*/
 
 	/*profiling: */
@@ -357,4 +365,52 @@
 }
 /*}}}*/
+FemModel* FemModel::copy(void){/*{{{*/
+
+	FemModel* output=NULL;
+	int       i;
+	int       analysis_type;
+
+	output=new FemModel(*this); //Use default copy constructor.
+
+	output->comm = this->comm;
+	output->nummodels = this->nummodels;
+	output->solution_type = this->solution_type;
+	output->analysis_counter = this->analysis_counter;
+
+	/*Now, deep copy arrays: */
+	output->analysis_type_list=xNew<int>(nummodels);
+	xMemCpy<int>(output->analysis_type_list,this->analysis_type_list,this->nummodels);
+
+	output->profiler=static_cast<Profiler*>(this->profiler->copy());
+
+	output->loads=static_cast<Loads*>(this->loads->Copy());
+	output->materials=static_cast<Materials*>(this->materials->Copy());
+	output->parameters=static_cast<Parameters*>(this->parameters->Copy());
+	output->constraints=static_cast<Constraints*>(this->constraints->Copy());
+	output->results=static_cast<Results*>(this->results->Copy());
+
+	output->nodes=static_cast<Nodes*>(this->nodes->Copy());
+	output->vertices=static_cast<Vertices*>(this->vertices->Copy());
+	output->elements=static_cast<Elements*>(this->elements->Copy());
+
+	/*reset hooks for elements, loads and nodes: */
+	output->elements->ResetHooks();
+	output->loads->ResetHooks();
+	output->materials->ResetHooks();
+
+	/*do the post-processing of the datasets to get an FemModel that can actually run analyses: */
+	for(i=0;i<nummodels;i++){
+		analysis_type=output->analysis_type_list[i];
+		output->SetCurrentConfiguration(analysis_type);
+		if(i==0) VerticesDofx(output->vertices,output->parameters); //only call once, we only have one set of vertices
+		SpcNodesx(output->nodes,output->constraints,output->parameters,analysis_type);
+		NodesDofx(output->nodes,output->parameters,analysis_type);
+		ConfigureObjectsx(output->elements,output->loads,output->nodes,output->vertices,output->materials,output->parameters);
+	}
+
+	return output;
+}
+/*}}}*/
+
 /*Modules:*/
 int  FemModel::UpdateVertexPositionsx(void){ /*{{{*/
@@ -436,15 +492,15 @@
 		case IceVolumeAboveFloatationEnum: this->IceVolumeAboveFloatationx(responses); break;
 		case MinVelEnum:                   this->MinVelx(responses); break;
-		case MaxVelEnum:                   this->MaxVelx(                  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 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 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 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;
@@ -459,4 +515,5 @@
 		case DragCoefficientAbsGradientEnum:DragCoefficientAbsGradientx(responses, elements,nodes, vertices, loads, materials, parameters); break;
 		case BalancethicknessMisfitEnum:   BalancethicknessMisfitx(responses); break;
+		case Balancethickness2MisfitEnum:  Balancethickness2Misfitx(responses); break;
 		case TotalSmbEnum:					  this->TotalSmbx(responses); break;
 		case MaterialsRheologyBbarEnum:    this->ElementResponsex(responses,MaterialsRheologyBbarEnum); break;
@@ -535,4 +592,5 @@
 				case DragCoefficientAbsGradientEnum:DragCoefficientAbsGradientx(&double_result,elements,nodes,vertices,loads,materials,parameters); break;
 				case BalancethicknessMisfitEnum:    BalancethicknessMisfitx(&double_result);                                                        break;
+				case Balancethickness2MisfitEnum:  Balancethickness2Misfitx(&double_result); break;
 
 			   /*Vector */
@@ -541,10 +599,17 @@
 					/*Vector layout*/
 					int interpolation,nodesperelement,size;
+					int rank_interpolation=-1,rank_nodesperelement=-1;
 
 					/*Get interpolation (and compute input if necessary)*/
 					for(int j=0;j<elements->Size();j++){
 						Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(j));
-						element->ResultInterpolation(&interpolation,&nodesperelement,output_enum);
+						element->ResultInterpolation(&rank_interpolation,&rank_nodesperelement,output_enum);
 					}
+
+					/*Broadcast for cpus that do not have any elements*/
+					ISSM_MPI_Reduce(&rank_interpolation,&interpolation,1,ISSM_MPI_INT,ISSM_MPI_MAX,0,IssmComm::GetComm());
+					ISSM_MPI_Reduce(&rank_nodesperelement,&nodesperelement,1,ISSM_MPI_INT,ISSM_MPI_MAX,0,IssmComm::GetComm());
+					ISSM_MPI_Bcast(&interpolation,1,ISSM_MPI_INT,0,IssmComm::GetComm());
+					ISSM_MPI_Bcast(&nodesperelement,1,ISSM_MPI_INT,0,IssmComm::GetComm());
 
 					if(results_on_nodes){
@@ -774,6 +839,6 @@
 	maxabsvx=-INFINITY;
 	for(i=0;i<this->elements->Size();i++){
-		Element* element=(Element*)this->elements->GetObjectByOffset(i);
-		element->MaxAbsVx(&element_maxabsvx);
+		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element_maxabsvx=element->inputs->MaxAbs(VxEnum);
 		if(element_maxabsvx>maxabsvx) maxabsvx=element_maxabsvx;
 	}
@@ -798,6 +863,6 @@
 	maxabsvy=-INFINITY;
 	for(i=0;i<this->elements->Size();i++){
-		Element* element=(Element*)this->elements->GetObjectByOffset(i);
-		element->MaxAbsVy(&element_maxabsvy);
+		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element_maxabsvy=element->inputs->MaxAbs(VyEnum);
 		if(element_maxabsvy>maxabsvy) maxabsvy=element_maxabsvy;
 	}
@@ -822,6 +887,6 @@
 	maxabsvz=-INFINITY;
 	for(i=0;i<this->elements->Size();i++){
-		Element* element=(Element*)this->elements->GetObjectByOffset(i);
-		element->MaxAbsVz(&element_maxabsvz);
+		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element_maxabsvz=element->inputs->MaxAbs(VzEnum);
 		if(element_maxabsvz>maxabsvz) maxabsvz=element_maxabsvz;
 	}
@@ -846,6 +911,6 @@
 	maxvel=-INFINITY;
 	for(i=0;i<this->elements->Size();i++){
-		Element* element=(Element*)this->elements->GetObjectByOffset(i);
-		element->MaxVel(&element_maxvel);
+		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element_maxvel = element->inputs->Max(VelEnum);
 		if(element_maxvel>maxvel) maxvel=element_maxvel;
 	}
@@ -870,6 +935,6 @@
 	maxvx=-INFINITY;
 	for(i=0;i<this->elements->Size();i++){
-		Element* element=(Element*)this->elements->GetObjectByOffset(i);
-		element->MaxVx(&element_maxvx);
+		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element_maxvx = element->inputs->Max(VxEnum);
 		if(element_maxvx>maxvx) maxvx=element_maxvx;
 	}
@@ -894,6 +959,6 @@
 	maxvy=-INFINITY;
 	for(i=0;i<this->elements->Size();i++){
-		Element* element=(Element*)this->elements->GetObjectByOffset(i);
-		element->MaxVy(&element_maxvy);
+		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element_maxvy = element->inputs->Max(VyEnum);
 		if(element_maxvy>maxvy) maxvy=element_maxvy;
 	}
@@ -918,6 +983,6 @@
 	maxvz=-INFINITY;
 	for(i=0;i<this->elements->Size();i++){
-		Element* element=(Element*)this->elements->GetObjectByOffset(i);
-		element->MaxVz(&element_maxvz);
+		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element_maxvz = element->inputs->Max(VzEnum);
 		if(element_maxvz>maxvz) maxvz=element_maxvz;
 	}
@@ -942,6 +1007,6 @@
 	minvel=INFINITY;
 	for(i=0;i<this->elements->Size();i++){
-		Element* element=(Element*)this->elements->GetObjectByOffset(i);
-		element->MinVel(&element_minvel);
+		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element_minvel = element->inputs->Min(VelEnum);
 		if(element_minvel<minvel) minvel=element_minvel;
 	}
@@ -966,6 +1031,6 @@
 	minvx=INFINITY;
 	for(i=0;i<this->elements->Size();i++){
-		Element* element=(Element*)this->elements->GetObjectByOffset(i);
-		element->MinVx(&element_minvx);
+		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element_minvx = element->inputs->Min(VxEnum);
 		if(element_minvx<minvx) minvx=element_minvx;
 	}
@@ -990,6 +1055,6 @@
 	minvy=INFINITY;
 	for(i=0;i<this->elements->Size();i++){
-		Element* element=(Element*)this->elements->GetObjectByOffset(i);
-		element->MinVy(&element_minvy);
+		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element_minvy = element->inputs->Min(VyEnum);
 		if(element_minvy<minvy) minvy=element_minvy;
 	}
@@ -1014,6 +1079,6 @@
 	minvz=INFINITY;
 	for(i=0;i<this->elements->Size();i++){
-		Element* element=(Element*)this->elements->GetObjectByOffset(i);
-		element->MinVz(&element_minvz);
+		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element_minvz = element->inputs->Min(VzEnum);
 		if(element_minvz<minvz) minvz=element_minvz;
 	}
@@ -1139,5 +1204,5 @@
 
 	IssmDouble  weight,vx,vy,H,dvx[2],dvy[2],dH[2];
-	IssmDouble  temp,Jdet,dhdt,basal_melting,surface_mass_balance;
+	IssmDouble  temp,Jdet,dhdt,groundedice_melting,surface_mass_balance;
 	IssmDouble* xyz_list = NULL;
 	IssmDouble  dp[3];
@@ -1152,11 +1217,11 @@
 		/* Get node coordinates*/
 		element->GetVerticesCoordinates(&xyz_list);
-		Input* weights_input              = element->GetInput(InversionCostFunctionsCoefficientsEnum);   _assert_(weights_input);
-		Input* thickness_input            = element->GetInput(ThicknessEnum); _assert_(thickness_input);
-		Input* vx_input                   = element->GetInput(VxEnum);                                 _assert_(vx_input);
-		Input* vy_input                   = element->GetInput(VyEnum);                                 _assert_(vy_input);
-		Input* surface_mass_balance_input = element->GetInput(SurfaceforcingsMassBalanceEnum);         _assert_(surface_mass_balance_input);
-		Input* basal_melting_input        = element->GetInput(BasalforcingsMeltingRateEnum);           _assert_(basal_melting_input);
-		Input* dhdt_input                 = element->GetInput(BalancethicknessThickeningRateEnum);     _assert_(dhdt_input);
+		Input* weights_input                   = element->GetInput(InversionCostFunctionsCoefficientsEnum);   _assert_(weights_input);
+		Input* thickness_input                 = element->GetInput(ThicknessEnum); _assert_(thickness_input);
+		Input* vx_input                        = element->GetInput(VxEnum);                                  _assert_(vx_input);
+		Input* vy_input                        = element->GetInput(VyEnum);                                  _assert_(vy_input);
+		Input* surface_mass_balance_input      = element->GetInput(SurfaceforcingsMassBalanceEnum);          _assert_(surface_mass_balance_input);
+		Input* groundedice_melting_input       = element->GetInput(BasalforcingsGroundediceMeltingRateEnum); _assert_(groundedice_melting_input);
+		Input* dhdt_input                      = element->GetInput(BalancethicknessThickeningRateEnum);      _assert_(dhdt_input);
 
 		/* Start  looping on the number of gaussian points: */
@@ -1174,5 +1239,5 @@
 			thickness_input->GetInputDerivativeValue(&dH[0],xyz_list,gauss);
 			surface_mass_balance_input->GetInputValue(&surface_mass_balance,gauss);
-			basal_melting_input->GetInputValue(&basal_melting,gauss);
+			groundedice_melting_input->GetInputValue(&groundedice_melting,gauss);
 			dhdt_input->GetInputValue(&dhdt,gauss);
 			vx_input->GetInputValue(&vx,gauss);
@@ -1182,5 +1247,5 @@
 
 			/*Balance thickness soft constraint J = 1/2 (div(Hv)-a)^2*/
-			temp  = vx*dH[0]+vy*dH[1]+H*(dvx[0]+dvy[1]) - (surface_mass_balance-basal_melting-dhdt);
+			temp  = vx*dH[0]+vy*dH[1]+H*(dvx[0]+dvy[1]) - (surface_mass_balance-groundedice_melting-dhdt);
 			J    +=weight*1/2*temp*temp*Jdet*gauss->weight;
 		}
@@ -1200,4 +1265,81 @@
 
 }/*}}}*/
+void FemModel::Balancethickness2Misfitx(IssmDouble* presponse){/*{{{*/
+
+	/*output: */
+	IssmDouble J=0.;
+	IssmDouble J_sum;
+
+	IssmDouble  weight,thicknessobs,thickness,potential;
+	IssmDouble  vx,vy,vxbar,vybar,vxobs,vyobs,vxbarobs,vybarobs,nux,nuy;
+	IssmDouble  Jdet;
+	IssmDouble* xyz_list = NULL;
+
+	/*Compute Misfit: */
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+
+		/*If on water, return 0: */
+		if(!element->IsIceInElement()) continue;
+
+		/* Get node coordinates*/
+		element->GetVerticesCoordinates(&xyz_list);
+		Input* weights_input     =element->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+		Input* thickness_input   =element->GetInput(ThicknessEnum);                          _assert_(thickness_input);
+		Input* thicknessobs_input=element->GetInput(InversionThicknessObsEnum);              _assert_(thicknessobs_input);
+		Input* potential_input   =element->GetInput(PotentialEnum);                          _assert_(potential_input);
+		Input* vxobs_input       =element->GetInput(BalancethicknessVxObsEnum); _assert_(vxobs_input);
+		Input* vyobs_input       =element->GetInput(BalancethicknessVyObsEnum); _assert_(vyobs_input);
+		Input* vx_input          =element->GetInput(VxEnum); _assert_(vx_input);
+		Input* vy_input          =element->GetInput(VyEnum); _assert_(vy_input);
+		Input* nux_input       = element->GetInput(BalancethicknessNuxEnum);   _assert_(nux_input);
+		Input* nuy_input       = element->GetInput(BalancethicknessNuyEnum);   _assert_(nuy_input);
+
+		/* Start  looping on the number of gaussian points: */
+		Gauss* gauss=element->NewGauss(2);
+		for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+			gauss->GaussPoint(ig);
+
+			/* Get Jacobian determinant: */
+			element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+
+			/*Get all parameters at gaussian point*/
+			weights_input->GetInputValue(&weight,gauss,Balancethickness2MisfitEnum);
+			thickness_input->GetInputValue(&thickness,gauss);
+			thicknessobs_input->GetInputValue(&thicknessobs,gauss);
+			potential_input->GetInputValue(&potential,gauss);
+			vxobs_input->GetInputValue(&vxobs,gauss);
+			vyobs_input->GetInputValue(&vyobs,gauss);
+			vx_input->GetInputValue(&vxbar,gauss);
+			vy_input->GetInputValue(&vybar,gauss);
+			nux_input->GetInputValue(&nux,gauss);
+			nuy_input->GetInputValue(&nuy,gauss);
+
+			vxbarobs = nux*vxobs;
+			vybarobs = nuy*vyobs;
+
+			/*J = (H^2 - Hobs^2)^2*/
+			//J +=0.5*(thickness*thickness - thicknessobs*thicknessobs)*(thickness*thickness - thicknessobs*thicknessobs)*weight*Jdet*gauss->weight;
+			/*J = phi^2*/
+			//J +=.5*potential*potential*weight*Jdet*gauss->weight; OK
+			/*J = (ubar - nux*uobs)^2*/
+			J +=0.5*((vxbarobs - vxbar)*(vxbarobs - vxbar) + (vybarobs - vybar)*(vybarobs - vybar))*weight*Jdet*gauss->weight;
+		}
+
+		/*clean up and Return: */
+		xDelete<IssmDouble>(xyz_list);
+		delete gauss;
+	}
+
+	/*Sum all J from all cpus of the cluster:*/
+	ISSM_MPI_Reduce (&J,&J_sum,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&J_sum,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+	J=J_sum;
+
+	/*Assign output pointers: */
+	*presponse=J;
+
+}/*}}}*/
 void FemModel::ThicknessAbsGradientx( IssmDouble* pJ){/*{{{*/
 
@@ -1235,5 +1377,5 @@
 
 			/*Get all parameters at gaussian point*/
-			weights_input->GetInputValue(&weight,gauss,ThicknessAcrossGradientEnum);
+			weights_input->GetInputValue(&weight,gauss,ThicknessAbsMisfitEnum);
 			thickness_input->GetInputDerivativeValue(&dp[0],xyz_list,gauss);
 
Index: issm/trunk/src/c/classes/FemModel.h
===================================================================
--- issm/trunk/src/c/classes/FemModel.h	(revision 18081)
+++ issm/trunk/src/c/classes/FemModel.h	(revision 18301)
@@ -52,5 +52,7 @@
 		/*Methods:*/
 		void Echo();
+		FemModel* copy();
 		void InitFromFiles(char* rootpath, char* inputfilename, char* outputfilename, char* petscfilename, char* lockfilename, const int solution_type,const int* analyses,const int nummodels);
+		void CleanUp(void);
 		void Solve(void);
 		void SetStaticComm();
@@ -77,4 +79,5 @@
 		void ElementResponsex(IssmDouble* presponse,int response_enum);
 		void BalancethicknessMisfitx(IssmDouble* pV);
+		void Balancethickness2Misfitx(IssmDouble* pV);
 		#ifdef  _HAVE_DAKOTA_
 		void DakotaResponsesx(double* d_responses,char** responses_descriptors,int numresponsedescriptors,int d_numresponses);
Index: issm/trunk/src/c/classes/Hook.cpp
===================================================================
--- issm/trunk/src/c/classes/Hook.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Hook.cpp	(revision 18301)
@@ -16,6 +16,5 @@
 
 /*Constructor/Destructors*/
-/*FUNCTION Hook::Hook(){{{*/
-Hook::Hook(){
+Hook::Hook(){/*{{{*/
 	this->num     = 0;
 	this->objects = NULL;
@@ -24,6 +23,5 @@
 }
 /*}}}*/
-/*FUNCTION Hook::Hook(int* ids, int num){{{*/
-Hook::Hook(int* in_ids, int in_num){
+Hook::Hook(int* in_ids, int in_num){/*{{{*/
 
 	/*Get number of objects to hook*/
@@ -31,15 +29,16 @@
 
 	/*Get out if num=0*/
-	if (num==0){
+	if (this->num<=0){
 		/*Empty hook*/
 		this->ids     = NULL;
 		this->objects = NULL;
 		this->offsets = NULL;
+		this->num = 0;
 	}
 	else{
 		/*Allocate: */
-		this->objects=xNew<Object*>(this->num);
-		this->ids=xNew<int>(this->num);
-		this->offsets=xNew<int>(this->num);
+		this->objects=xNew<Object*>(in_num);
+		this->ids=xNew<int>(in_num);
+		this->offsets=xNew<int>(in_num);
 
 		/*Copy ids: */
@@ -52,6 +51,5 @@
 }
 /*}}}*/
-/*FUNCTION Hook::~Hook(){{{*/
-Hook::~Hook(){
+Hook::~Hook(){/*{{{*/
 	xDelete<Object*>(this->objects);
 	xDelete<int>(this->ids);
@@ -61,6 +59,5 @@
 
 /*Some of the Object functionality: */
-/*FUNCTION Hook::Echo{{{*/
-void Hook::Echo(void){
+void Hook::Echo(void){/*{{{*/
 	_assert_(this);
 	int i;
@@ -80,6 +77,5 @@
 }
 /*}}}*/
-/*FUNCTION Hook::DeepEcho{{{*/
-void Hook::DeepEcho(void){
+void Hook::DeepEcho(void){/*{{{*/
 
 	int i;
@@ -108,6 +104,5 @@
 }
 /*}}}*/
-/*FUNCTION Hook::copy {{{*/
-Object* Hook::copy(void){
+Object* Hook::copy(void){/*{{{*/
 
 	/*output: */
@@ -115,18 +110,9 @@
 
 	/*initalize output: */
-	output=new Hook();
-
-	/*copy in the fields: */
-	output->num=this->num;
-	if(output->num){
-		output->objects = xNew<Object*>(output->num);
-		output->ids     = xNew<int>(output->num);
-		output->offsets = xNew<int>(output->num);
-	}
+	output=new Hook(this->ids,this->num);
 
 	for(int i=0;i<output->num;i++){
 		output->objects[i] = this->objects[i];
 		output->offsets[i] = this->offsets[i];
-		output->ids[i]     = this->ids[i];
 	}
 
@@ -136,6 +122,16 @@
 
 /*Hook management: */
-/*FUNCTION Hook::configure{{{*/
-void Hook::configure(DataSet* dataset){
+void Hook::reset(){/*{{{*/
+
+	/*intermediary: */
+	Object* object=NULL;
+	int i;
+
+	for(i=0;i<this->num;i++){
+			this->objects[i]=NULL; //reset this node.
+	}
+}
+/*}}}*/
+void Hook::configure(DataSet* dataset){/*{{{*/
 
 	/*intermediary: */
@@ -168,4 +164,5 @@
 			else this->offsets[i]=UNDEF; //object offset was wrong, reset it.
 		}
+		else this->offsets[i]=UNDEF;
 
 		/*Now, for this->objects that did not get resolved, and for which we have no offset, chase them in the dataset, by id: */
@@ -178,9 +175,8 @@
 }
 /*}}}*/
-/*FUNCTION Hook::delivers{{{*/
-Object* Hook::delivers(void){
+Object* Hook::delivers(void){/*{{{*/
 
 	/*first, check that we only have one T object in our object list: */
-	if (this->num!=1) _error_("trying to delivery a single hook object when hook holds " << this->num << " objects" << "\n");
+	if (this->num!=1) _error_("trying to deliver a single hook object when hook holds " << this->num << " objects" << "\n");
 
 	/*check NULL: */
@@ -191,21 +187,17 @@
 
 /*}}}*/
-/*FUNCTION Hook::deliverp{{{*/
-Object** Hook::deliverp(void){
+Object** Hook::deliverp(void){/*{{{*/
 	return objects;
 }
 /*}}}*/
-/*FUNCTION Hook::Ids{{{*/
-int* Hook::Ids(void){
+int* Hook::Ids(void){/*{{{*/
 	return this->ids;
 }
 /*}}}*/
-/*FUNCTION Hook::GetNum{{{*/
-int Hook::GetNum(void){
+int Hook::GetNum(void){/*{{{*/
 	return this->num;
 }
 /*}}}*/
-/*FUNCTION Hook::Spawn{{{*/
-Hook* Hook::Spawn(int* indices, int numindices){
+Hook* Hook::Spawn(int* indices, int numindices){/*{{{*/
 
 	/*output: */
Index: issm/trunk/src/c/classes/Hook.h
===================================================================
--- issm/trunk/src/c/classes/Hook.h	(revision 18081)
+++ issm/trunk/src/c/classes/Hook.h	(revision 18301)
@@ -39,4 +39,5 @@
 		Object**   deliverp(void); //deliver all objects
 		void       configure(DataSet* dataset);
+		void       reset(void);
 		Hook*      Spawn(int* indices, int numindices);
 		int*       Ids(void);
Index: issm/trunk/src/c/classes/IndependentObject.cpp
===================================================================
--- issm/trunk/src/c/classes/IndependentObject.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/IndependentObject.cpp	(revision 18301)
@@ -14,6 +14,5 @@
 
 /*IndependentObject constructors and destructor*/
-/*FUNCTION IndependentObject::IndependentObject(){{{*/
-IndependentObject::IndependentObject(){
+IndependentObject::IndependentObject(){/*{{{*/
 	this->name=NoneEnum;
 	this->type=0;
@@ -21,6 +20,5 @@
 }
 /*}}}*/
-/*FUNCTION IndependentObject::IndependentObject(int in_name, int in_type){{{*/
-IndependentObject::IndependentObject(int in_name, int in_type){
+IndependentObject::IndependentObject(int in_name, int in_type){/*{{{*/
 
 	this->numberofindependents=0;
@@ -31,12 +29,10 @@
 }
 /*}}}*/
-/*FUNCTION IndependentObject::~IndependentObject() {{{*/
-IndependentObject::~IndependentObject(){ //destructor
+IndependentObject::~IndependentObject(){ //destructor/*{{{*/
 }
 /*}}}*/
 
 /*Object virtual functions definitions:*/
-/*FUNCTION IndependentObject::Echo{{{*/
-void IndependentObject::Echo(void){
+void IndependentObject::Echo(void){/*{{{*/
 
 	_printf_("IndependentObject:\n");
@@ -51,14 +47,11 @@
 }
 /*}}}*/
-/*FUNCTION IndependentObject::DeepEcho{{{*/
-void IndependentObject::DeepEcho(void){
+void IndependentObject::DeepEcho(void){/*{{{*/
 	this->Echo();
 }
 /*}}}*/
-/*FUNCTION IndependentObject::Id{{{*/
-int    IndependentObject::Id(void){ return -1; }
+int    IndependentObject::Id(void){ return -1; }/*{{{*/
 /*}}}*/
-/*FUNCTION IndependentObject::ObjectEnum{{{*/
-int IndependentObject::ObjectEnum(void){
+int IndependentObject::ObjectEnum(void){/*{{{*/
 
 	return IndependentObjectEnum;
@@ -66,6 +59,5 @@
 }
 /*}}}*/
-/*FUNCTION IndependentObject::copy{{{*/
-Object* IndependentObject::copy(void) { 
+Object* IndependentObject::copy(void) { /*{{{*/
 
 	IndependentObject* object=new IndependentObject();
@@ -78,6 +70,5 @@
 
 /*IndependentObject methods: */
-/*FUNCTION IndependentObject::FetchIndependent{{{*/
-void IndependentObject::FetchIndependent(IoModel* iomodel){
+void IndependentObject::FetchIndependent(IoModel* iomodel){/*{{{*/
 
 	int my_rank;
@@ -183,12 +174,10 @@
 }
 /*}}}*/
-/*FUNCTION IndependentObject::NumIndependents{{{*/
-int  IndependentObject::NumIndependents(void){
+int  IndependentObject::NumIndependents(void){/*{{{*/
 
 	return this->numberofindependents;;
 }
 /*}}}*/
-/*FUNCTION IndependentObject::FillIndependents{{{*/
-void IndependentObject::FillIndependents(IssmDouble** data, IssmDouble* xp){
+void IndependentObject::FillIndependents(IssmDouble** data, IssmDouble* xp){/*{{{*/
 
 	int i;
Index: issm/trunk/src/c/classes/Inputs/BoolInput.cpp
===================================================================
--- issm/trunk/src/c/classes/Inputs/BoolInput.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Inputs/BoolInput.cpp	(revision 18301)
@@ -13,11 +13,9 @@
 
 /*BoolInput constructors and destructor*/
-/*FUNCTION BoolInput::BoolInput(){{{*/
-BoolInput::BoolInput(){
+BoolInput::BoolInput(){/*{{{*/
 	return;
 }
 /*}}}*/
-/*FUNCTION BoolInput::BoolInput(int in_enum_type,bool in_value){{{*/
-BoolInput::BoolInput(int in_enum_type,bool in_value){
+BoolInput::BoolInput(int in_enum_type,bool in_value){/*{{{*/
 
 	enum_type=in_enum_type;
@@ -25,6 +23,5 @@
 }
 /*}}}*/
-/*FUNCTION BoolInput::~BoolInput(){{{*/
-BoolInput::~BoolInput(){
+BoolInput::~BoolInput(){/*{{{*/
 	return;
 }
@@ -32,20 +29,16 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION BoolInput::Echo {{{*/
-void BoolInput::Echo(void){
+void BoolInput::Echo(void){/*{{{*/
 	this->DeepEcho();
 }
 /*}}}*/
-/*FUNCTION BoolInput::DeepEcho{{{*/
-void BoolInput::DeepEcho(void){
+void BoolInput::DeepEcho(void){/*{{{*/
 
 	_printf_(setw(15)<<"   BoolInput "<<setw(25)<<left<<EnumToStringx(this->enum_type)<<" "<<(value?"true":"false") << "\n");
 }
 /*}}}*/
-/*FUNCTION BoolInput::Id{{{*/
-int    BoolInput::Id(void){ return -1; }
+int    BoolInput::Id(void){ return -1; }/*{{{*/
 /*}}}*/
-/*FUNCTION BoolInput::ObjectEnum{{{*/
-int BoolInput::ObjectEnum(void){
+int BoolInput::ObjectEnum(void){/*{{{*/
 
 	return BoolInputEnum;
@@ -53,6 +46,5 @@
 }
 /*}}}*/
-/*FUNCTION BoolInput::copy{{{*/
-Object* BoolInput::copy() {
+Object* BoolInput::copy() {/*{{{*/
 
 	return new BoolInput(this->enum_type,this->value);
@@ -62,6 +54,5 @@
 
 /*BoolInput management*/
-/*FUNCTION BoolInput::InstanceEnum{{{*/
-int BoolInput::InstanceEnum(void){
+int BoolInput::InstanceEnum(void){/*{{{*/
 
 	return this->enum_type;
@@ -69,6 +60,5 @@
 }
 /*}}}*/
-/*FUNCTION BoolInput::SpawnTriaInput{{{*/
-Input* BoolInput::SpawnTriaInput(int index1,int index2,int index3){
+Input* BoolInput::SpawnTriaInput(int index1,int index2,int index3){/*{{{*/
 
 		/*output*/
@@ -84,6 +74,5 @@
 }
 /*}}}*/
-/*FUNCTION BoolInput::SpawnSegInput{{{*/
-Input* BoolInput::SpawnSegInput(int index1,int index2){
+Input* BoolInput::SpawnSegInput(int index1,int index2){/*{{{*/
 
 		/*output*/
@@ -101,36 +90,28 @@
 
 /*Object functions*/
-/*FUNCTION BoolInput::GetInputValue(bool* pvalue) {{{*/
-void BoolInput::GetInputValue(bool* pvalue){
+void BoolInput::GetInputValue(bool* pvalue){/*{{{*/
 	*pvalue=value;
 }
 /*}}}*/
-/*FUNCTION BoolInput::GetInputValue(int* pvalue){{{*/
-void BoolInput::GetInputValue(int* pvalue){_error_("not supported yet!");}
+void BoolInput::GetInputValue(int* pvalue){_error_("not supported yet!");}/*{{{*/
 /*}}}*/
-/*FUNCTION BoolInput::GetInputValue(IssmDouble* pvalue){{{*/
-void BoolInput::GetInputValue(IssmDouble* pvalue){_error_("not supported yet!");}
+void BoolInput::GetInputValue(IssmDouble* pvalue){_error_("not supported yet!");}/*{{{*/
 /*}}}*/
-/*FUNCTION BoolInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){{{*/
-void BoolInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){_error_("not supported yet!");}
+void BoolInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){_error_("not supported yet!");}/*{{{*/
 /*}}}*/
-/*FUNCTION BoolInput::ChangeEnum{{{*/
-void BoolInput::ChangeEnum(int newenumtype){
+void BoolInput::ChangeEnum(int newenumtype){/*{{{*/
 	this->enum_type=newenumtype;
 }
 /*}}}*/
-/*FUNCTION BoolInput::SquareMin{{{*/
-void BoolInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){
+void BoolInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){/*{{{*/
 	/*square of a bool is the bool itself: */
 	*psquaremin=value;
 }
 /*}}}*/
-/*FUNCTION BoolInput::Scale{{{*/
-void BoolInput::Scale(IssmDouble scale_factor){
+void BoolInput::Scale(IssmDouble scale_factor){/*{{{*/
 	/*a bool cannot be scaled: */
 }
 /*}}}*/
-/*FUNCTION BoolInput::AXPY{{{*/
-void BoolInput::AXPY(Input* xinput,IssmDouble scalar){
+void BoolInput::AXPY(Input* xinput,IssmDouble scalar){/*{{{*/
 
 	BoolInput*  xboolinput=NULL;
@@ -152,6 +133,5 @@
 }
 /*}}}*/
-/*FUNCTION BoolInput::Extrude{{{*/
-void BoolInput::Extrude(void){
+void BoolInput::Extrude(void){/*{{{*/
 
 	/*do nothing*/
@@ -159,6 +139,5 @@
 }
 /*}}}*/
-/*FUNCTION BoolInput::GetVectorFromInputs{{{*/
-void BoolInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){
+void BoolInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){/*{{{*/
 
 	_error_("not supporte yet!");
@@ -166,6 +145,5 @@
 }
 /*}}}*/
-/*FUNCTION BoolInput::Configure{{{*/
-void BoolInput::Configure(Parameters* parameters){
+void BoolInput::Configure(Parameters* parameters){/*{{{*/
 	/*do nothing: */
 }
Index: issm/trunk/src/c/classes/Inputs/ControlInput.cpp
===================================================================
--- issm/trunk/src/c/classes/Inputs/ControlInput.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Inputs/ControlInput.cpp	(revision 18301)
@@ -13,6 +13,5 @@
 
 /*ControlInput constructors and destructor*/
-/*FUNCTION ControlInput::ControlInput(){{{*/
-ControlInput::ControlInput(){
+ControlInput::ControlInput(){/*{{{*/
 	control_id  = 0;
 	values      = NULL;
@@ -23,6 +22,5 @@
 }
 /*}}}*/
-/*FUNCTION ControlInput::ControlInput(int enum_type,int enum_input,IssmDouble* pvalues,IssmDouble* pmin,IssmDouble* pmax,int id){{{*/
-ControlInput::ControlInput(int in_enum_type,int enum_input,IssmDouble* pvalues,IssmDouble* pmin,IssmDouble* pmax,int id){
+ControlInput::ControlInput(int in_enum_type,int enum_input,IssmDouble* pvalues,IssmDouble* pmin,IssmDouble* pmax,int id){/*{{{*/
 
 	control_id=id;
@@ -48,6 +46,5 @@
 }
 /*}}}*/
-/*FUNCTION ControlInput::~ControlInput(){{{*/
-ControlInput::~ControlInput(){
+ControlInput::~ControlInput(){/*{{{*/
 	delete values;
 	delete savedvalues;
@@ -59,11 +56,9 @@
 
 /*Object virtual functions definitions:*/
-		/*FUNCTION ControlInput::Echo {{{*/
-void ControlInput::Echo(void){
+void ControlInput::Echo(void){/*{{{*/
 	this->DeepEcho();
 }
 /*}}}*/
-/*FUNCTION ControlInput::DeepEcho{{{*/
-void ControlInput::DeepEcho(void){
+void ControlInput::DeepEcho(void){/*{{{*/
 
 	_printf_("ControlInput:\n");
@@ -76,9 +71,7 @@
 }
 /*}}}*/
-/*FUNCTION ControlInput::Id{{{*/
-int    ControlInput::Id(void){ return -1; }
-/*}}}*/
-/*FUNCTION ControlInput::ObjectEnum{{{*/
-int ControlInput::ObjectEnum(void){
+int    ControlInput::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int ControlInput::ObjectEnum(void){/*{{{*/
 
 	return ControlInputEnum;
@@ -86,6 +79,5 @@
 }
 /*}}}*/
-/*FUNCTION ControlInput::copy{{{*/
-Object* ControlInput::copy() {
+Object* ControlInput::copy() {/*{{{*/
 
 	ControlInput* output=NULL;
@@ -106,6 +98,5 @@
 
 /*ControlInput management*/
-/*FUNCTION ControlInput::InstanceEnum{{{*/
-int ControlInput::InstanceEnum(void){
+int ControlInput::InstanceEnum(void){/*{{{*/
 
 	return this->enum_type;
@@ -115,10 +106,8 @@
 
 /*Object functions*/
-/*FUNCTION ControlInput::AXPY(){{{*/
-void ControlInput::AXPY(Input* xinput,IssmDouble scalar){
+void ControlInput::AXPY(Input* xinput,IssmDouble scalar){/*{{{*/
 	values->AXPY(xinput,scalar);
 }/*}}}*/
-/*FUNCTION ControlInput::Constrain(){{{*/
-void ControlInput::Constrain(void){
+void ControlInput::Constrain(void){/*{{{*/
 
 	Input* newvalues=NULL;
@@ -129,16 +118,13 @@
 	delete values; this->values=newvalues;
 }/*}}}*/
-/*FUNCTION ControlInput::Constrain(IssmDouble min, IssmDouble max){{{*/
-void ControlInput::Constrain(IssmDouble min, IssmDouble max){
+void ControlInput::Constrain(IssmDouble min, IssmDouble max){/*{{{*/
 	   values->Constrain(min,max);
 }/*}}}*/
-/*FUNCTION ControlInput::Extrude{{{*/
-void ControlInput::Extrude(void){
+void ControlInput::Extrude(void){/*{{{*/
 	values->Extrude();
 	savedvalues->Extrude();
 	//gradient->Extrude();
 }/*}}}*/
-/*FUNCTION ControlInput::GetResultInterpolation{{{*/
-int  ControlInput::GetResultInterpolation(void){
+int  ControlInput::GetResultInterpolation(void){/*{{{*/
 
 	return values->GetResultInterpolation();
@@ -146,6 +132,5 @@
 }
 /*}}}*/
-/*FUNCTION ControlInput::GetResultNumberOfNodes{{{*/
-int  ControlInput::GetResultNumberOfNodes(void){
+int  ControlInput::GetResultNumberOfNodes(void){/*{{{*/
 
 	return values->GetResultNumberOfNodes();
@@ -153,15 +138,12 @@
 }
 /*}}}*/
-/*FUNCTION ControlInput::GetGradient{{{*/
-void ControlInput::GetGradient(Vector<IssmDouble>* gradient_vec,int* doflist){
+void ControlInput::GetGradient(Vector<IssmDouble>* gradient_vec,int* doflist){/*{{{*/
 	if(gradient) gradient->GetVectorFromInputs(gradient_vec,doflist);
 }/*}}}*/
-/*FUNCTION ControlInput::ScaleGradient{{{*/
-void ControlInput::ScaleGradient(IssmDouble scaling_factor){
+void ControlInput::ScaleGradient(IssmDouble scaling_factor){/*{{{*/
 	if(!gradient) _error_("Gradient of ControlInput " << EnumToStringx(enum_type) << " not found");
 	gradient->Scale(scaling_factor);
 }/*}}}*/
-/*FUNCTION ControlInput::SetGradient{{{*/
-void ControlInput::SetGradient(Input* gradient_in){
+void ControlInput::SetGradient(Input* gradient_in){/*{{{*/
 
 	/*Get enum for current gradient*/
@@ -185,6 +167,5 @@
 
 }/*}}}*/
-/*FUNCTION ControlInput::SetInput{{{*/
-void ControlInput::SetInput(Input* in_input){
+void ControlInput::SetInput(Input* in_input){/*{{{*/
 
 	delete values; this->values=in_input;
@@ -192,18 +173,14 @@
 
 }/*}}}*/
-/*FUNCTION ControlInput::SpawnTriaInput{{{*/
-Input* ControlInput::SpawnTriaInput(int index1,int index2,int index3){
+Input* ControlInput::SpawnTriaInput(int index1,int index2,int index3){/*{{{*/
 	return values->SpawnTriaInput(index1,index2,index3);
 }/*}}}*/
-/*FUNCTION ControlInput::SpawnSegInput{{{*/
-Input* ControlInput::SpawnSegInput(int index1,int index2){
+Input* ControlInput::SpawnSegInput(int index1,int index2){/*{{{*/
 	return values->SpawnSegInput(index1,index2);
 }/*}}}*/
-/*FUNCTION ControlInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){{{*/
-void ControlInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){
+void ControlInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){/*{{{*/
 	values->GetVectorFromInputs(vector,doflist);
 }/*}}}*/
-/*FUNCTION ControlInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist,const char* data){{{*/
-void ControlInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist,const char* data){
+void ControlInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist,const char* data){/*{{{*/
 	 if(strcmp(data,"value")==0){
 		 _assert_(values);
@@ -226,34 +203,32 @@
 	 }
 }/*}}}*/
-/*FUNCTION ControlInput::GetInputAverage(IssmDouble* pvalue){{{*/
-void ControlInput::GetInputAverage(IssmDouble* pvalue){
+void ControlInput::GetInputAverage(IssmDouble* pvalue){/*{{{*/
 	values->GetInputAverage(pvalue);
 }/*}}}*/
-/*FUNCTION ControlInput::GetInputValue(bool* pvalue){{{*/
-void ControlInput::GetInputValue(bool* pvalue){
+void ControlInput::GetInputValue(bool* pvalue){/*{{{*/
 	values->GetInputValue(pvalue);
 }/*}}}*/
-/*FUNCTION ControlInput::GetInputValue(int* pvalue){{{*/
-void ControlInput::GetInputValue(int* pvalue){
+void ControlInput::GetInputValue(int* pvalue){/*{{{*/
 	values->GetInputValue(pvalue);
 }/*}}}*/
-/*FUNCTION ControlInput::GetInputValue(IssmDouble* pvalue){{{*/
-void ControlInput::GetInputValue(IssmDouble* pvalue){
+void ControlInput::GetInputValue(IssmDouble* pvalue){/*{{{*/
 	values->GetInputValue(pvalue);
 }/*}}}*/
-/*FUNCTION ControlInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){{{*/
-void ControlInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){
+void ControlInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){/*{{{*/
 	values->GetInputValue(pvalue,gauss);
 }/*}}}*/
-/*FUNCTION ControlInput::GetGradientValue{{{*/
-void ControlInput::GetGradientValue(IssmDouble* pvalue,Gauss* gauss){
+void ControlInput::GetGradientValue(IssmDouble* pvalue,Gauss* gauss){/*{{{*/
 	gradient->GetInputValue(pvalue,gauss);
 }/*}}}*/
-/*FUNCTION ControlInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, Gauss* gauss){{{*/
-void ControlInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, Gauss* gauss){
+void ControlInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, Gauss* gauss){/*{{{*/
 	values->GetInputDerivativeValue(derivativevalues,xyz_list,gauss);
 }/*}}}*/
-/*FUNCTION ControlInput::SaveValue{{{*/
-void ControlInput::SaveValue(void){
+IssmDouble ControlInput::Min(void){/*{{{*/
+
+	return values->Min();
+
+}
+/*}}}*/
+void ControlInput::SaveValue(void){/*{{{*/
 	if(!values) _error_("Values of " << EnumToStringx(this->enum_type) << " not found");
 
@@ -261,6 +236,5 @@
 	this->savedvalues=dynamic_cast<Input*>(this->values->copy());
 }/*}}}*/
-/*FUNCTION ControlInput::UpdateValue{{{*/
-void ControlInput::UpdateValue(IssmDouble scalar){
+void ControlInput::UpdateValue(IssmDouble scalar){/*{{{*/
 	if(!gradient)    _error_("Gradient of " << EnumToStringx(this->enum_type) << " not found");
 	if(!savedvalues) _error_("Values of " << EnumToStringx(this->enum_type) << " not found");
@@ -270,10 +244,8 @@
 	this->values->AXPY(gradient,scalar);
 }/*}}}*/
-/*FUNCTION ControlInput::VerticallyIntegrate{{{*/
-void ControlInput::VerticallyIntegrate(Input* thickness_input){
+void ControlInput::VerticallyIntegrate(Input* thickness_input){/*{{{*/
 	values->VerticallyIntegrate(thickness_input);
 }/*}}}*/
-/*FUNCTION ControlInput::Configure{{{*/
-void ControlInput::Configure(Parameters* parameters){
+void ControlInput::Configure(Parameters* parameters){/*{{{*/
 	/*do nothing: */
 }
Index: issm/trunk/src/c/classes/Inputs/ControlInput.h
===================================================================
--- issm/trunk/src/c/classes/Inputs/ControlInput.h	(revision 18081)
+++ issm/trunk/src/c/classes/Inputs/ControlInput.h	(revision 18301)
@@ -70,5 +70,5 @@
 		IssmDouble Max(void){_error_("not implemented yet");};
 		IssmDouble MaxAbs(void){_error_("not implemented yet");};
-		IssmDouble Min(void){_error_("not implemented yet");};
+		IssmDouble Min(void);
 		IssmDouble MinAbs(void){_error_("not implemented yet");};
 		void Extrude(void);
Index: issm/trunk/src/c/classes/Inputs/DatasetInput.cpp
===================================================================
--- issm/trunk/src/c/classes/Inputs/DatasetInput.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Inputs/DatasetInput.cpp	(revision 18301)
@@ -14,6 +14,5 @@
 
 /*DatasetInput constructors and destructor*/
-/*FUNCTION DatasetInput::DatasetInput(){{{*/
-DatasetInput::DatasetInput(){
+DatasetInput::DatasetInput(){/*{{{*/
 	enum_type = UNDEF;
 	inputs    = NULL;
@@ -22,6 +21,5 @@
 }
 /*}}}*/
-/*FUNCTION DatasetInput::DatasetInput(int in_enum_type,int* idlist,int numids) {{{*/
-DatasetInput::DatasetInput(int in_enum_type){
+DatasetInput::DatasetInput(int in_enum_type){/*{{{*/
 
 	enum_type = in_enum_type;
@@ -31,6 +29,5 @@
 }
 /*}}}*/
-/*FUNCTION DatasetInput::~DatasetInput(){{{*/
-DatasetInput::~DatasetInput(){
+DatasetInput::~DatasetInput(){/*{{{*/
 	xDelete<int>(this->ids);
 	delete inputs;
@@ -39,11 +36,9 @@
 
 /*Object virtual functions definitions:*/
-		/*FUNCTION DatasetInput::Echo {{{*/
-void DatasetInput::Echo(void){
+void DatasetInput::Echo(void){/*{{{*/
 	this->DeepEcho();
 }
 /*}}}*/
-/*FUNCTION DatasetInput::DeepEcho{{{*/
-void DatasetInput::DeepEcho(void){
+void DatasetInput::DeepEcho(void){/*{{{*/
 
 	_printf_("DatasetInput:\n");
@@ -56,9 +51,7 @@
 }
 /*}}}*/
-/*FUNCTION DatasetInput::Id{{{*/
-int    DatasetInput::Id(void){ return -1; }
+int    DatasetInput::Id(void){ return -1; }/*{{{*/
 /*}}}*/
-/*FUNCTION DatasetInput::ObjectEnum{{{*/
-int DatasetInput::ObjectEnum(void){
+int DatasetInput::ObjectEnum(void){/*{{{*/
 
 	return DatasetInputEnum;
@@ -66,6 +59,5 @@
 }
 /*}}}*/
-/*FUNCTION DatasetInput::copy{{{*/
-Object* DatasetInput::copy() {
+Object* DatasetInput::copy() {/*{{{*/
 
 	DatasetInput* output=NULL;
@@ -73,11 +65,13 @@
 	output = new DatasetInput();
 	output->enum_type=this->enum_type;
-	output->inputs=(Inputs*)this->inputs->Copy();
+	output->numids=this->numids;
+	output->ids=xNew<int>(output->numids);
+	xMemCpy(output->ids,this->ids,output->numids);
+	output->inputs=static_cast<Inputs*>(this->inputs->Copy());
 
-	return output;
+	return (Object*)output;
 }
 /*}}}*/
-/*FUNCTION DatasetInput::SpawnTriaInput{{{*/
-Input* DatasetInput::SpawnTriaInput(int index1,int index2,int index3){
+Input* DatasetInput::SpawnTriaInput(int index1,int index2,int index3){/*{{{*/
 
 	/*output*/
@@ -96,6 +90,5 @@
 }
 /*}}}*/
-/*FUNCTION DatasetInput::SpawnSegInput{{{*/
-Input* DatasetInput::SpawnSegInput(int index1,int index2){
+Input* DatasetInput::SpawnSegInput(int index1,int index2){/*{{{*/
 
 	/*output*/
@@ -116,6 +109,5 @@
 
 /*DatasetInput management*/
-/*FUNCTION DatasetInput::AddInput{{{*/
-void DatasetInput::AddInput(Input* input,int id){
+void DatasetInput::AddInput(Input* input,int id){/*{{{*/
 
 	_assert_(this->numids == this->inputs->Size());
@@ -144,6 +136,5 @@
 }
 /*}}}*/
-/*FUNCTION DatasetInput::InstanceEnum{{{*/
-int DatasetInput::InstanceEnum(void){
+int DatasetInput::InstanceEnum(void){/*{{{*/
 
 	return this->enum_type;
@@ -153,11 +144,9 @@
 
 /*Object functions*/
-/*FUNCTION DatasetInput::Configure{{{*/
-void DatasetInput::Configure(Parameters* parameters){
+void DatasetInput::Configure(Parameters* parameters){/*{{{*/
 	/*do nothing: */
 }
 /*}}}*/
-/*FUNCTION DatasetInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss,int id){{{*/
-void DatasetInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss,int id){
+void DatasetInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss,int id){/*{{{*/
 
 	int  offset = -1;
@@ -166,5 +155,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 );
 
 	Input* input=dynamic_cast<Input*>(this->inputs->GetObjectByOffset(offset));
Index: issm/trunk/src/c/classes/Inputs/DoubleInput.cpp
===================================================================
--- issm/trunk/src/c/classes/Inputs/DoubleInput.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Inputs/DoubleInput.cpp	(revision 18301)
@@ -13,11 +13,9 @@
 
 /*DoubleInput constructors and destructor*/
-/*FUNCTION DoubleInput::DoubleInput(){{{*/
-DoubleInput::DoubleInput(){
+DoubleInput::DoubleInput(){/*{{{*/
 	return;
 }
 /*}}}*/
-/*FUNCTION DoubleInput::DoubleInput(IssmDouble value){{{*/
-DoubleInput::DoubleInput(int in_enum_type,IssmDouble in_value){
+DoubleInput::DoubleInput(int in_enum_type,IssmDouble in_value){/*{{{*/
 
 	enum_type=in_enum_type;
@@ -25,6 +23,5 @@
 }
 /*}}}*/
-/*FUNCTION DoubleInput::~DoubleInput(){{{*/
-DoubleInput::~DoubleInput(){
+DoubleInput::~DoubleInput(){/*{{{*/
 	return;
 }
@@ -32,20 +29,16 @@
 
 /*Object virtual functions definitions:*/
-		/*FUNCTION DoubleInput::Echo {{{*/
-void DoubleInput::Echo(void){
+void DoubleInput::Echo(void){/*{{{*/
 	this->DeepEcho();
 }
 /*}}}*/
-/*FUNCTION DoubleInput::DeepEcho{{{*/
-void DoubleInput::DeepEcho(void){
+void DoubleInput::DeepEcho(void){/*{{{*/
 
 	_printf_(setw(15)<<"   DoubleInput "<<setw(25)<<left<<EnumToStringx(this->enum_type)<<" "<<this->value<<"\n");
 }
 /*}}}*/
-/*FUNCTION DoubleInput::Id{{{*/
-int    DoubleInput::Id(void){ return -1; }
-/*}}}*/
-/*FUNCTION DoubleInput::ObjectEnum{{{*/
-int DoubleInput::ObjectEnum(void){
+int    DoubleInput::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int DoubleInput::ObjectEnum(void){/*{{{*/
 
 	return DoubleInputEnum;
@@ -53,6 +46,5 @@
 }
 /*}}}*/
-/*FUNCTION DoubleInput::copy{{{*/
-Object* DoubleInput::copy() {
+Object* DoubleInput::copy() {/*{{{*/
 
 	return new DoubleInput(this->enum_type,this->value);
@@ -62,6 +54,5 @@
 
 /*DoubleInput management*/
-/*FUNCTION DoubleInput::InstanceEnum{{{*/
-int DoubleInput::InstanceEnum(void){
+int DoubleInput::InstanceEnum(void){/*{{{*/
 
 	return this->enum_type;
@@ -69,6 +60,5 @@
 }
 /*}}}*/
-/*FUNCTION DoubleInput::SpawnTriaInput{{{*/
-Input* DoubleInput::SpawnTriaInput(int index1,int index2,int index3){
+Input* DoubleInput::SpawnTriaInput(int index1,int index2,int index3){/*{{{*/
 
 	/*output*/
@@ -84,6 +74,5 @@
 }
 /*}}}*/
-/*FUNCTION DoubleInput::SpawnSegInput{{{*/
-Input* DoubleInput::SpawnSegInput(int index1,int index2){
+Input* DoubleInput::SpawnSegInput(int index1,int index2){/*{{{*/
 
 	/*output*/
@@ -101,18 +90,15 @@
 
 /*Object functions*/
-/*FUNCTION DoubleInput::GetInputValue(bool* pvalue) {{{*/
-void DoubleInput::GetInputValue(bool* pvalue){
+void DoubleInput::GetInputValue(bool* pvalue){/*{{{*/
 	_error_("Double input of enum " << EnumToStringx(enum_type) << " cannot return a boolean");
 
 }
 /*}}}*/
-/*FUNCTION DoubleInput::GetInputValue(int* pvalue){{{*/
-void DoubleInput::GetInputValue(int* pvalue){
+void DoubleInput::GetInputValue(int* pvalue){/*{{{*/
 	_error_("Double input of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an integer");
 
 }
 /*}}}*/
-/*FUNCTION DoubleInput::GetInputValue(IssmDouble* pvalue){{{*/
-void DoubleInput::GetInputValue(IssmDouble* pvalue){
+void DoubleInput::GetInputValue(IssmDouble* pvalue){/*{{{*/
 
 	/*return value*/
@@ -120,14 +106,11 @@
 }
 /*}}}*/
-/*FUNCTION DoubleInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){{{*/
-void DoubleInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){*pvalue=this->value;}
-/*}}}*/
-/*FUNCTION DoubleInput::ChangeEnum{{{*/
-void DoubleInput::ChangeEnum(int newenumtype){
+void DoubleInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){*pvalue=this->value;}/*{{{*/
+/*}}}*/
+void DoubleInput::ChangeEnum(int newenumtype){/*{{{*/
 	this->enum_type=newenumtype;
 }
 /*}}}*/
-/*FUNCTION DoubleInput::SquareMin{{{*/
-void DoubleInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){
+void DoubleInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){/*{{{*/
 
 	/*square min of a IssmDouble is the square of the IssmDouble itself: */
@@ -135,16 +118,13 @@
 }
 /*}}}*/
-/*FUNCTION DoubleInput::Scale{{{*/
-void DoubleInput::Scale(IssmDouble scale_factor){
+void DoubleInput::Scale(IssmDouble scale_factor){/*{{{*/
 	value=value*scale_factor;
 }
 /*}}}*/
-/*FUNCTION DoubleInput::ConstrainMin{{{*/
-void DoubleInput::ConstrainMin(IssmDouble minimum){
+void DoubleInput::ConstrainMin(IssmDouble minimum){/*{{{*/
 	if (value<minimum) value=minimum;
 }
 /*}}}*/
-/*FUNCTION DoubleInput::AXPY{{{*/
-void DoubleInput::AXPY(Input* xinput,IssmDouble scalar){
+void DoubleInput::AXPY(Input* xinput,IssmDouble scalar){/*{{{*/
 
 	DoubleInput*  xIssmDoubleinput=NULL;
@@ -166,6 +146,5 @@
 }
 /*}}}*/
-/*FUNCTION DoubleInput::Constrain{{{*/
-void DoubleInput::Constrain(IssmDouble cm_min, IssmDouble cm_max){
+void DoubleInput::Constrain(IssmDouble cm_min, IssmDouble cm_max){/*{{{*/
 
 	if(!xIsNan<IssmDouble>(cm_min)) if (this->value<cm_min)this->value=cm_min;
@@ -174,26 +153,21 @@
 }
 /*}}}*/
-/*FUNCTION DoubleInput::Max{{{*/
-IssmDouble DoubleInput::Max(void){
+IssmDouble DoubleInput::Max(void){/*{{{*/
 	return this->value;
 }
 /*}}}*/
-/*FUNCTION DoubleInput::MaxAbs{{{*/
-IssmDouble DoubleInput::MaxAbs(void){
+IssmDouble DoubleInput::MaxAbs(void){/*{{{*/
 	return fabs(this->value);
 }
 /*}}}*/
-/*FUNCTION DoubleInput::Min{{{*/
-IssmDouble DoubleInput::Min(void){
+IssmDouble DoubleInput::Min(void){/*{{{*/
 	return this->value;
 }
 /*}}}*/
-/*FUNCTION DoubleInput::MinAbs{{{*/
-IssmDouble DoubleInput::MinAbs(void){
+IssmDouble DoubleInput::MinAbs(void){/*{{{*/
 	return fabs(this->value);
 }
 /*}}}*/
-/*FUNCTION DoubleInput::GetVectorFromInputs{{{*/
-void DoubleInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){
+void DoubleInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){/*{{{*/
 
 	_error_("not supporte yet!");
@@ -201,11 +175,9 @@
 }
 /*}}}*/
-/*FUNCTION DoubleInput::GetInputAverage{{{*/
-void DoubleInput::GetInputAverage(IssmDouble* pvalue){
+void DoubleInput::GetInputAverage(IssmDouble* pvalue){/*{{{*/
 	*pvalue=value;
 }
 /*}}}*/
-/*FUNCTION DoubleInput::VerticallyIntegrate{{{*/
-void DoubleInput::VerticallyIntegrate(Input* thickness_input){
+void DoubleInput::VerticallyIntegrate(Input* thickness_input){/*{{{*/
 
 	/*Intermediaries*/
@@ -228,6 +200,5 @@
 }
 /*}}}*/
-/*FUNCTION DoubleInput::PointwiseDivide{{{*/
-Input* DoubleInput::PointwiseDivide(Input* inputB){
+Input* DoubleInput::PointwiseDivide(Input* inputB){/*{{{*/
 
 	/*Ouput*/
@@ -248,6 +219,5 @@
 }
 /*}}}*/
-/*FUNCTION DoubleInput::PointwiseMin{{{*/
-Input* DoubleInput::PointwiseMin(Input* input){
+Input* DoubleInput::PointwiseMin(Input* input){/*{{{*/
 
 	/*Ouput*/
@@ -269,6 +239,5 @@
 }
 /*}}}*/
-/*FUNCTION DoubleInput::PointwiseMax{{{*/
-Input* DoubleInput::PointwiseMax(Input* input){
+Input* DoubleInput::PointwiseMax(Input* input){/*{{{*/
 
 	/*Ouput*/
@@ -290,6 +259,5 @@
 }
 /*}}}*/
-/*FUNCTION DoubleInput::Configure{{{*/
-void DoubleInput::Configure(Parameters* parameters){
+void DoubleInput::Configure(Parameters* parameters){/*{{{*/
 	/*do nothing: */
 }
Index: issm/trunk/src/c/classes/Inputs/Inputs.cpp
===================================================================
--- issm/trunk/src/c/classes/Inputs/Inputs.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Inputs/Inputs.cpp	(revision 18301)
@@ -19,11 +19,9 @@
 
 /*Object constructors and destructor*/
-/*FUNCTION Inputs::Inputs(){{{*/
-Inputs::Inputs(){
+Inputs::Inputs(){/*{{{*/
 	return;
 }
 /*}}}*/
-/*FUNCTION Inputs::~Inputs(){{{*/
-Inputs::~Inputs(){
+Inputs::~Inputs(){/*{{{*/
 	return;
 }
@@ -31,6 +29,5 @@
 
 /*Object management*/
-/*FUNCTION Inputs::GetInputValue(bool* pvalue,int enum-type){{{*/
-void Inputs::GetInputValue(bool* pvalue,int enum_type){
+void Inputs::GetInputValue(bool* pvalue,int enum_type){/*{{{*/
 
 	vector<Object*>::iterator object;
@@ -59,6 +56,5 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::GetInputValue(int* pvalue,int enum-type){{{*/
-void Inputs::GetInputValue(int* pvalue,int enum_type){
+void Inputs::GetInputValue(int* pvalue,int enum_type){/*{{{*/
 
 	vector<Object*>::iterator object;
@@ -87,6 +83,5 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::GetInputValue(IssmDouble* pvalue,int enum-type){{{*/
-void Inputs::GetInputValue(IssmDouble* pvalue,int enum_type){
+void Inputs::GetInputValue(IssmDouble* pvalue,int enum_type){/*{{{*/
 
 	vector<Object*>::iterator object;
@@ -115,6 +110,5 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::GetInputAverage{{{*/
-void Inputs::GetInputAverage(IssmDouble* pvalue,int enum_type){
+void Inputs::GetInputAverage(IssmDouble* pvalue,int enum_type){/*{{{*/
 
 	vector<Object*>::iterator object;
@@ -143,6 +137,5 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::AddInput{{{*/
-int  Inputs::AddInput(Input* in_input){
+int  Inputs::AddInput(Input* in_input){/*{{{*/
 
 	/*First, go through dataset of inputs and check whether any input 
@@ -169,6 +162,5 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::ChangeEnum{{{*/
-void  Inputs::ChangeEnum(int oldenumtype,int newenumtype){
+void  Inputs::ChangeEnum(int oldenumtype,int newenumtype){/*{{{*/
 
 	/*Go through dataset of inputs and look for input with 
@@ -199,6 +191,5 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::ConstrainMin{{{*/
-void  Inputs::ConstrainMin(int constrain_enum, IssmDouble minimum){
+void  Inputs::ConstrainMin(int constrain_enum, IssmDouble minimum){/*{{{*/
 
 	/*Find x and y inputs: */
@@ -212,6 +203,5 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::InfinityNorm{{{*/
-IssmDouble Inputs::InfinityNorm(int enumtype){
+IssmDouble Inputs::InfinityNorm(int enumtype){/*{{{*/
 
 	/*Output*/
@@ -233,6 +223,5 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::Max{{{*/
-IssmDouble Inputs::Max(int enumtype){
+IssmDouble Inputs::Max(int enumtype){/*{{{*/
 
 	/*Output*/
@@ -254,6 +243,5 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::MaxAbs{{{*/
-IssmDouble Inputs::MaxAbs(int enumtype){
+IssmDouble Inputs::MaxAbs(int enumtype){/*{{{*/
 
 	/*Output*/
@@ -275,6 +263,5 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::Min{{{*/
-IssmDouble Inputs::Min(int enumtype){
+IssmDouble Inputs::Min(int enumtype){/*{{{*/
 
 	/*Output*/
@@ -296,6 +283,5 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::MinAbs{{{*/
-IssmDouble Inputs::MinAbs(int enumtype){
+IssmDouble Inputs::MinAbs(int enumtype){/*{{{*/
 
 	/*Output*/
@@ -317,6 +303,5 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::GetInput{{{*/
-Input* Inputs::GetInput(int enum_name){
+Input* Inputs::GetInput(int enum_name){/*{{{*/
 
 	vector<Object*>::iterator object;
@@ -334,6 +319,5 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::DeleteInput{{{*/
-int  Inputs::DeleteInput(int enum_type){
+int  Inputs::DeleteInput(int enum_type){/*{{{*/
 
 	vector<Object*>::iterator object;
@@ -354,6 +338,5 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::DuplicateInput{{{*/
-void  Inputs::DuplicateInput(int original_enum,int new_enum){
+void  Inputs::DuplicateInput(int original_enum,int new_enum){/*{{{*/
 
 	/*Make a copy of the original input: */
@@ -369,6 +352,5 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::SpawnTriaInputs{{{*/
-Inputs* Inputs::SpawnTriaInputs(int index1,int index2,int index3){
+Inputs* Inputs::SpawnTriaInputs(int index1,int index2,int index3){/*{{{*/
 
 	/*Intermediary*/
@@ -395,6 +377,5 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::SpawnSegInputs{{{*/
-Inputs* Inputs::SpawnSegInputs(int index1,int index2){
+Inputs* Inputs::SpawnSegInputs(int index1,int index2){/*{{{*/
 
 	/*Intermediary*/
@@ -421,6 +402,5 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::AXPY{{{*/
-void  Inputs::AXPY(int inputy_enum, IssmDouble scalar, int inputx_enum){
+void  Inputs::AXPY(int inputy_enum, IssmDouble scalar, int inputx_enum){/*{{{*/
 
 	/*Find x and y inputs: */
@@ -436,6 +416,5 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::Configure{{{*/
-void Inputs::Configure(Parameters* parameters){
+void Inputs::Configure(Parameters* parameters){/*{{{*/
 
 	vector<Object*>::iterator object;
Index: issm/trunk/src/c/classes/Inputs/IntInput.cpp
===================================================================
--- issm/trunk/src/c/classes/Inputs/IntInput.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Inputs/IntInput.cpp	(revision 18301)
@@ -13,11 +13,9 @@
 
 /*IntInput constructors and destructor*/
-/*FUNCTION IntInput::IntInput(){{{*/
-IntInput::IntInput(){
+IntInput::IntInput(){/*{{{*/
 	return;
 }
 /*}}}*/
-/*FUNCTION IntInput::IntInput(IssmDouble* values){{{*/
-IntInput::IntInput(int in_enum_type,IssmInt in_value){
+IntInput::IntInput(int in_enum_type,IssmInt in_value){/*{{{*/
 
 	enum_type=in_enum_type;
@@ -25,6 +23,5 @@
 }
 /*}}}*/
-/*FUNCTION IntInput::~IntInput(){{{*/
-IntInput::~IntInput(){
+IntInput::~IntInput(){/*{{{*/
 	return;
 }
@@ -32,15 +29,12 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION IntInput::DeepEcho{{{*/
-void IntInput::DeepEcho(void){
+void IntInput::DeepEcho(void){/*{{{*/
 
 	_printf_(setw(15)<<"   IntInput "<<setw(25)<<left<<EnumToStringx(this->enum_type)<<" "<<this->value<<"\n");
 }
 /*}}}*/
-/*FUNCTION IntInput::Id{{{*/
-int    IntInput::Id(void){ return -1; }
+int    IntInput::Id(void){ return -1; }/*{{{*/
 /*}}}*/
-/*FUNCTION IntInput::ObjectEnum{{{*/
-int IntInput::ObjectEnum(void){
+int IntInput::ObjectEnum(void){/*{{{*/
 
 	return IntInputEnum;
@@ -48,6 +42,5 @@
 }
 /*}}}*/
-/*FUNCTION IntInput::copy{{{*/
-Object* IntInput::copy() {
+Object* IntInput::copy() {/*{{{*/
 
 	return new IntInput(this->enum_type,this->value);
@@ -57,11 +50,9 @@
 
 /*IntInput management*/
-/*FUNCTION IntInput::Echo {{{*/
-void IntInput::Echo(void){
+void IntInput::Echo(void){/*{{{*/
 	this->DeepEcho();
 }
 /*}}}*/
-/*FUNCTION IntInput::InstanceEnum{{{*/
-int IntInput::InstanceEnum(void){
+int IntInput::InstanceEnum(void){/*{{{*/
 
 	return this->enum_type;
@@ -69,6 +60,5 @@
 }
 /*}}}*/
-/*FUNCTION IntInput::SpawnTriaInput{{{*/
-Input* IntInput::SpawnTriaInput(int index1,int index2,int index3){
+Input* IntInput::SpawnTriaInput(int index1,int index2,int index3){/*{{{*/
 
 	/*output*/
@@ -83,6 +73,5 @@
 }
 /*}}}*/
-/*FUNCTION IntInput::SpawnSegInput{{{*/
-Input* IntInput::SpawnSegInput(int index1,int index2){
+Input* IntInput::SpawnSegInput(int index1,int index2){/*{{{*/
 
 	/*output*/
@@ -99,27 +88,21 @@
 
 /*Object functions*/
-/*FUNCTION IntInput::GetInputValue(bool* pvalue) {{{*/
-void IntInput::GetInputValue(bool* pvalue){_error_("not supported yet!");}
+void IntInput::GetInputValue(bool* pvalue){_error_("not supported yet!");}/*{{{*/
 /*}}}*/
-/*FUNCTION IntInput::GetInputValue(int* pvalue){{{*/
-void IntInput::GetInputValue(int* pvalue){
+void IntInput::GetInputValue(int* pvalue){/*{{{*/
 	*pvalue=value;
 }
 /*}}}*/
-/*FUNCTION IntInput::GetInputValue(IssmDouble* pvalue){{{*/
-void IntInput::GetInputValue(IssmDouble* pvalue){
+void IntInput::GetInputValue(IssmDouble* pvalue){/*{{{*/
 	_error_("IntInput cannot return a IssmDouble in parallel");
 }
 /*}}}*/
-/*FUNCTION IntInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){{{*/
-void IntInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){_error_("not supported yet!");}
+void IntInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){_error_("not supported yet!");}/*{{{*/
 /*}}}*/
-/*FUNCTION IntInput::ChangeEnum{{{*/
-void IntInput::ChangeEnum(int newenumtype){
+void IntInput::ChangeEnum(int newenumtype){/*{{{*/
 	this->enum_type=newenumtype;
 }
 /*}}}*/
-/*FUNCTION IntInput::SquareMin{{{*/
-void IntInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){
+void IntInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){/*{{{*/
 
 	/*square min of an integer is the square of the integer itself: */
@@ -127,12 +110,10 @@
 }
 /*}}}*/
-/*FUNCTION IntInput::Scale{{{*/
-void IntInput::Scale(IssmDouble scale_factor){
+void IntInput::Scale(IssmDouble scale_factor){/*{{{*/
 	IssmDouble dvalue=(IssmDouble)value*scale_factor;
 	value=reCast<int>(dvalue);
 }
 /*}}}*/
-/*FUNCTION IntInput::AXPY{{{*/
-void IntInput::AXPY(Input* xinput,IssmDouble scalar){
+void IntInput::AXPY(Input* xinput,IssmDouble scalar){/*{{{*/
 
 	IssmDouble dvalue;
@@ -156,6 +137,5 @@
 }
 /*}}}*/
-/*FUNCTION IntInput::Constrain{{{*/
-void IntInput::Constrain(IssmDouble cm_min, IssmDouble cm_max){
+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);
@@ -164,6 +144,5 @@
 }
 /*}}}*/
-/*FUNCTION IntInput::GetVectorFromInputs{{{*/
-void IntInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){
+void IntInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){/*{{{*/
 
 	_error_("not supporte yet!");
@@ -171,6 +150,5 @@
 }
 /*}}}*/
-/*FUNCTION IntInput::Configure{{{*/
-void IntInput::Configure(Parameters* parameters){
+void IntInput::Configure(Parameters* parameters){/*{{{*/
 	/*do nothing: */
 }
Index: issm/trunk/src/c/classes/Inputs/PentaInput.cpp
===================================================================
--- issm/trunk/src/c/classes/Inputs/PentaInput.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Inputs/PentaInput.cpp	(revision 18301)
@@ -13,28 +13,28 @@
 
 /*PentaInput constructors and destructor*/
-/*FUNCTION PentaInput::PentaInput(){{{*/
-PentaInput::PentaInput(){
+PentaInput::PentaInput(){/*{{{*/
 	values = NULL;
 }
 /*}}}*/
-/*FUNCTION PentaInput::PentaInput(int in_enum_type,IssmDouble* values,int element_type){{{*/
-PentaInput::PentaInput(int in_enum_type,IssmDouble* in_values,int element_type_in)
-		:PentaRef(1)
-{
-
-	/*Set PentaRef*/
-	this->SetElementType(element_type_in,0);
-	this->element_type=element_type_in;
+PentaInput::PentaInput(int in_enum_type,IssmDouble* in_values,int interpolation_type_in){/*{{{*/
 
 	/*Set Enum*/
-	enum_type=in_enum_type;
+	this->enum_type=in_enum_type;
+	this->interpolation_type=interpolation_type_in;
+
+	int numnodes = this->NumberofNodes(this->interpolation_type);
 
 	/*Set values*/
-	this->values=xNew<IssmDouble>(this->NumberofNodes());
-	for(int i=0;i<this->NumberofNodes();i++) values[i]=in_values[i];
-}
-/*}}}*/
-/*FUNCTION PentaInput::~PentaInput(){{{*/
-PentaInput::~PentaInput(){
+	if (numnodes > 0){
+		this->values=xNew<IssmDouble>((unsigned int)numnodes);
+		for(int i=0;i<this->NumberofNodes(this->interpolation_type);i++) values[i]=in_values[i];
+	}
+	else{
+		this->values = NULL;
+	}
+
+}
+/*}}}*/
+PentaInput::~PentaInput(){/*{{{*/
 	xDelete<IssmDouble>(this->values);
 }
@@ -42,22 +42,18 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION PentaInput::Echo {{{*/
-void PentaInput::Echo(void){
+void PentaInput::Echo(void){/*{{{*/
 	this->DeepEcho();
 }
 /*}}}*/
-/*FUNCTION PentaInput::DeepEcho{{{*/
-void PentaInput::DeepEcho(void){
+void PentaInput::DeepEcho(void){/*{{{*/
 
 	_printf_(setw(15)<<"   PentaInput "<<setw(25)<<left<<EnumToStringx(this->enum_type)<<" [");
-	for(int i=0;i<this->NumberofNodes();i++) _printf_(" "<<this->values[i]);
+	for(int i=0;i<this->NumberofNodes(this->interpolation_type);i++) _printf_(" "<<this->values[i]);
 	_printf_("]\n");
 }
 /*}}}*/
-/*FUNCTION PentaInput::Id{{{*/
-int    PentaInput::Id(void){ return -1; }
-/*}}}*/
-/*FUNCTION PentaInput::ObjectEnum{{{*/
-int PentaInput::ObjectEnum(void){
+int    PentaInput::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int PentaInput::ObjectEnum(void){/*{{{*/
 
 	return PentaInputEnum;
@@ -65,8 +61,7 @@
 }
 /*}}}*/
-/*FUNCTION PentaInput::copy{{{*/
-Object* PentaInput::copy() {
-
-	return new PentaInput(this->enum_type,this->values,this->element_type);
+Object* PentaInput::copy() {/*{{{*/
+
+	return new PentaInput(this->enum_type,this->values,this->interpolation_type);
 
 }
@@ -74,6 +69,5 @@
 
 /*PentaInput management*/
-/*FUNCTION PentaInput::InstanceEnum{{{*/
-int PentaInput::InstanceEnum(void){
+int PentaInput::InstanceEnum(void){/*{{{*/
 
 	return this->enum_type;
@@ -81,11 +75,10 @@
 }
 /*}}}*/
-/*FUNCTION PentaInput::SpawnTriaInput{{{*/
-Input* PentaInput::SpawnTriaInput(int index1,int index2,int index3){
+Input* PentaInput::SpawnTriaInput(int index1,int index2,int index3){/*{{{*/
 
 	/*output*/
 	TriaInput* outinput=NULL;
 
-	if(this->element_type==P0Enum){ 
+	if(this->interpolation_type==P0Enum){ 
 		outinput=new TriaInput(this->enum_type,&this->values[0],P0Enum);
 	}
@@ -112,28 +105,27 @@
 }
 /*}}}*/
-/*FUNCTION PentaInput::SpawnSegInput{{{*/
-Input* PentaInput::SpawnSegInput(int index1,int index2){
+Input* PentaInput::SpawnSegInput(int index1,int index2){/*{{{*/
 
 	_error_("not supported");
 }
 /*}}}*/
-/*FUNCTION PentaInput::GetResultInterpolation{{{*/
-int  PentaInput::GetResultInterpolation(void){
-
+int  PentaInput::GetResultInterpolation(void){/*{{{*/
+
+	if(this->interpolation_type==P0Enum){
+		return P0Enum;
+	}
 	return P1Enum;
 
 }
 /*}}}*/
-/*FUNCTION PentaInput::GetResultNumberOfNodes{{{*/
-int  PentaInput::GetResultNumberOfNodes(void){
-
-	return this->NumberofNodes();;
-
-}
-/*}}}*/
-/*FUNCTION PentaInput::ResultToPatch{{{*/
-void PentaInput::ResultToPatch(IssmDouble* values,int nodesperelement,int sid){
-
-	int numnodes = this->NumberofNodes();
+int  PentaInput::GetResultNumberOfNodes(void){/*{{{*/
+
+	return this->NumberofNodes(this->interpolation_type);;
+
+}
+/*}}}*/
+void PentaInput::ResultToPatch(IssmDouble* values,int nodesperelement,int sid){/*{{{*/
+
+	int numnodes = this->NumberofNodes(this->interpolation_type);
 
 	/*Some checks*/
@@ -147,8 +139,7 @@
 
 /*Object functions*/
-/*FUNCTION PentaInput::GetInputValue(IssmDouble* pvalue){{{*/
-void PentaInput::GetInputValue(IssmDouble* pvalue){
-
-	if(this->element_type==P0Enum){
+void PentaInput::GetInputValue(IssmDouble* pvalue){/*{{{*/
+
+	if(this->interpolation_type==P0Enum){
 		pvalue=&values[0];
 	}
@@ -156,30 +147,26 @@
 }
 /*}}}*/
-/*FUNCTION PentaInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){{{*/
-void PentaInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){
+void PentaInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){/*{{{*/
 
 	/*Call PentaRef function*/
 	_assert_(gauss->Enum()==GaussPentaEnum);
-	PentaRef::GetInputValue(pvalue,&values[0],(GaussPenta*)gauss);
-
-}
-/*}}}*/
-/*FUNCTION PentaInput::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list, Gauss* gauss){{{*/
-void PentaInput::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list,Gauss* gauss){
+	PentaRef::GetInputValue(pvalue,&values[0],(GaussPenta*)gauss,this->interpolation_type);
+
+}
+/*}}}*/
+void PentaInput::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 
 	/*Call PentaRef function*/
 	_assert_(gauss->Enum()==GaussPentaEnum);
-	PentaRef::GetInputDerivativeValue(p,&values[0],xyz_list,(GaussPenta*)gauss);
-}
-/*}}}*/
-/*FUNCTION PentaInput::ChangeEnum{{{*/
-void PentaInput::ChangeEnum(int newenumtype){
+	PentaRef::GetInputDerivativeValue(p,&values[0],xyz_list,(GaussPenta*)gauss,this->interpolation_type);
+}
+/*}}}*/
+void PentaInput::ChangeEnum(int newenumtype){/*{{{*/
 	this->enum_type=newenumtype;
 }
 /*}}}*/
-/*FUNCTION PentaInput::GetInputAverage{{{*/
-void PentaInput::GetInputAverage(IssmDouble* pvalue){
-
-	int        numnodes  = this->NumberofNodes();
+void PentaInput::GetInputAverage(IssmDouble* pvalue){/*{{{*/
+
+	int        numnodes  = this->NumberofNodes(this->interpolation_type);
 	IssmDouble numnodesd = reCast<int,IssmDouble>(numnodes);
 	IssmDouble value     = 0.;
@@ -193,8 +180,7 @@
 
 /*Intermediary*/
-/*FUNCTION PentaInput::SquareMin{{{*/
-void PentaInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){
-
-	int        numnodes=this->NumberofNodes();
+void PentaInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){/*{{{*/
+
+	int        numnodes=this->NumberofNodes(this->interpolation_type);
 	IssmDouble squaremin;
 
@@ -208,17 +194,15 @@
 }
 /*}}}*/
-/*FUNCTION PentaInput::ConstrainMin{{{*/
-void PentaInput::ConstrainMin(IssmDouble minimum){
-
-	int numnodes = this->NumberofNodes();
+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;
 }
 /*}}}*/
-/*FUNCTION PentaInput::InfinityNorm{{{*/
-IssmDouble PentaInput::InfinityNorm(void){
+IssmDouble PentaInput::InfinityNorm(void){/*{{{*/
 
 	/*Output*/
 	IssmDouble norm=0.;
-	int numnodes=this->NumberofNodes();
+	int numnodes=this->NumberofNodes(this->interpolation_type);
 
 	for(int i=0;i<numnodes;i++) if(fabs(values[i])>norm) norm=fabs(values[i]);
@@ -226,8 +210,7 @@
 }
 /*}}}*/
-/*FUNCTION PentaInput::Max{{{*/
-IssmDouble PentaInput::Max(void){
-
-	int  numnodes=this->NumberofNodes();
+IssmDouble PentaInput::Max(void){/*{{{*/
+
+	int  numnodes=this->NumberofNodes(this->interpolation_type);
 	IssmDouble max=values[0];
 
@@ -238,8 +221,7 @@
 }
 /*}}}*/
-/*FUNCTION PentaInput::MaxAbs{{{*/
-IssmDouble PentaInput::MaxAbs(void){
-
-	int  numnodes=this->NumberofNodes();
+IssmDouble PentaInput::MaxAbs(void){/*{{{*/
+
+	int  numnodes=this->NumberofNodes(this->interpolation_type);
 	IssmDouble max=fabs(values[0]);
 
@@ -250,8 +232,7 @@
 }
 /*}}}*/
-/*FUNCTION PentaInput::Min{{{*/
-IssmDouble PentaInput::Min(void){
-
-	const int  numnodes=this->NumberofNodes();
+IssmDouble PentaInput::Min(void){/*{{{*/
+
+	const int  numnodes=this->NumberofNodes(this->interpolation_type);
 	IssmDouble min=values[0];
 
@@ -262,8 +243,7 @@
 }
 /*}}}*/
-/*FUNCTION PentaInput::MinAbs{{{*/
-IssmDouble PentaInput::MinAbs(void){
-
-	const int  numnodes=this->NumberofNodes();
+IssmDouble PentaInput::MinAbs(void){/*{{{*/
+
+	const int  numnodes=this->NumberofNodes(this->interpolation_type);
 	IssmDouble min=fabs(values[0]);
 
@@ -274,15 +254,13 @@
 }
 /*}}}*/
-/*FUNCTION PentaInput::Scale{{{*/
-void PentaInput::Scale(IssmDouble scale_factor){
-
-	const int numnodes=this->NumberofNodes();
+void PentaInput::Scale(IssmDouble scale_factor){/*{{{*/
+
+	const int numnodes=this->NumberofNodes(this->interpolation_type);
 	for(int i=0;i<numnodes;i++)values[i]=values[i]*scale_factor;
 }
 /*}}}*/
-/*FUNCTION PentaInput::AXPY{{{*/
-void PentaInput::AXPY(Input* xinput,IssmDouble scalar){
-
-	const int numnodes=this->NumberofNodes();
+void PentaInput::AXPY(Input* xinput,IssmDouble scalar){/*{{{*/
+
+	const int numnodes=this->NumberofNodes(this->interpolation_type);
 	PentaInput* xpentainput=NULL;
 
@@ -296,5 +274,5 @@
 	  _error_("Operation not permitted because xinput is of type " << EnumToStringx(xinput->ObjectEnum()));
 	xpentainput=(PentaInput*)xinput;
-	if(xpentainput->element_type!=this->element_type) _error_("Operation not permitted because xinput is of type " << EnumToStringx(xpentainput->element_type));
+	if(xpentainput->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because xinput is of type " << EnumToStringx(xpentainput->interpolation_type));
 
 	/*Carry out the AXPY operation depending on type:*/
@@ -303,9 +281,8 @@
 }
 /*}}}*/
-/*FUNCTION PentaInput::Constrain{{{*/
-void PentaInput::Constrain(IssmDouble cm_min, IssmDouble cm_max){
+void PentaInput::Constrain(IssmDouble cm_min, IssmDouble cm_max){/*{{{*/
 
 	int i;
-	const int numnodes=this->NumberofNodes();
+	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;
@@ -314,18 +291,16 @@
 }
 /*}}}*/
-/*FUNCTION PentaInput::Extrude{{{*/
-void PentaInput::Extrude(void){
-
-	switch(this->element_type){
+void PentaInput::Extrude(void){/*{{{*/
+
+	switch(this->interpolation_type){
 		case P1Enum:
 			for(int i=0;i<3;i++) this->values[3+i]=this->values[i];
 			break;
 		default:
-			_error_("not supported yet for type "<<EnumToStringx(this->element_type));
-	}
-}
-/*}}}*/
-/*FUNCTION PentaInput::VerticallyIntegrate{{{*/
-void PentaInput::VerticallyIntegrate(Input* thickness_input){
+			_error_("not supported yet for type "<<EnumToStringx(this->interpolation_type));
+	}
+}
+/*}}}*/
+void PentaInput::VerticallyIntegrate(Input* thickness_input){/*{{{*/
 
 	IssmDouble thickness;
@@ -336,10 +311,10 @@
 
 	/*vertically integrate depending on type (and use P1 interpolation from now on)*/
-	switch(this->element_type){
+	switch(this->interpolation_type){
 		case P1Enum:
 		case P1bubbleEnum:
 		case P2Enum:
 			  {
-				this->element_type=P1Enum;
+				this->interpolation_type=P1Enum;
 				GaussPenta *gauss=new GaussPenta();
 				for(int iv=0;iv<3;iv++){
@@ -353,10 +328,9 @@
 			  }
 		default:
-			_error_("not supported yet for type "<<EnumToStringx(this->element_type));
-	}
-}
-/*}}}*/
-/*FUNCTION PentaInput::PointwiseDivide{{{*/
-Input* PentaInput::PointwiseDivide(Input* inputB){
+			_error_("not supported yet for type "<<EnumToStringx(this->interpolation_type));
+	}
+}
+/*}}}*/
+Input* PentaInput::PointwiseDivide(Input* inputB){/*{{{*/
 
 	/*Ouput*/
@@ -365,10 +339,10 @@
 	/*Intermediaries*/
 	PentaInput *xinputB  = NULL;
-	const int   numnodes = this->NumberofNodes();
+	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->element_type!=this->element_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->element_type));
+	if(xinputB->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->interpolation_type));
 
 	/*Allocate intermediary*/
@@ -382,5 +356,5 @@
 
 	/*Create new Penta vertex input (copy of current input)*/
-	outinput=new PentaInput(this->enum_type,AdotBvalues,this->element_type);
+	outinput=new PentaInput(this->enum_type,AdotBvalues,this->interpolation_type);
 
 	/*Return output pointer*/
@@ -390,6 +364,5 @@
 }
 /*}}}*/
-/*FUNCTION PentaInput::PointwiseMin{{{*/
-Input* PentaInput::PointwiseMin(Input* inputB){
+Input* PentaInput::PointwiseMin(Input* inputB){/*{{{*/
 
 	/*Ouput*/
@@ -399,5 +372,5 @@
 	int         i;
 	PentaInput  *xinputB   = NULL;
-	const int   numnodes  = this->NumberofNodes();
+	const int   numnodes  = this->NumberofNodes(this->interpolation_type);
 	IssmDouble *minvalues = xNew<IssmDouble>(numnodes);
 
@@ -405,5 +378,5 @@
 	if(inputB->ObjectEnum()!=PentaInputEnum)       _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
 	xinputB=(PentaInput*)inputB;
-	if(xinputB->element_type!=this->element_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->element_type));
+	if(xinputB->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->interpolation_type));
 
 	/*Create point wise min*/
@@ -414,5 +387,5 @@
 
 	/*Create new Penta vertex input (copy of current input)*/
-	outinput=new PentaInput(this->enum_type,&minvalues[0],this->element_type);
+	outinput=new PentaInput(this->enum_type,&minvalues[0],this->interpolation_type);
 
 	/*Return output pointer*/
@@ -421,6 +394,5 @@
 }
 /*}}}*/
-/*FUNCTION PentaInput::PointwiseMax{{{*/
-Input* PentaInput::PointwiseMax(Input* inputB){
+Input* PentaInput::PointwiseMax(Input* inputB){/*{{{*/
 
 	/*Ouput*/
@@ -430,5 +402,5 @@
 	int         i;
 	PentaInput  *xinputB   = NULL;
-	const int   numnodes  = this->NumberofNodes();
+	const int   numnodes  = this->NumberofNodes(this->interpolation_type);
 	IssmDouble *maxvalues = xNew<IssmDouble>(numnodes);
 
@@ -436,5 +408,5 @@
 	if(inputB->ObjectEnum()!=PentaInputEnum) _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
 	xinputB=(PentaInput*)inputB;
-	if(xinputB->element_type!=this->element_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->element_type));
+	if(xinputB->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->interpolation_type));
 
 	/*Create point wise max*/
@@ -445,5 +417,5 @@
 
 	/*Create new Penta vertex input (copy of current input)*/
-	outinput=new PentaInput(this->enum_type,&maxvalues[0],this->element_type);
+	outinput=new PentaInput(this->enum_type,&maxvalues[0],this->interpolation_type);
 
 	/*Return output pointer*/
@@ -452,11 +424,9 @@
 }
 /*}}}*/
-/*FUNCTION PentaInput::GetVectorFromInputs{{{*/
-void PentaInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){
+void PentaInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){/*{{{*/
 	const int numvertices=6;
 	vector->SetValues(numvertices,doflist,this->values,INS_VAL);
 } /*}}}*/
-/*FUNCTION PentaInput::Configure{{{*/
-void PentaInput::Configure(Parameters* parameters){
+void PentaInput::Configure(Parameters* parameters){/*{{{*/
 	/*do nothing: */
 }
Index: issm/trunk/src/c/classes/Inputs/PentaInput.h
===================================================================
--- issm/trunk/src/c/classes/Inputs/PentaInput.h	(revision 18081)
+++ issm/trunk/src/c/classes/Inputs/PentaInput.h	(revision 18301)
@@ -17,5 +17,6 @@
 
 	public:
-		int        enum_type;
+		int         enum_type;
+		int         interpolation_type;
 		IssmDouble* values;
 
Index: issm/trunk/src/c/classes/Inputs/SegInput.cpp
===================================================================
--- issm/trunk/src/c/classes/Inputs/SegInput.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Inputs/SegInput.cpp	(revision 18301)
@@ -13,28 +13,20 @@
 
 /*SegInput constructors and destructor*/
-/*FUNCTION SegInput::SegInput(){{{*/
-SegInput::SegInput(){
+SegInput::SegInput(){/*{{{*/
 	values = NULL;
 }
 /*}}}*/
-/*FUNCTION SegInput::SegInput(int in_enum_type,IssmDouble* invalues,element_type_in){{{*/
-SegInput::SegInput(int in_enum_type,IssmDouble* in_values,int element_type_in)
-	:SegRef(1)
-{
-
-	/*Set SegRef*/
-	this->SetElementType(element_type_in,0);
-	this->element_type=element_type_in;
+SegInput::SegInput(int in_enum_type,IssmDouble* in_values,int interpolation_type_in){/*{{{*/
 
 	/*Set Enum*/
 	enum_type=in_enum_type;
+	this->interpolation_type=interpolation_type_in;
 
 	/*Set values*/
-	this->values=xNew<IssmDouble>(this->NumberofNodes());
-	for(int i=0;i<this->NumberofNodes();i++) values[i]=in_values[i];
+	this->values=xNew<IssmDouble>(this->NumberofNodes(this->interpolation_type));
+	for(int i=0;i<this->NumberofNodes(this->interpolation_type);i++) values[i]=in_values[i];
 }
 /*}}}*/
-/*FUNCTION SegInput::~SegInput(){{{*/
-SegInput::~SegInput(){
+SegInput::~SegInput(){/*{{{*/
 	xDelete<IssmDouble>(this->values);
 }
@@ -42,22 +34,18 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION SegInput::Echo {{{*/
-void SegInput::Echo(void){
+void SegInput::Echo(void){/*{{{*/
 	this->DeepEcho();
 }
 /*}}}*/
-/*FUNCTION SegInput::DeepEcho{{{*/
-void SegInput::DeepEcho(void){
+void SegInput::DeepEcho(void){/*{{{*/
 
 	_printf_(setw(15)<<"   SegInput "<<setw(25)<<left<<EnumToStringx(this->enum_type)<<" [");
-	for(int i=0;i<this->NumberofNodes();i++) _printf_(" "<<this->values[i]);
+	for(int i=0;i<this->NumberofNodes(this->interpolation_type);i++) _printf_(" "<<this->values[i]);
 	_printf_("]\n");
 }
 /*}}}*/
-/*FUNCTION SegInput::Id{{{*/
-int    SegInput::Id(void){ return -1; }
+int    SegInput::Id(void){ return -1; }/*{{{*/
 /*}}}*/
-/*FUNCTION SegInput::ObjectEnum{{{*/
-int SegInput::ObjectEnum(void){
+int SegInput::ObjectEnum(void){/*{{{*/
 
 	return SegInputEnum;
@@ -65,8 +53,7 @@
 }
 /*}}}*/
-/*FUNCTION SegInput::copy{{{*/
-Object* SegInput::copy() {
+Object* SegInput::copy() {/*{{{*/
 
-	return new SegInput(this->enum_type,this->values,this->element_type);
+	return new SegInput(this->enum_type,this->values,this->interpolation_type);
 
 }
@@ -74,6 +61,5 @@
 
 /*SegInput management*/
-/*FUNCTION SegInput::InstanceEnum{{{*/
-int SegInput::InstanceEnum(void){
+int SegInput::InstanceEnum(void){/*{{{*/
 
 	return this->enum_type;
@@ -83,8 +69,7 @@
 
 /*Object functions*/
-/*FUNCTION SegInput::GetInputAverage{{{*/
-void SegInput::GetInputAverage(IssmDouble* pvalue){
+void SegInput::GetInputAverage(IssmDouble* pvalue){/*{{{*/
 
-	int        numnodes  = this->NumberofNodes();
+	int        numnodes  = this->NumberofNodes(this->interpolation_type);
 	IssmDouble numnodesd = reCast<int,IssmDouble>(numnodes);
 	IssmDouble value     = 0.;
@@ -96,30 +81,26 @@
 }
 /*}}}*/
-/*FUNCTION SegInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){{{*/
-void SegInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){
+void SegInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){/*{{{*/
 
 	/*Call SegRef function*/
 	_assert_(gauss->Enum()==GaussSegEnum);
-	SegRef::GetInputValue(pvalue,&values[0],(GaussSeg*)gauss);
+	SegRef::GetInputValue(pvalue,&values[0],(GaussSeg*)gauss,this->interpolation_type);
 
 }
 /*}}}*/
-/*FUNCTION SegInput::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list, Gauss* gauss){{{*/
-void SegInput::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list,Gauss* gauss){
+void SegInput::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 
 	/*Call SegRef function*/
 	_assert_(gauss->Enum()==GaussSegEnum);
-	SegRef::GetInputDerivativeValue(p,&values[0],xyz_list,(GaussSeg*)gauss);
+	SegRef::GetInputDerivativeValue(p,&values[0],xyz_list,(GaussSeg*)gauss,this->interpolation_type);
 }
 /*}}}*/
-/*FUNCTION SegInput::Configure{{{*/
-void SegInput::Configure(Parameters* parameters){
+void SegInput::Configure(Parameters* parameters){/*{{{*/
 	/*do nothing: */
 }
 /*}}}*/
-/*FUNCTION SegInput::Min{{{*/
-IssmDouble SegInput::Min(void){
+IssmDouble SegInput::Min(void){/*{{{*/
 
-	const int  numnodes=this->NumberofNodes();
+	const int  numnodes=this->NumberofNodes(this->interpolation_type);
 	IssmDouble min=values[0];
 
Index: issm/trunk/src/c/classes/Inputs/SegInput.h
===================================================================
--- issm/trunk/src/c/classes/Inputs/SegInput.h	(revision 18081)
+++ issm/trunk/src/c/classes/Inputs/SegInput.h	(revision 18301)
@@ -18,4 +18,5 @@
 	public:
 		int         enum_type;
+		int         interpolation_type;
 		IssmDouble* values;
 
Index: issm/trunk/src/c/classes/Inputs/TetraInput.cpp
===================================================================
--- issm/trunk/src/c/classes/Inputs/TetraInput.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Inputs/TetraInput.cpp	(revision 18301)
@@ -13,28 +13,28 @@
 
 /*TetraInput constructors and destructor*/
-/*FUNCTION TetraInput::TetraInput(){{{*/
-TetraInput::TetraInput(){
+TetraInput::TetraInput(){/*{{{*/
 	values = NULL;
 }
 /*}}}*/
-/*FUNCTION TetraInput::TetraInput(int in_enum_type,IssmDouble* invalues,element_type_in){{{*/
-TetraInput::TetraInput(int in_enum_type,IssmDouble* in_values,int element_type_in)
-	:TetraRef(1)
-{
-
-	/*Set TetraRef*/
-	this->SetElementType(element_type_in,0);
-	this->element_type=element_type_in;
+TetraInput::TetraInput(int in_enum_type,IssmDouble* in_values,int interpolation_type_in){/*{{{*/
 
 	/*Set Enum*/
-	enum_type=in_enum_type;
+	this->enum_type=in_enum_type;
+	this->interpolation_type=interpolation_type_in;
+
+	int numnodes = this->NumberofNodes(this->interpolation_type);
 
 	/*Set values*/
-	this->values=xNew<IssmDouble>(this->NumberofNodes());
-	for(int i=0;i<this->NumberofNodes();i++) values[i]=in_values[i];
-}
-/*}}}*/
-/*FUNCTION TetraInput::~TetraInput(){{{*/
-TetraInput::~TetraInput(){
+	if (numnodes > 0){
+		this->values=xNew<IssmDouble>((unsigned int)numnodes);
+		for(int i=0;i<this->NumberofNodes(this->interpolation_type);i++) values[i]=in_values[i];
+	}
+	else{
+		this->values = NULL;
+	}
+
+}
+/*}}}*/
+TetraInput::~TetraInput(){/*{{{*/
 	xDelete<IssmDouble>(this->values);
 }
@@ -42,22 +42,18 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION TetraInput::Echo {{{*/
-void TetraInput::Echo(void){
+void TetraInput::Echo(void){/*{{{*/
 	this->DeepEcho();
 }
 /*}}}*/
-/*FUNCTION TetraInput::DeepEcho{{{*/
-void TetraInput::DeepEcho(void){
+void TetraInput::DeepEcho(void){/*{{{*/
 
 	_printf_(setw(15)<<"   TetraInput "<<setw(25)<<left<<EnumToStringx(this->enum_type)<<" [");
-	for(int i=0;i<this->NumberofNodes();i++) _printf_(" "<<this->values[i]);
-	_printf_("] ("<<EnumToStringx(this->element_type)<<")\n");
-}
-/*}}}*/
-/*FUNCTION TetraInput::Id{{{*/
-int    TetraInput::Id(void){ return -1; }
-/*}}}*/
-/*FUNCTION TetraInput::ObjectEnum{{{*/
-int TetraInput::ObjectEnum(void){
+	for(int i=0;i<this->NumberofNodes(this->interpolation_type);i++) _printf_(" "<<this->values[i]);
+	_printf_("] ("<<EnumToStringx(this->interpolation_type)<<")\n");
+}
+/*}}}*/
+int    TetraInput::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int TetraInput::ObjectEnum(void){/*{{{*/
 
 	return TetraInputEnum;
@@ -65,8 +61,7 @@
 }
 /*}}}*/
-/*FUNCTION TetraInput::copy{{{*/
-Object* TetraInput::copy() {
-
-	return new TetraInput(this->enum_type,this->values,this->element_type);
+Object* TetraInput::copy() {/*{{{*/
+
+	return new TetraInput(this->enum_type,this->values,this->interpolation_type);
 
 }
@@ -74,6 +69,5 @@
 
 /*TetraInput management*/
-/*FUNCTION TetraInput::InstanceEnum{{{*/
-int TetraInput::InstanceEnum(void){
+int TetraInput::InstanceEnum(void){/*{{{*/
 
 	return this->enum_type;
@@ -81,22 +75,22 @@
 }
 /*}}}*/
-/*FUNCTION TetraInput::GetResultInterpolation{{{*/
-int  TetraInput::GetResultInterpolation(void){
-
+int  TetraInput::GetResultInterpolation(void){/*{{{*/
+
+	if(this->interpolation_type==P0Enum){
+		return P0Enum;
+	}
 	return P1Enum;
 
 }
 /*}}}*/
-/*FUNCTION TetraInput::GetResultNumberOfNodes{{{*/
-int  TetraInput::GetResultNumberOfNodes(void){
-
-	return this->NumberofNodes();
-
-}
-/*}}}*/
-/*FUNCTION TetraInput::ResultToPatch{{{*/
-void TetraInput::ResultToPatch(IssmDouble* values,int nodesperelement,int sid){
-
-	int numnodes = this->NumberofNodes();
+int  TetraInput::GetResultNumberOfNodes(void){/*{{{*/
+
+	return this->NumberofNodes(this->interpolation_type);
+
+}
+/*}}}*/
+void TetraInput::ResultToPatch(IssmDouble* values,int nodesperelement,int sid){/*{{{*/
+
+	int numnodes = this->NumberofNodes(this->interpolation_type);
 
 	/*Some checks*/
@@ -110,30 +104,26 @@
 
 /*Object functions*/
-/*FUNCTION TetraInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){{{*/
-void TetraInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){
+void TetraInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){/*{{{*/
 
 	/*Call TetraRef function*/
 	_assert_(gauss->Enum()==GaussTetraEnum);
-	TetraRef::GetInputValue(pvalue,&values[0],(GaussTetra*)gauss);
-
-}
-/*}}}*/
-/*FUNCTION TetraInput::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list, Gauss* gauss){{{*/
-void TetraInput::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list, Gauss* gauss){
+	TetraRef::GetInputValue(pvalue,&values[0],(GaussTetra*)gauss,this->interpolation_type);
+
+}
+/*}}}*/
+void TetraInput::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list, Gauss* gauss){/*{{{*/
 
 	/*Call TetraRef function*/
 	_assert_(gauss->Enum()==GaussTetraEnum);
-	TetraRef::GetInputDerivativeValue(p,&values[0],xyz_list,(GaussTetra*)gauss);
-}
-/*}}}*/
-/*FUNCTION TetraInput::ChangeEnum{{{*/
-void TetraInput::ChangeEnum(int newenumtype){
+	TetraRef::GetInputDerivativeValue(p,&values[0],xyz_list,(GaussTetra*)gauss,this->interpolation_type);
+}
+/*}}}*/
+void TetraInput::ChangeEnum(int newenumtype){/*{{{*/
 	this->enum_type=newenumtype;
 }
 /*}}}*/
-/*FUNCTION TetraInput::GetInputAverage{{{*/
-void TetraInput::GetInputAverage(IssmDouble* pvalue){
-
-	int        numnodes  = this->NumberofNodes();
+void TetraInput::GetInputAverage(IssmDouble* pvalue){/*{{{*/
+
+	int        numnodes  = this->NumberofNodes(this->interpolation_type);
 	IssmDouble numnodesd = reCast<int,IssmDouble>(numnodes);
 	IssmDouble value     = 0.;
@@ -145,6 +135,5 @@
 }
 /*}}}*/
-/*FUNCTION TetraInput::GetInputAllTimeAverages{{{*/
-void TetraInput::GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes){
+void TetraInput::GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes){/*{{{*/
 
 	IssmDouble* outvalues=NULL;
@@ -165,6 +154,5 @@
 }
 /*}}}*/
-/*FUNCTION TetraInput::GetInputUpToCurrentTimeAverages{{{*/
-void TetraInput::GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime){
+void TetraInput::GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime){/*{{{*/
 
 	IssmDouble* outvalues=NULL;
@@ -185,11 +173,10 @@
 }
 /*}}}*/
-/*FUNCTION TetraInput::SpawnTriaInput{{{*/
-Input* TetraInput::SpawnTriaInput(int index1,int index2,int index3){
+Input* TetraInput::SpawnTriaInput(int index1,int index2,int index3){/*{{{*/
 
 	/*output*/
 	TriaInput* outinput=NULL;
 
-	if(this->element_type==P0Enum){ 
+	if(this->interpolation_type==P0Enum){ 
 		outinput=new TriaInput(this->enum_type,&this->values[0],P0Enum);
 	}
@@ -218,8 +205,7 @@
 
 /*Intermediary*/
-/*FUNCTION TetraInput::SquareMin{{{*/
-void TetraInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){
-
-	int        numnodes=this->NumberofNodes();
+void TetraInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){/*{{{*/
+
+	int        numnodes=this->NumberofNodes(this->interpolation_type);
 	IssmDouble squaremin;
 
@@ -233,17 +219,15 @@
 }
 /*}}}*/
-/*FUNCTION TetraInput::ContrainMin{{{*/
-void TetraInput::ConstrainMin(IssmDouble minimum){
-
-	int numnodes = this->NumberofNodes();
+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;
 }
 /*}}}*/
-/*FUNCTION TetraInput::InfinityNorm{{{*/
-IssmDouble TetraInput::InfinityNorm(void){
+IssmDouble TetraInput::InfinityNorm(void){/*{{{*/
 
 	/*Output*/
 	IssmDouble norm=0.;
-	int numnodes=this->NumberofNodes();
+	int numnodes=this->NumberofNodes(this->interpolation_type);
 
 	for(int i=0;i<numnodes;i++) if(fabs(values[i])>norm) norm=fabs(values[i]);
@@ -251,8 +235,7 @@
 }
 /*}}}*/
-/*FUNCTION TetraInput::Max{{{*/
-IssmDouble TetraInput::Max(void){
-
-	int  numnodes=this->NumberofNodes();
+IssmDouble TetraInput::Max(void){/*{{{*/
+
+	int  numnodes=this->NumberofNodes(this->interpolation_type);
 	IssmDouble max=values[0];
 
@@ -263,8 +246,7 @@
 }
 /*}}}*/
-/*FUNCTION TetraInput::MaxAbs{{{*/
-IssmDouble TetraInput::MaxAbs(void){
-
-	int  numnodes=this->NumberofNodes();
+IssmDouble TetraInput::MaxAbs(void){/*{{{*/
+
+	int  numnodes=this->NumberofNodes(this->interpolation_type);
 	IssmDouble max=fabs(values[0]);
 
@@ -275,8 +257,7 @@
 }
 /*}}}*/
-/*FUNCTION TetraInput::Min{{{*/
-IssmDouble TetraInput::Min(void){
-
-	const int  numnodes=this->NumberofNodes();
+IssmDouble TetraInput::Min(void){/*{{{*/
+
+	const int  numnodes=this->NumberofNodes(this->interpolation_type);
 	IssmDouble min=values[0];
 
@@ -287,8 +268,7 @@
 }
 /*}}}*/
-/*FUNCTION TetraInput::MinAbs{{{*/
-IssmDouble TetraInput::MinAbs(void){
-
-	const int  numnodes=this->NumberofNodes();
+IssmDouble TetraInput::MinAbs(void){/*{{{*/
+
+	const int  numnodes=this->NumberofNodes(this->interpolation_type);
 	IssmDouble min=fabs(values[0]);
 
@@ -299,22 +279,19 @@
 }
 /*}}}*/
-/*FUNCTION TetraInput::Scale{{{*/
-void TetraInput::Scale(IssmDouble scale_factor){
-
-	const int numnodes=this->NumberofNodes();
+void TetraInput::Scale(IssmDouble scale_factor){/*{{{*/
+
+	const int numnodes=this->NumberofNodes(this->interpolation_type);
 	for(int i=0;i<numnodes;i++)values[i]=values[i]*scale_factor;
 }
 /*}}}*/
-/*FUNCTION TetraInput::Set{{{*/
-void TetraInput::Set(IssmDouble setvalue){
-
-	const int numnodes=this->NumberofNodes();
+void TetraInput::Set(IssmDouble setvalue){/*{{{*/
+
+	const int numnodes=this->NumberofNodes(this->interpolation_type);
 	for(int i=0;i<numnodes;i++)values[i]=setvalue;
 }
 /*}}}*/
-/*FUNCTION TetraInput::AXPY{{{*/
-void TetraInput::AXPY(Input* xinput,IssmDouble scalar){
-
-	const int numnodes=this->NumberofNodes();
+void TetraInput::AXPY(Input* xinput,IssmDouble scalar){/*{{{*/
+
+	const int numnodes=this->NumberofNodes(this->interpolation_type);
 	TetraInput*  xtriainput=NULL;
 
@@ -322,5 +299,5 @@
 	if(xinput->ObjectEnum()!=TetraInputEnum) _error_("Operation not permitted because xinput is of type " << EnumToStringx(xinput->ObjectEnum()));
 	xtriainput=(TetraInput*)xinput;
-	if(xtriainput->element_type!=this->element_type) _error_("Operation not permitted because xinput is of type " << EnumToStringx(xinput->ObjectEnum()));
+	if(xtriainput->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because xinput is of type " << EnumToStringx(xinput->ObjectEnum()));
 
 	/*Carry out the AXPY operation depending on type:*/
@@ -329,9 +306,8 @@
 }
 /*}}}*/
-/*FUNCTION TetraInput::Constrain{{{*/
-void TetraInput::Constrain(IssmDouble cm_min, IssmDouble cm_max){
+void TetraInput::Constrain(IssmDouble cm_min, IssmDouble cm_max){/*{{{*/
 
 	int i;
-	const int numnodes=this->NumberofNodes();
+	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;
@@ -340,11 +316,9 @@
 }
 /*}}}*/
-/*FUNCTION TetraInput::GetVectorFromInputs{{{*/
-void TetraInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){
+void TetraInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){/*{{{*/
 	const int numvertices=4;
 	vector->SetValues(numvertices,doflist,this->values,INS_VAL);
 } /*}}}*/
-/*FUNCTION TetraInput::PointwiseMin{{{*/
-Input* TetraInput::PointwiseMin(Input* inputB){
+Input* TetraInput::PointwiseMin(Input* inputB){/*{{{*/
 
 	/*Ouput*/
@@ -354,5 +328,5 @@
 	int         i;
 	TetraInput  *xinputB   = NULL;
-	const int   numnodes  = this->NumberofNodes();
+	const int   numnodes  = this->NumberofNodes(this->interpolation_type);
 	IssmDouble *minvalues = xNew<IssmDouble>(numnodes);
 
@@ -360,5 +334,5 @@
 	if(inputB->ObjectEnum()!=TetraInputEnum)       _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
 	xinputB=(TetraInput*)inputB;
-	if(xinputB->element_type!=this->element_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->element_type));
+	if(xinputB->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->interpolation_type));
 
 	/*Create point wise min*/
@@ -369,5 +343,5 @@
 
 	/*Create new Tetra vertex input (copy of current input)*/
-	outinput=new TetraInput(this->enum_type,&minvalues[0],this->element_type);
+	outinput=new TetraInput(this->enum_type,&minvalues[0],this->interpolation_type);
 
 	/*Return output pointer*/
@@ -377,6 +351,5 @@
 }
 /*}}}*/
-/*FUNCTION TetraInput::PointwiseMax{{{*/
-Input* TetraInput::PointwiseMax(Input* inputB){
+Input* TetraInput::PointwiseMax(Input* inputB){/*{{{*/
 
 	/*Ouput*/
@@ -386,5 +359,5 @@
 	int         i;
 	TetraInput  *xinputB   = NULL;
-	const int   numnodes  = this->NumberofNodes();
+	const int   numnodes  = this->NumberofNodes(this->interpolation_type);
 	IssmDouble *maxvalues = xNew<IssmDouble>(numnodes);
 
@@ -392,5 +365,5 @@
 	if(inputB->ObjectEnum()!=TetraInputEnum) _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
 	xinputB=(TetraInput*)inputB;
-	if(xinputB->element_type!=this->element_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->element_type));
+	if(xinputB->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->interpolation_type));
 
 	/*Create point wise max*/
@@ -401,5 +374,5 @@
 
 	/*Create new Tetra vertex input (copy of current input)*/
-	outinput=new TetraInput(this->enum_type,&maxvalues[0],this->element_type);
+	outinput=new TetraInput(this->enum_type,&maxvalues[0],this->interpolation_type);
 
 	/*Return output pointer*/
@@ -409,6 +382,5 @@
 }
 /*}}}*/
-/*FUNCTION TetraInput::PointwiseDivide{{{*/
-Input* TetraInput::PointwiseDivide(Input* inputB){
+Input* TetraInput::PointwiseDivide(Input* inputB){/*{{{*/
 
 	/*Ouput*/
@@ -417,10 +389,10 @@
 	/*Intermediaries*/
 	TetraInput *xinputB  = NULL;
-	const int   numnodes = this->NumberofNodes();
+	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->element_type!=this->element_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->element_type));
+	if(xinputB->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->interpolation_type));
 
 	/*Allocate intermediary*/
@@ -434,5 +406,5 @@
 
 	/*Create new Tetra vertex input (copy of current input)*/
-	outinput=new TetraInput(this->enum_type,AdotBvalues,this->element_type);
+	outinput=new TetraInput(this->enum_type,AdotBvalues,this->interpolation_type);
 
 	/*Return output pointer*/
@@ -442,6 +414,5 @@
 }
 /*}}}*/
-/*FUNCTION TetraInput::Configure{{{*/
-void TetraInput::Configure(Parameters* parameters){
+void TetraInput::Configure(Parameters* parameters){/*{{{*/
 	/*do nothing: */
 }
Index: issm/trunk/src/c/classes/Inputs/TetraInput.h
===================================================================
--- issm/trunk/src/c/classes/Inputs/TetraInput.h	(revision 18081)
+++ issm/trunk/src/c/classes/Inputs/TetraInput.h	(revision 18301)
@@ -18,4 +18,5 @@
 	public:
 		int         enum_type;
+		int         interpolation_type;
 		IssmDouble* values;
 
Index: issm/trunk/src/c/classes/Inputs/TransientInput.cpp
===================================================================
--- issm/trunk/src/c/classes/Inputs/TransientInput.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Inputs/TransientInput.cpp	(revision 18301)
@@ -14,6 +14,5 @@
 
 /*TransientInput constructors and destructor*/
-/*FUNCTION TransientInput::TransientInput(){{{*/
-TransientInput::TransientInput(){
+TransientInput::TransientInput(){/*{{{*/
 
 	enum_type=UNDEF;
@@ -25,6 +24,5 @@
 }
 /*}}}*/
-/*FUNCTION TransientInput::TransientInput(int in_enum_type){{{*/
-TransientInput::TransientInput(int in_enum_type)
+TransientInput::TransientInput(int in_enum_type)/*{{{*/
 {
 	/*Set Enum*/
@@ -39,6 +37,5 @@
 }
 /*}}}*/
-/*FUNCTION TransientInput::TransientInput(int in_enum_type,IssmDouble* timesin,int N){{{*/
-TransientInput::TransientInput(int in_enum_type,IssmDouble* timesin,int N){
+TransientInput::TransientInput(int in_enum_type,IssmDouble* timesin,int N){/*{{{*/
 
 	/*Set Enum*/
@@ -54,6 +51,5 @@
 }
 /*}}}*/
-/*FUNCTION TransientInput::~TransientInput{{{*/
-TransientInput::~TransientInput(){
+TransientInput::~TransientInput(){/*{{{*/
 	xDelete(this->timesteps);
 	this->timesteps=NULL;
@@ -66,11 +62,9 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION TransientInput::Echo {{{*/
-void TransientInput::Echo(void){
+void TransientInput::Echo(void){/*{{{*/
 	this->DeepEcho();
 }
 /*}}}*/
-/*FUNCTION TransientInput::DeepEcho{{{*/
-void TransientInput::DeepEcho(void){
+void TransientInput::DeepEcho(void){/*{{{*/
 
 	int i;
@@ -86,9 +80,7 @@
 }
 /*}}}*/
-/*FUNCTION TransientInput::Id{{{*/
-int    TransientInput::Id(void){ return -1; }
-/*}}}*/
-/*FUNCTION TransientInput::ObjectEnum{{{*/
-int TransientInput::ObjectEnum(void){
+int  TransientInput::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int  TransientInput::ObjectEnum(void){/*{{{*/
 
 	return TransientInputEnum;
@@ -96,6 +88,5 @@
 }
 /*}}}*/
-/*FUNCTION TransientInput::copy{{{*/
-Object* TransientInput::copy() {
+Object* TransientInput::copy() {/*{{{*/
 
 	TransientInput* output=NULL;
@@ -105,9 +96,9 @@
 	output->numtimesteps=this->numtimesteps;
 	output->timesteps=xNew<IssmDouble>(this->numtimesteps);
-        xMemCpy(output->timesteps,this->timesteps,this->numtimesteps);
-	output->inputs=(Inputs*)this->inputs->Copy();
+	xMemCpy(output->timesteps,this->timesteps,this->numtimesteps);
+	output->inputs=static_cast<Inputs*>(this->inputs->Copy());
 	output->parameters=this->parameters;
 
-	return output;
+	return (Object*)output;
 
 }
@@ -115,6 +106,5 @@
 
 /*TransientInput management*/
-/*FUNCTION TransientInput::InstanceEnum{{{*/
-int TransientInput::InstanceEnum(void){
+int TransientInput::InstanceEnum(void){/*{{{*/
 
 	return this->enum_type;
@@ -122,6 +112,5 @@
 }
 /*}}}*/
-/*FUNCTION TransientInput::SpawnTriaInput{{{*/
-Input* TransientInput::SpawnTriaInput(int index1,int index2,int index3){
+Input* TransientInput::SpawnTriaInput(int index1,int index2,int index3){/*{{{*/
 
 	/*output*/
@@ -142,6 +131,5 @@
 }
 /*}}}*/
-/*FUNCTION TransientInput::SpawnSegInput{{{*/
-Input* TransientInput::SpawnSegInput(int index1,int index2){
+Input* TransientInput::SpawnSegInput(int index1,int index2){/*{{{*/
 
 	/*output*/
@@ -164,6 +152,5 @@
 
 /*Object functions*/
-/*FUNCTION TransientInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){{{*/
-void TransientInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){
+void TransientInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){/*{{{*/
 	IssmDouble time;
 
@@ -180,6 +167,5 @@
 }
 /*}}}*/
-/*FUNCTION TransientInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss,IssmDouble time){{{*/
-void TransientInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss,IssmDouble time){
+void TransientInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss,IssmDouble time){/*{{{*/
 
 	/*Retrieve interpolated values for this time step: */
@@ -192,6 +178,5 @@
 }
 /*}}}*/
-/*FUNCTION TransientInput::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list, Gauss* gauss){{{*/
-void TransientInput::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list, Gauss* gauss){
+void TransientInput::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list, Gauss* gauss){/*{{{*/
 
 	IssmDouble time;
@@ -209,11 +194,9 @@
 }
 /*}}}*/
-/*FUNCTION TransientInput::ChangeEnum{{{*/
-void TransientInput::ChangeEnum(int newenumtype){
+void TransientInput::ChangeEnum(int newenumtype){/*{{{*/
 	this->enum_type=newenumtype;
 }
 /*}}}*/
-/*FUNCTION TransientInput::GetInputAverage{{{*/
-void TransientInput::GetInputAverage(IssmDouble* pvalue){
+void TransientInput::GetInputAverage(IssmDouble* pvalue){/*{{{*/
 
 	IssmDouble time;
@@ -232,6 +215,5 @@
 }
 /*}}}*/
-/*FUNCTION TransientInput::GetInputAllTimeAverages{{{*/
-void TransientInput::GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes){
+void TransientInput::GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes){/*{{{*/
 
 	int i;
@@ -254,6 +236,5 @@
 }
 /*}}}*/
-/*FUNCTION TransientInput::GetInputUpToCurrentTimeAverages{{{*/
-void TransientInput::GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime){
+void TransientInput::GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime){/*{{{*/
 
 	int         i;
@@ -299,6 +280,5 @@
 
 /*Intermediary*/
-/*FUNCTION TransientInput::AddTimeInput{{{*/
-void TransientInput::AddTimeInput(Input* input,IssmDouble time){
+void TransientInput::AddTimeInput(Input* input,IssmDouble time){/*{{{*/
 
 	/*insert values at time step: */
@@ -328,6 +308,5 @@
 }
 /*}}}*/
-/*FUNCTION TransientInput::AddTimeInput{{{*/
-void TransientInput::AddTimeInput(Input* input){
+void TransientInput::AddTimeInput(Input* input){/*{{{*/
 
 	_assert_(this->inputs->Size()<this->numtimesteps);
@@ -336,6 +315,5 @@
 }
 /*}}}*/
-/*FUNCTION TransientInput::GetResultInterpolation{{{*/
-int TransientInput::GetResultInterpolation(void){
+int  TransientInput::GetResultInterpolation(void){/*{{{*/
 
 	IssmDouble time;
@@ -352,6 +330,5 @@
 }
 /*}}}*/
-/*FUNCTION TransientInput::GetResultNumberOfNodes{{{*/
-int TransientInput::GetResultNumberOfNodes(void){
+int  TransientInput::GetResultNumberOfNodes(void){/*{{{*/
 
 	IssmDouble time;
@@ -368,6 +345,5 @@
 }
 /*}}}*/
-/*FUNCTION TransientInput::Extrude{{{*/
-void TransientInput::Extrude(void){
+void TransientInput::Extrude(void){/*{{{*/
 
 	for(int i=0;i<this->numtimesteps;i++){
@@ -376,6 +352,5 @@
 }
 /*}}}*/
-/*FUNCTION TransientInput::SquareMin{{{*/
-void TransientInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){
+void TransientInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){/*{{{*/
 
 	IssmDouble time;
@@ -394,6 +369,5 @@
 }
 /*}}}*/
-/*FUNCTION TransientInput::InfinityNorm{{{*/
-IssmDouble TransientInput::InfinityNorm(void){
+IssmDouble TransientInput::InfinityNorm(void){/*{{{*/
 
 	IssmDouble time;
@@ -414,6 +388,5 @@
 }
 /*}}}*/
-/*FUNCTION TransientInput::Max{{{*/
-IssmDouble TransientInput::Max(void){
+IssmDouble TransientInput::Max(void){/*{{{*/
 
 	IssmDouble time;
@@ -434,6 +407,5 @@
 }
 /*}}}*/
-/*FUNCTION TransientInput::MaxAbs{{{*/
-IssmDouble TransientInput::MaxAbs(void){
+IssmDouble TransientInput::MaxAbs(void){/*{{{*/
 
 	IssmDouble time;
@@ -455,6 +427,5 @@
 }
 /*}}}*/
-/*FUNCTION TransientInput::Min{{{*/
-IssmDouble TransientInput::Min(void){
+IssmDouble TransientInput::Min(void){/*{{{*/
 
 	IssmDouble time;
@@ -476,6 +447,5 @@
 }
 /*}}}*/
-/*FUNCTION TransientInput::MinAbs{{{*/
-IssmDouble TransientInput::MinAbs(void){
+IssmDouble TransientInput::MinAbs(void){/*{{{*/
 
 	IssmDouble time;
@@ -496,6 +466,5 @@
 }
 /*}}}*/
-/*FUNCTION TransientInput::GetVectorFromInputs{{{*/
-void TransientInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){
+void TransientInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){/*{{{*/
 
 	IssmDouble time;
@@ -513,6 +482,5 @@
 
 } /*}}}*/
-/*FUNCTION TransientInput::GetTimeInput{{{*/
-Input* TransientInput::GetTimeInput(IssmDouble intime){
+Input* TransientInput::GetTimeInput(IssmDouble intime){/*{{{*/
 
 	IssmDouble deltat;
@@ -520,4 +488,8 @@
 	int        found;
 	int        offset;
+	bool       interp;
+
+	/*First, recover interp bool: */
+	this->parameters->FindParam(&interp,TimesteppingInterpForcingsEnum);
 
 	Input *input  = NULL;
@@ -535,10 +507,10 @@
 		input=(Input*)((Input*)this->inputs->GetObjectByOffset(0))->copy();
 	}
-	else if(offset==(this->numtimesteps-1)){
+	else if(offset==(this->numtimesteps-1) || !interp){
 		/*get values for the last time: */
 		_assert_(intime>=this->timesteps[offset]);
 		input=(Input*)((Input*)this->inputs->GetObjectByOffset(offset))->copy();
 	}
-	else{
+	else {
 		/*get values between two times [offset:offset+1[, Interpolate linearly*/
 		_assert_(intime>=this->timesteps[offset] && intime<this->timesteps[offset+1]);
@@ -559,6 +531,5 @@
 }
 /*}}}*/
-/*FUNCTION TransientInput::Configure{{{*/
-void TransientInput::Configure(Parameters* parameters){
+void TransientInput::Configure(Parameters* parameters){/*{{{*/
 	this->parameters=parameters;
 }
Index: issm/trunk/src/c/classes/Inputs/TriaInput.cpp
===================================================================
--- issm/trunk/src/c/classes/Inputs/TriaInput.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Inputs/TriaInput.cpp	(revision 18301)
@@ -13,28 +13,27 @@
 
 /*TriaInput constructors and destructor*/
-/*FUNCTION TriaInput::TriaInput(){{{*/
-TriaInput::TriaInput(){
+TriaInput::TriaInput(){/*{{{*/
 	values = NULL;
 }
 /*}}}*/
-/*FUNCTION TriaInput::TriaInput(int in_enum_type,IssmDouble* invalues,element_type_in){{{*/
-TriaInput::TriaInput(int in_enum_type,IssmDouble* in_values,int element_type_in)
-	:TriaRef(1)
-{
-
-	/*Set TriaRef*/
-	this->SetElementType(element_type_in,0);
-	this->element_type=element_type_in;
+TriaInput::TriaInput(int in_enum_type,IssmDouble* in_values,int interpolation_type_in){/*{{{*/
 
 	/*Set Enum*/
-	enum_type=in_enum_type;
+	this->enum_type=in_enum_type;
+	this->interpolation_type=interpolation_type_in;
+
+	int numnodes = this->NumberofNodes(this->interpolation_type);
 
 	/*Set values*/
-	this->values=xNew<IssmDouble>(this->NumberofNodes());
-	for(int i=0;i<this->NumberofNodes();i++) values[i]=in_values[i];
-}
-/*}}}*/
-/*FUNCTION TriaInput::~TriaInput(){{{*/
-TriaInput::~TriaInput(){
+	if (numnodes > 0){
+		this->values=xNew<IssmDouble>((unsigned int)numnodes);
+		for(int i=0;i<this->NumberofNodes(this->interpolation_type);i++) values[i]=in_values[i];
+	}
+	else{
+		this->values = NULL;
+	}
+}
+/*}}}*/
+TriaInput::~TriaInput(){/*{{{*/
 	xDelete<IssmDouble>(this->values);
 }
@@ -42,22 +41,18 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION TriaInput::Echo {{{*/
-void TriaInput::Echo(void){
+void TriaInput::Echo(void){/*{{{*/
 	this->DeepEcho();
 }
 /*}}}*/
-/*FUNCTION TriaInput::DeepEcho{{{*/
-void TriaInput::DeepEcho(void){
+void TriaInput::DeepEcho(void){/*{{{*/
 
 	_printf_(setw(15)<<"   TriaInput "<<setw(25)<<left<<EnumToStringx(this->enum_type)<<" [");
-	for(int i=0;i<this->NumberofNodes();i++) _printf_(" "<<this->values[i]);
-	_printf_("] ("<<EnumToStringx(this->element_type)<<")\n");
-}
-/*}}}*/
-/*FUNCTION TriaInput::Id{{{*/
-int    TriaInput::Id(void){ return -1; }
-/*}}}*/
-/*FUNCTION TriaInput::ObjectEnum{{{*/
-int TriaInput::ObjectEnum(void){
+	for(int i=0;i<this->NumberofNodes(this->interpolation_type);i++) _printf_(" "<<this->values[i]);
+	_printf_("] ("<<EnumToStringx(this->interpolation_type)<<")\n");
+}
+/*}}}*/
+int  TriaInput::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int  TriaInput::ObjectEnum(void){/*{{{*/
 
 	return TriaInputEnum;
@@ -65,8 +60,7 @@
 }
 /*}}}*/
-/*FUNCTION TriaInput::copy{{{*/
-Object* TriaInput::copy() {
-
-	return new TriaInput(this->enum_type,this->values,this->element_type);
+Object* TriaInput::copy() {/*{{{*/
+
+	return new TriaInput(this->enum_type,this->values,this->interpolation_type);
 
 }
@@ -74,6 +68,5 @@
 
 /*TriaInput management*/
-/*FUNCTION TriaInput::InstanceEnum{{{*/
-int TriaInput::InstanceEnum(void){
+int TriaInput::InstanceEnum(void){/*{{{*/
 
 	return this->enum_type;
@@ -81,6 +74,5 @@
 }
 /*}}}*/
-/*FUNCTION TriaInput::SpawnTriaInput{{{*/
-Input* TriaInput::SpawnTriaInput(int index1,int index2,int index3){
+Input* TriaInput::SpawnTriaInput(int index1,int index2,int index3){/*{{{*/
 
 	/*output*/
@@ -88,5 +80,5 @@
 
 	/*Create new Tria input (copy of current input)*/
-	outinput=new TriaInput(this->enum_type,&this->values[0],this->element_type);
+	outinput=new TriaInput(this->enum_type,&this->values[0],this->interpolation_type);
 
 	/*Assign output*/
@@ -95,11 +87,10 @@
 }
 /*}}}*/
-/*FUNCTION TriaInput::SpawnSegInput{{{*/
-Input* TriaInput::SpawnSegInput(int index1,int index2){
+Input* TriaInput::SpawnSegInput(int index1,int index2){/*{{{*/
 
 	/*output*/
 	SegInput* outinput=NULL;
 
-	if(this->element_type==P0Enum){ 
+	if(this->interpolation_type==P0Enum){ 
 		outinput=new SegInput(this->enum_type,&this->values[0],P0Enum);
 	}
@@ -121,22 +112,22 @@
 }
 /*}}}*/
-/*FUNCTION TriaInput::GetResultInterpolation{{{*/
-int  TriaInput::GetResultInterpolation(void){
-
+int  TriaInput::GetResultInterpolation(void){/*{{{*/
+
+	if(this->interpolation_type==P0Enum){
+		return P0Enum;
+	}
 	return P1Enum;
 
 }
 /*}}}*/
-/*FUNCTION TriaInput::GetResultNumberOfNodes{{{*/
-int  TriaInput::GetResultNumberOfNodes(void){
-
-	return this->NumberofNodes();
-
-}
-/*}}}*/
-/*FUNCTION TriaInput::ResultToPatch{{{*/
-void TriaInput::ResultToPatch(IssmDouble* values,int nodesperelement,int sid){
-
-	int numnodes = this->NumberofNodes();
+int  TriaInput::GetResultNumberOfNodes(void){/*{{{*/
+
+	return this->NumberofNodes(this->interpolation_type);
+
+}
+/*}}}*/
+void TriaInput::ResultToPatch(IssmDouble* values,int nodesperelement,int sid){/*{{{*/
+
+	int numnodes = this->NumberofNodes(this->interpolation_type);
 
 	/*Some checks*/
@@ -150,30 +141,26 @@
 
 /*Object functions*/
-/*FUNCTION TriaInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){{{*/
-void TriaInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){
+void TriaInput::GetInputValue(IssmDouble* pvalue,Gauss* gauss){/*{{{*/
 
 	/*Call TriaRef function*/
 	_assert_(gauss->Enum()==GaussTriaEnum);
-	TriaRef::GetInputValue(pvalue,&values[0],(GaussTria*)gauss);
-
-}
-/*}}}*/
-/*FUNCTION TriaInput::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list, Gauss* gauss){{{*/
-void TriaInput::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list, Gauss* gauss){
+	TriaRef::GetInputValue(pvalue,&values[0],(GaussTria*)gauss,this->interpolation_type);
+
+}
+/*}}}*/
+void TriaInput::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list, Gauss* gauss){/*{{{*/
 
 	/*Call TriaRef function*/
 	_assert_(gauss->Enum()==GaussTriaEnum);
-	TriaRef::GetInputDerivativeValue(p,&values[0],xyz_list,(GaussTria*)gauss);
-}
-/*}}}*/
-/*FUNCTION TriaInput::ChangeEnum{{{*/
-void TriaInput::ChangeEnum(int newenumtype){
+	TriaRef::GetInputDerivativeValue(p,&values[0],xyz_list,(GaussTria*)gauss,this->interpolation_type);
+}
+/*}}}*/
+void TriaInput::ChangeEnum(int newenumtype){/*{{{*/
 	this->enum_type=newenumtype;
 }
 /*}}}*/
-/*FUNCTION TriaInput::GetInputAverage{{{*/
-void TriaInput::GetInputAverage(IssmDouble* pvalue){
-
-	int        numnodes  = this->NumberofNodes();
+void TriaInput::GetInputAverage(IssmDouble* pvalue){/*{{{*/
+
+	int        numnodes  = this->NumberofNodes(this->interpolation_type);
 	IssmDouble numnodesd = reCast<int,IssmDouble>(numnodes);
 	IssmDouble value     = 0.;
@@ -185,6 +172,5 @@
 }
 /*}}}*/
-/*FUNCTION TriaInput::GetInputAllTimeAverages{{{*/
-void TriaInput::GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes){
+void TriaInput::GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes){/*{{{*/
 
 	IssmDouble* outvalues=NULL;
@@ -205,6 +191,5 @@
 }
 /*}}}*/
-/*FUNCTION TriaInput::GetInputUpToCurrentTimeAverages{{{*/
-void TriaInput::GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime){
+void TriaInput::GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime){/*{{{*/
 
 	IssmDouble* outvalues=NULL;
@@ -227,8 +212,7 @@
 
 /*Intermediary*/
-/*FUNCTION TriaInput::SquareMin{{{*/
-void TriaInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){
-
-	int        numnodes=this->NumberofNodes();
+void TriaInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){/*{{{*/
+
+	int        numnodes=this->NumberofNodes(this->interpolation_type);
 	IssmDouble squaremin;
 
@@ -242,17 +226,15 @@
 }
 /*}}}*/
-/*FUNCTION TriaInput::ContrainMin{{{*/
-void TriaInput::ConstrainMin(IssmDouble minimum){
-
-	int numnodes = this->NumberofNodes();
+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;
 }
 /*}}}*/
-/*FUNCTION TriaInput::InfinityNorm{{{*/
-IssmDouble TriaInput::InfinityNorm(void){
+IssmDouble TriaInput::InfinityNorm(void){/*{{{*/
 
 	/*Output*/
 	IssmDouble norm=0.;
-	int numnodes=this->NumberofNodes();
+	int numnodes=this->NumberofNodes(this->interpolation_type);
 
 	for(int i=0;i<numnodes;i++) if(fabs(values[i])>norm) norm=fabs(values[i]);
@@ -260,8 +242,7 @@
 }
 /*}}}*/
-/*FUNCTION TriaInput::Max{{{*/
-IssmDouble TriaInput::Max(void){
-
-	int  numnodes=this->NumberofNodes();
+IssmDouble TriaInput::Max(void){/*{{{*/
+
+	int  numnodes=this->NumberofNodes(this->interpolation_type);
 	IssmDouble max=values[0];
 
@@ -272,8 +253,7 @@
 }
 /*}}}*/
-/*FUNCTION TriaInput::MaxAbs{{{*/
-IssmDouble TriaInput::MaxAbs(void){
-
-	int  numnodes=this->NumberofNodes();
+IssmDouble TriaInput::MaxAbs(void){/*{{{*/
+
+	int  numnodes=this->NumberofNodes(this->interpolation_type);
 	IssmDouble max=fabs(values[0]);
 
@@ -284,8 +264,7 @@
 }
 /*}}}*/
-/*FUNCTION TriaInput::Min{{{*/
-IssmDouble TriaInput::Min(void){
-
-	const int  numnodes=this->NumberofNodes();
+IssmDouble TriaInput::Min(void){/*{{{*/
+
+	const int  numnodes=this->NumberofNodes(this->interpolation_type);
 	IssmDouble min=values[0];
 
@@ -296,8 +275,7 @@
 }
 /*}}}*/
-/*FUNCTION TriaInput::MinAbs{{{*/
-IssmDouble TriaInput::MinAbs(void){
-
-	const int  numnodes=this->NumberofNodes();
+IssmDouble TriaInput::MinAbs(void){/*{{{*/
+
+	const int  numnodes=this->NumberofNodes(this->interpolation_type);
 	IssmDouble min=fabs(values[0]);
 
@@ -308,22 +286,19 @@
 }
 /*}}}*/
-/*FUNCTION TriaInput::Scale{{{*/
-void TriaInput::Scale(IssmDouble scale_factor){
-
-	const int numnodes=this->NumberofNodes();
+void TriaInput::Scale(IssmDouble scale_factor){/*{{{*/
+
+	const int numnodes=this->NumberofNodes(this->interpolation_type);
 	for(int i=0;i<numnodes;i++)values[i]=values[i]*scale_factor;
 }
 /*}}}*/
-/*FUNCTION TriaInput::Set{{{*/
-void TriaInput::Set(IssmDouble setvalue){
-
-	const int numnodes=this->NumberofNodes();
+void TriaInput::Set(IssmDouble setvalue){/*{{{*/
+
+	const int numnodes=this->NumberofNodes(this->interpolation_type);
 	for(int i=0;i<numnodes;i++)values[i]=setvalue;
 }
 /*}}}*/
-/*FUNCTION TriaInput::AXPY{{{*/
-void TriaInput::AXPY(Input* xinput,IssmDouble scalar){
-
-	const int numnodes=this->NumberofNodes();
+void TriaInput::AXPY(Input* xinput,IssmDouble scalar){/*{{{*/
+
+	const int numnodes=this->NumberofNodes(this->interpolation_type);
 	TriaInput*  xtriainput=NULL;
 
@@ -331,5 +306,5 @@
 	if(xinput->ObjectEnum()!=TriaInputEnum) _error_("Operation not permitted because xinput is of type " << EnumToStringx(xinput->ObjectEnum()));
 	xtriainput=(TriaInput*)xinput;
-	if(xtriainput->element_type!=this->element_type) _error_("Operation not permitted because xinput is of type " << EnumToStringx(xinput->ObjectEnum()));
+	if(xtriainput->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because xinput is of type " << EnumToStringx(xinput->ObjectEnum()));
 
 	/*Carry out the AXPY operation depending on type:*/
@@ -338,9 +313,8 @@
 }
 /*}}}*/
-/*FUNCTION TriaInput::Constrain{{{*/
-void TriaInput::Constrain(IssmDouble cm_min, IssmDouble cm_max){
+void TriaInput::Constrain(IssmDouble cm_min, IssmDouble cm_max){/*{{{*/
 
 	int i;
-	const int numnodes=this->NumberofNodes();
+	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;
@@ -349,11 +323,9 @@
 }
 /*}}}*/
-/*FUNCTION TriaInput::GetVectorFromInputs{{{*/
-void TriaInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){
+void TriaInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){/*{{{*/
 	const int numvertices=3;
 	vector->SetValues(numvertices,doflist,this->values,INS_VAL);
 } /*}}}*/
-/*FUNCTION TriaInput::PointwiseMin{{{*/
-Input* TriaInput::PointwiseMin(Input* inputB){
+Input* TriaInput::PointwiseMin(Input* inputB){/*{{{*/
 
 	/*Ouput*/
@@ -363,5 +335,5 @@
 	int         i;
 	TriaInput  *xinputB   = NULL;
-	const int   numnodes  = this->NumberofNodes();
+	const int   numnodes  = this->NumberofNodes(this->interpolation_type);
 	IssmDouble *minvalues = xNew<IssmDouble>(numnodes);
 
@@ -369,5 +341,5 @@
 	if(inputB->ObjectEnum()!=TriaInputEnum)       _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
 	xinputB=(TriaInput*)inputB;
-	if(xinputB->element_type!=this->element_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->element_type));
+	if(xinputB->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->interpolation_type));
 
 	/*Create point wise min*/
@@ -378,5 +350,5 @@
 
 	/*Create new Tria vertex input (copy of current input)*/
-	outinput=new TriaInput(this->enum_type,&minvalues[0],this->element_type);
+	outinput=new TriaInput(this->enum_type,&minvalues[0],this->interpolation_type);
 
 	/*Return output pointer*/
@@ -386,6 +358,5 @@
 }
 /*}}}*/
-/*FUNCTION TriaInput::PointwiseMax{{{*/
-Input* TriaInput::PointwiseMax(Input* inputB){
+Input* TriaInput::PointwiseMax(Input* inputB){/*{{{*/
 
 	/*Ouput*/
@@ -395,5 +366,5 @@
 	int         i;
 	TriaInput  *xinputB   = NULL;
-	const int   numnodes  = this->NumberofNodes();
+	const int   numnodes  = this->NumberofNodes(this->interpolation_type);
 	IssmDouble *maxvalues = xNew<IssmDouble>(numnodes);
 
@@ -401,5 +372,5 @@
 	if(inputB->ObjectEnum()!=TriaInputEnum) _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
 	xinputB=(TriaInput*)inputB;
-	if(xinputB->element_type!=this->element_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->element_type));
+	if(xinputB->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->interpolation_type));
 
 	/*Create point wise max*/
@@ -410,5 +381,5 @@
 
 	/*Create new Tria vertex input (copy of current input)*/
-	outinput=new TriaInput(this->enum_type,&maxvalues[0],this->element_type);
+	outinput=new TriaInput(this->enum_type,&maxvalues[0],this->interpolation_type);
 
 	/*Return output pointer*/
@@ -418,6 +389,5 @@
 }
 /*}}}*/
-/*FUNCTION TriaInput::PointwiseDivide{{{*/
-Input* TriaInput::PointwiseDivide(Input* inputB){
+Input* TriaInput::PointwiseDivide(Input* inputB){/*{{{*/
 
 	/*Ouput*/
@@ -426,10 +396,10 @@
 	/*Intermediaries*/
 	TriaInput *xinputB  = NULL;
-	const int   numnodes = this->NumberofNodes();
+	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->element_type!=this->element_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->element_type));
+	if(xinputB->interpolation_type!=this->interpolation_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->interpolation_type));
 
 	/*Allocate intermediary*/
@@ -443,5 +413,5 @@
 
 	/*Create new Tria vertex input (copy of current input)*/
-	outinput=new TriaInput(this->enum_type,AdotBvalues,this->element_type);
+	outinput=new TriaInput(this->enum_type,AdotBvalues,this->interpolation_type);
 
 	/*Return output pointer*/
@@ -451,6 +421,5 @@
 }
 /*}}}*/
-/*FUNCTION TriaInput::Configure{{{*/
-void TriaInput::Configure(Parameters* parameters){
+void TriaInput::Configure(Parameters* parameters){/*{{{*/
 	/*do nothing: */
 }
Index: issm/trunk/src/c/classes/Inputs/TriaInput.h
===================================================================
--- issm/trunk/src/c/classes/Inputs/TriaInput.h	(revision 18081)
+++ issm/trunk/src/c/classes/Inputs/TriaInput.h	(revision 18301)
@@ -18,4 +18,5 @@
 	public:
 		int         enum_type;
+		int         interpolation_type;
 		IssmDouble* values;
 
Index: issm/trunk/src/c/classes/IoModel.cpp
===================================================================
--- issm/trunk/src/c/classes/IoModel.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/IoModel.cpp	(revision 18301)
@@ -19,6 +19,5 @@
 #include "../shared/shared.h"
 
-/*FUNCTION IoModel::IoModel(){{{*/
-IoModel::IoModel(){
+IoModel::IoModel(){/*{{{*/
 	this->fid=NULL;
 	this->data=NULL;
@@ -51,6 +50,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::IoModel(FILE*  iomodel_handle){{{*/
-IoModel::IoModel(FILE* iomodel_handle){
+IoModel::IoModel(FILE* iomodel_handle){/*{{{*/
 
 	/*First, keep track of the file handle: */
@@ -97,6 +95,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::~IoModel(){{{*/
-IoModel::~IoModel(){
+IoModel::~IoModel(){/*{{{*/
 
 	/*Delete independents*/
@@ -140,6 +137,5 @@
 /*}}}*/
 
-/*FUNCTION IoModel::CheckEnumSync{{{*/
-void  IoModel::CheckEnumSync(void){
+void  IoModel::CheckEnumSync(void){/*{{{*/
 
 	int record_enum,record_length;
@@ -226,6 +222,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::Constant(bool* poutput,int constant_enum){{{*/
-void IoModel::Constant(bool* poutput,int constant_enum){
+void IoModel::Constant(bool* poutput,int constant_enum){/*{{{*/
 
 	_assert_(constant_enum>=0);
@@ -235,6 +230,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::Constant(int* poutput,int constant_enum){{{*/
-void IoModel::Constant(int* poutput,int constant_enum){
+void IoModel::Constant(int* poutput,int constant_enum){/*{{{*/
 
 	_assert_(constant_enum>=0);
@@ -244,6 +238,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::Constant(IssmDouble* poutput,int constant_enum){{{*/
-void IoModel::Constant(IssmDouble* poutput,int constant_enum){
+void IoModel::Constant(IssmDouble* poutput,int constant_enum){/*{{{*/
 
 	_assert_(constant_enum>=0);
@@ -253,6 +246,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::Constant(char** poutput,int constant_enum){{{*/
-void IoModel::Constant(char** poutput,int constant_enum){
+void IoModel::Constant(char** poutput,int constant_enum){/*{{{*/
 
 	_assert_(constant_enum>=0);
@@ -262,6 +254,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::CopyConstantObject{{{*/
-Param* IoModel::CopyConstantObject(int constant_enum){
+Param* IoModel::CopyConstantObject(int constant_enum){/*{{{*/
 
 	_assert_(this->constants);
@@ -274,6 +265,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::Data{{{*/
-IssmDouble* IoModel::Data(int data_enum){
+IssmDouble* IoModel::Data(int data_enum){/*{{{*/
 
 	_assert_(data_enum<MaximumNumberOfDefinitionsEnum);
@@ -283,6 +273,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::StartTrace{{{*/
-void IoModel::StartTrace(void){
+void IoModel::StartTrace(void){/*{{{*/
 
 	bool autodiff = false;
@@ -322,6 +311,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::DeclareIndependents{{{*/
-void IoModel::DeclareIndependents(void){
+void IoModel::DeclareIndependents(void){/*{{{*/
 
 	int  i;
@@ -374,6 +362,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::DeleteData(int num,...){{{*/
-void  IoModel::DeleteData(int num,...){
+void  IoModel::DeleteData(int num,...){/*{{{*/
 
 	va_list ap;
@@ -391,6 +378,5 @@
 	va_end(ap);
 } /*}}}*/
-/*FUNCTION IoModel::DeleteData(IssmDouble* {{{*/
-void  IoModel::DeleteData(IssmDouble* vector, int dataenum){
+void  IoModel::DeleteData(IssmDouble* vector, int dataenum){/*{{{*/
 
 	/*do not erase independent variables for the AD mode computations!: */
@@ -398,6 +384,5 @@
 
 } /*}}}*/
-/*FUNCTION IoModel::DeleteData(char*** pstringarray, int numstrings, int dataenum) {{{*/
-void  IoModel::DeleteData(char*** pstringarray, int numstrings, int dataenum){
+void  IoModel::DeleteData(char*** pstringarray, int numstrings, int dataenum){/*{{{*/
 
 	int i;
@@ -413,6 +398,5 @@
 	*pstringarray=NULL;
 } /*}}}*/
-/*FUNCTION IoModel::FetchConstants{{{*/
-void  IoModel::FetchConstants(void){
+void  IoModel::FetchConstants(void){/*{{{*/
 
 	int my_rank;
@@ -637,6 +621,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::FetchData(bool*         pbool,int data_enum){{{*/
-void  IoModel::FetchData(bool* pboolean,int data_enum){
+void  IoModel::FetchData(bool* pboolean,int data_enum){/*{{{*/
 
 	int my_rank;
@@ -666,6 +649,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::FetchData(int*          pinteger,int data_enum){{{*/
-void  IoModel::FetchData(int* pinteger,int data_enum){
+void  IoModel::FetchData(int* pinteger,int data_enum){/*{{{*/
 
 	int my_rank;
@@ -694,6 +676,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::FetchData(IssmDouble*   pscalar,int data_enum){{{*/
-void  IoModel::FetchData(IssmDouble* pscalar,int data_enum){
+void  IoModel::FetchData(IssmDouble* pscalar,int data_enum){/*{{{*/
 
 	int my_rank;
@@ -722,6 +703,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::FetchData(char**        pstring,int data_enum){{{*/
-void  IoModel::FetchData(char** pstring,int data_enum){
+void  IoModel::FetchData(char** pstring,int data_enum){/*{{{*/
 
 	int my_rank;
@@ -769,6 +749,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::FetchData(int**         pintegerematrix,int* pM,int* pN,int data_enum){{{*/
-void  IoModel::FetchData(int** pmatrix,int* pM,int* pN,int data_enum){
+void  IoModel::FetchData(int** pmatrix,int* pM,int* pN,int data_enum){/*{{{*/
 
 	int my_rank;
@@ -838,6 +817,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::FetchData(IssmDouble**  pIssmDoublematrix,int* pM,int* pN,int data_enum){{{*/
-void  IoModel::FetchData(IssmDouble** pmatrix,int* pM,int* pN,int data_enum){
+void  IoModel::FetchData(IssmDouble** pmatrix,int* pM,int* pN,int data_enum){/*{{{*/
 
 	int my_rank;
@@ -898,6 +876,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::FetchData(char***       pstrings,int* pnumstrings,int data_enum){{{*/
-void  IoModel::FetchData(char*** pstrings,int* pnumstrings,int data_enum){
+void  IoModel::FetchData(char*** pstrings,int* pnumstrings,int data_enum){/*{{{*/
 
 	int my_rank;
@@ -964,6 +941,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::FetchData(IssmDouble*** pmatrices,int** pmdims,int** pndims, int* pM,int data_enum){{{*/
-void  IoModel::FetchData(IssmDouble*** pmatrices,int** pmdims,int** pndims, int* pnumrecords,int data_enum){
+void  IoModel::FetchData(IssmDouble*** pmatrices,int** pmdims,int** pndims, int* pnumrecords,int data_enum){/*{{{*/
 
 	int i;
@@ -1050,6 +1026,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::FetchData(Option**  poption,int data_enum){{{*/
-void  IoModel::FetchData(Option** poption,int index){
+void  IoModel::FetchData(Option** poption,int index){/*{{{*/
 
 	/*output: */
@@ -1096,6 +1071,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::FetchData(int num,...){{{*/
-void  IoModel::FetchData(int num,...){
+void  IoModel::FetchData(int num,...){/*{{{*/
 
 	va_list     ap;
@@ -1138,6 +1112,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::FetchMultipleData(char***       pstrings,int* pnumstrings,int data_enum){{{*/
-void  IoModel::FetchMultipleData(char*** pstrings,int* pnumstrings,int data_enum){
+void  IoModel::FetchMultipleData(char*** pstrings,int* pnumstrings,int data_enum){/*{{{*/
 
 	int  num_instances;
@@ -1203,6 +1176,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::FetchMultipleData(int** pvector, int* pM,int data_enum){{{*/
-void  IoModel::FetchMultipleData(int** pvector, int* pnum_instances,int data_enum){
+void  IoModel::FetchMultipleData(int** pvector, int* pnum_instances,int data_enum){/*{{{*/
 
 	int     num_instances;
@@ -1257,6 +1229,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::FetchMultipleData(IssmDouble*** pmatrices,int** pmdims,int** pndims, int* pM,int data_enum){{{*/
-void  IoModel::FetchMultipleData(IssmDouble*** pmatrices,int** pmdims,int** pndims, int* pnumrecords,int data_enum){
+void  IoModel::FetchMultipleData(IssmDouble*** pmatrices,int** pmdims,int** pndims, int* pnumrecords,int data_enum){/*{{{*/
 
 	int     num_instances;
@@ -1362,6 +1333,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::FetchMultipleData(int*** pmatrices,int** pmdims,int** pndims, int* pM,int data_enum){{{*/
-void  IoModel::FetchMultipleData(int*** pmatrices,int** pmdims,int** pndims, int* pnumrecords,int data_enum){
+void  IoModel::FetchMultipleData(int*** pmatrices,int** pmdims,int** pndims, int* pnumrecords,int data_enum){/*{{{*/
 
 	int     num_instances;
@@ -1469,6 +1439,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::FetchDataToInput(Elements* elements,int vector_enum,IssmDouble default_value){{{*/
-void IoModel::FetchDataToInput(Elements* elements,int vector_enum,IssmDouble default_value){
+void IoModel::FetchDataToInput(Elements* elements,int vector_enum,IssmDouble default_value){/*{{{*/
 
 	/*intermediary: */
@@ -1495,6 +1464,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::FetchDataToInput(Elements* elements,int vector_enum){{{*/
-void IoModel::FetchDataToInput(Elements* elements,int vector_enum){
+void IoModel::FetchDataToInput(Elements* elements,int vector_enum){/*{{{*/
 
 	/*intermediary: */
@@ -1568,6 +1536,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::LastIndex{{{*/
-void IoModel::LastIndex(int *pindex){
+void IoModel::LastIndex(int *pindex){/*{{{*/
 
 	int my_rank;
@@ -1669,6 +1636,5 @@
 }
 /*}}}*/
-/*FUNCTION IoModel::SetFilePointersToData{{{*/
-fpos_t* IoModel::SetFilePointersToData(int** pcodes,int** pvector_types, int* pnum_instances, int data_enum){
+fpos_t* IoModel::SetFilePointersToData(int** pcodes,int** pvector_types, int* pnum_instances, int data_enum){/*{{{*/
 
 	int     found          = 0;
Index: issm/trunk/src/c/classes/Loads/Friction.cpp
===================================================================
--- issm/trunk/src/c/classes/Loads/Friction.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Loads/Friction.cpp	(revision 18301)
@@ -16,6 +16,5 @@
 
 /*Constructors/destructors*/
-/*FUNCTION Friction::Friction() {{{*/
-Friction::Friction(){
+Friction::Friction(){/*{{{*/
 	this->element=NULL;
 	this->dim=0;
@@ -24,6 +23,5 @@
 }
 /*}}}*/
-/*FUNCTION Friction::Friction(Element* element,int dim){{{*/
-Friction::Friction(Element* element_in,int dim_in){
+Friction::Friction(Element* element_in,int dim_in){/*{{{*/
 
 	this->element=element_in;
@@ -32,18 +30,15 @@
 }
 /*}}}*/
-/*FUNCTION Friction::~Friction() {{{*/
-Friction::~Friction(){
+Friction::~Friction(){/*{{{*/
 }
 /*}}}*/
 
 /*methods: */
-/*FUNCTION Friction::Echo {{{*/
-void Friction::Echo(void){
+void Friction::Echo(void){/*{{{*/
 	_printf_("Friction:\n");
 	_printf_("   dim: " << this->dim<< "\n");
 }
 /*}}}*/
-/*FUNCTION Friction::GetAlpha2{{{*/
-void Friction::GetAlpha2(IssmDouble* palpha2, Gauss* gauss){
+void Friction::GetAlpha2(IssmDouble* palpha2, Gauss* gauss){/*{{{*/
 
 	switch(this->law){
@@ -59,6 +54,5 @@
 
 }/*}}}*/
-/*FUNCTION Friction::GetAlpha2{{{*/
-void Friction::GetAlpha2Viscous(IssmDouble* palpha2, Gauss* gauss){
+void Friction::GetAlpha2Viscous(IssmDouble* palpha2, Gauss* gauss){/*{{{*/
 
 	/*This routine calculates the basal friction coefficient 
@@ -120,6 +114,5 @@
 	*palpha2=alpha2;
 }/*}}}*/
-/*FUNCTION Friction::GetAlpha2Weertman{{{*/
-void Friction::GetAlpha2Weertman(IssmDouble* palpha2, Gauss* gauss){
+void Friction::GetAlpha2Weertman(IssmDouble* palpha2, Gauss* gauss){/*{{{*/
 
 	/*This routine calculates the basal friction coefficient alpha2= C^-1/m |v|^(1/m-1) */
@@ -162,6 +155,5 @@
 	*palpha2=alpha2;
 }/*}}}*/
-/*FUNCTION Friction::GetAlphaComplement(IssmDouble* palpha_complement, Gauss* gauss,int vxenum,int vyenum,int vzenum) {{{*/
-void Friction::GetAlphaComplement(IssmDouble* palpha_complement, Gauss* gauss){
+void Friction::GetAlphaComplement(IssmDouble* palpha_complement, Gauss* gauss){/*{{{*/
 
 	/* FrictionGetAlpha2 computes alpha2= drag^2 * Neff ^r * vel ^s, with Neff=rho_ice*g*thickness+rho_ice*g*bed, r=q/p and s=1/p. 
Index: issm/trunk/src/c/classes/Loads/Load.h
===================================================================
--- issm/trunk/src/c/classes/Loads/Load.h	(revision 18081)
+++ issm/trunk/src/c/classes/Loads/Load.h	(revision 18301)
@@ -26,4 +26,5 @@
 		virtual       ~Load(){};
 		virtual void  Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters)=0;
+		virtual void  ResetHooks()=0;
 		virtual bool  IsPenalty(void)=0;
 		virtual int   GetNumberOfNodes(void)=0;
Index: issm/trunk/src/c/classes/Loads/Loads.cpp
===================================================================
--- issm/trunk/src/c/classes/Loads/Loads.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Loads/Loads.cpp	(revision 18301)
@@ -23,12 +23,10 @@
 
 /*Object constructors and destructor*/
-/*FUNCTION Loads::Loads(){{{*/
-Loads::Loads(){
+Loads::Loads(){/*{{{*/
 	enum_type=LoadsEnum;
 	return;
 }
 /*}}}*/
-/*FUNCTION Loads::~Loads(){{{*/
-Loads::~Loads(){
+Loads::~Loads(){/*{{{*/
 	return;
 }
@@ -36,6 +34,5 @@
 
 /*Numerics:*/
-/*FUNCTION Loads::Configure{{{*/
-void Loads::Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){
+void Loads::Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){/*{{{*/
 
 	vector<Object*>::iterator object;
@@ -51,6 +48,19 @@
 }
 /*}}}*/
-/*FUNCTION Loads::IsPenalty{{{*/
-bool Loads::IsPenalty(int analysis_type){
+void Loads::ResetHooks(){/*{{{*/
+
+	vector<Object*>::iterator object;
+	Load* load=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		load=dynamic_cast<Load*>((*object));
+		load->ResetHooks();
+
+	}
+
+}
+/*}}}*/
+bool Loads::IsPenalty(int analysis_type){/*{{{*/
 
 	int ispenalty=0;
@@ -76,6 +86,5 @@
 }
 /*}}}*/
-/*FUNCTION Loads::MaxNumNodes{{{*/
-int Loads::MaxNumNodes(int analysis_type){
+int Loads::MaxNumNodes(int analysis_type){/*{{{*/
 
 	int max=0;
@@ -100,6 +109,5 @@
 }
 /*}}}*/
-/*FUNCTION Loads::NumberOfLoads(){{{*/
-int Loads::NumberOfLoads(void){
+int Loads::NumberOfLoads(void){/*{{{*/
 
 	int localloads;
@@ -116,6 +124,5 @@
 }
 /*}}}*/
-/*FUNCTION Loads::NumberOfLoads(int analysis){{{*/
-int Loads::NumberOfLoads(int analysis_type){
+int Loads::NumberOfLoads(int analysis_type){/*{{{*/
 
 	int localloads = 0;
@@ -138,12 +145,10 @@
 }
 /*}}}*/
-/*FUNCTION Loads::Size(){{{*/
-int Loads::Size(void){
+int Loads::Size(void){/*{{{*/
 
 	return this->DataSet::Size();
 }
 /*}}}*/
-/*FUNCTION Loads::Size(int analysis){{{*/
-int Loads::Size(int analysis_type){
+int Loads::Size(int analysis_type){/*{{{*/
 
 	int localloads = 0;
@@ -161,6 +166,5 @@
 }
 /*}}}*/
-/*FUNCTION Loads::SetCurrentConfiguration{{{*/
-void Loads::SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){
+void Loads::SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){/*{{{*/
 
 	vector<Object*>::iterator object;
Index: issm/trunk/src/c/classes/Loads/Loads.h
===================================================================
--- issm/trunk/src/c/classes/Loads/Loads.h	(revision 18081)
+++ issm/trunk/src/c/classes/Loads/Loads.h	(revision 18301)
@@ -24,4 +24,5 @@
 		/*numerics*/
 		void  Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
+		void  ResetHooks();
 		bool  IsPenalty(int analysis);
 		int   MaxNumNodes(int analysis);
Index: issm/trunk/src/c/classes/Loads/Numericalflux.cpp
===================================================================
--- issm/trunk/src/c/classes/Loads/Numericalflux.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Loads/Numericalflux.cpp	(revision 18301)
@@ -21,6 +21,5 @@
 
 /*Numericalflux constructors and destructor*/
-/*FUNCTION Numericalflux::Numericalflux(){{{*/
-Numericalflux::Numericalflux(){
+Numericalflux::Numericalflux(){/*{{{*/
 	this->parameters = NULL;
 	this->helement   = NULL;
@@ -31,6 +30,5 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::Numericalflux(int id, int i, IoModel* iomodel, int analysis_type) {{{*/
-Numericalflux::Numericalflux(int numericalflux_id,int i,int index,IoModel* iomodel, int in_analysis_type){
+Numericalflux::Numericalflux(int numericalflux_id,int i,int index,IoModel* iomodel, int in_analysis_type){/*{{{*/
 
 	/* Intermediary */
@@ -124,6 +122,5 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::~Numericalflux(){{{*/
-Numericalflux::~Numericalflux(){
+Numericalflux::~Numericalflux(){/*{{{*/
 	this->parameters=NULL;
 	delete helement;
@@ -134,6 +131,5 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION Numericalflux::Echo {{{*/
-void Numericalflux::Echo(void){
+void Numericalflux::Echo(void){/*{{{*/
 	_printf_("Numericalflux:\n");
 	_printf_("   id: " << id << "\n");
@@ -146,6 +142,5 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::DeepEcho {{{*/
-void Numericalflux::DeepEcho(void){
+void Numericalflux::DeepEcho(void){/*{{{*/
 
 	_printf_("Numericalflux:\n");
@@ -163,11 +158,9 @@
 }		
 /*}}}*/
-/*FUNCTION Numericalflux::Id {{{*/
-int    Numericalflux::Id(void){
+int Numericalflux::Id(void){/*{{{*/
 	return id;
 }
 /*}}}*/
-/*FUNCTION Numericalflux::ObjectEnum{{{*/
-int Numericalflux::ObjectEnum(void){
+int Numericalflux::ObjectEnum(void){/*{{{*/
 
 	return NumericalfluxEnum;
@@ -175,6 +168,5 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::copy {{{*/
-Object* Numericalflux::copy() {
+Object* Numericalflux::copy() {/*{{{*/
 
 	Numericalflux* numericalflux=NULL;
@@ -205,6 +197,5 @@
 
 /*Load virtual functions definitions:*/
-/*FUNCTION Numericalflux::Configure {{{*/
-void  Numericalflux::Configure(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
+void  Numericalflux::Configure(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){/*{{{*/
 
 	/*Take care of hooking up all objects for this element, ie links the objects in the hooks to their respective 
@@ -223,11 +214,23 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::SetCurrentConfiguration {{{*/
-void  Numericalflux::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
-
-}
-/*}}}*/
-/*FUNCTION Numericalflux::CreateKMatrix {{{*/
-void  Numericalflux::CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){
+void  Numericalflux::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){/*{{{*/
+
+}
+/*}}}*/
+void  Numericalflux::ResetHooks(){/*{{{*/
+
+	this->nodes=NULL;
+	this->vertices=NULL;
+	this->element=NULL;
+	this->parameters=NULL;
+
+	/*Get Element type*/
+	this->hnodes->reset();
+	this->hvertices->reset();
+	this->helement->reset();
+
+}
+/*}}}*/
+void  Numericalflux::CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){/*{{{*/
 
 	/*recover some parameters*/
@@ -259,6 +262,5 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::CreatePVector {{{*/
-void  Numericalflux::CreatePVector(Vector<IssmDouble>* pf){
+void  Numericalflux::CreatePVector(Vector<IssmDouble>* pf){/*{{{*/
 
 	/*recover some parameters*/
@@ -289,6 +291,5 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::GetNodesSidList{{{*/
-void Numericalflux::GetNodesSidList(int* sidlist){
+void  Numericalflux::GetNodesSidList(int* sidlist){/*{{{*/
 
 	_assert_(sidlist);
@@ -307,6 +308,5 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::GetNodesLidList{{{*/
-void Numericalflux::GetNodesLidList(int* lidlist){
+void  Numericalflux::GetNodesLidList(int* lidlist){/*{{{*/
 
 	_assert_(lidlist);
@@ -325,6 +325,5 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::GetNumberOfNodes{{{*/
-int Numericalflux::GetNumberOfNodes(void){
+int   Numericalflux::GetNumberOfNodes(void){/*{{{*/
 
 	switch(this->flux_type){
@@ -339,11 +338,9 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::IsPenalty{{{*/
-bool Numericalflux::IsPenalty(void){
+bool  Numericalflux::IsPenalty(void){/*{{{*/
 	return false;
 }
 /*}}}*/
-/*FUNCTION Numericalflux::PenaltyCreateKMatrix {{{*/
-void  Numericalflux::PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,IssmDouble kmax){
+void  Numericalflux::PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,IssmDouble kmax){/*{{{*/
 
 	/*No stiffness loads applied, do nothing: */
@@ -352,6 +349,5 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::PenaltyCreatePVector{{{*/
-void  Numericalflux::PenaltyCreatePVector(Vector<IssmDouble>* pf,IssmDouble kmax){
+void  Numericalflux::PenaltyCreatePVector(Vector<IssmDouble>* pf,IssmDouble kmax){/*{{{*/
 
 	/*No penalty loads applied, do nothing: */
@@ -360,12 +356,10 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::InAnalysis{{{*/
-bool Numericalflux::InAnalysis(int in_analysis_type){
+bool  Numericalflux::InAnalysis(int in_analysis_type){/*{{{*/
 	if (in_analysis_type==this->analysis_type) return true;
 	else return false;
 }
 /*}}}*/
-/*FUNCTION Numericalflux::SetwiseNodeConnectivity{{{*/
-void Numericalflux::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int* flagsindices,int set1_enum,int set2_enum){
+void  Numericalflux::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int* flagsindices,int set1_enum,int set2_enum){/*{{{*/
 
 	/*Output */
@@ -423,6 +417,5 @@
 
 /*Numericalflux management*/
-/*FUNCTION Numericalflux::CreateKMatrixMasstransport{{{*/
-ElementMatrix* Numericalflux::CreateKMatrixMasstransport(void){
+ElementMatrix* Numericalflux::CreateKMatrixMasstransport(void){/*{{{*/
 
 	switch(this->flux_type){
@@ -436,6 +429,5 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::CreateKMatrixMasstransportInternal {{{*/
-ElementMatrix* Numericalflux::CreateKMatrixMasstransportInternal(void){
+ElementMatrix* Numericalflux::CreateKMatrixMasstransportInternal(void){/*{{{*/
 
 	/* constants*/
@@ -473,6 +465,6 @@
 		gauss->GaussPoint(ig);
 
-		tria->GetSegmentBFlux(&B[0],gauss,index1,index2);
-		tria->GetSegmentBprimeFlux(&Bprime[0],gauss,index1,index2);
+		tria->GetSegmentBFlux(&B[0],gauss,index1,index2,tria->FiniteElement());
+		tria->GetSegmentBprimeFlux(&Bprime[0],gauss,index1,index2,tria->FiniteElement());
 
 		vxaverage_input->GetInputValue(&vx,gauss);
@@ -501,6 +493,5 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::CreateKMatrixMasstransportBoundary {{{*/
-ElementMatrix* Numericalflux::CreateKMatrixMasstransportBoundary(void){
+ElementMatrix* Numericalflux::CreateKMatrixMasstransportBoundary(void){/*{{{*/
 
 	/* constants*/
@@ -552,5 +543,5 @@
 		gauss->GaussPoint(ig);
 
-		tria->GetSegmentNodalFunctions(&L[0],gauss,index1,index2);
+		tria->GetSegmentNodalFunctions(&L[0],gauss,index1,index2,tria->FiniteElement());
 
 		vxaverage_input->GetInputValue(&vx,gauss);
@@ -573,6 +564,5 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::CreateKMatrixBalancethickness{{{*/
-ElementMatrix* Numericalflux::CreateKMatrixBalancethickness(void){
+ElementMatrix* Numericalflux::CreateKMatrixBalancethickness(void){/*{{{*/
 
 	switch(this->flux_type){
@@ -586,6 +576,5 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::CreateKMatrixBalancethicknessInternal {{{*/
-ElementMatrix* Numericalflux::CreateKMatrixBalancethicknessInternal(void){
+ElementMatrix* Numericalflux::CreateKMatrixBalancethicknessInternal(void){/*{{{*/
 
 	/* constants*/
@@ -622,6 +611,6 @@
 		gauss->GaussPoint(ig);
 
-		tria->GetSegmentBFlux(&B[0],gauss,index1,index2);
-		tria->GetSegmentBprimeFlux(&Bprime[0],gauss,index1,index2);
+		tria->GetSegmentBFlux(&B[0],gauss,index1,index2,tria->FiniteElement());
+		tria->GetSegmentBprimeFlux(&Bprime[0],gauss,index1,index2,tria->FiniteElement());
 
 		vxaverage_input->GetInputValue(&vx,gauss);
@@ -650,6 +639,5 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::CreateKMatrixBalancethicknessBoundary {{{*/
-ElementMatrix* Numericalflux::CreateKMatrixBalancethicknessBoundary(void){
+ElementMatrix* Numericalflux::CreateKMatrixBalancethicknessBoundary(void){/*{{{*/
 
 	/* constants*/
@@ -700,5 +688,5 @@
 		gauss->GaussPoint(ig);
 
-		tria->GetSegmentNodalFunctions(&L[0],gauss,index1,index2);
+		tria->GetSegmentNodalFunctions(&L[0],gauss,index1,index2,tria->FiniteElement());
 
 		vxaverage_input->GetInputValue(&vx,gauss);
@@ -721,6 +709,5 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::CreateKMatrixAdjointBalancethickness{{{*/
-ElementMatrix* Numericalflux::CreateKMatrixAdjointBalancethickness(void){
+ElementMatrix* Numericalflux::CreateKMatrixAdjointBalancethickness(void){/*{{{*/
 
 	switch(this->flux_type){
@@ -734,6 +721,5 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::CreateKMatrixAdjointBalancethicknessInternal {{{*/
-ElementMatrix* Numericalflux::CreateKMatrixAdjointBalancethicknessInternal(void){
+ElementMatrix* Numericalflux::CreateKMatrixAdjointBalancethicknessInternal(void){/*{{{*/
 
 	ElementMatrix* Ke=CreateKMatrixBalancethicknessInternal();
@@ -742,6 +728,5 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::CreateKMatrixAdjointBalancethicknessBoundary {{{*/
-ElementMatrix* Numericalflux::CreateKMatrixAdjointBalancethicknessBoundary(void){
+ElementMatrix* Numericalflux::CreateKMatrixAdjointBalancethicknessBoundary(void){/*{{{*/
 
 	ElementMatrix* Ke=CreateKMatrixBalancethicknessBoundary();
@@ -750,6 +735,5 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::CreatePVectorMasstransport{{{*/
-ElementVector* Numericalflux::CreatePVectorMasstransport(void){
+ElementVector* Numericalflux::CreatePVectorMasstransport(void){/*{{{*/
 
 	switch(this->flux_type){
@@ -763,6 +747,5 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::CreatePVectorMasstransportInternal{{{*/
-ElementVector* Numericalflux::CreatePVectorMasstransportInternal(void){
+ElementVector* Numericalflux::CreatePVectorMasstransportInternal(void){/*{{{*/
 
 	/*Nothing added to PVector*/
@@ -771,6 +754,5 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::CreatePVectorMasstransportBoundary{{{*/
-ElementVector* Numericalflux::CreatePVectorMasstransportBoundary(void){
+ElementVector* Numericalflux::CreatePVectorMasstransportBoundary(void){/*{{{*/
 
 	/* constants*/
@@ -822,5 +804,5 @@
 		gauss->GaussPoint(ig);
 
-		tria->GetSegmentNodalFunctions(&L[0],gauss,index1,index2);
+		tria->GetSegmentNodalFunctions(&L[0],gauss,index1,index2,tria->FiniteElement());
 
 		vxaverage_input->GetInputValue(&vx,gauss);
@@ -841,6 +823,5 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::CreatePVectorBalancethickness{{{*/
-ElementVector* Numericalflux::CreatePVectorBalancethickness(void){
+ElementVector* Numericalflux::CreatePVectorBalancethickness(void){/*{{{*/
 
 	switch(this->flux_type){
@@ -854,6 +835,5 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::CreatePVectorBalancethicknessInternal{{{*/
-ElementVector* Numericalflux::CreatePVectorBalancethicknessInternal(void){
+ElementVector* Numericalflux::CreatePVectorBalancethicknessInternal(void){/*{{{*/
 
 	/*Nothing added to PVector*/
@@ -862,6 +842,5 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::CreatePVectorBalancethicknessBoundary{{{*/
-ElementVector* Numericalflux::CreatePVectorBalancethicknessBoundary(void){
+ElementVector* Numericalflux::CreatePVectorBalancethicknessBoundary(void){/*{{{*/
 
 	/* constants*/
@@ -911,5 +890,5 @@
 		gauss->GaussPoint(ig);
 
-		tria->GetSegmentNodalFunctions(&L[0],gauss,index1,index2);
+		tria->GetSegmentNodalFunctions(&L[0],gauss,index1,index2,tria->FiniteElement());
 
 		vxaverage_input->GetInputValue(&vx,gauss);
@@ -929,6 +908,5 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::CreatePVectorAdjointBalancethickness{{{*/
-ElementVector* Numericalflux::CreatePVectorAdjointBalancethickness(void){
+ElementVector* Numericalflux::CreatePVectorAdjointBalancethickness(void){/*{{{*/
 
 	/*No PVector for the Adjoint*/
@@ -936,6 +914,5 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::GetNormal {{{*/
-void Numericalflux:: GetNormal(IssmDouble* normal,IssmDouble xyz_list[4][3]){
+void Numericalflux:: GetNormal(IssmDouble* normal,IssmDouble xyz_list[4][3]){/*{{{*/
 
 	/*Build unit outward pointing vector*/
Index: issm/trunk/src/c/classes/Loads/Numericalflux.h
===================================================================
--- issm/trunk/src/c/classes/Loads/Numericalflux.h	(revision 18081)
+++ issm/trunk/src/c/classes/Loads/Numericalflux.h	(revision 18301)
@@ -58,4 +58,5 @@
 		void Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
 		void SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
+		void ResetHooks();
 		void CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs);
 		void CreatePVector(Vector<IssmDouble>* pf);
Index: issm/trunk/src/c/classes/Loads/Pengrid.cpp
===================================================================
--- issm/trunk/src/c/classes/Loads/Pengrid.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Loads/Pengrid.cpp	(revision 18301)
@@ -20,6 +20,5 @@
 
 /*Pengrid constructors and destructor*/
-/*FUNCTION Pengrid::Pengrid(){{{*/
-Pengrid::Pengrid(){
+Pengrid::Pengrid(){/*{{{*/
 	this->parameters=NULL;
 	this->hnode=NULL;
@@ -36,6 +35,5 @@
 }
 /*}}}*/
-/*FUNCTION Pengrid::Pengrid(int index, int id, IoModel* iomodel,int analysis_type){{{*/
-Pengrid::Pengrid(int id, int index, IoModel* iomodel, int in_analysis_type){ //i is the element index
+Pengrid::Pengrid(int id, int index, IoModel* iomodel, int in_analysis_type){ //i is the element index/*{{{*/
 
 	int pengrid_node_id;
@@ -74,6 +72,5 @@
 }
 /*}}}*/
-/*FUNCTION Pengrid::~Pengrid(){{{*/
-Pengrid::~Pengrid(){
+Pengrid::~Pengrid(){/*{{{*/
 	delete hnode;
 	delete helement;
@@ -84,11 +81,9 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION Pengrid::Echo {{{*/
-void Pengrid::Echo(void){
+void Pengrid::Echo(void){/*{{{*/
 	this->DeepEcho();
 }
 /*}}}*/
-/*FUNCTION Pengrid::DeepEcho{{{*/
-void Pengrid::DeepEcho(void){
+void Pengrid::DeepEcho(void){/*{{{*/
 
 	_printf_("Pengrid:\n");
@@ -104,15 +99,12 @@
 }
 /*}}}*/
-/*FUNCTION Pengrid::Id {{{*/
-int    Pengrid::Id(void){ return id; }
-/*}}}*/
-/*FUNCTION Pengrid::ObjectEnum{{{*/
-int Pengrid::ObjectEnum(void){
+int    Pengrid::Id(void){ return id; }/*{{{*/
+/*}}}*/
+int Pengrid::ObjectEnum(void){/*{{{*/
 
 	return PengridEnum;
 }
 /*}}}*/
-/*FUNCTION Icefront::copy {{{*/
-Object* Pengrid::copy() {
+Object* Pengrid::copy() {/*{{{*/
 
 	Pengrid* pengrid=NULL;
@@ -147,6 +139,5 @@
 
 /*Load virtual functions definitions:*/
-/*FUNCTION Pengrid::Configure {{{*/
-void  Pengrid::Configure(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
+void  Pengrid::Configure(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){/*{{{*/
 
 	/*Take care of hooking up all objects for this load, ie links the objects in the hooks to their respective 
@@ -165,11 +156,23 @@
 }
 /*}}}*/
-/*FUNCTION Pengrid::SetCurrentConfiguration {{{*/
-void  Pengrid::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
-
-}
-/*}}}*/
-/*FUNCTION Pengrid::CreateKMatrix {{{*/
-void  Pengrid::CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){
+void  Pengrid::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){/*{{{*/
+
+}
+/*}}}*/
+void  Pengrid::ResetHooks(){/*{{{*/
+
+	this->node=NULL;
+	this->element=NULL;
+	this->matpar=NULL;
+	this->parameters=NULL;
+
+	/*Get Element type*/
+	this->hnode->reset();
+	this->helement->reset();
+	this->hmatpar->reset();
+
+}
+/*}}}*/
+void  Pengrid::CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){/*{{{*/
 
 	/*No loads applied, do nothing: */
@@ -178,6 +181,5 @@
 }
 /*}}}*/
-/*FUNCTION Pengrid::CreatePVector {{{*/
-void  Pengrid::CreatePVector(Vector<IssmDouble>* pf){
+void  Pengrid::CreatePVector(Vector<IssmDouble>* pf){/*{{{*/
 
 	ElementVector* pe=NULL;
@@ -201,6 +203,5 @@
 }
 /*}}}*/
-/*FUNCTION Pengrid::GetNodesSidList{{{*/
-void Pengrid::GetNodesSidList(int* sidlist){
+void  Pengrid::GetNodesSidList(int* sidlist){/*{{{*/
 
 	_assert_(sidlist);
@@ -210,6 +211,5 @@
 }
 /*}}}*/
-/*FUNCTION Pengrid::GetNodesLidList{{{*/
-void Pengrid::GetNodesLidList(int* lidlist){
+void  Pengrid::GetNodesLidList(int* lidlist){/*{{{*/
 
 	_assert_(lidlist);
@@ -219,12 +219,10 @@
 }
 /*}}}*/
-/*FUNCTION Pengrid::GetNumberOfNodes{{{*/
-int Pengrid::GetNumberOfNodes(void){
+int   Pengrid::GetNumberOfNodes(void){/*{{{*/
 
 	return NUMVERTICES;
 }
 /*}}}*/
-/*FUNCTION Pengrid::PenaltyCreateMatrix {{{*/
-void  Pengrid::PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,IssmDouble kmax){
+void  Pengrid::PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,IssmDouble kmax){/*{{{*/
 
 	/*Retrieve parameters: */
@@ -254,6 +252,5 @@
 }
 /*}}}*/
-/*FUNCTION Pengrid::PenaltyCreatePVector {{{*/
-void  Pengrid::PenaltyCreatePVector(Vector<IssmDouble>* pf,IssmDouble kmax){
+void  Pengrid::PenaltyCreatePVector(Vector<IssmDouble>* pf,IssmDouble kmax){/*{{{*/
 
 	/*Retrieve parameters: */
@@ -285,17 +282,14 @@
 }
 /*}}}*/
-/*FUNCTION Pengrid::InAnalysis{{{*/
-bool Pengrid::InAnalysis(int in_analysis_type){
+bool  Pengrid::InAnalysis(int in_analysis_type){/*{{{*/
 	if (in_analysis_type==this->analysis_type)return true;
 	else return false;
 }
 /*}}}*/
-/*FUNCTION Pengrid::IsPenalty{{{*/
-bool Pengrid::IsPenalty(void){
+bool  Pengrid::IsPenalty(void){/*{{{*/
 	return true;
 }
 /*}}}*/
-/*FUNCTION Pengrid::SetwiseNodeConnectivity{{{*/
-void Pengrid::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int* flagsindices,int set1_enum,int set2_enum){
+void  Pengrid::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int* flagsindices,int set1_enum,int set2_enum){/*{{{*/
 
 	/*Output */
@@ -349,31 +343,25 @@
 
 /*Update virtual functions definitions:*/
-/*FUNCTION Pengrid::InputUpdateFromVector(IssmDouble* vector, int name, int type) {{{*/
-void  Pengrid::InputUpdateFromVector(IssmDouble* vector, int name, int type){
+void  Pengrid::InputUpdateFromVector(IssmDouble* vector, int name, int type){/*{{{*/
 	/*Nothing updated yet*/
 }
 /*}}}*/
-/*FUNCTION Pengrid::InputUpdateFromMatrixDakota(IssmDouble* vector, int nrows, int ncols, int name, int type) {{{*/
-void  Pengrid::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type){
+void  Pengrid::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type){/*{{{*/
 	/*Nothing updated yet*/
 }
 /*}}}*/
-/*FUNCTION Pengrid::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type) {{{*/
-void  Pengrid::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){
+void  Pengrid::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){/*{{{*/
 	/*Nothing updated yet*/
 }
 /*}}}*/
-/*FUNCTION Pengrid::InputUpdateFromConstant(IssmDouble constant, int name) {{{*/
-void  Pengrid::InputUpdateFromConstant(IssmDouble constant, int name){
+void  Pengrid::InputUpdateFromConstant(IssmDouble constant, int name){/*{{{*/
 	/*Nothing*/
 }
 /*}}}*/
-/*FUNCTION Pengrid::InputUpdateFromConstant(int constant, int name) {{{*/
-void  Pengrid::InputUpdateFromConstant(int constant, int name){
+void  Pengrid::InputUpdateFromConstant(int constant, int name){/*{{{*/
 	/*Nothing updated yet*/
 }
 /*}}}*/
-/*FUNCTION Pengrid::InputUpdateFromConstant(bool constant, int name) {{{*/
-void  Pengrid::InputUpdateFromConstant(bool constant, int name){
+void  Pengrid::InputUpdateFromConstant(bool constant, int name){/*{{{*/
 
 	switch(name){
@@ -388,6 +376,5 @@
 
 /*Pengrid management:*/
-/*FUNCTION Pengrid::ConstraintActivate {{{*/
-void  Pengrid::ConstraintActivate(int* punstable){
+void  Pengrid::ConstraintActivate(int* punstable){/*{{{*/
 
 	int analysis_type;
@@ -417,6 +404,5 @@
 }
 /*}}}*/
-/*FUNCTION Pengrid::ConstraintActivateThermal {{{*/
-void  Pengrid::ConstraintActivateThermal(int* punstable){
+void  Pengrid::ConstraintActivateThermal(int* punstable){/*{{{*/
 
 	//   The penalty is stable if it doesn't change during to successive iterations.   
@@ -481,6 +467,5 @@
 }
 /*}}}*/
-/*FUNCTION Pengrid::PenaltyCreateKMatrixMelting {{{*/
-ElementMatrix* Pengrid::PenaltyCreateKMatrixMelting(IssmDouble kmax){
+ElementMatrix* Pengrid::PenaltyCreateKMatrixMelting(IssmDouble kmax){/*{{{*/
 
 	IssmDouble pressure,temperature,t_pmp;
@@ -510,6 +495,5 @@
 }
 /*}}}*/
-/*FUNCTION Pengrid::PenaltyCreateKMatrixThermal {{{*/
-ElementMatrix* Pengrid::PenaltyCreateKMatrixThermal(IssmDouble kmax){
+ElementMatrix* Pengrid::PenaltyCreateKMatrixThermal(IssmDouble kmax){/*{{{*/
 
 	IssmDouble    penalty_factor;
@@ -528,6 +512,5 @@
 }
 /*}}}*/
-/*FUNCTION Pengrid::PenaltyCreatePVectorMelting {{{*/
-ElementVector* Pengrid::PenaltyCreatePVectorMelting(IssmDouble kmax){
+ElementVector* Pengrid::PenaltyCreatePVectorMelting(IssmDouble kmax){/*{{{*/
 
 	IssmDouble pressure;
@@ -570,6 +553,5 @@
 }
 /*}}}*/
-/*FUNCTION Pengrid::PenaltyCreatePVectorThermal {{{*/
-ElementVector* Pengrid::PenaltyCreatePVectorThermal(IssmDouble kmax){
+ElementVector* Pengrid::PenaltyCreatePVectorThermal(IssmDouble kmax){/*{{{*/
 
 	IssmDouble pressure;
@@ -596,6 +578,5 @@
 }
 /*}}}*/
-/*FUNCTION Pengrid::ConstraintActivateHydrologyDCInefficient{{{*/
-void  Pengrid::ConstraintActivateHydrologyDCInefficient(int* punstable){
+void  Pengrid::ConstraintActivateHydrologyDCInefficient(int* punstable){/*{{{*/
 
 	//   The penalty is stable if it doesn't change during two consecutive iterations.   
@@ -657,6 +638,5 @@
 }
 /*}}}*/
-/*FUNCTION Pengrid::PenaltyCreateKMatrixHydrologyDCInefficient {{{*/
-ElementMatrix* Pengrid::PenaltyCreateKMatrixHydrologyDCInefficient(IssmDouble kmax){
+ElementMatrix* Pengrid::PenaltyCreateKMatrixHydrologyDCInefficient(IssmDouble kmax){/*{{{*/
 	IssmDouble    penalty_factor;
 
@@ -674,6 +654,5 @@
 }
 /*}}}*/
-/*FUNCTION Pengrid::PenaltyCreatePVectorHydrologyDCInefficient {{{*/
-ElementVector* Pengrid::PenaltyCreatePVectorHydrologyDCInefficient(IssmDouble kmax){
+ElementVector* Pengrid::PenaltyCreatePVectorHydrologyDCInefficient(IssmDouble kmax){/*{{{*/
 
 	IssmDouble h_max;
@@ -699,6 +678,5 @@
 }
 /*}}}*/
-/*FUNCTION Pengrid::CreatePVectorHydrologyDCInefficient {{{*/
-ElementVector* Pengrid::CreatePVectorHydrologyDCInefficient(void){
+ElementVector* Pengrid::CreatePVectorHydrologyDCInefficient(void){/*{{{*/
 
 	IssmDouble moulin_load,dt;
@@ -716,6 +694,5 @@
  }
 /*}}}*/
-/*FUNCTION Pengrid::ResetConstraint {{{*/
-void  Pengrid::ResetConstraint(void){
+void  Pengrid::ResetConstraint(void){/*{{{*/
 	active         = 0;
 	zigzag_counter = 0;
Index: issm/trunk/src/c/classes/Loads/Pengrid.h
===================================================================
--- issm/trunk/src/c/classes/Loads/Pengrid.h	(revision 18081)
+++ issm/trunk/src/c/classes/Loads/Pengrid.h	(revision 18301)
@@ -68,4 +68,5 @@
 		void  Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
 		void  SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
+		void  ResetHooks();
 		void  CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs);
 		void  CreatePVector(Vector<IssmDouble>* pf);
Index: issm/trunk/src/c/classes/Loads/Penpair.cpp
===================================================================
--- issm/trunk/src/c/classes/Loads/Penpair.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Loads/Penpair.cpp	(revision 18301)
@@ -19,6 +19,5 @@
 
 /*Penpair constructors and destructor*/
-/*FUNCTION Penpair::constructor {{{*/
-Penpair::Penpair(){
+Penpair::Penpair(){/*{{{*/
 
 	this->hnodes=NULL;
@@ -28,6 +27,5 @@
 }
 /*}}}*/
-/*FUNCTION Penpair::creation {{{*/
-Penpair::Penpair(int penpair_id, int* penpair_node_ids,int in_analysis_type){
+Penpair::Penpair(int penpair_id, int* penpair_node_ids,int in_analysis_type){/*{{{*/
 
 	this->id=penpair_id;
@@ -40,6 +38,5 @@
 }
 /*}}}*/
-/*FUNCTION Penpair::destructor {{{*/
-Penpair::~Penpair(){
+Penpair::~Penpair(){/*{{{*/
 	delete hnodes;
 	return;
@@ -48,6 +45,5 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION Penpair::Echo {{{*/
-void Penpair::Echo(void){
+void Penpair::Echo(void){/*{{{*/
 
 	_printf_("Penpair:\n");
@@ -59,6 +55,5 @@
 }
 /*}}}*/
-/*FUNCTION Penpair::DeepEcho {{{*/
-void Penpair::DeepEcho(void){
+void Penpair::DeepEcho(void){/*{{{*/
 
 	_printf_("Penpair:\n");
@@ -70,15 +65,12 @@
 }		
 /*}}}*/
-/*FUNCTION Penpair::Id {{{*/
-int    Penpair::Id(void){ return id; }
-/*}}}*/
-/*FUNCTION Penpair::ObjectEnum{{{*/
-int Penpair::ObjectEnum(void){
+int  Penpair::Id(void){ return id; }/*{{{*/
+/*}}}*/
+int  Penpair::ObjectEnum(void){/*{{{*/
 
 	return PenpairEnum;
 }
 /*}}}*/
-/*FUNCTION Penpair::copy {{{*/
-Object* Penpair::copy() {
+Object* Penpair::copy() {/*{{{*/
 
 	Penpair* penpair=NULL;
@@ -103,6 +95,5 @@
 
 /*Load virtual functions definitions:*/
-/*FUNCTION Penpair::Configure {{{*/
-void  Penpair::Configure(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
+void  Penpair::Configure(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){/*{{{*/
 
 	/*Take care of hooking up all objects for this element, ie links the objects in the hooks to their respective 
@@ -118,11 +109,19 @@
 }
 /*}}}*/
-/*FUNCTION Penpair::SetCurrentConfiguration {{{*/
-void  Penpair::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
-
-}
-/*}}}*/
-/*FUNCTION Penpair::CreateKMatrix {{{*/
-void  Penpair::CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){
+void  Penpair::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){/*{{{*/
+
+}
+/*}}}*/
+void  Penpair::ResetHooks(){/*{{{*/
+
+	this->nodes=NULL;
+	this->parameters=NULL;
+
+	/*Get Element type*/
+	this->hnodes->reset();
+
+}
+/*}}}*/
+void  Penpair::CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){/*{{{*/
 	/*If you code this piece, don't forget that a penalty will be inactive if it is dealing with clone nodes*/
 	/*No loads applied, do nothing: */
@@ -131,6 +130,5 @@
 }
 /*}}}*/
-/*FUNCTION Penpair::CreatePVector {{{*/
-void  Penpair::CreatePVector(Vector<IssmDouble>* pf){
+void  Penpair::CreatePVector(Vector<IssmDouble>* pf){/*{{{*/
 
 	/*No loads applied, do nothing: */
@@ -139,11 +137,9 @@
 }
 /*}}}*/
-/*FUNCTION Penpair::CreateJacobianMatrix{{{*/
-void  Penpair::CreateJacobianMatrix(Matrix<IssmDouble>* Jff){
+void  Penpair::CreateJacobianMatrix(Matrix<IssmDouble>* Jff){/*{{{*/
 	this->CreateKMatrix(Jff,NULL);
 }
 /*}}}*/
-/*FUNCTION Penpair::GetNodesSidList{{{*/
-void Penpair::GetNodesSidList(int* sidlist){
+void  Penpair::GetNodesSidList(int* sidlist){/*{{{*/
 
 	_assert_(sidlist);
@@ -153,6 +149,5 @@
 }
 /*}}}*/
-/*FUNCTION Penpair::GetNodesLidList{{{*/
-void Penpair::GetNodesLidList(int* lidlist){
+void  Penpair::GetNodesLidList(int* lidlist){/*{{{*/
 
 	_assert_(lidlist);
@@ -162,17 +157,14 @@
 }
 /*}}}*/
-/*FUNCTION Penpair::GetNumberOfNodes{{{*/
-int Penpair::GetNumberOfNodes(void){
+int   Penpair::GetNumberOfNodes(void){/*{{{*/
 
 	return NUMVERTICES;
 }
 /*}}}*/
-/*FUNCTION Penpair::IsPenalty{{{*/
-bool Penpair::IsPenalty(void){
+bool  Penpair::IsPenalty(void){/*{{{*/
 	return true;
 }
 /*}}}*/
-/*FUNCTION Penpair::PenaltyCreateKMatrix {{{*/
-void  Penpair::PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,IssmDouble kmax){
+void  Penpair::PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,IssmDouble kmax){/*{{{*/
 
 	/*Retrieve parameters: */
@@ -199,23 +191,19 @@
 }
 /*}}}*/
-/*FUNCTION Penpair::PenaltyCreatePVector {{{*/
-void  Penpair::PenaltyCreatePVector(Vector<IssmDouble>* pf,IssmDouble kmax){
+void  Penpair::PenaltyCreatePVector(Vector<IssmDouble>* pf,IssmDouble kmax){/*{{{*/
 	/*No loads applied, do nothing: */
 	return;
 }
 /*}}}*/
-/*FUNCTION Penpair::PenaltyCreateJacobianMatrix{{{*/
-void  Penpair::PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax){
+void  Penpair::PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax){/*{{{*/
 	this->PenaltyCreateKMatrix(Jff,NULL,kmax);
 }
 /*}}}*/
-/*FUNCTION Penpair::InAnalysis{{{*/
-bool Penpair::InAnalysis(int in_analysis_type){
+bool  Penpair::InAnalysis(int in_analysis_type){/*{{{*/
 	if (in_analysis_type==this->analysis_type)return true;
 	else return false;
 }
 /*}}}*/
-/*FUNCTION Penpair::SetwiseNodeConnectivity{{{*/
-void Penpair::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int* flagsindices,int set1_enum,int set2_enum){
+void  Penpair::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int* flagsindices,int set1_enum,int set2_enum){/*{{{*/
 
 	/*Output */
@@ -273,21 +261,17 @@
 
 /*Update virtual functions definitions:*/
-/*FUNCTION Penpair::InputUpdateFromConstant(IssmDouble constant, int name) {{{*/
-void  Penpair::InputUpdateFromConstant(IssmDouble constant, int name){
+void  Penpair::InputUpdateFromConstant(IssmDouble constant, int name){/*{{{*/
 	/*Nothing updated yet*/
 }
 /*}}}*/
-/*FUNCTION Penpair::InputUpdateFromConstant(int constant, int name) {{{*/
-void  Penpair::InputUpdateFromConstant(int constant, int name){
+void  Penpair::InputUpdateFromConstant(int constant, int name){/*{{{*/
 	/*Nothing updated yet*/
 }
 /*}}}*/
-/*FUNCTION Penpair::InputUpdateFromConstant(bool constant, int name) {{{*/
-void  Penpair::InputUpdateFromConstant(bool constant, int name){
+void  Penpair::InputUpdateFromConstant(bool constant, int name){/*{{{*/
 	/*Nothing updated yet*/
 }
 /*}}}*/
-/*FUNCTION Penpair::InputUpdateFromVector(IssmDouble* vector, int name, int type) {{{*/
-void  Penpair::InputUpdateFromVector(IssmDouble* vector, int name, int type){
+void  Penpair::InputUpdateFromVector(IssmDouble* vector, int name, int type){/*{{{*/
 	/*Nothing updated yet*/
 }
@@ -295,6 +279,5 @@
 
 /*Penpair management:*/
-/*FUNCTION Penpair::PenaltyCreateKMatrixStressbalanceHoriz{{{*/
-ElementMatrix* Penpair::PenaltyCreateKMatrixStressbalanceHoriz(IssmDouble kmax){
+ElementMatrix* Penpair::PenaltyCreateKMatrixStressbalanceHoriz(IssmDouble kmax){/*{{{*/
 
 	int    approximation0=nodes[0]->GetApproximation();
@@ -329,6 +312,5 @@
 }
 /*}}}*/
-/*FUNCTION Penpair::PenaltyCreateKMatrixStressbalanceSSAHO {{{*/
-ElementMatrix* Penpair::PenaltyCreateKMatrixStressbalanceSSAHO(IssmDouble kmax){
+ElementMatrix* Penpair::PenaltyCreateKMatrixStressbalanceSSAHO(IssmDouble kmax){/*{{{*/
 
 	const int numdof=NUMVERTICES*NDOF2;
@@ -356,6 +338,5 @@
 }
 /*}}}*/
-/*FUNCTION Penpair::PenaltyCreateKMatrixStressbalanceFS {{{*/
-ElementMatrix* Penpair::PenaltyCreateKMatrixStressbalanceFS(IssmDouble kmax){
+ElementMatrix* Penpair::PenaltyCreateKMatrixStressbalanceFS(IssmDouble kmax){/*{{{*/
 
 	const int  numdof=NUMVERTICES*NDOF3;
@@ -388,6 +369,5 @@
 }
 /*}}}*/
-/*FUNCTION Penpair::PenaltyCreateKMatrixMasstransport {{{*/
-ElementMatrix* Penpair::PenaltyCreateKMatrixMasstransport(IssmDouble kmax){
+ElementMatrix* Penpair::PenaltyCreateKMatrixMasstransport(IssmDouble kmax){/*{{{*/
 
 	const int numdof=NUMVERTICES*NDOF1;
Index: issm/trunk/src/c/classes/Loads/Penpair.h
===================================================================
--- issm/trunk/src/c/classes/Loads/Penpair.h	(revision 18081)
+++ issm/trunk/src/c/classes/Loads/Penpair.h	(revision 18301)
@@ -48,4 +48,5 @@
 			/*Load virtual functions definitions: {{{*/
 		void  Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
+		void  ResetHooks();
 		void  SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
 		void  CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs);
Index: issm/trunk/src/c/classes/Loads/Riftfront.cpp
===================================================================
--- issm/trunk/src/c/classes/Loads/Riftfront.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Loads/Riftfront.cpp	(revision 18301)
@@ -20,6 +20,5 @@
 
 /*Riftfront constructors and destructor*/
-/*FUNCTION Riftfront::Riftfront(){{{*/
-Riftfront::Riftfront(){
+Riftfront::Riftfront(){/*{{{*/
 	this->parameters=NULL;
 	this->hnodes=NULL;
@@ -31,6 +30,5 @@
 }
 /*}}}*/
-/*FUNCTION Riftfront::Riftfront(int id, int i, IoModel* iomodel,int analysis_type){{{*/
-Riftfront::Riftfront(int riftfront_id,int i, IoModel* iomodel,int riftfront_analysis_type){
+Riftfront::Riftfront(int riftfront_id,int i, IoModel* iomodel,int riftfront_analysis_type){/*{{{*/
 
 	/*data: */
@@ -101,6 +99,5 @@
 }
 /*}}}*/
-/*FUNCTION Riftfront::~Riftfront(){{{*/
-Riftfront::~Riftfront(){
+Riftfront::~Riftfront(){/*{{{*/
 	this->parameters=NULL;
 	delete hnodes;
@@ -111,6 +108,5 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION Riftfront::Echo {{{*/
-void Riftfront::Echo(void){
+void Riftfront::Echo(void){/*{{{*/
 
 	_printf_("Riftfront:\n");
@@ -138,6 +134,5 @@
 }
 /*}}}*/
-/*FUNCTION Riftfront::DeepEcho{{{*/
-void Riftfront::DeepEcho(void){
+void Riftfront::DeepEcho(void){/*{{{*/
 
 	_printf_("Riftfront:\n");
@@ -151,9 +146,7 @@
 }
 /*}}}*/
-/*FUNCTION Riftfront::Id {{{*/
-int    Riftfront::Id(void){ return id; }
-/*}}}*/
-/*FUNCTION Riftfront::ObjectEnum{{{*/
-int Riftfront::ObjectEnum(void){
+int    Riftfront::Id(void){ return id; }/*{{{*/
+/*}}}*/
+int Riftfront::ObjectEnum(void){/*{{{*/
 
 	return RiftfrontEnum;
@@ -161,6 +154,5 @@
 }
 /*}}}*/
-/*FUNCTION Riftfront::copy {{{*/
-Object* Riftfront::copy() {
+Object* Riftfront::copy() {/*{{{*/
 
 	Riftfront* riftfront=NULL;
@@ -209,15 +201,12 @@
 
 /*Update virtual functions definitions:*/
-/*FUNCTION Riftfront::InputUpdateFromConstant(bool constant,int name) {{{*/
-void  Riftfront::InputUpdateFromConstant(bool constant,int name){
-}
-/*}}}*/
-/*FUNCTION Riftfront::InputUpdateFromConstant(IssmDouble constant,int name) {{{*/
-void  Riftfront::InputUpdateFromConstant(IssmDouble constant,int name){
-
-}
-/*}}}*/
-/*FUNCTION Riftfront::InputUpdateFromVector(IssmDouble* constant,int name) {{{*/
-void    Riftfront::InputUpdateFromVector(IssmDouble* vector, int name, int type){
+void  Riftfront::InputUpdateFromConstant(bool constant,int name){/*{{{*/
+}
+/*}}}*/
+void  Riftfront::InputUpdateFromConstant(IssmDouble constant,int name){/*{{{*/
+
+}
+/*}}}*/
+void  Riftfront::InputUpdateFromVector(IssmDouble* vector, int name, int type){/*{{{*/
 
 	_error_("not implemented yet");
@@ -227,6 +216,5 @@
 
 /*Load virtual functions definitions:*/
-/*FUNCTION Riftfront::Configure {{{*/
-void  Riftfront::Configure(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
+void  Riftfront::Configure(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){/*{{{*/	
 
 	/*Take care of hooking up all objects for this element, ie links the objects in the hooks to their respective 
@@ -246,16 +234,27 @@
 }
 /*}}}*/
-/*FUNCTION Riftfront::IsPenalty{{{*/
-bool Riftfront::IsPenalty(void){
+void  Riftfront::ResetHooks(){/*{{{*/
+
+	this->nodes=NULL;
+	this->elements=NULL;
+	this->matpar=NULL;
+	this->parameters=NULL;
+
+	/*Get Element type*/
+	this->hnodes->reset();
+	this->helements->reset();
+	this->hmatpar->reset();
+
+}
+/*}}}*/
+bool  Riftfront::IsPenalty(void){/*{{{*/
 	return true;
 }
 /*}}}*/
-/*FUNCTION Riftfront::SetCurrentConfiguration {{{*/
-void  Riftfront::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
-
-}
-/*}}}*/
-/*FUNCTION Riftfront::PenaltyCreateKMatrix {{{*/
-void  Riftfront::PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,IssmDouble kmax){
+void  Riftfront::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){/*{{{*/
+
+}
+/*}}}*/
+void  Riftfront::PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,IssmDouble kmax){/*{{{*/
 
 	/*Retrieve parameters: */
@@ -282,6 +281,5 @@
 }
 /*}}}*/
-/*FUNCTION Riftfront::PenaltyCreatePVector {{{*/
-void  Riftfront::PenaltyCreatePVector(Vector<IssmDouble>* pf,IssmDouble kmax){
+void  Riftfront::PenaltyCreatePVector(Vector<IssmDouble>* pf,IssmDouble kmax){/*{{{*/
 
 	/*Retrieve parameters: */
@@ -308,18 +306,15 @@
 }
 /*}}}*/
-/*FUNCTION Riftfront::CreateKMatrix {{{*/
-void  Riftfront::CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){
+void  Riftfront::CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){/*{{{*/
 	/*do nothing: */
 	return;
 }
 /*}}}*/
-/*FUNCTION Riftfront::CreatePVector {{{*/
-void  Riftfront::CreatePVector(Vector<IssmDouble>* pf){
+void  Riftfront::CreatePVector(Vector<IssmDouble>* pf){/*{{{*/
 	/*do nothing: */
 	return;
 }
 /*}}}*/
-/*FUNCTION Riftfront::GetNodesSidList{{{*/
-void Riftfront::GetNodesSidList(int* sidlist){
+void  Riftfront::GetNodesSidList(int* sidlist){/*{{{*/
 
 	_assert_(sidlist);
@@ -329,6 +324,5 @@
 }
 /*}}}*/
-/*FUNCTION Riftfront::GetNodesLidList{{{*/
-void Riftfront::GetNodesLidList(int* lidlist){
+void  Riftfront::GetNodesLidList(int* lidlist){/*{{{*/
 
 	_assert_(lidlist);
@@ -338,18 +332,15 @@
 }
 /*}}}*/
-/*FUNCTION Riftfront::GetNumberOfNodes{{{*/
-int Riftfront::GetNumberOfNodes(void){
+int   Riftfront::GetNumberOfNodes(void){/*{{{*/
 
 	return NUMVERTICES;
 }
 /*}}}*/
-/*FUNCTION Riftfront::InAnalysis{{{*/
-bool Riftfront::InAnalysis(int in_analysis_type){
+bool  Riftfront::InAnalysis(int in_analysis_type){/*{{{*/
 	if (in_analysis_type==this->analysis_type) return true;
 	else return false;
 }
 /*}}}*/
-/*FUNCTION Riftfront::SetwiseNodeConnectivity{{{*/
-void Riftfront::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int* flagsindices,int set1_enum,int set2_enum){
+void  Riftfront::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int* flagsindices,int set1_enum,int set2_enum){/*{{{*/
 
 	/*Output */
@@ -407,6 +398,5 @@
 
 /*Riftfront numerics*/
-/*FUNCTION Riftfront::PenaltyCreateKMatrixStressbalanceHoriz {{{*/
-ElementMatrix* Riftfront::PenaltyCreateKMatrixStressbalanceHoriz(IssmDouble kmax){
+ElementMatrix* Riftfront::PenaltyCreateKMatrixStressbalanceHoriz(IssmDouble kmax){/*{{{*/
 
 	const int   numdof = NDOF2*NUMVERTICES;
@@ -485,6 +475,5 @@
 }
 /*}}}*/
-/*FUNCTION Riftfront::PenaltyCreatePVectorStressbalanceHoriz {{{*/
-ElementVector* Riftfront::PenaltyCreatePVectorStressbalanceHoriz(IssmDouble kmax){
+ElementVector* Riftfront::PenaltyCreatePVectorStressbalanceHoriz(IssmDouble kmax){/*{{{*/
 
 	int        j;
@@ -580,8 +569,6 @@
 }
 /*}}}*/
-/*FUNCTION Riftfront::Constrain {{{*/
 #define _ZIGZAGCOUNTER_
-
-int Riftfront::Constrain(int* punstable){
+int    Riftfront::Constrain(int* punstable){/*{{{*/
 
 	IssmDouble  penetration;
@@ -664,6 +651,5 @@
 }
 /*}}}*/
-/*FUNCTION Riftfront::FreezeConstraints{{{*/
-void   Riftfront::FreezeConstraints(void){
+void   Riftfront::FreezeConstraints(void){/*{{{*/
 
 	/*Just set frozen flag to 1: */
@@ -672,6 +658,5 @@
 }
 /*}}}*/
-/*FUNCTION Riftfront::IsFrozen{{{*/
-bool   Riftfront::IsFrozen(void){
+bool   Riftfront::IsFrozen(void){/*{{{*/
 
 	/*Just set frozen flag to 1: */
Index: issm/trunk/src/c/classes/Loads/Riftfront.h
===================================================================
--- issm/trunk/src/c/classes/Loads/Riftfront.h	(revision 18081)
+++ issm/trunk/src/c/classes/Loads/Riftfront.h	(revision 18301)
@@ -74,4 +74,5 @@
 		/*Load virtual functions definitions: {{{*/
 		void  Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
+		void  ResetHooks();
 		void  SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
 		void  CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs);
Index: issm/trunk/src/c/classes/Massfluxatgate.h
===================================================================
--- issm/trunk/src/c/classes/Massfluxatgate.h	(revision 18081)
+++ issm/trunk/src/c/classes/Massfluxatgate.h	(revision 18301)
@@ -29,6 +29,5 @@
 
 		/*Massfluxatgate constructors, destructors :*/
-		/*FUNCTION Massfluxatgate() {{{*/
-		Massfluxatgate(){
+		Massfluxatgate(){/*{{{*/
 			this->name        = 0;
 			this->numsegments = 0;
@@ -36,6 +35,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Massfluxatgate(char* name, int numsegments, doubletype* segments) {{{*/
-		Massfluxatgate(char* in_name, int in_numsegments, doubletype* in_segments) {
+		Massfluxatgate(char* in_name, int in_numsegments, doubletype* in_segments) {/*{{{*/
 			
 			int i;
@@ -63,6 +61,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Massfluxatgate(char* name, int numsegments, doubletype* x1, doubletype* y1, doubletype* x2, doubletype* y2,int* elements) {{{*/
-		Massfluxatgate(char* in_name, int in_numsegments, doubletype* in_x1, doubletype* in_y1, doubletype* in_x2, doubletype* in_y2,int* in_elements){
+		Massfluxatgate(char* in_name, int in_numsegments, doubletype* in_x1, doubletype* in_y1, doubletype* in_x2, doubletype* in_y2,int* in_elements){/*{{{*/
 
 			this->name   = xNew<char>(strlen(in_name)+1);
@@ -81,6 +78,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION ~Massfluxatgate() {{{*/
-		~Massfluxatgate(){
+		~Massfluxatgate(){/*{{{*/
 			xDelete<doubletype>(this->x1);
 			xDelete<doubletype>(this->y1);
@@ -93,6 +89,5 @@
 
 		/*Object virtual function resolutoin: */
-		/*FUNCTION Echo(){{{*/
-		void Echo(void){
+		void Echo(void){/*{{{*/
 			_printf_(" Massfluxatgate: " << name << "\n");
 			_printf_("    numsegments: " << numsegments << "\n");
@@ -105,27 +100,22 @@
 		}
 		/*}}}*/
-		/*FUNCTION DeepEcho(){{{*/
-		void DeepEcho(void){
+		void DeepEcho(void){/*{{{*/
 			this->Echo();
 		}
 		/*}}}*/
-		/*FUNCTION Id(){{{*/
-		int Id(void){
+		int Id(void){/*{{{*/
 			return -1;
 		}
 		/*}}}*/
-		/*FUNCTION ObjectEnum{{{*/
-		int ObjectEnum(void){
+		int ObjectEnum(void){/*{{{*/
 			return MassfluxatgateEnum;
 		}
 		/*}}}*/
-		/*FUNCTION copy {{{*/
-		Object* copy() {
+		Object* copy() {/*{{{*/
 			return new Massfluxatgate(this->name,this->numsegments,this->x1,this->y1,this->x2,this->y2,this->elements); 
 		}
 		/*}}}*/
 		/*Definition virtual function resolutoin: */
-		/*FUNCTION char* Name() {{{*/
-		char* Name(){
+		char* Name(){/*{{{*/
 
 			char* name2=xNew<char>(strlen(this->name)+1);
@@ -135,6 +125,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION doubletype* Response(FemModel* femmodel) {{{*/
-		 IssmDouble Response(FemModel* femmodel){
+		 IssmDouble Response(FemModel* femmodel){/*{{{*/
 
 			int          i,j;
Index: issm/trunk/src/c/classes/Materials/Material.h
===================================================================
--- issm/trunk/src/c/classes/Materials/Material.h	(revision 18081)
+++ issm/trunk/src/c/classes/Materials/Material.h	(revision 18301)
@@ -26,4 +26,6 @@
 		virtual void       Configure(Elements* elements)=0;
 		virtual void       GetViscosity(IssmDouble* pviscosity,IssmDouble epseff)=0;
+		virtual void       GetViscosity_B(IssmDouble* pviscosity,IssmDouble epseff)=0;
+		virtual void       GetViscosity_D(IssmDouble* pviscosity,IssmDouble epseff)=0;
 		virtual void       GetViscosityBar(IssmDouble* pviscosity,IssmDouble epseff)=0;
 		virtual void       GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon)=0;
@@ -39,4 +41,5 @@
 		virtual IssmDouble GetDbar()=0;
 		virtual bool       IsDamage()=0;
+		virtual void       ResetHooks()=0;
 
 };
Index: issm/trunk/src/c/classes/Materials/Materials.cpp
===================================================================
--- issm/trunk/src/c/classes/Materials/Materials.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Materials/Materials.cpp	(revision 18301)
@@ -19,12 +19,10 @@
 
 /*Object constructors and destructor*/
-/*FUNCTION Materials::Materials(){{{*/
-Materials::Materials(){
+Materials::Materials(){/*{{{*/
 	enum_type=MaterialsEnum;
 	return;
 }
 /*}}}*/
-/*FUNCTION Materials::~Materials(){{{*/
-Materials::~Materials(){
+Materials::~Materials(){/*{{{*/
 	return;
 }
@@ -32,6 +30,5 @@
 
 /*Object management*/
-/*FUNCTION Materials::Configure{{{*/
-void Materials::Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){
+void Materials::Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){/*{{{*/
 
 	vector<Object*>::iterator object;
@@ -47,2 +44,16 @@
 }
 /*}}}*/
+void Materials::ResetHooks(){/*{{{*/
+
+	vector<Object*>::iterator object;
+	Material* material=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		material=dynamic_cast<Material*>((*object));
+		material->ResetHooks();
+
+	}
+
+}
+/*}}}*/
Index: issm/trunk/src/c/classes/Materials/Materials.h
===================================================================
--- issm/trunk/src/c/classes/Materials/Materials.h	(revision 18081)
+++ issm/trunk/src/c/classes/Materials/Materials.h	(revision 18301)
@@ -24,4 +24,5 @@
 		/*numerics*/
 		void  Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
+		void  ResetHooks();
 
 };
Index: issm/trunk/src/c/classes/Materials/Matice.cpp
===================================================================
--- issm/trunk/src/c/classes/Materials/Matice.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Materials/Matice.cpp	(revision 18301)
@@ -27,6 +27,5 @@
 
 /*Matice constructors and destructor*/
-/*FUNCTION Matice::Matice(){{{*/
-Matice::Matice(){
+Matice::Matice(){/*{{{*/
 	this->helement=NULL;
 	this->element=NULL;
@@ -34,6 +33,5 @@
 }
 /*}}}*/
-/*FUNCTION Matice::Matice(int id, int index, IoModel* iomodel, int num_vertices){{{*/
-Matice::Matice(int matice_mid,int index, IoModel* iomodel){
+Matice::Matice(int matice_mid,int index, IoModel* iomodel){/*{{{*/
 
 	/*Intermediaries:*/
@@ -59,6 +57,5 @@
 }
 /*}}}*/
-/*FUNCTION Matice::~Matice(){{{*/
-Matice::~Matice(){
+Matice::~Matice(){/*{{{*/
 	delete helement;
 	return;
@@ -67,6 +64,5 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION Matice::Echo {{{*/
-void Matice::Echo(void){
+void Matice::Echo(void){/*{{{*/
 
 	_printf_("Matice:\n");
@@ -76,6 +72,5 @@
 }
 /*}}}*/
-/*FUNCTION Matice::DeepEcho {{{*/
-void Matice::DeepEcho(void){
+void Matice::DeepEcho(void){/*{{{*/
 
 	_printf_("Matice:\n");
@@ -85,9 +80,7 @@
 }		
 /*}}}*/
-/*FUNCTION Matice::Id {{{*/
-int    Matice::Id(void){ return mid; }
-/*}}}*/
-/*FUNCTION Matice::ObjectEnum{{{*/
-int Matice::ObjectEnum(void){
+int    Matice::Id(void){ return mid; }/*{{{*/
+/*}}}*/
+int Matice::ObjectEnum(void){/*{{{*/
 
 	return MaticeEnum;
@@ -95,6 +88,5 @@
 }
 /*}}}*/
-/*FUNCTION Matice::copy() {{{*/
-Object* Matice::copy() {
+Object* Matice::copy() {/*{{{*/
 
 	/*Output*/
@@ -113,6 +105,5 @@
 }
 /*}}}*/
-/*FUNCTION Matice::copy2(Element* element) {{{*/
-Material* Matice::copy2(Element* element_in) {
+Material* Matice::copy2(Element* element_in) {/*{{{*/
 
 	/*Output*/
@@ -133,6 +124,5 @@
 
 /*Matice management*/
-/*FUNCTION Matice::Configure {{{*/
-void  Matice::Configure(Elements* elementsin){
+void  Matice::Configure(Elements* elementsin){/*{{{*/
 
 	/*Take care of hooking up all objects for this element, ie links the objects in the hooks to their respective 
@@ -142,11 +132,9 @@
 }
 /*}}}*/
-/*FUNCTION Matice::SetCurrentConfiguration {{{*/
-void  Matice::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
-
-}
-/*}}}*/
-/*FUNCTION Matice::GetA {{{*/
-IssmDouble Matice::GetA(){
+void  Matice::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){/*{{{*/
+
+}
+/*}}}*/
+IssmDouble Matice::GetA(){/*{{{*/
 	/*
 	 * A = 1/B^n
@@ -161,6 +149,5 @@
 }
 /*}}}*/
-/*FUNCTION Matice::GetAbar {{{*/
-IssmDouble Matice::GetAbar(){
+IssmDouble Matice::GetAbar(){/*{{{*/
 	/*
 	 * A = 1/B^n
@@ -175,6 +162,5 @@
 }
 /*}}}*/
-/*FUNCTION Matice::GetB {{{*/
-IssmDouble Matice::GetB(){
+IssmDouble Matice::GetB(){/*{{{*/
 
 	/*Output*/
@@ -185,6 +171,5 @@
 }
 /*}}}*/
-/*FUNCTION Matice::GetBbar {{{*/
-IssmDouble Matice::GetBbar(){
+IssmDouble Matice::GetBbar(){/*{{{*/
 
 	/*Output*/
@@ -195,6 +180,5 @@
 }
 /*}}}*/
-/*FUNCTION Matice::GetN {{{*/
-IssmDouble Matice::GetN(){
+IssmDouble Matice::GetN(){/*{{{*/
 
 	/*Output*/
@@ -205,6 +189,5 @@
 }
 /*}}}*/
-/*FUNCTION Matice::GetD {{{*/
-IssmDouble Matice::GetD(){
+IssmDouble Matice::GetD(){/*{{{*/
 
 	_assert_(this->isdamaged);
@@ -215,6 +198,5 @@
 }
 /*}}}*/
-/*FUNCTION Matice::GetDbar {{{*/
-IssmDouble Matice::GetDbar(){
+IssmDouble Matice::GetDbar(){/*{{{*/
 
 	_assert_(this->isdamaged);
@@ -225,12 +207,10 @@
 }
 /*}}}*/
-/*FUNCTION Matice::IsDamage() {{{*/
-bool Matice::IsDamage(){
+bool Matice::IsDamage(){/*{{{*/
 
 	return this->isdamaged;
 }
 /*}}}*/
-/*FUNCTION Matice::GetViscosity {{{*/
-void  Matice::GetViscosity(IssmDouble* pviscosity,IssmDouble eps_eff){
+void  Matice::GetViscosity(IssmDouble* pviscosity,IssmDouble eps_eff){/*{{{*/
 	/*From a string tensor and a material object, return viscosity, using Glen's flow law.
 								(1-D) B
@@ -284,6 +264,59 @@
 }
 /*}}}*/
-/*FUNCTION Matice::GetViscosityBar {{{*/
-void  Matice::GetViscosityBar(IssmDouble* pviscosity,IssmDouble eps_eff){
+void  Matice::GetViscosity_B(IssmDouble* pdmudB,IssmDouble eps_eff){/*{{{*/
+
+	/*output: */
+	IssmDouble dmudB;
+
+	/*Intermediary: */
+	IssmDouble D=0.,n;
+
+	/*Get B and n*/
+	n=GetN(); _assert_(n>0.);
+	if(this->isdamaged){
+		D=GetD();
+		_assert_(D>=0. && D<1.);
+	}
+
+	if(n==1.){
+		/*Linear Viscous behavior (Newtonian fluid) dmudB=B/2: */
+		dmudB=(1.-D)/2.;
+	}
+	else{
+		if(eps_eff==0.) dmudB = 0.;
+		else            dmudB = (1.-D)/(2.*pow(eps_eff,(n-1.)/n));
+	}
+
+	/*Return: */
+	*pdmudB=dmudB;
+}
+/*}}}*/
+void  Matice::GetViscosity_D(IssmDouble* pdmudD,IssmDouble eps_eff){/*{{{*/
+
+	/*output: */
+	IssmDouble dmudD;
+
+	/*Intermediary: */
+	IssmDouble n,B;
+
+	/*Get B and n*/
+	n=GetN(); _assert_(n>0.);
+	B=GetBbar();
+	_assert_(this->isdamaged);
+
+	if(n==1.){
+		/*Linear Viscous behavior (Newtonian fluid) dmudB=B/2: */
+		dmudD=-B/2.;
+	}
+	else{
+		if(eps_eff==0.) dmudD = 0.;
+		else            dmudD = -B/(2.*pow(eps_eff,(n-1.)/n));
+	}
+
+	/*Return: */
+	*pdmudD=dmudD;
+}
+/*}}}*/
+void  Matice::GetViscosityBar(IssmDouble* pviscosity,IssmDouble eps_eff){/*{{{*/
 	/*From a string tensor and a material object, return viscosity, using Glen's flow law.
 								(1-D) B
@@ -336,6 +369,5 @@
 }
 /*}}}*/
-/*FUNCTION Matice::GetViscosityComplement {{{*/
-void  Matice::GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* epsilon){
+void  Matice::GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* epsilon){/*{{{*/
 	/*Return viscosity accounting for steady state power law creep [Thomas and SSA, 1982]: 
 	 *
@@ -395,6 +427,5 @@
 }
 /*}}}*/
-/*FUNCTION Matice::GetViscosityDComplement {{{*/
-void  Matice::GetViscosityDComplement(IssmDouble* pviscosity_complement, IssmDouble* epsilon){
+void  Matice::GetViscosityDComplement(IssmDouble* pviscosity_complement, IssmDouble* epsilon){/*{{{*/
 	/*Return viscosity derivative for control method d(mu)/dD: 
 	 *
@@ -451,6 +482,5 @@
 }
 /*}}}*/
-/*FUNCTION Matice::GetViscosityDerivativeEpsSquare{{{*/
-void  Matice::GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* epsilon){
+void  Matice::GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* epsilon){/*{{{*/
 
 	/*output: */
@@ -485,6 +515,5 @@
 }
 /*}}}*/
-/*FUNCTION Matice::GetViscosity2dDerivativeEpsSquare{{{*/
-void  Matice::GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* epsilon){
+void  Matice::GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* epsilon){/*{{{*/
 
 	/*output: */
@@ -514,32 +543,35 @@
 }
 /*}}}*/
-/*FUNCTION Matice::InputUpdateFromVector(IssmDouble* vector, int name, int type) {{{*/
-void  Matice::InputUpdateFromVector(IssmDouble* vector, int name, int type){
-
-}
-/*}}}*/
-/*FUNCTION Matice::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type) {{{*/
-void  Matice::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){
-
-}
-/*}}}*/
-/*FUNCTION Matice::InputUpdateFromMatrixDakota(int* vector, int name, int type) {{{*/
-void  Matice::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols,int name, int type){
+void  Matice::InputUpdateFromVector(IssmDouble* vector, int name, int type){/*{{{*/
+
+}
+/*}}}*/
+void  Matice::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){/*{{{*/
+
+}
+/*}}}*/
+void  Matice::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols,int name, int type){/*{{{*/
 	/*Nothing updated yet*/
 }
 /*}}}*/
-/*FUNCTION Matice::InputUpdateFromConstant(IssmDouble constant, int name) {{{*/
-void  Matice::InputUpdateFromConstant(IssmDouble constant, int name){
+void  Matice::InputUpdateFromConstant(IssmDouble constant, int name){/*{{{*/
 	/*Nothing updated yet*/
 }
 /*}}}*/
-/*FUNCTION Matice::InputUpdateFromConstant(int constant, int name) {{{*/
-void  Matice::InputUpdateFromConstant(int constant, int name){
+void  Matice::InputUpdateFromConstant(int constant, int name){/*{{{*/
 	/*Nothing updated yet*/
 }
 /*}}}*/
-/*FUNCTION Matice::InputUpdateFromConstant(bool constant, int name) {{{*/
-void  Matice::InputUpdateFromConstant(bool constant, int name){
+void  Matice::InputUpdateFromConstant(bool constant, int name){/*{{{*/
 	/*Nothing updated yet*/
 }
 /*}}}*/
+void  Matice::ResetHooks(){/*{{{*/
+
+	this->element=NULL;
+
+	/*Get Element type*/
+	this->helement->reset();
+
+}
+/*}}}*/
Index: issm/trunk/src/c/classes/Materials/Matice.h
===================================================================
--- issm/trunk/src/c/classes/Materials/Matice.h	(revision 18081)
+++ issm/trunk/src/c/classes/Materials/Matice.h	(revision 18301)
@@ -41,5 +41,5 @@
 		Object* copy();
 		/*}}}*/
-		/*Update virtual functions definitions: {{{*/
+		/*Update virtual funictions definitions: {{{*/
 		void  InputUpdateFromVector(IssmDouble* vector, int name, int type);
 		void  InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrow, int ncols, int name, int type);
@@ -55,4 +55,6 @@
 		void       SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
 		void       GetViscosity(IssmDouble* pviscosity, IssmDouble eps_eff);
+		void       GetViscosity_B(IssmDouble* pviscosity, IssmDouble eps_eff);
+		void       GetViscosity_D(IssmDouble* pviscosity, IssmDouble eps_eff);
 		void       GetViscosityBar(IssmDouble* pviscosity, IssmDouble eps_eff);
 		void       GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon);
@@ -68,4 +70,5 @@
 		IssmDouble GetN();
 		bool       IsDamage();
+		void       ResetHooks();
 		/*}}}*/
 };
Index: issm/trunk/src/c/classes/Materials/Matpar.cpp
===================================================================
--- issm/trunk/src/c/classes/Materials/Matpar.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Materials/Matpar.cpp	(revision 18301)
@@ -13,11 +13,9 @@
 
 /*Matpar constructors and destructor*/
-/*FUNCTION Matpar::Matpar() {{{*/
-Matpar::Matpar(){
+Matpar::Matpar(){/*{{{*/
 	return;
 }
 /*}}}*/
-/*FUNCTION Matpar::Matpar(int matpar_mid,IoModel* iomodel){{{*/
-Matpar::Matpar(int matpar_mid, IoModel* iomodel){
+Matpar::Matpar(int matpar_mid, IoModel* iomodel){/*{{{*/
 
 	bool isefficientlayer;
@@ -56,4 +54,10 @@
 			/*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");
@@ -88,6 +92,5 @@
 }
 /*}}}*/
-/*FUNCTION Matpar::~Matpar() {{{*/
-Matpar::~Matpar(){
+Matpar::~Matpar(){/*{{{*/
 	return;
 }
@@ -95,6 +98,5 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION Matpar::Echo {{{*/
-void Matpar::Echo(void){
+void Matpar::Echo(void){/*{{{*/
 
 	_printf_("Matpar:\n");
@@ -119,15 +121,12 @@
 }
 /*}}}*/
-/*FUNCTION Matpar::DeepEcho {{{*/
-void Matpar::DeepEcho(void){
+void Matpar::DeepEcho(void){/*{{{*/
 
 	this->Echo();
 }		
 /*}}}*/
-/*FUNCTION Matpar::Id {{{*/
-int    Matpar::Id(void){ return mid; }
-/*}}}*/
-/*FUNCTION Matpar::ObjectEnum{{{*/
-int Matpar::ObjectEnum(void){
+int    Matpar::Id(void){ return mid; }/*{{{*/
+/*}}}*/
+int Matpar::ObjectEnum(void){/*{{{*/
 
 	return MatparEnum;
@@ -135,28 +134,65 @@
 }
 /*}}}*/
-/*FUNCTION Matpar::copy {{{*/
-Object* Matpar::copy() {
-	return new Matpar(*this); 
+Object* Matpar::copy() {/*{{{*/
+
+	/*Output*/
+	Matpar* matpar;
+
+	/*Initialize output*/
+	matpar=new Matpar(*this);
+
+	/*copy fields: */
+	matpar->mid=this->mid;
+	matpar->rho_ice=this->rho_ice;
+	matpar->rho_water=this->rho_water;
+	matpar->rho_freshwater=this->rho_freshwater;
+	matpar->mu_water=this->mu_water;
+	matpar->heatcapacity=this->heatcapacity;
+	matpar->thermalconductivity=this->thermalconductivity;
+	matpar->temperateiceconductivity=this->temperateiceconductivity;
+	matpar->latentheat=this->latentheat;
+	matpar->beta=this->beta;
+	matpar->meltingpoint=this->meltingpoint;
+	matpar->referencetemperature=this->referencetemperature;
+	matpar->mixed_layer_capacity=this->mixed_layer_capacity;
+	matpar->thermal_exchange_velocity=this->thermal_exchange_velocity;
+	matpar->g=this->g;
+	matpar->desfac=this->desfac;
+	matpar->s0p=this->s0p;
+
+	matpar->sediment_compressibility=this->sediment_compressibility;
+	matpar->sediment_porosity=this->sediment_porosity;
+	matpar->sediment_thickness=this->sediment_thickness;
+	matpar->water_compressibility=this->water_compressibility;
+
+	matpar->epl_compressibility=this->epl_compressibility;
+	matpar->epl_porosity=this->epl_porosity;
+	matpar->epl_init_thickness=this->epl_init_thickness;
+	matpar->epl_max_thickness=this->epl_max_thickness;
+	matpar->epl_conductivity=this->epl_conductivity;
+
+	matpar->lithosphere_shear_modulus=this->lithosphere_shear_modulus;
+	matpar->lithosphere_density=this->lithosphere_density;
+	matpar->mantle_shear_modulus=this->mantle_shear_modulus;
+	matpar->mantle_density=this->mantle_density;
+
+	return matpar;
 }
 /*}}}*/
 
 /*Update virtual functions definitions:*/
-/*FUNCTION Matpar::InputUpdateFromVector(IssmDouble* vector, int name, int type) {{{*/
-void   Matpar::InputUpdateFromVector(IssmDouble* vector, int name, int type){
+void   Matpar::InputUpdateFromVector(IssmDouble* vector, int name, int type){/*{{{*/
 	/*Nothing updated yet*/
 }
 /*}}}*/
-/*FUNCTION Matpar::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type) {{{*/
-void   Matpar::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){
+void   Matpar::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){/*{{{*/
 	/*Nothing updated yet*/
 }
 /*}}}*/
-/*FUNCTION Matpar::InputUpdateFromMatrixDakota(IssmDouble* vector, int name, int type) {{{*/
-void  Matpar::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols,int name, int type){
+void  Matpar::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols,int name, int type){/*{{{*/
 	/*Nothing updated yet*/
 }
 /*}}}*/
-/*FUNCTION Matpar::InputUpdateFromConstant(IssmDouble constant, int name) {{{*/
-void   Matpar::InputUpdateFromConstant(IssmDouble constant, int name){
+void   Matpar::InputUpdateFromConstant(IssmDouble constant, int name){/*{{{*/
 
 	switch(name){
@@ -215,11 +251,9 @@
 }
 /*}}}*/
-/*FUNCTION Matpar::InputUpdateFromConstant(int constant, int name) {{{*/
-void   Matpar::InputUpdateFromConstant(int constant, int name){
+void   Matpar::InputUpdateFromConstant(int constant, int name){/*{{{*/
 	/*Nothing updated yet*/
 }
 /*}}}*/
-/*FUNCTION Matpar::InputUpdateFromConstant(bool constant, int name) {{{*/
-void   Matpar::InputUpdateFromConstant(bool constant, int name){
+void   Matpar::InputUpdateFromConstant(bool constant, int name){/*{{{*/
 	/*Nothing updated yet*/
 }
@@ -227,6 +261,5 @@
 
 /*Matpar management: */
-/*FUNCTION Matpar::Configure {{{*/
-void  Matpar::Configure(Elements* elementsin){
+void  Matpar::Configure(Elements* elementsin){/*{{{*/
 
 	/*nothing done yet!*/
@@ -234,6 +267,5 @@
 }
 /*}}}*/
-/*FUNCTION Matpar::Configure {{{*/
-IssmDouble Matpar::GetMaterialParameter(int enum_in){
+IssmDouble Matpar::GetMaterialParameter(int enum_in){/*{{{*/
 
 	switch(enum_in){
@@ -266,57 +298,46 @@
 }
 /*}}}*/
-/*FUNCTION Matpar::GetBeta {{{*/
-IssmDouble Matpar::GetBeta(){
+IssmDouble Matpar::GetBeta(){/*{{{*/
 	return beta;
 }
 /*}}}*/
-/*FUNCTION Matpar::GetG {{{*/
-IssmDouble Matpar::GetG(){
+IssmDouble Matpar::GetG(){/*{{{*/
 	return g;
 }
 /*}}}*/
-/*FUNCTION Matpar::GetMeltingPoint {{{*/
-IssmDouble Matpar::GetMeltingPoint(){
+IssmDouble Matpar::GetMeltingPoint(){/*{{{*/
 	return meltingpoint;
 }
 /*}}}*/
-/*FUNCTION Matpar::GetRhoIce {{{*/
-IssmDouble Matpar::GetRhoIce(){
+IssmDouble Matpar::GetRhoIce(){/*{{{*/
 
 	return rho_ice;
 }
 /*}}}*/
-/*FUNCTION Matpar::GetRhoWater {{{*/
-IssmDouble Matpar::GetRhoWater(){
+IssmDouble Matpar::GetRhoWater(){/*{{{*/
 	return rho_water;
 }
 /*}}}*/
-/*FUNCTION Matpar::GetRhoFreshwater {{{*/
-IssmDouble Matpar::GetRhoFreshwater(){
+IssmDouble Matpar::GetRhoFreshwater(){/*{{{*/
 	return rho_freshwater;
 }
 /*}}}*/
-/*FUNCTION Matpar::GetDesFac {{{*/
-IssmDouble Matpar::GetDesFac(){
+IssmDouble Matpar::GetDesFac(){/*{{{*/
 	return desfac;
 }
 /*}}}*/
-/*FUNCTION Matpar::GetS0p {{{*/
-IssmDouble Matpar::GetS0p(){
+IssmDouble Matpar::GetS0p(){/*{{{*/
 	return s0p;
 }
 /*}}}*/
-/*FUNCTION Matpar::TMeltingPoint {{{*/
-IssmDouble Matpar::TMeltingPoint(IssmDouble pressure){
+IssmDouble Matpar::TMeltingPoint(IssmDouble pressure){/*{{{*/
 	return meltingpoint-beta*pressure;
 }
 /*}}}*/
-/*FUNCTION Matpar::PureIceEnthalpy{{{*/
-IssmDouble Matpar::PureIceEnthalpy(IssmDouble pressure){
+IssmDouble Matpar::PureIceEnthalpy(IssmDouble pressure){/*{{{*/
 	return heatcapacity*(TMeltingPoint(pressure)-referencetemperature);
 }
 /*}}}*/
-/*FUNCTION Matpar::GetEnthalpyDiffusionParameter{{{*/
-IssmDouble Matpar::GetEnthalpyDiffusionParameter(IssmDouble enthalpy,IssmDouble pressure){
+IssmDouble Matpar::GetEnthalpyDiffusionParameter(IssmDouble enthalpy,IssmDouble pressure){/*{{{*/
 	if (enthalpy<PureIceEnthalpy(pressure))
 		return thermalconductivity/heatcapacity;
@@ -325,6 +346,5 @@
 }
 /*}}}*/
-/*FUNCTION Matpar::GetEnthalpyDiffusionParameterVolume{{{*/
-IssmDouble Matpar::GetEnthalpyDiffusionParameterVolume(int numvertices,IssmDouble* enthalpy,IssmDouble* pressure){
+IssmDouble Matpar::GetEnthalpyDiffusionParameterVolume(int numvertices,IssmDouble* enthalpy,IssmDouble* pressure){/*{{{*/
 
 	int         iv;
@@ -372,6 +392,5 @@
 }
 /*}}}*/
-/*FUNCTION Matpar::EnthalpyToThermal {{{*/
-void Matpar::EnthalpyToThermal(IssmDouble* ptemperature,IssmDouble* pwaterfraction,IssmDouble enthalpy,IssmDouble pressure){
+void Matpar::EnthalpyToThermal(IssmDouble* ptemperature,IssmDouble* pwaterfraction,IssmDouble enthalpy,IssmDouble pressure){/*{{{*/
 
 	/*Ouput*/
@@ -392,6 +411,5 @@
 }
 /*}}}*/
-/*FUNCTION Matpar::ThermalToEnthalpy {{{*/
-void Matpar::ThermalToEnthalpy(IssmDouble * penthalpy,IssmDouble temperature,IssmDouble waterfraction,IssmDouble pressure){
+void Matpar::ThermalToEnthalpy(IssmDouble * penthalpy,IssmDouble temperature,IssmDouble waterfraction,IssmDouble pressure){/*{{{*/
 
 	/*Ouput*/
@@ -409,22 +427,24 @@
 }
 /*}}}*/
-/*FUNCTION Matpar::GetLithosphereShearModulus {{{*/			 
-IssmDouble Matpar::GetLithosphereShearModulus(){		 
+IssmDouble Matpar::GetLithosphereShearModulus(){		 /*{{{*/
 	return lithosphere_shear_modulus;			 
 }		 
 /*}}}*/ 
-/*FUNCTION Matpar::GetLithosphereDensity {{{*/			 
-IssmDouble Matpar::GetLithosphereDensity(){		 
+IssmDouble Matpar::GetLithosphereDensity(){		 /*{{{*/
 	return lithosphere_density;			 
 }		 
 /*}}}*/ 
-/*FUNCTION Matpar::GetMantleDensity {{{*/			 
-IssmDouble Matpar::GetMantleDensity(){		 
+IssmDouble Matpar::GetMantleDensity(){		 /*{{{*/
 	return mantle_density;			 
 }		 
 /*}}}*/ 
-/*FUNCTION Matpar::GetMantleShearModulus {{{*/			 
-IssmDouble Matpar::GetMantleShearModulus(){		 
+IssmDouble Matpar::GetMantleShearModulus(){		 /*{{{*/
 	return mantle_shear_modulus;			 
 }		 
 /*}}}*/ 
+void  Matpar::ResetHooks(){/*{{{*/
+
+	//Nothing to be done
+	return;
+}
+/*}}}*/
Index: issm/trunk/src/c/classes/Materials/Matpar.h
===================================================================
--- issm/trunk/src/c/classes/Materials/Matpar.h	(revision 18081)
+++ issm/trunk/src/c/classes/Materials/Matpar.h	(revision 18301)
@@ -76,4 +76,6 @@
 		void       Configure(Elements* elements);
 		void       GetViscosity(IssmDouble* pviscosity,IssmDouble eps_eff){_error_("not supported");};
+		void       GetViscosity_B(IssmDouble* pviscosity,IssmDouble eps_eff){_error_("not supported");};
+		void       GetViscosity_D(IssmDouble* pviscosity,IssmDouble eps_eff){_error_("not supported");};
 		void       GetViscosityBar(IssmDouble* pviscosity,IssmDouble eps_eff){_error_("not supported");};
 		void       GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon){_error_("not supported");};
@@ -89,4 +91,5 @@
 		IssmDouble GetDbar(){_error_("not supported");};
 		bool       IsDamage(){_error_("not supported");};
+		void       ResetHooks();
 		/*}}}*/
 		/*Numerics: {{{*/
Index: issm/trunk/src/c/classes/Misfit.h
===================================================================
--- issm/trunk/src/c/classes/Misfit.h	(revision 18081)
+++ issm/trunk/src/c/classes/Misfit.h	(revision 18301)
@@ -31,6 +31,5 @@
 		
 		/*Misfit constructors, destructors :*/
-		/*FUNCTION Misfit() {{{*/
-		Misfit(){
+		Misfit(){/*{{{*/
 
 			this->name = NULL;
@@ -44,6 +43,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Misfit(char* in_name, int in_model_enum, int in_observation_enum char* in_timeinterpolation, int in_weights_enum) {{{*/
-		Misfit(char* in_name, int in_model_enum, int in_observation_enum, char* in_timeinterpolation, int in_weights_enum){
+		Misfit(char* in_name, int in_model_enum, int in_observation_enum, char* in_timeinterpolation, int in_weights_enum){/*{{{*/
 
 			this->name   = xNew<char>(strlen(in_name)+1);
@@ -61,6 +59,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION ~Misfit() {{{*/
-		~Misfit(){
+		~Misfit(){/*{{{*/
 			if(this->name)xDelete(this->name);
 			if(this->timeinterpolation)xDelete(this->timeinterpolation);
@@ -70,6 +67,5 @@
 		/*}}}*/
 		/*Object virtual function resolutoin: */
-		/*FUNCTION Echo(){{{*/
-		void Echo(void){
+		void Echo(void){/*{{{*/
 			_printf_(" Misfit: " << name << "\n");
 			_printf_("    model_enum: " << model_enum << " " << EnumToStringx(model_enum) << "\n");
@@ -79,27 +75,25 @@
 		}
 		/*}}}*/
-		/*FUNCTION DeepEcho(){{{*/
-		void DeepEcho(void){
+		void DeepEcho(void){/*{{{*/
 			this->Echo();
 		}
 		/*}}}*/
-		/*FUNCTION Id(){{{*/
-		int Id(void){
+		int Id(void){/*{{{*/
 			return -1;
 		}
 		/*}}}*/
-		/*FUNCTION ObjectEnum{{{*/
-		int ObjectEnum(void){
+		int ObjectEnum(void){/*{{{*/
 			return MisfitEnum;
 		}
 		/*}}}*/
-		/*FUNCTION copy {{{*/
-		Object* copy() {
-			return new Misfit(this->name,this->model_enum,this->observation_enum,this->timeinterpolation,this->weights_enum);
+		Object* copy() {/*{{{*/
+			Misfit* mf = new Misfit(this->name,this->model_enum,this->observation_enum,this->timeinterpolation,this->weights_enum);
+			mf->misfit=this->misfit;
+			mf->lock=this->lock;
+			return (Object*) mf;
 		}
 		/*}}}*/
 		/*Definition virtual function resolutoin: */
-		/*FUNCTION char* Name() {{{*/
-		char* Name(){
+		char* Name(){/*{{{*/
 
 			char* name2=xNew<char>(strlen(this->name)+1);
@@ -109,6 +103,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION IssmDouble Response(FemModel* femmodel) {{{*/
-		 IssmDouble Response(FemModel* femmodel){
+		 IssmDouble Response(FemModel* femmodel){/*{{{*/
 
 			 int i;
Index: issm/trunk/src/c/classes/Node.cpp
===================================================================
--- issm/trunk/src/c/classes/Node.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Node.cpp	(revision 18301)
@@ -17,11 +17,9 @@
 
 /*Node constructors and destructors:*/
-/*FUNCTION Node::Node() default constructor {{{*/
-Node::Node(){
+Node::Node(){/*{{{*/
 	this->approximation=0;
 }
 /*}}}*/
-/*FUNCTION Node::Node(int node_id,int node_sid,int node_lid,int io_index, IoModel* iomodel,int analysis_enum,int approximation) {{{*/
-Node::Node(int node_id,int node_sid,int node_lid,int io_index, IoModel* iomodel,int analysis_enum,int in_approximation){
+Node::Node(int node_id,int node_sid,int node_lid,int io_index, IoModel* iomodel,int analysis_enum,int in_approximation){/*{{{*/
 
 	/*Intermediary*/
@@ -123,13 +121,38 @@
 }
 /*}}}*/
-/*FUNCTION Node::~Node(){{{*/
-Node::~Node(){
+Node::~Node(){/*{{{*/
 	return;
 }
 /*}}}*/
+Object* Node::copy(void){/*{{{*/
+
+	int k,l;
+
+	/*output: */
+	Node* output=NULL;
+
+	/*initalize output: */
+	output=new Node();
+
+	/*id: */
+	output->id  = this->id;
+	output->sid = this->sid;
+	output->lid = this->lid;
+	output->analysis_enum = this->analysis_enum;
+	output->approximation = this->approximation;
+
+	/*Initialize coord_system: */
+	for(k=0;k<3;k++) for(l=0;l<3;l++) output->coord_system[k][l]=this->coord_system[k][l];
+
+	/*indexing:*/
+	output->indexingupdate = this->indexingupdate;
+	output->indexing.copy(this->indexing);
+
+	return (Object*)output; 
+}
+/*}}}*/
 
 /*Object virtual functions definitions:*/
-/*FUNCTION Node::Echo{{{*/
-void Node::Echo(void){
+void Node::Echo(void){/*{{{*/
 
 	_printf_("Node:\n");
@@ -143,6 +166,5 @@
 }
 /*}}}*/
-/*FUNCTION Node::DeepEcho{{{*/
-void Node::DeepEcho(void){
+void Node::DeepEcho(void){/*{{{*/
 
 	_printf_("Node:\n");
@@ -156,9 +178,7 @@
 }
 /*}}}*/
-/*FUNCTION Node::Id{{{*/
-int    Node::Id(void){ return id; }
-/*}}}*/
-/*FUNCTION Node::ObjectEnum{{{*/
-int Node::ObjectEnum(void){
+int  Node::Id(void){ return id; }/*{{{*/
+/*}}}*/
+int  Node::ObjectEnum(void){/*{{{*/
 
 	return NodeEnum;
@@ -168,6 +188,5 @@
 
 /*Node management:*/
-/*FUNCTION Node::GetDof {{{*/
-int   Node::GetDof(int dofindex,int setenum){
+int  Node::GetDof(int dofindex,int setenum){/*{{{*/
 
 	_assert_(!this->indexingupdate);
@@ -187,6 +206,5 @@
 
 } /*}}}*/
-/*FUNCTION Node::GetDofList{{{*/
-void  Node::GetDofList(int* outdoflist,int approximation_enum,int setenum){
+void Node::GetDofList(int* outdoflist,int approximation_enum,int setenum){/*{{{*/
 	int i;
 	int count=0;
@@ -251,6 +269,5 @@
 }
 /*}}}*/
-/*FUNCTION Node::GetLocalDofList{{{*/
-void  Node::GetLocalDofList(int* outdoflist,int approximation_enum,int setenum){
+void Node::GetLocalDofList(int* outdoflist,int approximation_enum,int setenum){/*{{{*/
 	int i;
 	int count=0;
@@ -352,16 +369,13 @@
 }
 /*}}}*/
-/*FUNCTION Node::Sid{{{*/
-int Node::Sid(void){
+int  Node::Sid(void){/*{{{*/
 	return sid; 
 }
 /*}}}*/
-/*FUNCTION Node::Lid{{{*/
-int  Node::Lid(void){
+int  Node::Lid(void){/*{{{*/
 	return lid; 
 }
 /*}}}*/
-/*FUNCTION Node::GetCoordinateSystem{{{*/
-void Node::GetCoordinateSystem(IssmDouble* coord_system_out){
+void Node::GetCoordinateSystem(IssmDouble* coord_system_out){/*{{{*/
 
 	/*Copy coord_system*/
@@ -370,6 +384,5 @@
 }
 /*}}}*/
-/*FUNCTION Node::InAnalysis{{{*/
-bool Node::InAnalysis(int in_analysis_enum){
+bool Node::InAnalysis(int in_analysis_enum){/*{{{*/
 	if (in_analysis_enum==this->analysis_enum) return true;
 	else return false;
@@ -378,6 +391,5 @@
 
 /*Node numerics:*/
-/*FUNCTION Node::ApplyConstraints{{{*/
-void  Node::ApplyConstraint(int dof,IssmDouble value){
+void Node::ApplyConstraint(int dof,IssmDouble value){/*{{{*/
 
 	/*Dof should be added in the s set, describing which 
@@ -387,6 +399,5 @@
 }
 /*}}}*/
-/*FUNCTION Node::RequiresDofReindexing{{{*/
-bool Node::RequiresDofReindexing(void){
+bool Node::RequiresDofReindexing(void){/*{{{*/
 
 	return this->indexingupdate;
@@ -394,6 +405,5 @@
 }
 /*}}}*/
-/*FUNCTION Node::ReindexingDone{{{*/
-void Node::ReindexingDone(void){
+void Node::ReindexingDone(void){/*{{{*/
 
 	this->indexingupdate = false;
@@ -401,6 +411,5 @@
 }
 /*}}}*/
-/*FUNCTION Node::RelaxConstraint{{{*/
-void  Node::RelaxConstraint(int dof){
+void Node::RelaxConstraint(int dof){/*{{{*/
 
 	/*Dof should be added to the f-set, and taken out of the s-set:*/
@@ -409,6 +418,5 @@
 }
 /*}}}*/
-/*FUNCTION Node::CreateNodalConstraints{{{*/
-void  Node::CreateNodalConstraints(Vector<IssmDouble>* ys){
+void Node::CreateNodalConstraints(Vector<IssmDouble>* ys){/*{{{*/
 
 	int i;
@@ -437,6 +445,5 @@
 }
 /*}}}*/
-/*FUNCTION Node::DofInSSet {{{*/
-void  Node::DofInSSet(int dof){
+void Node::DofInSSet(int dof){/*{{{*/
 
 	/*Put dof for this node into the s set (ie, this dof will be constrained 
@@ -451,6 +458,5 @@
 }
 /*}}}*/
-/*FUNCTION Node::DofInFSet {{{*/
-void  Node::DofInFSet(int dof){
+void Node::DofInFSet(int dof){/*{{{*/
 
 	/*Put dof for this node into the f set (ie, this dof will NOT be constrained 
@@ -465,6 +471,5 @@
 }
 /*}}}*/
-/*FUNCTION Node::FreezeDof{{{*/
-void  Node::FreezeDof(int dof){
+void Node::FreezeDof(int dof){/*{{{*/
 
 	DofInSSet(dof); //with 0 displacement for this dof.
@@ -472,6 +477,5 @@
 }
 /*}}}*/
-/*FUNCTION Node::Deactivate{{{*/
-void  Node::Deactivate(void){
+void Node::Deactivate(void){/*{{{*/
 
 	if(IsActive()){
@@ -482,6 +486,5 @@
 }
 /*}}}*/
-/*FUNCTION Node::Activate{{{*/
-void  Node::Activate(void){
+void Node::Activate(void){/*{{{*/
 
 	if(!IsActive()){
@@ -492,6 +495,5 @@
 }
 /*}}}*/
-/*FUNCTION Node::IsActive{{{*/
-bool Node::IsActive(void){
+bool Node::IsActive(void){/*{{{*/
 
 	return indexing.active;
@@ -499,12 +501,10 @@
 }
 /*}}}*/
-/*FUNCTION Node::GetApproximation {{{*/
-int   Node::GetApproximation(){
+int  Node::GetApproximation(){/*{{{*/
 
 	return approximation;
 }
 /*}}}*/
-/*FUNCTION Node::GetNumberOfDofs{{{*/
-int   Node::GetNumberOfDofs(int approximation_enum,int setenum){
+int  Node::GetNumberOfDofs(int approximation_enum,int setenum){/*{{{*/
 
 	/*Get number of degrees of freedom in a node, for a certain set (g,f or s-set)
@@ -541,5 +541,5 @@
 		else if (setenum==SsetEnum){
 			if(this->indexing.doftype){
-				numdofs=0;
+			numdofs=0;
 				for(i=0;i<this->indexing.gsize;i++){
 					if((this->indexing.doftype[i]==approximation_enum) && (this->indexing.s_set[i])) numdofs++;
@@ -553,6 +553,5 @@
 }
 /*}}}*/
-/*FUNCTION Node::IsClone {{{*/
-int   Node::IsClone(){
+int  Node::IsClone(){/*{{{*/
 
 	return indexing.clone;
@@ -560,6 +559,5 @@
 }
 /*}}}*/
-/*FUNCTION Node::VecMerge {{{*/
-void Node::VecMerge(Vector<IssmDouble>* ug, IssmDouble* vector_serial,int setenum){
+void Node::VecMerge(Vector<IssmDouble>* ug, IssmDouble* vector_serial,int setenum){/*{{{*/
 
 	IssmDouble *values  = NULL;
@@ -611,6 +609,5 @@
 }
 /*}}}*/
-/*FUNCTION Node::VecReduce {{{*/
-void   Node::VecReduce(Vector<IssmDouble>* vector, IssmDouble* ug_serial,int setenum){
+void Node::VecReduce(Vector<IssmDouble>* vector, IssmDouble* ug_serial,int setenum){/*{{{*/
 
 	IssmDouble* values=NULL;
@@ -658,6 +655,5 @@
 
 /* indexing routines:*/
-/*FUNCTION Node::DistributeDofs{{{*/
-void  Node::DistributeDofs(int* pdofcount,int setenum){
+void Node::DistributeDofs(int* pdofcount,int setenum){/*{{{*/
 
 	int i;
@@ -700,6 +696,5 @@
 }
 /*}}}*/
-/*FUNCTION Node::OffsetDofs{{{*/
-void  Node::OffsetDofs(int dofcount,int setenum){
+void Node::OffsetDofs(int dofcount,int setenum){/*{{{*/
 
 	int i;
@@ -723,6 +718,5 @@
 }
 /*}}}*/
-/*FUNCTION Node::ShowTrueDofs{{{*/
-void  Node::ShowTrueDofs(int* truedofs, int ncols,int setenum){
+void Node::ShowTrueDofs(int* truedofs, int ncols,int setenum){/*{{{*/
 
 	int j;
@@ -748,6 +742,5 @@
 }
 /*}}}*/
-/*FUNCTION Node::UpdateCloneDofs{{{*/
-void  Node::UpdateCloneDofs(int* alltruedofs,int ncols,int setenum){
+void Node::UpdateCloneDofs(int* alltruedofs,int ncols,int setenum){/*{{{*/
 
 	int j;
@@ -773,6 +766,5 @@
 }
 /*}}}*/
-/*FUNCTION Node::SetClone {{{*/
-void  Node::SetClone(int* minranks){
+void Node::SetClone(int* minranks){/*{{{*/
 
 	int my_rank;
Index: issm/trunk/src/c/classes/Node.h
===================================================================
--- issm/trunk/src/c/classes/Node.h	(revision 18081)
+++ issm/trunk/src/c/classes/Node.h	(revision 18301)
@@ -49,5 +49,5 @@
 		int     Id();
 		int     ObjectEnum();
-		Object *copy(){_error_("Not implemented yet (similar to Elements)"); };
+		Object *copy();
 
 		/*Node numerical routines*/
Index: issm/trunk/src/c/classes/Nodes.cpp
===================================================================
--- issm/trunk/src/c/classes/Nodes.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Nodes.cpp	(revision 18301)
@@ -19,12 +19,10 @@
 
 /*Object constructors and destructor*/
-/*FUNCTION Nodes::Nodes(){{{*/
-Nodes::Nodes(){
+Nodes::Nodes(){/*{{{*/
 	enum_type=NodesEnum;
 	return;
 }
 /*}}}*/
-/*FUNCTION Nodes::~Nodes(){{{*/
-Nodes::~Nodes(){
+Nodes::~Nodes(){/*{{{*/
 	return;
 }
@@ -32,6 +30,5 @@
 
 /*Numerics*/
-/*FUNCTION Nodes::DistributeDofs{{{*/
-void  Nodes::DistributeDofs(int analysis_type,int setenum){
+void  Nodes::DistributeDofs(int analysis_type,int setenum){/*{{{*/
 
 	int  i;
@@ -122,6 +119,5 @@
 }
 /*}}}*/
-/*FUNCTION Nodes::FlagClones{{{*/
-void  Nodes::FlagClones(int analysis_type){
+void  Nodes::FlagClones(int analysis_type){/*{{{*/
 
 	int i;
@@ -168,6 +164,5 @@
 }
 /*}}}*/
-/*FUNCTION Nodes::MaxNumDofs{{{*/
-int   Nodes::MaxNumDofs(int analysis_type,int setenum){
+int   Nodes::MaxNumDofs(int analysis_type,int setenum){/*{{{*/
 
 	int max=0;
@@ -194,6 +189,5 @@
 }
 /*}}}*/
-/*FUNCTION Nodes::MaximymId{{{*/
-int Nodes::MaximumId(){
+int   Nodes::MaximumId(){/*{{{*/
 
 	int max=-1;
@@ -225,6 +219,5 @@
 }
 /*}}}*/
-/*FUNCTION Nodes::NumberOfDofs{{{*/
-int   Nodes::NumberOfDofs(int analysis_type,int setenum){
+int   Nodes::NumberOfDofs(int analysis_type,int setenum){/*{{{*/
 
 	int   allnumdofs;
@@ -238,6 +231,5 @@
 }
 /*}}}*/
-/*FUNCTION Nodes::NumberOfDofsLocal{{{*/
-int   Nodes::NumberOfDofsLocal(int analysis_type,int setenum){
+int   Nodes::NumberOfDofsLocal(int analysis_type,int setenum){/*{{{*/
 
 	int   numdofs=0;
@@ -261,6 +253,5 @@
 }
 /*}}}*/
-/*FUNCTION Nodes::NumberOfNodes(){{{*/
-int Nodes::NumberOfNodes(void){
+int   Nodes::NumberOfNodes(void){/*{{{*/
 
 	/*Careful! only use once all clones have been setup for all nodes!: */
@@ -283,6 +274,5 @@
 }
 /*}}}*/
-/*FUNCTION Nodes::NumberOfNodes(analysis){{{*/
-int Nodes::NumberOfNodes(int analysis_type){
+int   Nodes::NumberOfNodes(int analysis_type){/*{{{*/
 
 	int i;
@@ -315,6 +305,5 @@
 }
 /*}}}*/
-/*FUNCTION Nodes::Ranks{{{*/
-void   Nodes::Ranks(int* ranks,int analysis_type){
+void  Nodes::Ranks(int* ranks,int analysis_type){/*{{{*/
 
 	int my_rank;
@@ -338,6 +327,5 @@
 }
 /*}}}*/
-/*FUNCTION Nodes::RequiresDofReindexing{{{*/
-bool Nodes::RequiresDofReindexing(int analysis_type){
+bool Nodes::RequiresDofReindexing(int analysis_type){/*{{{*/
 
 	int flag = 0;
Index: issm/trunk/src/c/classes/Options/OptionUtilities.cpp
===================================================================
--- issm/trunk/src/c/classes/Options/OptionUtilities.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Options/OptionUtilities.cpp	(revision 18301)
@@ -15,6 +15,5 @@
 /*}}}*/
 
-/*FUNCTION ColumnWiseDimsFromIndex{{{*/
-int ColumnWiseDimsFromIndex(int* dims,int index,int* size,int ndims){
+int ColumnWiseDimsFromIndex(int* dims,int index,int* size,int ndims){/*{{{*/
 
 	int   i;
@@ -34,6 +33,5 @@
 	return(0);
 }/*}}}*/
-/*FUNCTION IndexFromColumnWiseDims{{{*/
-int IndexFromColumnWiseDims(int* dims, int* size, int ndims) {
+int IndexFromColumnWiseDims(int* dims, int* size, int ndims) {/*{{{*/
 
 	int   i;
@@ -53,6 +51,5 @@
 	return(index);
 }/*}}}*/
-/*FUNCTION RowWiseDimsFromIndex{{{*/
-int RowWiseDimsFromIndex(int* dims, int index, int* size, int ndims) {
+int RowWiseDimsFromIndex(int* dims, int index, int* size, int ndims) {/*{{{*/
 
 	int   i;
@@ -72,6 +69,5 @@
 	return(0);
 }/*}}}*/
-/*FUNCTION IndexFromRowWiseDims{{{*/
-int IndexFromRowWiseDims(int* dims, int* size, int ndims) {
+int IndexFromRowWiseDims(int* dims, int* size, int ndims) {/*{{{*/
 
 	int   i;
@@ -91,6 +87,5 @@
 	return(index);
 }/*}}}*/
-/*FUNCTION StringFromDims{{{*/
-int StringFromDims(char* cstr, int* dims, int ndims) {
+int StringFromDims(char* cstr, int* dims, int ndims) {/*{{{*/
 
 	sprintf(&cstr[0],"[");
@@ -100,6 +95,5 @@
 	return(0);
 }/*}}}*/
-/*FUNCTION StringFromSize{{{*/
-int StringFromSize(char* cstr, int* size, int ndims) {
+int StringFromSize(char* cstr, int* size, int ndims) {/*{{{*/
 
 	sprintf(&cstr[0],"[");
Index: issm/trunk/src/c/classes/Options/Options.cpp
===================================================================
--- issm/trunk/src/c/classes/Options/Options.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Options/Options.cpp	(revision 18301)
@@ -21,11 +21,9 @@
 
 /*Object constructors and destructor*/
-/*FUNCTION Options::Options(){{{*/
-Options::Options(){
+Options::Options(){/*{{{*/
 	return;
 }
 /*}}}*/
-/*FUNCTION Options::~Options(){{{*/
-Options::~Options(){
+Options::~Options(){/*{{{*/
 	return;
 }
@@ -33,6 +31,5 @@
 
 /*Object management*/
-/*FUNCTION Options::AddOption{{{*/
-int  Options::AddOption(Option* in_option){
+int  Options::AddOption(Option* in_option){/*{{{*/
 
 	char* name=NULL;
@@ -68,6 +65,5 @@
 }
 /*}}}*/
-/*FUNCTION Options::GetOption{{{*/
-Option* Options::GetOption(const char* name){
+Option* Options::GetOption(const char* name){/*{{{*/
 
 	vector<Object*>::iterator object;
Index: issm/trunk/src/c/classes/Params/BoolParam.cpp
===================================================================
--- issm/trunk/src/c/classes/Params/BoolParam.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Params/BoolParam.cpp	(revision 18301)
@@ -16,11 +16,9 @@
 
 /*BoolParam constructors and destructor*/
-/*FUNCTION BoolParam::BoolParam(){{{*/
-BoolParam::BoolParam(){
+BoolParam::BoolParam(){/*{{{*/
 	return;
 }
 /*}}}*/
-/*FUNCTION BoolParam::BoolParam(int enum_type,bool value){{{*/
-BoolParam::BoolParam(int in_enum_type,bool in_value){
+BoolParam::BoolParam(int in_enum_type,bool in_value){/*{{{*/
 
 	enum_type=in_enum_type;
@@ -28,6 +26,5 @@
 }
 /*}}}*/
-/*FUNCTION BoolParam::~BoolParam(){{{*/
-BoolParam::~BoolParam(){
+BoolParam::~BoolParam(){/*{{{*/
 	return;
 }
@@ -35,19 +32,15 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION BoolParam::Echo {{{*/
-void BoolParam::Echo(void){
+void BoolParam::Echo(void){/*{{{*/
 	this->DeepEcho();
 }
 /*}}}*/
-/*FUNCTION BoolParam::DeepEcho{{{*/
-void BoolParam::DeepEcho(void){
+void BoolParam::DeepEcho(void){/*{{{*/
 	_printf_(setw(22)<<"   BoolParam "<<setw(35)<<left<<EnumToStringx(this->enum_type)<<" "<<(value?"true":"false")<<"\n");
 }
 /*}}}*/
-/*FUNCTION BoolParam::Id{{{*/
-int    BoolParam::Id(void){ return -1; }
+int    BoolParam::Id(void){ return -1; }/*{{{*/
 /*}}}*/
-/*FUNCTION BoolParam::ObjectEnum{{{*/
-int BoolParam::ObjectEnum(void){
+int BoolParam::ObjectEnum(void){/*{{{*/
 
 	return BoolParamEnum;
@@ -55,6 +48,5 @@
 }
 /*}}}*/
-/*FUNCTION BoolParam::copy{{{*/
-Object* BoolParam::copy() {
+Object* BoolParam::copy() {/*{{{*/
 
 	return new BoolParam(this->enum_type,this->value);
Index: issm/trunk/src/c/classes/Params/DataSetParam.cpp
===================================================================
--- issm/trunk/src/c/classes/Params/DataSetParam.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Params/DataSetParam.cpp	(revision 18301)
@@ -16,12 +16,10 @@
 
 /*DataSetParam constructors and destructor*/
-/*FUNCTION DataSetParam::DataSetParam(){{{*/
-DataSetParam::DataSetParam(){
+DataSetParam::DataSetParam(){/*{{{*/
 	value=NULL;
 	return;
 }
 /*}}}*/
-/*FUNCTION DataSetParam::DataSetParam(int enum_type,DataSet *value){{{*/
-DataSetParam::DataSetParam(int in_enum_type,DataSet* in_value){
+DataSetParam::DataSetParam(int in_enum_type,DataSet* in_value){/*{{{*/
 
 	enum_type=in_enum_type;
@@ -29,6 +27,5 @@
 }
 /*}}}*/
-/*FUNCTION DataSetParam::~DataSetParam(){{{*/
-DataSetParam::~DataSetParam(){
+DataSetParam::~DataSetParam(){/*{{{*/
 	delete value;
 }
@@ -36,11 +33,9 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION DataSetParam::Echo {{{*/
-void DataSetParam::Echo(void){
+void DataSetParam::Echo(void){/*{{{*/
 	this->DeepEcho();
 }
 /*}}}*/
-/*FUNCTION DataSetParam::DeepEcho{{{*/
-void DataSetParam::DeepEcho(void){
+void DataSetParam::DeepEcho(void){/*{{{*/
 
 	_printf_(setw(22)<<"   DataSetParam "<<setw(35)<<left<<EnumToStringx(this->enum_type)<<" ----- begin\n");
@@ -49,9 +44,7 @@
 }
 /*}}}*/
-/*FUNCTION DataSetParam::Id{{{*/
-int    DataSetParam::Id(void){ return -1; }
+int    DataSetParam::Id(void){ return -1; }/*{{{*/
 /*}}}*/
-/*FUNCTION DataSetParam::ObjectEnum{{{*/
-int DataSetParam::ObjectEnum(void){
+int DataSetParam::ObjectEnum(void){/*{{{*/
 
 	return DataSetParamEnum;
@@ -59,6 +52,5 @@
 }
 /*}}}*/
-/*FUNCTION DataSetParam::copy{{{*/
-Object* DataSetParam::copy() {
+Object* DataSetParam::copy() {/*{{{*/
 
 	return new DataSetParam(this->enum_type,this->value);
@@ -68,6 +60,5 @@
 
 /*DataSetParam virtual functions definitions: */
-/*FUNCTION DataSetParam::GetParameterValue{{{*/
-void DataSetParam::GetParameterValue(DataSet** pdataset){
+void DataSetParam::GetParameterValue(DataSet** pdataset){/*{{{*/
 	*pdataset=value->Copy();
 }
Index: issm/trunk/src/c/classes/Params/DoubleMatArrayParam.cpp
===================================================================
--- issm/trunk/src/c/classes/Params/DoubleMatArrayParam.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Params/DoubleMatArrayParam.cpp	(revision 18301)
@@ -16,11 +16,9 @@
 
 /*DoubleMatArrayParam constructors and destructor*/
-/*FUNCTION DoubleMatArrayParam::DoubleMatArrayParam(){{{*/
-DoubleMatArrayParam::DoubleMatArrayParam(){
+DoubleMatArrayParam::DoubleMatArrayParam(){/*{{{*/
 	return;
 }
 /*}}}*/
-/*FUNCTION DoubleMatArrayParam::DoubleMatArrayParam(int enum_type,IssmDouble** array, int M, int* mdim_array, int* ndim_array){{{*/
-DoubleMatArrayParam::DoubleMatArrayParam(int in_enum_type,IssmDouble** in_array, int in_M, int* in_mdim_array, int* in_ndim_array){
+DoubleMatArrayParam::DoubleMatArrayParam(int in_enum_type,IssmDouble** in_array, int in_M, int* in_mdim_array, int* in_ndim_array){/*{{{*/
 
 	int i;
@@ -59,6 +57,5 @@
 }
 /*}}}*/
-/*FUNCTION DoubleMatArrayParam::~DoubleMatArrayParam(){{{*/
-DoubleMatArrayParam::~DoubleMatArrayParam(){
+DoubleMatArrayParam::~DoubleMatArrayParam(){/*{{{*/
 
 	int i;
@@ -79,6 +76,5 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION DoubleMatArrayParam::Echo {{{*/
-void DoubleMatArrayParam::Echo(void){
+void DoubleMatArrayParam::Echo(void){/*{{{*/
 
 	_printf_("DoubleMatArrayParam:\n");
@@ -89,6 +85,5 @@
 }
 /*}}}*/
-/*FUNCTION DoubleMatArrayParam::DeepEcho{{{*/
-void DoubleMatArrayParam::DeepEcho(void){
+void DoubleMatArrayParam::DeepEcho(void){/*{{{*/
 
 	int i,j,k;
@@ -113,9 +108,7 @@
 }
 /*}}}*/
-/*FUNCTION DoubleMatArrayParam::Id{{{*/
-int    DoubleMatArrayParam::Id(void){ return -1; }
-/*}}}*/
-/*FUNCTION DoubleMatArrayParam::ObjectEnum{{{*/
-int DoubleMatArrayParam::ObjectEnum(void){
+int    DoubleMatArrayParam::Id(void){ return -1; }/*{{{*/
+/*}}}*/
+int DoubleMatArrayParam::ObjectEnum(void){/*{{{*/
 
 	return DoubleMatArrayParamEnum;
@@ -123,6 +116,5 @@
 }
 /*}}}*/
-/*FUNCTION DoubleMatArrayParam::copy{{{*/
-Object* DoubleMatArrayParam::copy() {
+Object* DoubleMatArrayParam::copy() {/*{{{*/
 
 	return new DoubleMatArrayParam(this->enum_type,this->array, this->M, this->mdim_array,this->ndim_array);
@@ -132,6 +124,5 @@
 
 /*DoubleMatArrayParam virtual functions definitions: */
-/*FUNCTION DoubleMatArrayParam::GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){{{*/
-void  DoubleMatArrayParam::GetParameterValue(IssmDouble*** pout_array, int* pout_M,int** pout_mdim_array, int** pout_ndim_array){
+void  DoubleMatArrayParam::GetParameterValue(IssmDouble*** pout_array, int* pout_M,int** pout_mdim_array, int** pout_ndim_array){/*{{{*/
 
 	int i,m,n;
@@ -183,6 +174,5 @@
 }
 /*}}}*/
-/*FUNCTION DoubleMatArrayParam::SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){{{*/
-void  DoubleMatArrayParam::SetValue(IssmDouble** in_array, int in_M, int* in_mdim_array, int* in_ndim_array){
+void  DoubleMatArrayParam::SetValue(IssmDouble** in_array, int in_M, int* in_mdim_array, int* in_ndim_array){/*{{{*/
 
 	int i,m,n;
Index: issm/trunk/src/c/classes/Params/DoubleMatParam.cpp
===================================================================
--- issm/trunk/src/c/classes/Params/DoubleMatParam.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Params/DoubleMatParam.cpp	(revision 18301)
@@ -16,11 +16,9 @@
 
 /*DoubleMatParam constructors and destructor*/
-/*FUNCTION DoubleMatParam::DoubleMatParam(){{{*/
-DoubleMatParam::DoubleMatParam(){
+DoubleMatParam::DoubleMatParam(){/*{{{*/
 	return;
 }
 /*}}}*/
-/*FUNCTION DoubleMatParam::DoubleMatParam(int enum_type,IssmDoubleMat value){{{*/
-DoubleMatParam::DoubleMatParam(int in_enum_type,IssmDouble* in_value, int in_M,int in_N){
+DoubleMatParam::DoubleMatParam(int in_enum_type,IssmDouble* in_value, int in_M,int in_N){/*{{{*/
 
 	enum_type=in_enum_type;
@@ -32,6 +30,5 @@
 }
 /*}}}*/
-/*FUNCTION DoubleMatParam::~DoubleMatParam(){{{*/
-DoubleMatParam::~DoubleMatParam(){
+DoubleMatParam::~DoubleMatParam(){/*{{{*/
 	xDelete<IssmDouble>(value);
 	return;
@@ -40,6 +37,5 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION DoubleMatParam::Echo {{{*/
-void DoubleMatParam::Echo(void){
+void DoubleMatParam::Echo(void){/*{{{*/
 
 	_printf_("DoubleMatParam:\n");
@@ -49,6 +45,5 @@
 }
 /*}}}*/
-/*FUNCTION DoubleMatParam::DeepEcho{{{*/
-void DoubleMatParam::DeepEcho(void){
+void DoubleMatParam::DeepEcho(void){/*{{{*/
 
 	int i,j;
@@ -64,9 +59,7 @@
 }
 /*}}}*/
-/*FUNCTION DoubleMatParam::Id{{{*/
-int    DoubleMatParam::Id(void){ return -1; }
+int    DoubleMatParam::Id(void){ return -1; }/*{{{*/
 /*}}}*/
-/*FUNCTION DoubleMatParam::ObjectEnum{{{*/
-int DoubleMatParam::ObjectEnum(void){
+int DoubleMatParam::ObjectEnum(void){/*{{{*/
 
 	return DoubleMatParamEnum;
@@ -74,6 +67,5 @@
 }
 /*}}}*/
-/*FUNCTION DoubleMatParam::copy{{{*/
-Object* DoubleMatParam::copy() {
+Object* DoubleMatParam::copy() {/*{{{*/
 
 	return new DoubleMatParam(this->enum_type,this->value,this->M,this->N);
@@ -83,6 +75,5 @@
 
 /*DoubleMatParam virtual functions definitions: */
-/*FUNCTION DoubleMatParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){{{*/
-void  DoubleMatParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){
+void  DoubleMatParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){/*{{{*/
 	IssmDouble* output=NULL;
 
@@ -96,11 +87,9 @@
 }
 /*}}}*/
-/*FUNCTION DoubleMatParam::GetParameterValue(int** pintarray,int* pM,int* pN){{{*/
-void  DoubleMatParam::GetParameterValue(int** pintarray,int* pM,int* pN){
+void  DoubleMatParam::GetParameterValue(int** pintarray,int* pM,int* pN){/*{{{*/
 	_error_("DoubleMat of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of int");
 }
 /*}}}*/
-/*FUNCTION DoubleMatParam::SetValue{{{*/
-void  DoubleMatParam::SetValue(IssmDouble* IssmDoublearray,int in_M,int in_N){
+void  DoubleMatParam::SetValue(IssmDouble* IssmDoublearray,int in_M,int in_N){/*{{{*/
 
 	/*avoid leak: */
Index: issm/trunk/src/c/classes/Params/DoubleParam.cpp
===================================================================
--- issm/trunk/src/c/classes/Params/DoubleParam.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Params/DoubleParam.cpp	(revision 18301)
@@ -13,11 +13,9 @@
 
 /*DoubleParam constructors and destructor*/
-/*FUNCTION DoubleParam::DoubleParam(){{{*/
-DoubleParam::DoubleParam(){
+DoubleParam::DoubleParam(){/*{{{*/
 	return;
 }
 /*}}}*/
-/*FUNCTION DoubleParam::DoubleParam(int enum_type,IssmDouble value){{{*/
-DoubleParam::DoubleParam(int in_enum_type,IssmDouble in_value){
+DoubleParam::DoubleParam(int in_enum_type,IssmDouble in_value){/*{{{*/
 
 	enum_type=in_enum_type;
@@ -25,6 +23,5 @@
 }
 /*}}}*/
-/*FUNCTION DoubleParam::~DoubleParam(){{{*/
-DoubleParam::~DoubleParam(){
+DoubleParam::~DoubleParam(){/*{{{*/
 	return;
 }
@@ -32,20 +29,16 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION DoubleParam::Echo {{{*/
-void DoubleParam::Echo(void){
+void DoubleParam::Echo(void){/*{{{*/
 	this->DeepEcho();
 }
 /*}}}*/
-/*FUNCTION DoubleParam::DeepEcho{{{*/
-void DoubleParam::DeepEcho(void){
+void DoubleParam::DeepEcho(void){/*{{{*/
 
 	_printf_(setw(22)<<"   DoubleParam "<<setw(35)<<left<<EnumToStringx(this->enum_type)<<" "<<this->value<<"\n");
 }
 /*}}}*/
-/*FUNCTION DoubleParam::Id{{{*/
-int    DoubleParam::Id(void){ return -1; }
+int  DoubleParam::Id(void){ return -1; }/*{{{*/
 /*}}}*/
-/*FUNCTION DoubleParam::ObjectEnum{{{*/
-int DoubleParam::ObjectEnum(void){
+int  DoubleParam::ObjectEnum(void){/*{{{*/
 
 	return DoubleParamEnum;
@@ -53,6 +46,5 @@
 }
 /*}}}*/
-/*FUNCTION DoubleParam::copy{{{*/
-Object* DoubleParam::copy() {
+Object* DoubleParam::copy() {/*{{{*/
 
 	return new DoubleParam(this->enum_type,this->value);
@@ -62,31 +54,25 @@
 
 /*DoubleParam virtual functions definitions: */
-/*FUNCTION DoubleParam::GetParameterValue(int* pinteger){{{*/
-void DoubleParam::GetParameterValue(int* pinteger){
+void DoubleParam::GetParameterValue(int* pinteger){/*{{{*/
 	_error_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an integer");
 }
 /*}}}*/
-/*FUNCTION DoubleParam::GetParameterValue(bool* pbool){{{*/
-void DoubleParam::GetParameterValue(bool* pbool){
+void DoubleParam::GetParameterValue(bool* pbool){/*{{{*/
 	_error_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an bool");
 }
 /*}}}*/
-/*FUNCTION DoubleParam::GetParameterValue(int** pintarray,int* pM){{{*/
-void DoubleParam::GetParameterValue(int** pintarray,int* pM){
+void DoubleParam::GetParameterValue(int** pintarray,int* pM){/*{{{*/
 	_error_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of integers");
 }
 /*}}}*/
-/*FUNCTION DoubleParam::GetParameterValue(int** pintarray,int* pM,int* pN){{{*/
-void DoubleParam::GetParameterValue(int** pintarray,int* pM,int* pN){
+void DoubleParam::GetParameterValue(int** pintarray,int* pM,int* pN){/*{{{*/
 	_error_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of integers");
 }
 /*}}}*/
-/*FUNCTION DoubleParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){{{*/
-void DoubleParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){
+void DoubleParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){/*{{{*/
 	_error_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of IssmDouble");
 }
 /*}}}*/
-/*FUNCTION DoubleParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){{{*/
-void DoubleParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){
+void DoubleParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){/*{{{*/
 	_error_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of IssmDouble");
 }
Index: issm/trunk/src/c/classes/Params/DoubleTransientMatParam.cpp
===================================================================
--- issm/trunk/src/c/classes/Params/DoubleTransientMatParam.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Params/DoubleTransientMatParam.cpp	(revision 18301)
@@ -15,6 +15,5 @@
 /*}}}*/
 
-/*FUNCTION DoubleTransientMatParam::DoubleTransientMatParam(int enum_type,IssmDoubleMat value){{{*/
-DoubleTransientMatParam::DoubleTransientMatParam(int in_enum_type,IssmDouble* in_value, int in_M,int in_N):DoubleMatParam(in_enum_type,in_value,in_M,in_N){
+DoubleTransientMatParam::DoubleTransientMatParam(int in_enum_type,IssmDouble* in_value, int in_M,int in_N):DoubleMatParam(in_enum_type,in_value,in_M,in_N){/*{{{*/
 }
 /*}}}*/
Index: issm/trunk/src/c/classes/Params/DoubleVecParam.cpp
===================================================================
--- issm/trunk/src/c/classes/Params/DoubleVecParam.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Params/DoubleVecParam.cpp	(revision 18301)
@@ -16,11 +16,9 @@
 
 /*DoubleVecParam constructors and destructor*/
-/*FUNCTION DoubleVecParam::DoubleVecParam(){{{*/
-DoubleVecParam::DoubleVecParam(){
+DoubleVecParam::DoubleVecParam(){/*{{{*/
 	return;
 }
 /*}}}*/
-/*FUNCTION DoubleVecParam::DoubleVecParam(int enum_type,IssmDoubleVec values,int M){{{*/
-DoubleVecParam::DoubleVecParam(int in_enum_type,IssmDouble* in_values, int in_M){
+DoubleVecParam::DoubleVecParam(int in_enum_type,IssmDouble* in_values, int in_M){/*{{{*/
 
 	enum_type=in_enum_type;
@@ -31,6 +29,5 @@
 }
 /*}}}*/
-/*FUNCTION DoubleVecParam::~DoubleVecParam(){{{*/
-DoubleVecParam::~DoubleVecParam(){
+DoubleVecParam::~DoubleVecParam(){/*{{{*/
 	xDelete<IssmDouble>(values);
 	return;
@@ -39,6 +36,5 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION DoubleVecParam::Echo {{{*/
-void DoubleVecParam::Echo(void){
+void DoubleVecParam::Echo(void){/*{{{*/
 
 	_printf_(setw(22)<<"   DoubleVecParam "<<setw(35)<<left<<EnumToStringx(this->enum_type)<<" size: "<<this->M<<"\n");
@@ -46,6 +42,5 @@
 }
 /*}}}*/
-/*FUNCTION DoubleVecParam::DeepEcho{{{*/
-void DoubleVecParam::DeepEcho(void){
+void DoubleVecParam::DeepEcho(void){/*{{{*/
 	_printf_(setw(22)<<"   DoubleVecParam "<<setw(35)<<left<<EnumToStringx(this->enum_type)<<" "<<"[");
 	for(int i=0;i<this->M;i++) _printf_(" "<< this->values[i]);
@@ -53,9 +48,7 @@
 }
 /*}}}*/
-/*FUNCTION DoubleVecParam::Id{{{*/
-int    DoubleVecParam::Id(void){ return -1; }
+int    DoubleVecParam::Id(void){ return -1; }/*{{{*/
 /*}}}*/
-/*FUNCTION DoubleVecParam::ObjectEnum{{{*/
-int DoubleVecParam::ObjectEnum(void){
+int DoubleVecParam::ObjectEnum(void){/*{{{*/
 
 	return DoubleVecParamEnum;
@@ -63,6 +56,5 @@
 }
 /*}}}*/
-/*FUNCTION DoubleVecParam::copy{{{*/
-Object* DoubleVecParam::copy() {
+Object* DoubleVecParam::copy() {/*{{{*/
 
 	return new DoubleVecParam(this->enum_type,this->values,this->M);
@@ -72,6 +64,5 @@
 
 /*DoubleVecParam virtual functions definitions: */
-/*FUNCTION DoubleVecParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){{{*/
-void  DoubleVecParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){
+void  DoubleVecParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){/*{{{*/
 	IssmDouble* output=NULL;
 	int M;
@@ -86,6 +77,5 @@
 }
 /*}}}*/
-/*FUNCTION DoubleVecParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){{{*/
-void  DoubleVecParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){
+void  DoubleVecParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){/*{{{*/
 	IssmDouble* output=NULL;
 	int M;
@@ -103,11 +93,9 @@
 }
 /*}}}*/
-/*FUNCTION DoubleVecParam::GetParameterValue(int** pintarray,int* pM){{{*/
-void  DoubleVecParam::GetParameterValue(int** pintarray,int* pM){
+void  DoubleVecParam::GetParameterValue(int** pintarray,int* pM){/*{{{*/
 	_error_("DoubleVec param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of int");
 }
 /*}}}*/
-/*FUNCTION DoubleVecParam::SetValue{{{*/
-void  DoubleVecParam::SetValue(IssmDouble* IssmDoublearray,int in_M){
+void  DoubleVecParam::SetValue(IssmDouble* IssmDoublearray,int in_M){/*{{{*/
 
 	/*avoid leak: */
Index: issm/trunk/src/c/classes/Params/FileParam.cpp
===================================================================
--- issm/trunk/src/c/classes/Params/FileParam.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Params/FileParam.cpp	(revision 18301)
@@ -16,11 +16,9 @@
 
 /*FileParam constructors and destructor*/
-/*FUNCTION FileParam::FileParam(){{{*/
-FileParam::FileParam(){
+FileParam::FileParam(){/*{{{*/
 	return;
 }
 /*}}}*/
-/*FUNCTION FileParam::FileParam(int enum_type,FILE *value){{{*/
-FileParam::FileParam(int in_enum_type,FILE* in_value){
+FileParam::FileParam(int in_enum_type,FILE* in_value){/*{{{*/
 
 	enum_type=in_enum_type;
@@ -28,6 +26,5 @@
 }
 /*}}}*/
-/*FUNCTION FileParam::~FileParam(){{{*/
-FileParam::~FileParam(){
+FileParam::~FileParam(){/*{{{*/
 	return;
 }
@@ -35,20 +32,16 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION FileParam::Echo {{{*/
-void FileParam::Echo(void){
+void FileParam::Echo(void){/*{{{*/
 	this->DeepEcho();
 }
 /*}}}*/
-/*FUNCTION FileParam::DeepEcho{{{*/
-void FileParam::DeepEcho(void){
+void FileParam::DeepEcho(void){/*{{{*/
 
 	_printf_(setw(22)<<"   FileParam "<<setw(35)<<left<<EnumToStringx(this->enum_type)<<" "<<this->value<<"\n");
 }
 /*}}}*/
-/*FUNCTION FileParam::Id{{{*/
-int    FileParam::Id(void){ return -1; }
+int    FileParam::Id(void){ return -1; }/*{{{*/
 /*}}}*/
-/*FUNCTION FileParam::ObjectEnum{{{*/
-int FileParam::ObjectEnum(void){
+int FileParam::ObjectEnum(void){/*{{{*/
 
 	return FileParamEnum;
@@ -56,6 +49,5 @@
 }
 /*}}}*/
-/*FUNCTION FileParam::copy{{{*/
-Object* FileParam::copy() {
+Object* FileParam::copy() {/*{{{*/
 
 	return new FileParam(this->enum_type,this->value);
Index: issm/trunk/src/c/classes/Params/IntMatParam.cpp
===================================================================
--- issm/trunk/src/c/classes/Params/IntMatParam.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Params/IntMatParam.cpp	(revision 18301)
@@ -16,11 +16,9 @@
 
 /*IntMatParam constructors and destructor*/
-/*FUNCTION IntMatParam::IntMatParam(){{{*/
-IntMatParam::IntMatParam(){
+IntMatParam::IntMatParam(){/*{{{*/
 	return;
 }
 /*}}}*/
-/*FUNCTION IntMatParam::IntMatParam(int enum_type,IssmIntMat value){{{*/
-IntMatParam::IntMatParam(int in_enum_type,int* in_value, int in_M,int in_N){
+IntMatParam::IntMatParam(int in_enum_type,int* in_value, int in_M,int in_N){/*{{{*/
 
 	enum_type=in_enum_type;
@@ -32,6 +30,5 @@
 }
 /*}}}*/
-/*FUNCTION IntMatParam::~IntMatParam(){{{*/
-IntMatParam::~IntMatParam(){
+IntMatParam::~IntMatParam(){/*{{{*/
 	xDelete<int>(value);
 	return;
@@ -40,6 +37,5 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION IntMatParam::Echo {{{*/
-void IntMatParam::Echo(void){
+void IntMatParam::Echo(void){/*{{{*/
 
 	_printf_("IntMatParam:\n");
@@ -49,6 +45,5 @@
 }
 /*}}}*/
-/*FUNCTION IntMatParam::DeepEcho{{{*/
-void IntMatParam::DeepEcho(void){
+void IntMatParam::DeepEcho(void){/*{{{*/
 
 	int i,j;
@@ -64,9 +59,7 @@
 }
 /*}}}*/
-/*FUNCTION IntMatParam::Id{{{*/
-int    IntMatParam::Id(void){ return -1; }
+int    IntMatParam::Id(void){ return -1; }/*{{{*/
 /*}}}*/
-/*FUNCTION IntMatParam::ObjectEnum{{{*/
-int IntMatParam::ObjectEnum(void){
+int IntMatParam::ObjectEnum(void){/*{{{*/
 
 	return IntMatParamEnum;
@@ -74,6 +67,5 @@
 }
 /*}}}*/
-/*FUNCTION IntMatParam::copy{{{*/
-Object* IntMatParam::copy() {
+Object* IntMatParam::copy() {/*{{{*/
 
 	return new IntMatParam(this->enum_type,this->value,this->M,this->N);
@@ -83,6 +75,5 @@
 
 /*IntMatParam virtual functions definitions: */
-/*FUNCTION IntMatParam::GetParameterValue{{{*/
-void  IntMatParam::GetParameterValue(int** pintarray,int* pM,int* pN){
+void  IntMatParam::GetParameterValue(int** pintarray,int* pM,int* pN){/*{{{*/
 	int* output=NULL;
 
@@ -96,6 +87,5 @@
 }
 /*}}}*/
-/*FUNCTION IntMatParam::SetValue{{{*/
-void  IntMatParam::SetValue(int* intarray,int in_M,int in_N){
+void  IntMatParam::SetValue(int* intarray,int in_M,int in_N){/*{{{*/
 
 	/*avoid leak: */
Index: issm/trunk/src/c/classes/Params/IntParam.cpp
===================================================================
--- issm/trunk/src/c/classes/Params/IntParam.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Params/IntParam.cpp	(revision 18301)
@@ -16,11 +16,9 @@
 
 /*IntParam constructors and destructor*/
-/*FUNCTION IntParam::IntParam(){{{*/
-IntParam::IntParam(){
+IntParam::IntParam(){/*{{{*/
 	return;
 }
 /*}}}*/
-/*FUNCTION IntParam::IntParam(int enum_type,IssmInt value){{{*/
-IntParam::IntParam(int in_enum_type,IssmInt in_value){
+IntParam::IntParam(int in_enum_type,IssmInt in_value){/*{{{*/
 
 	enum_type=in_enum_type;
@@ -28,6 +26,5 @@
 }
 /*}}}*/
-/*FUNCTION IntParam::~IntParam(){{{*/
-IntParam::~IntParam(){
+IntParam::~IntParam(){/*{{{*/
 	return;
 }
@@ -35,20 +32,16 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION IntParam::Echo {{{*/
-void IntParam::Echo(void){
+void IntParam::Echo(void){/*{{{*/
 	this->DeepEcho();
 }
 /*}}}*/
-/*FUNCTION IntParam::DeepEcho{{{*/
-void IntParam::DeepEcho(void){
+void IntParam::DeepEcho(void){/*{{{*/
 
 	_printf_(setw(22)<<"   IntParam "<<setw(35)<<left<<EnumToStringx(this->enum_type)<<" "<<this->value<<"\n");
 }
 /*}}}*/
-/*FUNCTION IntParam::Id{{{*/
-int    IntParam::Id(void){ return -1; }
+int    IntParam::Id(void){ return -1; }/*{{{*/
 /*}}}*/
-/*FUNCTION IntParam::ObjectEnum{{{*/
-int IntParam::ObjectEnum(void){
+int IntParam::ObjectEnum(void){/*{{{*/
 
 	return IntParamEnum;
@@ -56,6 +49,5 @@
 }
 /*}}}*/
-/*FUNCTION IntParam::copy{{{*/
-Object* IntParam::copy() {
+Object* IntParam::copy() {/*{{{*/
 
 	return new IntParam(this->enum_type,this->value);
Index: issm/trunk/src/c/classes/Params/IntVecParam.cpp
===================================================================
--- issm/trunk/src/c/classes/Params/IntVecParam.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Params/IntVecParam.cpp	(revision 18301)
@@ -16,11 +16,9 @@
 
 /*IntVecParam constructors and destructor*/
-/*FUNCTION IntVecParam::IntVecParam(){{{*/
-IntVecParam::IntVecParam(){
+IntVecParam::IntVecParam(){/*{{{*/
 	return;
 }
 /*}}}*/
-/*FUNCTION IntVecParam::IntVecParam(int enum_type,int* values,int M){{{*/
-IntVecParam::IntVecParam(int in_enum_type,int* in_values, int in_M){
+IntVecParam::IntVecParam(int in_enum_type,int* in_values, int in_M){/*{{{*/
 
 	enum_type=in_enum_type;
@@ -34,6 +32,5 @@
 }
 /*}}}*/
-/*FUNCTION IntVecParam::IntVecParam(int enum_type,IssmDouble* values,int M){{{*/
-IntVecParam::IntVecParam(int in_enum_type,IssmDouble* in_values, int in_M){
+IntVecParam::IntVecParam(int in_enum_type,IssmDouble* in_values, int in_M){/*{{{*/
 
 	enum_type=in_enum_type;
@@ -47,6 +44,5 @@
 }
 /*}}}*/
-/*FUNCTION IntVecParam::~IntVecParam(){{{*/
-IntVecParam::~IntVecParam(){
+IntVecParam::~IntVecParam(){/*{{{*/
 	xDelete<int>(values);
 	return;
@@ -55,6 +51,5 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION IntVecParam::Echo {{{*/
-void IntVecParam::Echo(void){
+void IntVecParam::Echo(void){/*{{{*/
 
 	_printf_("IntVecParam:\n");
@@ -64,6 +59,5 @@
 }
 /*}}}*/
-/*FUNCTION IntVecParam::DeepEcho{{{*/
-void IntVecParam::DeepEcho(void){
+void IntVecParam::DeepEcho(void){/*{{{*/
 
 	int i;
@@ -77,9 +71,7 @@
 }
 /*}}}*/
-/*FUNCTION IntVecParam::Id{{{*/
-int    IntVecParam::Id(void){ return -1; }
+int    IntVecParam::Id(void){ return -1; }/*{{{*/
 /*}}}*/
-/*FUNCTION IntVecParam::ObjectEnum{{{*/
-int IntVecParam::ObjectEnum(void){
+int IntVecParam::ObjectEnum(void){/*{{{*/
 
 	return IntVecParamEnum;
@@ -87,6 +79,5 @@
 }
 /*}}}*/
-/*FUNCTION IntVecParam::copy{{{*/
-Object* IntVecParam::copy() {
+Object* IntVecParam::copy() {/*{{{*/
 
 	return new IntVecParam(this->enum_type,this->values,this->M);
@@ -96,6 +87,5 @@
 
 /*IntVecParam virtual functions definitions: */
-/*FUNCTION IntVecParam::GetParameterValue{{{*/
-void  IntVecParam::GetParameterValue(int** pintarray,int* pM){
+void  IntVecParam::GetParameterValue(int** pintarray,int* pM){/*{{{*/
 	int* output=NULL;
 
@@ -110,6 +100,5 @@
 }
 /*}}}*/
-/*FUNCTION IntVecParam::SetValue{{{*/
-void  IntVecParam::SetValue(int* intarray,int in_M){
+void  IntVecParam::SetValue(int* intarray,int in_M){/*{{{*/
 
 	/*avoid leak: */
Index: issm/trunk/src/c/classes/Params/MatrixParam.cpp
===================================================================
--- issm/trunk/src/c/classes/Params/MatrixParam.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Params/MatrixParam.cpp	(revision 18301)
@@ -16,11 +16,9 @@
 
 /*MatrixParam constructors and destructor*/
-/*FUNCTION MatrixParam::MatrixParam(){{{*/
-MatrixParam::MatrixParam(){
+MatrixParam::MatrixParam(){/*{{{*/
 	return;
 }
 /*}}}*/
-/*FUNCTION MatrixParam::MatrixParam(int enum_type,Matrix<IssmDouble>* value){{{*/
-MatrixParam::MatrixParam(int in_enum_type,Matrix<IssmDouble>* in_value){
+MatrixParam::MatrixParam(int in_enum_type,Matrix<IssmDouble>* in_value){/*{{{*/
 
 	enum_type=in_enum_type;
@@ -32,6 +30,5 @@
 }
 /*}}}*/
-/*FUNCTION MatrixParam::~MatrixParam(){{{*/
-MatrixParam::~MatrixParam(){
+MatrixParam::~MatrixParam(){/*{{{*/
 	delete value;
 }
@@ -39,6 +36,5 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION MatrixParam::Echo {{{*/
-void MatrixParam::Echo(void){
+void MatrixParam::Echo(void){/*{{{*/
 
 	_printf_("MatrixParam:\n");
@@ -47,6 +43,5 @@
 }
 /*}}}*/
-/*FUNCTION MatrixParam::DeepEcho{{{*/
-void MatrixParam::DeepEcho(void){
+void MatrixParam::DeepEcho(void){/*{{{*/
 
 	_printf_("MatrixParam:\n");
@@ -55,9 +50,7 @@
 }
 /*}}}*/
-/*FUNCTION MatrixParam::Id{{{*/
-int    MatrixParam::Id(void){ return -1; }
+int    MatrixParam::Id(void){ return -1; }/*{{{*/
 /*}}}*/
-/*FUNCTION MatrixParam::ObjectEnum{{{*/
-int MatrixParam::ObjectEnum(void){
+int MatrixParam::ObjectEnum(void){/*{{{*/
 
 	return MatrixParamEnum;
@@ -65,6 +58,5 @@
 }
 /*}}}*/
-/*FUNCTION MatrixParam::copy{{{*/
-Object* MatrixParam::copy() {
+Object* MatrixParam::copy() {/*{{{*/
 
 	return new MatrixParam(this->enum_type,this->value);
@@ -74,6 +66,5 @@
 
 /*MatrixParam virtual functions definitions: */
-/*FUNCTION MatrixParam::GetParameterValue{{{*/
-void  MatrixParam::GetParameterValue(Matrix<IssmDouble>** poutput){
+void  MatrixParam::GetParameterValue(Matrix<IssmDouble>** poutput){/*{{{*/
 	Matrix<IssmDouble>* output=NULL;
 
@@ -84,6 +75,5 @@
 }
 /*}}}*/
-/*FUNCTION MatrixParam::SetValue{{{*/
-void  MatrixParam::SetValue(Matrix<IssmDouble>* matrix){
+void  MatrixParam::SetValue(Matrix<IssmDouble>* matrix){/*{{{*/
 
 	/*avoid leak: */
Index: issm/trunk/src/c/classes/Params/Parameters.cpp
===================================================================
--- issm/trunk/src/c/classes/Params/Parameters.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Params/Parameters.cpp	(revision 18301)
@@ -40,12 +40,10 @@
 
 /*Object constructors and destructor*/
-/*FUNCTION Parameters::Parameters(){{{*/
-Parameters::Parameters(){
+Parameters::Parameters(){/*{{{*/
 	enum_type=ParametersEnum;
 	return;
 }
 /*}}}*/
-/*FUNCTION Parameters::~Parameters(){{{*/
-Parameters::~Parameters(){
+Parameters::~Parameters(){/*{{{*/
 	return;
 }
@@ -53,6 +51,5 @@
 
 /*Object management*/
-/*FUNCTION Parameters::Exist{{{*/
-bool Parameters::Exist(int enum_type){
+bool Parameters::Exist(int enum_type){/*{{{*/
 
 	vector<Object*>::iterator object;
@@ -66,6 +63,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::FindParam(bool* pbool,int enum_type){{{*/
-void Parameters::FindParam(bool* pbool,int enum_type){ _assert_(this);
+void Parameters::FindParam(bool* pbool,int enum_type){ _assert_(this);/*{{{*/
 
 	vector<Object*>::iterator object;
@@ -83,6 +79,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::FindParam(int* pinteger,int enum_type){{{*/
-void Parameters::FindParam(int* pinteger,int enum_type){ _assert_(this);
+void Parameters::FindParam(int* pinteger,int enum_type){ _assert_(this);/*{{{*/
 
 	vector<Object*>::iterator object;
@@ -100,6 +95,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::FindParam(IssmDouble* pscalar, int enum_type){{{*/
-void Parameters::FindParam(IssmDouble* pscalar, int enum_type){ _assert_(this);
+void Parameters::FindParam(IssmDouble* pscalar, int enum_type){ _assert_(this);/*{{{*/
 
 	vector<Object*>::iterator object;
@@ -114,9 +108,8 @@
 		}
 	}
-	_error_("could not find parameter " << EnumToStringx(enum_type));
-}
-/*}}}*/
-/*FUNCTION Parameters::FindParam(IssmDouble* pscalar, int enum_type,IssmDouble time){{{*/
-void Parameters::FindParam(IssmDouble* pscalar, int enum_type,IssmDouble time){ _assert_(this);
+	_error_("could not find parameter " <<  EnumToStringx(enum_type));
+}
+/*}}}*/
+void Parameters::FindParam(IssmDouble* pscalar, int enum_type,IssmDouble time){ _assert_(this);/*{{{*/
 
 	vector<Object*>::iterator object;
@@ -134,6 +127,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::FindParam(char** pstring,int enum_type){{{*/
-void Parameters::FindParam(char** pstring,int enum_type){ _assert_(this);
+void Parameters::FindParam(char** pstring,int enum_type){ _assert_(this);/*{{{*/
 
 	vector<Object*>::iterator object;
@@ -152,6 +144,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::FindParam(char*** pstringarray,int* pM,int enum_type){{{*/
-void Parameters::FindParam(char*** pstringarray,int* pM,int enum_type){ _assert_(this);
+void Parameters::FindParam(char*** pstringarray,int* pM,int enum_type){ _assert_(this);/*{{{*/
 
 	vector<Object*>::iterator object;
@@ -170,6 +161,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::FindParam(int** pintarray,int* pM,int enum_type){{{*/
-void Parameters::FindParam(int** pintarray,int* pM, int enum_type){ _assert_(this);
+void Parameters::FindParam(int** pintarray,int* pM, int enum_type){ _assert_(this);/*{{{*/
 
 	vector<Object*>::iterator object;
@@ -188,6 +178,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::FindParam(int** pintarray,int* pM,int* pN,int enum_type){{{*/
-void Parameters::FindParam(int** pintarray,int* pM,int *pN,int enum_type){ _assert_(this);
+void Parameters::FindParam(int** pintarray,int* pM,int *pN,int enum_type){ _assert_(this);/*{{{*/
 
 	vector<Object*>::iterator object;
@@ -206,6 +195,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::FindParam(IssmDouble** pIssmDoublearray,int* pM,int enum_type){{{*/
-void Parameters::FindParam(IssmDouble** pIssmDoublearray,int* pM, int enum_type){ _assert_(this);
+void Parameters::FindParam(IssmDouble** pIssmDoublearray,int* pM, int enum_type){ _assert_(this);/*{{{*/
 
 	vector<Object*>::iterator object;
@@ -224,6 +212,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::FindParam(IssmDouble** pIssmDoublearray,int* pM, int* pN,int enum_type){{{*/
-void Parameters::FindParam(IssmDouble** pIssmDoublearray,int* pM, int* pN,int enum_type){ _assert_(this);
+void Parameters::FindParam(IssmDouble** pIssmDoublearray,int* pM, int* pN,int enum_type){ _assert_(this);/*{{{*/
 
 	vector<Object*>::iterator object;
@@ -242,6 +229,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::FindParam(IssmDouble*** parray,int* pM,int** pmdims_array,int** pndims_array,int enum_type){{{*/
-void Parameters::FindParam(IssmDouble*** parray,int* pM,int** pmdims_array,int** pndims_array,int enum_type){ _assert_(this);
+void Parameters::FindParam(IssmDouble*** parray,int* pM,int** pmdims_array,int** pndims_array,int enum_type){ _assert_(this);/*{{{*/
 
 	vector<Object*>::iterator object;
@@ -259,6 +245,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::FindParam(Vector<IssmDouble>** pvec,int enum_type){{{*/
-void Parameters::FindParam(Vector<IssmDouble>** pvec,int enum_type){ _assert_(this);
+void Parameters::FindParam(Vector<IssmDouble>** pvec,int enum_type){ _assert_(this);/*{{{*/
 
 	vector<Object*>::iterator object;
@@ -277,6 +262,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::FindParam(Matrix<IssmDouble>** pmat,int enum_type){{{*/
-void Parameters::FindParam(Matrix<IssmDouble>** pmat,int enum_type){ _assert_(this);
+void Parameters::FindParam(Matrix<IssmDouble>** pmat,int enum_type){ _assert_(this);/*{{{*/
 
 	vector<Object*>::iterator object;
@@ -295,6 +279,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::FindParam(FILE** pfid,int enum_type){{{*/
-void Parameters::FindParam(FILE** pfid,int enum_type){ _assert_(this);
+void Parameters::FindParam(FILE** pfid,int enum_type){ _assert_(this);/*{{{*/
 
 	vector<Object*>::iterator object;
@@ -312,6 +295,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::FindParam(DataSet** pdataset,int enum_type){{{*/
-void Parameters::FindParam(DataSet** pdataset,int enum_type){ 
+void Parameters::FindParam(DataSet** pdataset,int enum_type){ /*{{{*/
 	_assert_(this);
 
@@ -331,6 +313,5 @@
 /*}}}*/
 
-/*FUNCTION Parameters::SetParam(bool boolean,int enum_type);{{{*/
-void   Parameters::SetParam(bool boolean,int enum_type){
+void   Parameters::SetParam(bool boolean,int enum_type){/*{{{*/
 
 	Param* param=NULL;
@@ -343,6 +324,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::SetParam(int integer,int enum_type);{{{*/
-void   Parameters::SetParam(int integer,int enum_type){
+void   Parameters::SetParam(int integer,int enum_type){/*{{{*/
 
 	Param* param=NULL;
@@ -355,6 +335,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::SetParam(IssmDouble scalar,int enum_type);{{{*/
-void   Parameters::SetParam(IssmDouble scalar,int enum_type){
+void   Parameters::SetParam(IssmDouble scalar,int enum_type){/*{{{*/
 
 	Param* param=NULL;
@@ -367,6 +346,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::SetParam(char* string,int enum_type);{{{*/
-void   Parameters::SetParam(char* string,int enum_type){
+void   Parameters::SetParam(char* string,int enum_type){/*{{{*/
 
 	Param* param=NULL;
@@ -379,6 +357,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::SetParam(char** stringarray,int M, int enum_type);{{{*/
-void   Parameters::SetParam(char** stringarray,int M, int enum_type){
+void   Parameters::SetParam(char** stringarray,int M, int enum_type){/*{{{*/
 
 	Param* param=NULL;
@@ -391,6 +368,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::SetParam(IssmDouble* IssmDoublearray,int M,int enum_type);{{{*/
-void   Parameters::SetParam(IssmDouble* IssmDoublearray,int M, int enum_type){
+void   Parameters::SetParam(IssmDouble* IssmDoublearray,int M, int enum_type){/*{{{*/
 
 	Param* param=NULL;
@@ -403,6 +379,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::SetParam(IssmDouble* IssmDoublearray,int M,int N, int enum_type);{{{*/
-void   Parameters::SetParam(IssmDouble* IssmDoublearray,int M, int N, int enum_type){
+void   Parameters::SetParam(IssmDouble* IssmDoublearray,int M, int N, int enum_type){/*{{{*/
 
 	Param* param=NULL;
@@ -415,6 +390,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::SetParam(int* intarray,int M,int enum_type);{{{*/
-void   Parameters::SetParam(int* intarray,int M, int enum_type){
+void   Parameters::SetParam(int* intarray,int M, int enum_type){/*{{{*/
 
 	Param* param=NULL;
@@ -427,6 +401,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::SetParam(int* intarray,int M,int N, int enum_type);{{{*/
-void   Parameters::SetParam(int* intarray,int M, int N, int enum_type){
+void   Parameters::SetParam(int* intarray,int M, int N, int enum_type){/*{{{*/
 
 	Param* param=NULL;
@@ -439,6 +412,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::SetParam(Vector<IssmDouble>* vector,int enum_type);{{{*/
-void   Parameters::SetParam(Vector<IssmDouble>* vector,int enum_type){
+void   Parameters::SetParam(Vector<IssmDouble>* vector,int enum_type){/*{{{*/
 
 	Param* param=NULL;
@@ -451,6 +423,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::SetParam(Matrix<IssmDouble>* matrix,int enum_type);{{{*/
-void   Parameters::SetParam(Matrix<IssmDouble>* matrix,int enum_type){
+void   Parameters::SetParam(Matrix<IssmDouble>* matrix,int enum_type){/*{{{*/
 
 	Param* param=NULL;
@@ -463,6 +434,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::SetParam(FILE* fid,int enum_type);{{{*/
-void   Parameters::SetParam(FILE* fid,int enum_type){
+void   Parameters::SetParam(FILE* fid,int enum_type){/*{{{*/
 
 	Param* param=NULL;
@@ -475,6 +445,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::SetParam(DataSet* dataset, int enum_type);{{{*/
-void   Parameters::SetParam(DataSet* dataset,int enum_type){
+void   Parameters::SetParam(DataSet* dataset,int enum_type){/*{{{*/
 
 	Param* param=NULL;
@@ -488,6 +457,5 @@
 /*}}}*/
 
-/*FUNCTION Parameters::FindParamObject{{{*/
-Object* Parameters::FindParamObject(int enum_type){
+Object* Parameters::FindParamObject(int enum_type){/*{{{*/
 
 	vector<Object*>::iterator object;
Index: issm/trunk/src/c/classes/Params/StringArrayParam.cpp
===================================================================
--- issm/trunk/src/c/classes/Params/StringArrayParam.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Params/StringArrayParam.cpp	(revision 18301)
@@ -16,11 +16,9 @@
 
 /*StringArrayParam constructors and destructor*/
-/*FUNCTION StringArrayParam::StringArrayParam(){{{*/
-StringArrayParam::StringArrayParam(){
+StringArrayParam::StringArrayParam(){/*{{{*/
 	return;
 }
 /*}}}*/
-/*FUNCTION StringArrayParam::StringArrayParam(int enum_type,char** in_values,int in_numstrings){{{*/
-StringArrayParam::StringArrayParam(int in_enum_type,char** in_values, int in_numstrings){
+StringArrayParam::StringArrayParam(int in_enum_type,char** in_values, int in_numstrings){/*{{{*/
 
 	int i;
@@ -44,6 +42,5 @@
 }
 /*}}}*/
-/*FUNCTION StringArrayParam::~StringArrayParam(){{{*/
-StringArrayParam::~StringArrayParam(){
+StringArrayParam::~StringArrayParam(){/*{{{*/
 
 	int i;
@@ -59,11 +56,9 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION StringArrayParam::Echo {{{*/
-void StringArrayParam::Echo(void){
+void StringArrayParam::Echo(void){/*{{{*/
 	this->DeepEcho();
 }
 /*}}}*/
-/*FUNCTION StringArrayParam::DeepEcho{{{*/
-void StringArrayParam::DeepEcho(void){
+void StringArrayParam::DeepEcho(void){/*{{{*/
 
 	_printf_(setw(22)<<"   StringArrayParam "<<setw(35)<<left<<EnumToStringx(this->enum_type)<<" {");
@@ -72,9 +67,7 @@
 }
 /*}}}*/
-/*FUNCTION StringArrayParam::Id{{{*/
-int    StringArrayParam::Id(void){ return -1; }
+int    StringArrayParam::Id(void){ return -1; }/*{{{*/
 /*}}}*/
-/*FUNCTION StringArrayParam::ObjectEnum{{{*/
-int StringArrayParam::ObjectEnum(void){
+int StringArrayParam::ObjectEnum(void){/*{{{*/
 
 	return StringArrayParamEnum;
@@ -82,6 +75,5 @@
 }
 /*}}}*/
-/*FUNCTION StringArrayParam::copy{{{*/
-Object* StringArrayParam::copy() {
+Object* StringArrayParam::copy() {/*{{{*/
 
 	return new StringArrayParam(this->enum_type,this->value,this->numstrings);
@@ -91,6 +83,5 @@
 
 /*StringArrayParam virtual functions definitions: */
-/*FUNCTION StringArrayParam::GetParameterValue{{{*/
-void  StringArrayParam::GetParameterValue(char*** pstringarray,int* pM){
+void  StringArrayParam::GetParameterValue(char*** pstringarray,int* pM){/*{{{*/
 
 	int   i;
@@ -122,6 +113,5 @@
 }
 /*}}}*/
-/*FUNCTION StringArrayParam::SetValue{{{*/
-void  StringArrayParam::SetValue(char** stringarray,int M){
+void  StringArrayParam::SetValue(char** stringarray,int M){/*{{{*/
 
 	int   i;
Index: issm/trunk/src/c/classes/Params/StringParam.cpp
===================================================================
--- issm/trunk/src/c/classes/Params/StringParam.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Params/StringParam.cpp	(revision 18301)
@@ -16,11 +16,9 @@
 
 /*StringParam constructors and destructor*/
-/*FUNCTION StringParam::StringParam(){{{*/
-StringParam::StringParam(){
+StringParam::StringParam(){/*{{{*/
 	return;
 }
 /*}}}*/
-/*FUNCTION StringParam::StringParam(int enum_type,IssmString value){{{*/
-StringParam::StringParam(int in_enum_type,char* in_value){
+StringParam::StringParam(int in_enum_type,char* in_value){/*{{{*/
 
 	enum_type=in_enum_type;
@@ -30,6 +28,5 @@
 }
 /*}}}*/
-/*FUNCTION StringParam::~StringParam(){{{*/
-StringParam::~StringParam(){
+StringParam::~StringParam(){/*{{{*/
 	xDelete<char>(value);
 }
@@ -37,19 +34,15 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION StringParam::Echo {{{*/
-void StringParam::Echo(void){
+void StringParam::Echo(void){/*{{{*/
 	this->DeepEcho();
 }
 /*}}}*/
-/*FUNCTION StringParam::DeepEcho{{{*/
-void StringParam::DeepEcho(void){
+void StringParam::DeepEcho(void){/*{{{*/
 	_printf_(setw(22)<<"   StringParam "<<setw(35)<<left<<EnumToStringx(this->enum_type)<<" "<<this->value<<"\n");
 }
 /*}}}*/
-/*FUNCTION StringParam::Id{{{*/
-int    StringParam::Id(void){ return -1; }
+int    StringParam::Id(void){ return -1; }/*{{{*/
 /*}}}*/
-/*FUNCTION StringParam::ObjectEnum{{{*/
-int StringParam::ObjectEnum(void){
+int StringParam::ObjectEnum(void){/*{{{*/
 
 	return StringParamEnum;
@@ -57,6 +50,5 @@
 }
 /*}}}*/
-/*FUNCTION StringParam::copy{{{*/
-Object* StringParam::copy() {
+Object* StringParam::copy() {/*{{{*/
 
 	return new StringParam(this->enum_type,this->value);
@@ -66,6 +58,5 @@
 
 /*StringParam virtual functions definitions: */
-/*FUNCTION StringParam::GetParameterValue{{{*/
-void  StringParam::GetParameterValue(char** pstring){
+void  StringParam::GetParameterValue(char** pstring){/*{{{*/
 
 	char* outstring=NULL;
@@ -81,6 +72,5 @@
 }
 /*}}}*/
-/*FUNCTION StringParam::SetValue{{{*/
-void  StringParam::SetValue(char* string){
+void  StringParam::SetValue(char* string){/*{{{*/
 
 	int   stringsize;
Index: issm/trunk/src/c/classes/Params/TransientParam.cpp
===================================================================
--- issm/trunk/src/c/classes/Params/TransientParam.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Params/TransientParam.cpp	(revision 18301)
@@ -16,11 +16,9 @@
 
 /*TransientParam constructors and destructor*/
-/*FUNCTION TransientParam::TransientParam(){{{*/
-TransientParam::TransientParam(){
+TransientParam::TransientParam(){/*{{{*/
 	return;
 }
 /*}}}*/
-/*FUNCTION TransientParam::TransientParam(int enum_type,IssmDoubleMat value){{{*/
-TransientParam::TransientParam(int in_enum_type,IssmDouble* in_values,IssmDouble* in_time,int in_N){
+TransientParam::TransientParam(int in_enum_type,IssmDouble* in_values,IssmDouble* in_time,int in_N){/*{{{*/
 
 	_assert_(in_values && in_time);
@@ -36,6 +34,5 @@
 }
 /*}}}*/
-/*FUNCTION TransientParam::~TransientParam(){{{*/
-TransientParam::~TransientParam(){
+TransientParam::~TransientParam(){/*{{{*/
 	xDelete<IssmDouble>(values);
 	xDelete<IssmDouble>(timesteps);
@@ -44,6 +41,5 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION TransientParam::Echo {{{*/
-void TransientParam::Echo(void){
+void TransientParam::Echo(void){/*{{{*/
 
 	_printf_("TransientParam:\n");
@@ -53,6 +49,5 @@
 }
 /*}}}*/
-/*FUNCTION TransientParam::DeepEcho{{{*/
-void TransientParam::DeepEcho(void){
+void TransientParam::DeepEcho(void){/*{{{*/
 
 	_printf_("TransientParam:\n");
@@ -64,9 +59,7 @@
 }
 /*}}}*/
-/*FUNCTION TransientParam::Id{{{*/
-int    TransientParam::Id(void){ return -1; }
+int    TransientParam::Id(void){ return -1; }/*{{{*/
 /*}}}*/
-/*FUNCTION TransientParam::ObjectEnum{{{*/
-int TransientParam::ObjectEnum(void){
+int TransientParam::ObjectEnum(void){/*{{{*/
 
 	return TransientParamEnum;
@@ -74,6 +67,5 @@
 }
 /*}}}*/
-/*FUNCTION TransientParam::copy{{{*/
-Object* TransientParam::copy() {
+Object* TransientParam::copy() {/*{{{*/
 
 	return new TransientParam(this->enum_type,this->values,this->timesteps,this->N);
@@ -83,6 +75,5 @@
 
 /*TransientParam virtual functions definitions: */
-/*FUNCTION TransientParam::GetParameterValue(IssmDouble* pdouble,IssmDouble time){{{*/
-void  TransientParam::GetParameterValue(IssmDouble* pdouble,IssmDouble time){
+void  TransientParam::GetParameterValue(IssmDouble* pdouble,IssmDouble time){/*{{{*/
 
 	IssmDouble output;
Index: issm/trunk/src/c/classes/Params/VectorParam.cpp
===================================================================
--- issm/trunk/src/c/classes/Params/VectorParam.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Params/VectorParam.cpp	(revision 18301)
@@ -16,11 +16,9 @@
 
 /*VectorParam constructors and destructor*/
-/*FUNCTION VectorParam::VectorParam(){{{*/
-VectorParam::VectorParam(){
+VectorParam::VectorParam(){/*{{{*/
 	return;
 }
 /*}}}*/
-/*FUNCTION VectorParam::VectorParam(int enum_type,IssmVector value){{{*/
-VectorParam::VectorParam(int in_enum_type,Vector<IssmDouble>* in_value){
+VectorParam::VectorParam(int in_enum_type,Vector<IssmDouble>* in_value){/*{{{*/
 
 	enum_type=in_enum_type;
@@ -34,6 +32,5 @@
 }
 /*}}}*/
-/*FUNCTION VectorParam::~VectorParam(){{{*/
-VectorParam::~VectorParam(){
+VectorParam::~VectorParam(){/*{{{*/
 	delete value;
 }
@@ -41,6 +38,5 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION VectorParam::Echo {{{*/
-void VectorParam::Echo(void){
+void VectorParam::Echo(void){/*{{{*/
 
 	_printf_("VectorParam:\n");
@@ -49,6 +45,5 @@
 }
 /*}}}*/
-/*FUNCTION VectorParam::DeepEcho{{{*/
-void VectorParam::DeepEcho(void){
+void VectorParam::DeepEcho(void){/*{{{*/
 
 	_printf_("VectorParam:\n");
@@ -57,9 +52,7 @@
 }
 /*}}}*/
-/*FUNCTION VectorParam::Id{{{*/
-int    VectorParam::Id(void){ return -1; }
+int    VectorParam::Id(void){ return -1; }/*{{{*/
 /*}}}*/
-/*FUNCTION VectorParam::ObjectEnum{{{*/
-int VectorParam::ObjectEnum(void){
+int VectorParam::ObjectEnum(void){/*{{{*/
 
 	return VectorParamEnum;
@@ -67,6 +60,5 @@
 }
 /*}}}*/
-/*FUNCTION VectorParam::copy{{{*/
-Object* VectorParam::copy() {
+Object* VectorParam::copy() {/*{{{*/
 
 	return new VectorParam(this->enum_type,this->value);
@@ -76,6 +68,5 @@
 
 /*VectorParam virtual functions definitions: */
-/*FUNCTION VectorParam::GetParameterValue{{{*/
-void  VectorParam::GetParameterValue(Vector<IssmDouble>** poutput){
+void  VectorParam::GetParameterValue(Vector<IssmDouble>** poutput){/*{{{*/
 	Vector<IssmDouble>*  output=NULL;
 
@@ -87,6 +78,5 @@
 }
 /*}}}*/
-/*FUNCTION VectorParam::SetValue{{{*/
-void  VectorParam::SetValue(Vector<IssmDouble>* vector){
+void  VectorParam::SetValue(Vector<IssmDouble>* vector){/*{{{*/
 
 	/*avoid leak: */
Index: issm/trunk/src/c/classes/Profiler.cpp
===================================================================
--- issm/trunk/src/c/classes/Profiler.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Profiler.cpp	(revision 18301)
@@ -17,6 +17,5 @@
 
 /*Profiler constructors and destructors:*/
-/*FUNCTION Profiler::Profiler() default constructor {{{*/
-Profiler::Profiler(){
+Profiler::Profiler(){/*{{{*/
 		 this->time=new Parameters();
 		 this->flops=new Parameters();
@@ -24,6 +23,5 @@
 }
 /*}}}*/
-/*FUNCTION Profiler::~Profiler(){{{*/
-Profiler::~Profiler(){
+Profiler::~Profiler(){/*{{{*/
 	delete time;
 	delete flops;
@@ -31,8 +29,22 @@
 }
 /*}}}*/
+Object* Profiler::copy(){/*{{{*/
+	/*First do simple copy: */
+	Profiler* output=new Profiler();
+	delete output->time;
+	delete output->flops;
+	delete output->memory;
+
+	/*Now for deep copy: */
+	output->time=(Parameters*)this->time->Copy();
+	output->flops=(Parameters*)this->flops->Copy();
+	output->memory=(Parameters*)this->memory->Copy();
+
+	return (Object*)output;
+}
+/*}}}*/
 
 /*Object virtual functions definitions:*/
-/*FUNCTION Profiler::Echo{{{*/
-void Profiler::Echo(void){
+void Profiler::Echo(void){/*{{{*/
 
 	_printf_("Profiler:\n");
@@ -42,6 +54,5 @@
 }
 /*}}}*/
-/*FUNCTION Profiler::DeepEcho{{{*/
-void Profiler::DeepEcho(void){
+void Profiler::DeepEcho(void){/*{{{*/
 
 	_printf_("Profiler:\n");
@@ -51,9 +62,7 @@
 }
 /*}}}*/
-/*FUNCTION Profiler::Id{{{*/
-int    Profiler::Id(void){ return -1; }
+int  Profiler::Id(void){ return -1; }/*{{{*/
 /*}}}*/
-/*FUNCTION Profiler::ObjectEnum{{{*/
-int Profiler::ObjectEnum(void){
+int  Profiler::ObjectEnum(void){/*{{{*/
 
 	return ProfilerEnum;
@@ -63,6 +72,5 @@
 
 /*Profiler routines:*/
-/*FUNCTION Profiler::Tag {{{*/
-void  Profiler::Tag(int tagenum,bool dontmpisync){
+void  Profiler::Tag(int tagenum,bool dontmpisync){/*{{{*/
 
 	IssmDouble t;
@@ -98,6 +106,5 @@
 }
 /*}}}*/
-/*FUNCTION Profiler::DeltaTime {{{*/
-IssmDouble  Profiler::DeltaTime(int inittag, int finaltag){
+IssmDouble  Profiler::DeltaTime(int inittag, int finaltag){/*{{{*/
 
 	IssmDouble init, final;
@@ -112,6 +119,5 @@
 }
 /*}}}*/
-/*FUNCTION Profiler::DeltaFlops {{{*/
-IssmDouble  Profiler::DeltaFlops(int inittag, int finaltag){
+IssmDouble  Profiler::DeltaFlops(int inittag, int finaltag){/*{{{*/
 
 	IssmDouble init, final;
@@ -122,6 +128,5 @@
 }
 /*}}}*/
-/*FUNCTION Profiler::DeltaTimeModHour {{{*/
-int Profiler::DeltaTimeModHour(int inittag, int finishtag){
+int Profiler::DeltaTimeModHour(int inittag, int finishtag){/*{{{*/
 
 	IssmDouble init, finish;
@@ -137,6 +142,5 @@
 }
 /*}}}*/
-/*FUNCTION Profiler::DeltaTimeModMin {{{*/
-int Profiler::DeltaTimeModMin(int inittag, int finishtag){
+int Profiler::DeltaTimeModMin(int inittag, int finishtag){/*{{{*/
 
 	IssmDouble init, finish;
@@ -151,6 +155,5 @@
 }
 /*}}}*/
-/*FUNCTION Profiler::DeltaTimeModSec {{{*/
-int Profiler::DeltaTimeModSec(int inittag, int finishtag){
+int Profiler::DeltaTimeModSec(int inittag, int finishtag){/*{{{*/
 
 	IssmDouble init, finish;
@@ -165,6 +168,5 @@
 }
 /*}}}*/
-/*FUNCTION Profiler::Memory {{{*/
-IssmDouble  Profiler::Memory(int tag){
+IssmDouble  Profiler::Memory(int tag){/*{{{*/
 
 	IssmDouble m;
Index: issm/trunk/src/c/classes/Profiler.h
===================================================================
--- issm/trunk/src/c/classes/Profiler.h	(revision 18081)
+++ issm/trunk/src/c/classes/Profiler.h	(revision 18301)
@@ -42,5 +42,5 @@
 		int     Id();
 		int     ObjectEnum();
-		Object *copy()        {_error_("Not implemented yet"); };
+		Object *copy();
 		/*}}}*/
 		/*Profiler routines {{{*/
Index: issm/trunk/src/c/classes/Segment.h
===================================================================
--- issm/trunk/src/c/classes/Segment.h	(revision 18081)
+++ issm/trunk/src/c/classes/Segment.h	(revision 18301)
@@ -23,6 +23,5 @@
 
 		/*Segment constructors, destructors :*/
-		/*FUNCTION Segment() default constructor {{{*/
-		Segment(){
+		Segment(){/*{{{*/
 			this->eid = UNDEF;
 			this->x1  = UNDEF;
@@ -32,6 +31,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Segment(int eid, doubletype x1,doubletype y1,doubletype x2, doubletype y2){{{*/
-		Segment(int segment_eid, doubletype segment_x1,doubletype segment_y1,doubletype segment_x2, doubletype segment_y2){
+		Segment(int segment_eid, doubletype segment_x1,doubletype segment_y1,doubletype segment_x2, doubletype segment_y2){/*{{{*/
 
 			this->eid = segment_eid;
@@ -43,12 +41,10 @@
 		}
 		/*}}}*/
-		/*FUNCTION ~Segment(){{{*/
-		~Segment(){
+		~Segment(){/*{{{*/
 		}
 		/*}}}*/
 
 		/*Object virtual functions definitions:*/
-		/*FUNCTION Echo{{{*/
-		void Echo(void){
+		void Echo(void){/*{{{*/
 
 			_printf_("Segment:\n");
@@ -59,14 +55,11 @@
 		}
 		/*}}}*/
-		/*FUNCTION DeepEcho{{{*/
-		void DeepEcho(void){
+		void DeepEcho(void){/*{{{*/
 			this->Echo();
 		}
 		/*}}}*/
-		/*FUNCTION Id{{{*/
-		int    Id(void){ return eid; }
+		int    Id(void){ return eid; }/*{{{*/
 		/*}}}*/
-		/*FUNCTION ObjectEnum{{{*/
-		int ObjectEnum(void){
+		int ObjectEnum(void){/*{{{*/
 
 			return SegmentEnum;
@@ -74,6 +67,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION copy {{{*/
-		Object* copy() {
+		Object* copy() {/*{{{*/
 			return new Segment(this->eid,this->x1,this->y1,this->x2,this->y2);
 		}
Index: issm/trunk/src/c/classes/Vertex.cpp
===================================================================
--- issm/trunk/src/c/classes/Vertex.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Vertex.cpp	(revision 18301)
@@ -16,11 +16,9 @@
 
 /*Vertex constructors and destructor:*/
-/*FUNCTION Vertex::Vertex() {{{*/
-Vertex::Vertex(){
-	return;
-}
-/*}}}*/
-/*FUNCTION Vertex::Vertex(int vertex_id, int vertex_sid,int i, IoModel* iomodel) {{{*/
-Vertex::Vertex(int vertex_id, int vertex_sid,int i, IoModel* iomodel){
+Vertex::Vertex(){/*{{{*/
+	return;
+}
+/*}}}*/
+Vertex::Vertex(int vertex_id, int vertex_sid,int i, IoModel* iomodel){/*{{{*/
 
 	this->id           = vertex_id;
@@ -49,6 +47,5 @@
 }
 /*}}}*/
-/*FUNCTION Vertex::~Vertex() {{{*/
-Vertex::~Vertex(){
+Vertex::~Vertex(){/*{{{*/
 	return;
 }
@@ -56,6 +53,5 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION Vertex::Echo{{{*/
-void Vertex::Echo(void){
+void Vertex::Echo(void){/*{{{*/
 
 	_printf_("Vertex:\n");
@@ -73,14 +69,11 @@
 }
 /*}}}*/
-/*FUNCTION Vertex::DeepEcho{{{*/
-void Vertex::DeepEcho(void){
+void Vertex::DeepEcho(void){/*{{{*/
 	this->Echo();
 }
 /*}}}*/
-/*FUNCTION Vertex::Id{{{*/
-int    Vertex::Id(void){ return id; }
-/*}}}*/
-/*FUNCTION Vertex::ObjectEnum{{{*/
-int Vertex::ObjectEnum(void){
+int Vertex::Id(void){ return id; }/*{{{*/
+/*}}}*/
+int Vertex::ObjectEnum(void){/*{{{*/
 
 	return VertexEnum;
@@ -88,6 +81,5 @@
 }
 /*}}}*/
-/*FUNCTION Vertex::copy {{{*/
-Object* Vertex::copy() {
+Object* Vertex::copy() {/*{{{*/
 
 	return new Vertex(*this); 
@@ -97,30 +89,23 @@
 
 /*Vertex management: */
-/*FUNCTION Vertex::Connectivity{{{*/
-int    Vertex::Connectivity(void){return connectivity;}
-/*}}}*/
-/*FUNCTION Vertex::GetX {{{*/
-IssmDouble Vertex::GetX(){
+int        Vertex::Connectivity(void){return connectivity;}/*{{{*/
+/*}}}*/
+IssmDouble Vertex::GetX(){/*{{{*/
 	return this->x;
 }
 /*}}}*/
-/*FUNCTION Vertex::GetY {{{*/
-IssmDouble Vertex::GetY(){
+IssmDouble Vertex::GetY(){/*{{{*/
 	return this->y;
 }
 /*}}}*/
-/*FUNCTION Vertex::GetZ {{{*/
-IssmDouble Vertex::GetZ(){
+IssmDouble Vertex::GetZ(){/*{{{*/
 	return this->z;
 }
 /*}}}*/
-/*FUNCTION Vertex::Sid{{{*/
-int    Vertex::Sid(void){ return sid; }
-/*}}}*/
-/*FUNCTION Vertex::Pid{{{*/
-int    Vertex::Pid(void){ return pid; }
-/*}}}*/
-/*FUNCTION Vertex::UpdatePosition {{{*/
-void  Vertex::UpdatePosition(Vector<IssmDouble>* vx,Vector<IssmDouble>* vy,Vector<IssmDouble>* vz,Parameters* parameters,IssmDouble* surface,IssmDouble* bed){
+int        Vertex::Sid(void){ return sid; }/*{{{*/
+/*}}}*/
+int        Vertex::Pid(void){ return pid; }/*{{{*/
+/*}}}*/
+void       Vertex::UpdatePosition(Vector<IssmDouble>* vx,Vector<IssmDouble>* vy,Vector<IssmDouble>* vz,Parameters* parameters,IssmDouble* surface,IssmDouble* bed){/*{{{*/
 
 	IssmDouble oldy,newy,vely;
@@ -155,6 +140,5 @@
 }
 /*}}}*/
-/*FUNCTION Vertex::DistributePids{{{*/
-void  Vertex::DistributePids(int* ppidcount){
+void       Vertex::DistributePids(int* ppidcount){/*{{{*/
 
 	/*retrieve current pid*/
@@ -172,6 +156,5 @@
 }
 /*}}}*/
-/*FUNCTION Vertex::OffsetPids{{{*/
-void  Vertex::OffsetPids(int pidcount){
+void       Vertex::OffsetPids(int pidcount){/*{{{*/
 
 	/*This vertex is a clone, don't offset the pids*/
@@ -182,6 +165,5 @@
 }
 /*}}}*/
-/*FUNCTION Vertex::ShowTruePids{{{*/
-void  Vertex::ShowTruePids(int* truepids){
+void       Vertex::ShowTruePids(int* truepids){/*{{{*/
 
 	/*Are we a clone? : */
@@ -192,6 +174,5 @@
 }
 /*}}}*/
-/*FUNCTION Vertex::UpdateClonePids{{{*/
-void  Vertex::UpdateClonePids(int* alltruepids){
+void       Vertex::UpdateClonePids(int* alltruepids){/*{{{*/
 
 	/*If we are not a clone, don't update, we already have pids: */
@@ -203,6 +184,5 @@
 }
 /*}}}*/
-/*FUNCTION Vertex::SetClone {{{*/
-void  Vertex::SetClone(int* minranks){
+void       Vertex::SetClone(int* minranks){/*{{{*/
 
 	int my_rank;
@@ -222,6 +202,5 @@
 }
 /*}}}*/
-/*FUNCTION Vertex::ToXYZ {{{*/
-void  Vertex::ToXYZ(Matrix<IssmDouble>* matrix){
+void       Vertex::ToXYZ(Matrix<IssmDouble>* matrix){/*{{{*/
 
 	IssmDouble xyz[3];
@@ -240,6 +219,5 @@
 }
 /*}}}*/
-/*FUNCTION Vertex::VertexCoordinates {{{*/
-void  Vertex::VertexCoordinates(Vector<IssmDouble>* vx,Vector<IssmDouble>* vy,Vector<IssmDouble>* vz){
+void       Vertex::VertexCoordinates(Vector<IssmDouble>* vx,Vector<IssmDouble>* vy,Vector<IssmDouble>* vz){/*{{{*/
 
 	if (this->clone==true) return;
Index: issm/trunk/src/c/classes/Vertices.cpp
===================================================================
--- issm/trunk/src/c/classes/Vertices.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/Vertices.cpp	(revision 18301)
@@ -24,12 +24,10 @@
 
 /*Object constructors and destructor*/
-/*FUNCTION Vertices::Vertices(){{{*/
-Vertices::Vertices(){
+Vertices::Vertices(){/*{{{*/
 	enum_type=VerticesEnum;
 	return;
 }
 /*}}}*/
-/*FUNCTION Vertices::~Vertices(){{{*/
-Vertices::~Vertices(){
+Vertices::~Vertices(){/*{{{*/
 	return;
 }
@@ -37,6 +35,5 @@
 
 /*Numerics management*/
-/*FUNCTION Vertices::DistributePids{{{*/
-void  Vertices::DistributePids(int numberofobjects){
+void  Vertices::DistributePids(int numberofobjects){/*{{{*/
 
 	int num_procs;
@@ -102,6 +99,5 @@
 }
 /*}}}*/
-/*FUNCTION Vertices::FlagClones{{{*/
-void  Vertices::FlagClones(int numberofobjects){
+void  Vertices::FlagClones(int numberofobjects){/*{{{*/
 
 	int i;
@@ -142,6 +138,5 @@
 }
 /*}}}*/
-/*FUNCTION Vertices::NumberOfVertices{{{*/
-int Vertices::NumberOfVertices(void){
+int Vertices::NumberOfVertices(void){/*{{{*/
 
 	int i,sid;
@@ -166,6 +161,5 @@
 }
 /*}}}*/
-/*FUNCTION Vertices::Ranks{{{*/
-void   Vertices::Ranks(int* ranks){
+void   Vertices::Ranks(int* ranks){/*{{{*/
 
 	int my_rank;
@@ -184,6 +178,5 @@
 }
 /*}}}*/
-/*FUNCTION Vertices::ToXYZ{{{*/
-IssmDouble* Vertices::ToXYZ(void){
+IssmDouble* Vertices::ToXYZ(void){/*{{{*/
 
 	/*intermediary: */
Index: issm/trunk/src/c/classes/gauss/GaussPenta.cpp
===================================================================
--- issm/trunk/src/c/classes/gauss/GaussPenta.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/gauss/GaussPenta.cpp	(revision 18301)
@@ -13,6 +13,5 @@
 
 /*GaussPenta constructors and destructors:*/
-/*FUNCTION GaussPenta::GaussPenta() {{{*/
-GaussPenta::GaussPenta(){
+GaussPenta::GaussPenta(){/*{{{*/
 
 	numgauss=-1;
@@ -31,6 +30,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussPenta::GaussPenta(int order_horiz,int order_vert) {{{*/
-GaussPenta::GaussPenta(int order_horiz,int order_vert){
+GaussPenta::GaussPenta(int order_horiz,int order_vert){/*{{{*/
 
 	/*Intermediaries*/
@@ -85,6 +83,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussPenta::GaussPenta(int index1, int index2, int order){{{*/
-GaussPenta::GaussPenta(int index1, int index2,int order){
+GaussPenta::GaussPenta(int index1, int index2,int order){/*{{{*/
 
 	/*Intermediaties*/
@@ -142,6 +139,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussPenta::GaussPenta(int index1, int index2, int index3, int order){{{*/
-GaussPenta::GaussPenta(int index1, int index2, int index3, int order){
+GaussPenta::GaussPenta(int index1, int index2, int index3, int order){/*{{{*/
 
 	/*Basal Tria*/
@@ -171,6 +167,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussPenta::GaussPenta(int index1, int index2, int index3, int index4,int order_horiz,int order_vert){{{*/
-GaussPenta::GaussPenta(int index1, int index2, int index3, int index4,int order_horiz,int order_vert){
+GaussPenta::GaussPenta(int index1, int index2, int index3, int index4,int order_horiz,int order_vert){/*{{{*/
 
 	/*Intermediaties*/
@@ -238,6 +233,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussPenta::GaussPenta(int index,double r1,double r2,int order) {{{*/
-GaussPenta::GaussPenta(int index,IssmDouble r1,IssmDouble r2,bool mainlyfloating,int order){
+GaussPenta::GaussPenta(int index,IssmDouble r1,IssmDouble r2,bool mainlyfloating,int order){/*{{{*/
 
 	/*
@@ -400,6 +394,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussPenta::GaussPenta(IssmDouble area_coordinates[4][3],int order_horiz,int order_vert){{{*/
-GaussPenta::GaussPenta(IssmDouble area_coordinates[4][3],int order_horiz,int order_vert){
+GaussPenta::GaussPenta(IssmDouble area_coordinates[4][3],int order_horiz,int order_vert){/*{{{*/
 
 	/*Intermediaties*/
@@ -439,6 +432,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussPenta::~GaussPenta(){{{*/
-GaussPenta::~GaussPenta(){
+GaussPenta::~GaussPenta(){/*{{{*/
 	xDelete<IssmDouble>(weights);
 	xDelete<IssmDouble>(coords1);
@@ -450,6 +442,5 @@
 
 /*Methods*/
-/*FUNCTION GaussPenta::Echo{{{*/
-void GaussPenta::Echo(void){
+void GaussPenta::Echo(void){/*{{{*/
 
 	_printf_("GaussPenta:\n");
@@ -495,11 +486,9 @@
 }
 /*}}}*/
-/*FUNCTION GaussPenta::Enum{{{*/
-int GaussPenta::Enum(void){
+int GaussPenta::Enum(void){/*{{{*/
 	return GaussPentaEnum;
 }
 /*}}}*/
-/*FUNCTION GaussPenta::GaussPoint{{{*/
-void GaussPenta::GaussPoint(int ig){
+void GaussPenta::GaussPoint(int ig){/*{{{*/
 
 	/*Check input in debugging mode*/
@@ -515,6 +504,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussPenta::GaussVertex{{{*/
-void GaussPenta::GaussVertex(int iv){
+void GaussPenta::GaussVertex(int iv){/*{{{*/
 
 	/*in debugging mode: check that the default constructor has been called*/
@@ -535,6 +523,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussPenta::GaussFaceTria{{{*/
-void GaussPenta::GaussFaceTria(int index1, int index2, int index3, int order){
+void GaussPenta::GaussFaceTria(int index1, int index2, int index3, int order){/*{{{*/
 
 	/*in debugging mode: check that the default constructor has been called*/
@@ -553,6 +540,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussPenta::GaussNode{{{*/
-void GaussPenta::GaussNode(int finiteelement,int iv){
+void GaussPenta::GaussNode(int finiteelement,int iv){/*{{{*/
 
 	/*in debugging mode: check that the default constructor has been called*/
@@ -661,4 +647,32 @@
 			}
 			break;
+		case P2bubbleEnum: case P2bubblecondensedEnum:
+			switch(iv){
+				case 0: coord1=1.; coord2=0.; coord3=0.; coord4=-1.; break;
+				case 1: coord1=0.; coord2=1.; coord3=0.; coord4=-1.; break;
+				case 2: coord1=0.; coord2=0.; coord3=1.; coord4=-1.; break;
+				case 3: coord1=1.; coord2=0.; coord3=0.; coord4=+1.; break;
+				case 4: coord1=0.; coord2=1.; coord3=0.; coord4=+1.; break;
+				case 5: coord1=0.; coord2=0.; coord3=1.; coord4=+1.; break;
+
+				case 6: coord1=1.; coord2=0.; coord3=0.; coord4=0.; break;
+				case 7: coord1=0.; coord2=1.; coord3=0.; coord4=0.; break;
+				case 8: coord1=0.; coord2=0.; coord3=1.; coord4=0.; break;
+
+				case  9: coord1=0.; coord2=.5; coord3=.5; coord4=-1.;break;
+				case 10: coord1=.5; coord2=0.; coord3=.5; coord4=-1.;break;
+				case 11: coord1=.5; coord2=.5; coord3=0.; coord4=-1.;break;
+				case 12: coord1=0.; coord2=.5; coord3=.5; coord4=+1.;break;
+				case 13: coord1=.5; coord2=0.; coord3=.5; coord4=+1.;break;
+				case 14: coord1=.5; coord2=.5; coord3=0.; coord4=+1.;break;
+
+				case 15: coord1=0.; coord2=.5; coord3=.5; coord4=0.;break;
+				case 16: coord1=.5; coord2=0.; coord3=.5; coord4=0.;break;
+				case 17: coord1=.5; coord2=.5; coord3=0.; coord4=0.;break;
+
+				case 18: coord1=1./3.; coord2=1./3.; coord3=1./3.; coord4=0.;  break;
+				default: _error_("node index should be in [0 18]");
+			}
+			break;
 		case P2xP4Enum:
 			switch(iv){
@@ -705,6 +719,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussPenta::begin{{{*/
-int GaussPenta::begin(void){
+int GaussPenta::begin(void){/*{{{*/
 
 	/*Check that this has been initialized*/
@@ -720,6 +733,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussPenta::end{{{*/
-int GaussPenta::end(void){
+int GaussPenta::end(void){/*{{{*/
 
 	/*Check that this has been initialized*/
@@ -735,6 +747,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussPenta::SynchronizeGaussBase{{{*/
-void GaussPenta::SynchronizeGaussBase(Gauss* gauss){
+void GaussPenta::SynchronizeGaussBase(Gauss* gauss){/*{{{*/
 
 	_assert_(gauss->Enum()==GaussTriaEnum);
Index: issm/trunk/src/c/classes/gauss/GaussSeg.cpp
===================================================================
--- issm/trunk/src/c/classes/gauss/GaussSeg.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/gauss/GaussSeg.cpp	(revision 18301)
@@ -12,6 +12,5 @@
 
 /*GaussSeg constructors and destructors:*/
-/*FUNCTION GaussSeg::GaussSeg() {{{*/
-GaussSeg::GaussSeg(){
+GaussSeg::GaussSeg(){/*{{{*/
 
 	numgauss=-1;
@@ -24,6 +23,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussSeg::GaussSeg(int order) {{{*/
-GaussSeg::GaussSeg(int order){
+GaussSeg::GaussSeg(int order){/*{{{*/
 
 	IssmPDouble* pcoords1=NULL;
@@ -52,6 +50,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussSeg::GaussSeg(IssmDouble position) {{{*/
-GaussSeg::GaussSeg(IssmDouble position){
+GaussSeg::GaussSeg(IssmDouble position){/*{{{*/
 
 	/*Get gauss points*/
@@ -70,6 +67,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussSeg::~GaussSeg(){{{*/
-GaussSeg::~GaussSeg(){
+GaussSeg::~GaussSeg(){/*{{{*/
 	xDelete<IssmDouble>(weights);
 	xDelete<IssmDouble>(coords1);
@@ -78,6 +74,5 @@
 
 /*Methods*/
-/*FUNCTION GaussSeg::Echo{{{*/
-void GaussSeg::Echo(void){
+void GaussSeg::Echo(void){/*{{{*/
 
 	_printf_("GaussSeg:\n");
@@ -100,11 +95,9 @@
 }
 /*}}}*/
-/*FUNCTION GaussSeg::Enum{{{*/
-int GaussSeg::Enum(void){
+int GaussSeg::Enum(void){/*{{{*/
 	return GaussSegEnum;
 }
 /*}}}*/
-/*FUNCTION GaussSeg::GaussPoint{{{*/
-void GaussSeg::GaussPoint(int ig){
+void GaussSeg::GaussPoint(int ig){/*{{{*/
 
 	/*Check input in debugging mode*/
@@ -116,6 +109,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussSeg::GaussVertex{{{*/
-void GaussSeg::GaussVertex(int iv){
+void GaussSeg::GaussVertex(int iv){/*{{{*/
 
 	/*in debugging mode: check that the default constructor has been called*/
@@ -130,6 +122,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussSeg::GaussNode{{{*/
-void GaussSeg::GaussNode(int finiteelement,int iv){
+void GaussSeg::GaussNode(int finiteelement,int iv){/*{{{*/
 
 	/*in debugging mode: check that the default constructor has been called*/
@@ -150,6 +141,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussSeg::begin{{{*/
-int GaussSeg::begin(void){
+int GaussSeg::begin(void){/*{{{*/
 
 	/*Check that this has been initialized*/
@@ -162,6 +152,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussSeg::end{{{*/
-int GaussSeg::end(void){
+int GaussSeg::end(void){/*{{{*/
 
 	/*Check that this has been initialized*/
@@ -174,6 +163,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussSeg::SynchronizeGaussBase{{{*/
-void GaussSeg::SynchronizeGaussBase(Gauss* gauss){
+void GaussSeg::SynchronizeGaussBase(Gauss* gauss){/*{{{*/
 
 	_error_("not supported");
Index: issm/trunk/src/c/classes/gauss/GaussTetra.cpp
===================================================================
--- issm/trunk/src/c/classes/gauss/GaussTetra.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/gauss/GaussTetra.cpp	(revision 18301)
@@ -13,6 +13,5 @@
 
 /*GaussTetra constructors and destructors:*/
-/*FUNCTION GaussTetra::GaussTetra() {{{*/
-GaussTetra::GaussTetra(){
+GaussTetra::GaussTetra(){/*{{{*/
 
 	numgauss=-1;
@@ -31,6 +30,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussTetra::GaussTetra(int order) {{{*/
-GaussTetra::GaussTetra(int order){
+GaussTetra::GaussTetra(int order){/*{{{*/
 
 	/*Get gauss points*/
@@ -58,6 +56,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussTetra::GaussTetra(int index1,int index2,int index3,int order) {{{*/
-GaussTetra::GaussTetra(int index1,int index2,int index3,int order){
+GaussTetra::GaussTetra(int index1,int index2,int index3,int order){/*{{{*/
 
 	/*Basal Tria*/
@@ -87,6 +84,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussTetra::~GaussTetra(){{{*/
-GaussTetra::~GaussTetra(){
+GaussTetra::~GaussTetra(){/*{{{*/
 	xDelete<IssmDouble>(weights);
 	xDelete<IssmDouble>(coords1);
@@ -98,6 +94,5 @@
 
 /*Methods*/
-/*FUNCTION GaussTetra::Echo{{{*/
-void GaussTetra::Echo(void){
+void GaussTetra::Echo(void){/*{{{*/
 
 	_printf_("GaussTetra:\n");
@@ -143,11 +138,9 @@
 }
 /*}}}*/
-/*FUNCTION GaussTetra::Enum{{{*/
-int GaussTetra::Enum(void){
+int GaussTetra::Enum(void){/*{{{*/
 	return GaussTetraEnum;
 }
 /*}}}*/
-/*FUNCTION GaussTetra::GaussPoint{{{*/
-void GaussTetra::GaussPoint(int ig){
+void GaussTetra::GaussPoint(int ig){/*{{{*/
 
 	/*Check input in debugging mode*/
@@ -163,6 +156,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussTetra::GaussVertex{{{*/
-void GaussTetra::GaussVertex(int iv){
+void GaussTetra::GaussVertex(int iv){/*{{{*/
 
 	/*in debugging mode: check that the default constructor has been called*/
@@ -181,6 +173,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussTetra::GaussNode{{{*/
-void GaussTetra::GaussNode(int finiteelement,int iv){
+void GaussTetra::GaussNode(int finiteelement,int iv){/*{{{*/
 
 	/*in debugging mode: check that the default constructor has been called*/
@@ -229,6 +220,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussTetra::begin{{{*/
-int GaussTetra::begin(void){
+int GaussTetra::begin(void){/*{{{*/
 
 	/*Check that this has been initialized*/
@@ -244,6 +234,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussTetra::end{{{*/
-int GaussTetra::end(void){
+int GaussTetra::end(void){/*{{{*/
 
 	/*Check that this has been initialized*/
@@ -259,6 +248,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussTetra::SynchronizeGaussBase{{{*/
-void GaussTetra::SynchronizeGaussBase(Gauss* gauss){
+void GaussTetra::SynchronizeGaussBase(Gauss* gauss){/*{{{*/
 
 	_error_("not supported");
Index: issm/trunk/src/c/classes/gauss/GaussTria.cpp
===================================================================
--- issm/trunk/src/c/classes/gauss/GaussTria.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/gauss/GaussTria.cpp	(revision 18301)
@@ -7,6 +7,5 @@
 
 /*GaussTria constructors and destructors:*/
-/*FUNCTION GaussTria::GaussTria() {{{*/
-GaussTria::GaussTria(){
+GaussTria::GaussTria(){/*{{{*/
 
 	numgauss=-1;
@@ -23,6 +22,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussTria::GaussTria(int order) {{{*/
-GaussTria::GaussTria(int order){
+GaussTria::GaussTria(int order){/*{{{*/
 
 	/*Get gauss points*/
@@ -37,6 +35,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussTria::GaussTria(int index1,int index2,int order) {{{*/
-GaussTria::GaussTria(int index1,int index2,int order){
+GaussTria::GaussTria(int index1,int index2,int order){/*{{{*/
 
 	/*Intermediaties*/
@@ -100,6 +97,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussTria::GaussTria(IssmDouble area_coordinates,int order) {{{*/
-GaussTria::GaussTria(IssmDouble area_coordinates[2][3],int order){
+GaussTria::GaussTria(IssmDouble area_coordinates[2][3],int order){/*{{{*/
 
 	/*Intermediaties*/
@@ -136,6 +132,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussTria::GaussTria(int index,double r1,double r2,int order) {{{*/
-GaussTria::GaussTria(int index,IssmDouble r1,IssmDouble r2,bool mainlyfloating,int order){
+GaussTria::GaussTria(int index,IssmDouble r1,IssmDouble r2,bool mainlyfloating,int order){/*{{{*/
 
 	/*
@@ -292,6 +287,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussTria::~GaussTria(){{{*/
-GaussTria::~GaussTria(){
+GaussTria::~GaussTria(){/*{{{*/
 	xDelete<IssmDouble>(weights);
 	xDelete<IssmDouble>(coords3);
@@ -303,6 +297,5 @@
 
 /*Methods*/
-/*FUNCTION GaussTria::Echo{{{*/
-void GaussTria::Echo(void){
+void GaussTria::Echo(void){/*{{{*/
 
 	_printf_("GaussTria:\n");
@@ -341,11 +334,9 @@
 }
 /*}}}*/
-/*FUNCTION GaussTria::Enum{{{*/
-int GaussTria::Enum(void){
+int GaussTria::Enum(void){/*{{{*/
 	return GaussTriaEnum;
 }
 /*}}}*/
-/*FUNCTION GaussTria::GaussEdgeCenter{{{*/
-void GaussTria::GaussEdgeCenter(int index1,int index2){
+void GaussTria::GaussEdgeCenter(int index1,int index2){/*{{{*/
 
 	int     index3;
@@ -377,6 +368,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussTria::GaussPoint{{{*/
-void GaussTria::GaussPoint(int ig){
+void GaussTria::GaussPoint(int ig){/*{{{*/
 
 	/*Check input in debugging mode*/
@@ -391,6 +381,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussTria::GaussFromCoords{{{*/
-void GaussTria::GaussFromCoords(IssmDouble x,IssmDouble y,IssmDouble* xyz_list){
+void GaussTria::GaussFromCoords(IssmDouble x,IssmDouble y,IssmDouble* xyz_list){/*{{{*/
 
 	/*Intermediaries*/
@@ -418,6 +407,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussTria::GaussVertex{{{*/
-void GaussTria::GaussVertex(int iv){
+void GaussTria::GaussVertex(int iv){/*{{{*/
 
 	/*in debugging mode: check that the default constructor has been called*/
@@ -434,6 +422,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussTria::GaussNode{{{*/
-void GaussTria::GaussNode(int finiteelement,int iv){
+void GaussTria::GaussNode(int finiteelement,int iv){/*{{{*/
 
 	/*in debugging mode: check that the default constructor has been called*/
@@ -442,4 +429,10 @@
 	/*update static arrays*/
 	switch(finiteelement){
+		case P0Enum:
+			switch(iv){
+				case 0: coord1=1./3.; coord2=1./3.; coord3=1./3.; break;
+				default: _error_("node index should be 0");
+			}
+			break;
 		case P1Enum: case P1DGEnum:
 			switch(iv){
@@ -470,4 +463,16 @@
 			}
 			break;
+		case P2bubbleEnum: case P2bubblecondensedEnum:
+			switch(iv){
+				case 0: coord1=1.; coord2=0.; coord3=0.; break;
+				case 1: coord1=0.; coord2=1.; coord3=0.; break;
+				case 2: coord1=0.; coord2=0.; coord3=1.; break;
+				case 3: coord1=0.; coord2=.5; coord3=.5; break;
+				case 4: coord1=.5; coord2=0.; coord3=.5; break;
+				case 5: coord1=.5; coord2=.5; coord3=0.; break;
+				case 6: coord1=1./3.; coord2=1./3.; coord3=1./3.; break;
+				default: _error_("node index should be in [0 6]");
+			}
+			break;
 		default: _error_("Finite element "<<EnumToStringx(finiteelement)<<" not supported");
 	}
@@ -475,6 +480,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussTria::begin{{{*/
-int GaussTria::begin(void){
+int GaussTria::begin(void){/*{{{*/
 
 	/*Check that this has been initialized*/
@@ -489,6 +493,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussTria::end{{{*/
-int GaussTria::end(void){
+int GaussTria::end(void){/*{{{*/
 
 	/*Check that this has been initialized*/
@@ -503,6 +506,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussTria::SynchronizeGaussBase{{{*/
-void GaussTria::SynchronizeGaussBase(Gauss* gauss){
+void GaussTria::SynchronizeGaussBase(Gauss* gauss){/*{{{*/
 
 	_error_("not supported");
Index: issm/trunk/src/c/classes/kriging/ExponentialVariogram.cpp
===================================================================
--- issm/trunk/src/c/classes/kriging/ExponentialVariogram.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/kriging/ExponentialVariogram.cpp	(revision 18301)
@@ -13,6 +13,5 @@
 
 /*ExponentialVariogram constructors and destructor*/
-/*FUNCTION ExponentialVariogram::ExponentialVariogram(){{{*/
-ExponentialVariogram::ExponentialVariogram(){
+ExponentialVariogram::ExponentialVariogram(){/*{{{*/
 	this->nugget = 0.2;
 	this->sill   = 1;
@@ -21,6 +20,5 @@
 }
 /*}}}*/
-/*FUNCTION ExponentialVariogram::ExponentialVariogram(Options* options){{{*/
-ExponentialVariogram::ExponentialVariogram(Options* options){
+ExponentialVariogram::ExponentialVariogram(Options* options){/*{{{*/
 
 	/*Defaults*/
@@ -38,6 +36,5 @@
 }
 /*}}}*/
-/*FUNCTION ExponentialVariogram::~ExponentialVariogram(){{{*/
-ExponentialVariogram::~ExponentialVariogram(){
+ExponentialVariogram::~ExponentialVariogram(){/*{{{*/
 	return;
 }
@@ -45,6 +42,5 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION ExponentialVariogram::Echo {{{*/
-void ExponentialVariogram::Echo(void){
+void ExponentialVariogram::Echo(void){/*{{{*/
 	_printf_("ExponentialVariogram\n");
 	_printf_("   nugget: " << this->nugget << "\n");
@@ -53,8 +49,11 @@
 }
 /*}}}*/
+Object* ExponentialVariogram::copy(void){/*{{{*/
+	   return new ExponentialVariogram(*this);
+}
+/*}}}*/
 
 /*Variogram function*/
-/*FUNCTION ExponentialVariogram::Covariance{{{*/
-double ExponentialVariogram::Covariance(double deltax,double deltay){
+double ExponentialVariogram::Covariance(double deltax,double deltay){/*{{{*/
 	/*The covariance can be deduced from the variogram from the following
 	 * relationship:
@@ -76,6 +75,5 @@
 }
 /*}}}*/
-/*FUNCTION ExponentialVariogram::SemiVariogram{{{*/
-double ExponentialVariogram::SemiVariogram(double deltax,double deltay){
+double ExponentialVariogram::SemiVariogram(double deltax,double deltay){/*{{{*/
 	/*http://en.wikipedia.org/wiki/Variogram*/
 	double h,a,gamma;
Index: issm/trunk/src/c/classes/kriging/ExponentialVariogram.h
===================================================================
--- issm/trunk/src/c/classes/kriging/ExponentialVariogram.h	(revision 18081)
+++ issm/trunk/src/c/classes/kriging/ExponentialVariogram.h	(revision 18301)
@@ -26,5 +26,5 @@
 		int   Id(){_error_("Not implemented yet");}; 
 		int   ObjectEnum(){_error_("Not implemented yet");};
-		Object* copy(){_error_("Not implemented yet");};
+		Object* copy();
 
 		/*Variogram functions*/
Index: issm/trunk/src/c/classes/kriging/GaussianVariogram.cpp
===================================================================
--- issm/trunk/src/c/classes/kriging/GaussianVariogram.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/kriging/GaussianVariogram.cpp	(revision 18301)
@@ -13,6 +13,5 @@
 
 /*GaussianVariogram constructors and destructor*/
-/*FUNCTION GaussianVariogram::GaussianVariogram(){{{*/
-GaussianVariogram::GaussianVariogram(){
+GaussianVariogram::GaussianVariogram(){/*{{{*/
 	this->nugget = 0.2;
 	this->sill   = 1;
@@ -21,6 +20,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussianVariogram::GaussianVariogram(Options* options){{{*/
-GaussianVariogram::GaussianVariogram(Options* options){
+GaussianVariogram::GaussianVariogram(Options* options){/*{{{*/
 
 	/*Defaults*/
@@ -38,6 +36,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussianVariogram::~GaussianVariogram(){{{*/
-GaussianVariogram::~GaussianVariogram(){
+GaussianVariogram::~GaussianVariogram(){/*{{{*/
 	return;
 }
@@ -45,6 +42,5 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION GaussianVariogram::Echo {{{*/
-void GaussianVariogram::Echo(void){
+void GaussianVariogram::Echo(void){/*{{{*/
 	_printf_("GaussianVariogram\n");
 	_printf_("   nugget: " << this->nugget << "\n");
@@ -53,8 +49,11 @@
 }
 /*}}}*/
+Object* GaussianVariogram::copy(void){/*{{{*/
+	   return new GaussianVariogram(*this);
+}
+/*}}}*/
 
 /*Variogram function*/
-/*FUNCTION GaussianVariogram::Covariance{{{*/
-double GaussianVariogram::Covariance(double deltax,double deltay){
+double GaussianVariogram::Covariance(double deltax,double deltay){/*{{{*/
 	/*The covariance can be deduced from the variogram from the following
 	 * relationship:
@@ -77,6 +76,5 @@
 }
 /*}}}*/
-/*FUNCTION GaussianVariogram::SemiVariogram{{{*/
-double GaussianVariogram::SemiVariogram(double deltax,double deltay){
+double GaussianVariogram::SemiVariogram(double deltax,double deltay){/*{{{*/
 	/*http://en.wikipedia.org/wiki/Variogram*/
 	double h2,a,gamma;
Index: issm/trunk/src/c/classes/kriging/GaussianVariogram.h
===================================================================
--- issm/trunk/src/c/classes/kriging/GaussianVariogram.h	(revision 18081)
+++ issm/trunk/src/c/classes/kriging/GaussianVariogram.h	(revision 18301)
@@ -27,5 +27,5 @@
 		int   Id(){_error_("Not implemented yet");}; 
 		int   ObjectEnum(){_error_("Not implemented yet");};
-		Object* copy(){_error_("Not implemented yet");};
+		Object* copy();
 
 		/*Variogram functions*/
Index: issm/trunk/src/c/classes/kriging/Observation.cpp
===================================================================
--- issm/trunk/src/c/classes/kriging/Observation.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/kriging/Observation.cpp	(revision 18301)
@@ -7,11 +7,9 @@
 
 /*Observation constructors and destructor*/
-/*FUNCTION Observation::Observation(){{{*/
-Observation::Observation(){
+Observation::Observation(){/*{{{*/
 	return;
 }
 /*}}}*/
-/*FUNCTION Observation::Observation(double x,double y,int xi,int yi,int index,double value){{{*/
-Observation::Observation(double x_in,double y_in,int xi_in,int yi_in,int index_in,double value_in){
+Observation::Observation(double x_in,double y_in,int xi_in,int yi_in,int index_in,double value_in){/*{{{*/
 
 	this->x      = x_in;
@@ -25,6 +23,5 @@
 }
 /*}}}*/
-/*FUNCTION Observation::~Observation(){{{*/
-Observation::~Observation(){
+Observation::~Observation(){/*{{{*/
 	return;
 }
@@ -32,6 +29,5 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION Observation::Echo {{{*/
-void Observation::Echo(void){
+void Observation::Echo(void){/*{{{*/
 
 	_printf_("Observation\n");
@@ -45,8 +41,17 @@
 }
 /*}}}*/
+Object* Observation::copy(void){/*{{{*/
+
+	Observation* observation = new Observation(this->x,this->y,this->xi,this->yi,this->index,this->value);
+
+	observation->weight = this->weight;
+
+	return (Object*) observation;
+
+}
+/*}}}*/
 
 /*Observations functions*/
-/*FUNCTION Observation::WriteXYObs(double* px,double* py,double* pobs){{{*/
-void Observation::WriteXYObs(double* px,double* py,double* pobs){
+void Observation::WriteXYObs(double* px,double* py,double* pobs){/*{{{*/
 	*px   = this->x;
 	*py   = this->y;
Index: issm/trunk/src/c/classes/kriging/Observation.h
===================================================================
--- issm/trunk/src/c/classes/kriging/Observation.h	(revision 18081)
+++ issm/trunk/src/c/classes/kriging/Observation.h	(revision 18301)
@@ -27,5 +27,5 @@
 		int     Id()        {_error_("Not implemented yet"); };
 		int     ObjectEnum(){_error_("Not implemented yet"); };
-		Object *copy()      {_error_("Not implemented yet"); };
+		Object *copy();
 
 		/*Management*/
Index: issm/trunk/src/c/classes/kriging/Observations.cpp
===================================================================
--- issm/trunk/src/c/classes/kriging/Observations.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/kriging/Observations.cpp	(revision 18301)
@@ -30,12 +30,10 @@
 
 /*Object constructors and destructor*/
-/*FUNCTION Observations::Observations(){{{*/
-Observations::Observations(){
+Observations::Observations(){/*{{{*/
 	this->quadtree = NULL;
 	return;
 }
 /*}}}*/
-/*FUNCTION Observations::Observations(IssmPDouble* observations_list,IssmPDouble* x,IssmPDouble* y,int n,Options* options){{{*/
-Observations::Observations(IssmPDouble* observations_list,IssmPDouble* x,IssmPDouble* y,int n,Options* options){
+Observations::Observations(IssmPDouble* observations_list,IssmPDouble* x,IssmPDouble* y,int n,Options* options){/*{{{*/
 
 	/*Intermediaries*/
@@ -112,6 +110,5 @@
 }
 /*}}}*/
-/*FUNCTION Observations::~Observations(){{{*/
-Observations::~Observations(){
+Observations::~Observations(){/*{{{*/
 	delete quadtree;
 	return;
@@ -120,6 +117,5 @@
 
 /*Methods*/
-/*FUNCTION Observations::ClosestObservation{{{*/
-void Observations::ClosestObservation(IssmPDouble *px,IssmPDouble *py,IssmPDouble *pobs,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius){
+void Observations::ClosestObservation(IssmPDouble *px,IssmPDouble *py,IssmPDouble *pobs,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius){/*{{{*/
 
 	/*Output and Intermediaries*/
@@ -172,6 +168,5 @@
 
 }/*}}}*/
-/*FUNCTION Observations::Distances{{{*/
-void Observations::Distances(IssmPDouble* distances,IssmPDouble *x,IssmPDouble *y,int n,IssmPDouble radius){
+void Observations::Distances(IssmPDouble* distances,IssmPDouble *x,IssmPDouble *y,int n,IssmPDouble radius){/*{{{*/
 
 	IssmPDouble xi,yi,obs;
@@ -187,6 +182,5 @@
 	}
 }/*}}}*/
-/*FUNCTION Observations::ObservationList(IssmPDouble **px,IssmPDouble **py,IssmPDouble **pobs,int* pnobs,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius,int maxdata){{{*/
-void Observations::ObservationList(IssmPDouble **px,IssmPDouble **py,IssmPDouble **pobs,int* pnobs,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius,int maxdata){
+void Observations::ObservationList(IssmPDouble **px,IssmPDouble **py,IssmPDouble **pobs,int* pnobs,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius,int maxdata){/*{{{*/
 
 	/*Output and Intermediaries*/
@@ -270,6 +264,5 @@
 	*pnobs=nobs;
 }/*}}}*/
-/*FUNCTION Observations::ObservationList(IssmPDouble **px,IssmPDouble **py,IssmPDouble **pobs,int* pnobs){{{*/
-void Observations::ObservationList(IssmPDouble **px,IssmPDouble **py,IssmPDouble **pobs,int* pnobs){
+void Observations::ObservationList(IssmPDouble **px,IssmPDouble **py,IssmPDouble **pobs,int* pnobs){/*{{{*/
 
 	/*Output and Intermediaries*/
@@ -298,6 +291,5 @@
 	*pnobs=nobs;
 }/*}}}*/
-/*FUNCTION Observations::InterpolationIDW{{{*/
-void Observations::InterpolationIDW(IssmPDouble *pprediction,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius,int mindata,int maxdata,IssmPDouble power){
+void Observations::InterpolationIDW(IssmPDouble *pprediction,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius,int mindata,int maxdata,IssmPDouble power){/*{{{*/
 
 	/*Intermediaries*/
@@ -347,6 +339,5 @@
 	xDelete<IssmPDouble>(obs);
 }/*}}}*/
-/*FUNCTION Observations::InterpolationKriging{{{*/
-void Observations::InterpolationKriging(IssmPDouble *pprediction,IssmPDouble *perror,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius,int mindata,int maxdata,Variogram* variogram){
+void Observations::InterpolationKriging(IssmPDouble *pprediction,IssmPDouble *perror,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius,int mindata,int maxdata,Variogram* variogram){/*{{{*/
 
 	/*Intermediaries*/
@@ -424,6 +415,5 @@
 
 }/*}}}*/
-/*FUNCTION Observations::InterpolationNearestNeighbor{{{*/
-void Observations::InterpolationNearestNeighbor(IssmPDouble *pprediction,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius){
+void Observations::InterpolationNearestNeighbor(IssmPDouble *pprediction,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius){/*{{{*/
 
 	/*Intermediaries*/
@@ -436,6 +426,5 @@
 	*pprediction = obs;
 }/*}}}*/
-/*FUNCTION Observations::InterpolationV4{{{*/
-void Observations::InterpolationV4(IssmPDouble *pprediction,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius,int mindata,int maxdata){
+void Observations::InterpolationV4(IssmPDouble *pprediction,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius,int mindata,int maxdata){/*{{{*/
 	/* Reference:  David T. Sandwell, Biharmonic spline interpolation of GEOS-3
 	 * and SEASAT altimeter data, Geophysical Research Letters, 2, 139-142,
@@ -519,6 +508,5 @@
 	xDelete<IssmPDouble>(weights);
 }/*}}}*/
-/*FUNCTION Observations::QuadtreeColoring{{{*/
-void Observations::QuadtreeColoring(IssmPDouble* A,IssmPDouble *x,IssmPDouble *y,int n){
+void Observations::QuadtreeColoring(IssmPDouble* A,IssmPDouble *x,IssmPDouble *y,int n){/*{{{*/
 
 	int xi,yi,level;
@@ -531,6 +519,5 @@
 
 }/*}}}*/
-/*FUNCTION Observations::Variomap{{{*/
-void Observations::Variomap(IssmPDouble* gamma,IssmPDouble *x,int n){
+void Observations::Variomap(IssmPDouble* gamma,IssmPDouble *x,int n){/*{{{*/
 
 	/*Output and Intermediaries*/
Index: issm/trunk/src/c/classes/kriging/PowerVariogram.cpp
===================================================================
--- issm/trunk/src/c/classes/kriging/PowerVariogram.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/kriging/PowerVariogram.cpp	(revision 18301)
@@ -13,6 +13,5 @@
 
 /*PowerVariogram constructors and destructor*/
-/*FUNCTION PowerVariogram::PowerVariogram(){{{*/
-PowerVariogram::PowerVariogram(){
+PowerVariogram::PowerVariogram(){/*{{{*/
 	this->nugget = 0.2;
 	this->slope  = 1.;
@@ -21,6 +20,5 @@
 }
 /*}}}*/
-/*FUNCTION PowerVariogram::PowerVariogram(Options* options){{{*/
-PowerVariogram::PowerVariogram(Options* options){
+PowerVariogram::PowerVariogram(Options* options){/*{{{*/
 
 	/*Defaults*/
@@ -39,6 +37,5 @@
 }
 /*}}}*/
-/*FUNCTION PowerVariogram::~PowerVariogram(){{{*/
-PowerVariogram::~PowerVariogram(){
+PowerVariogram::~PowerVariogram(){/*{{{*/
 	return;
 }
@@ -46,6 +43,5 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION PowerVariogram::Echo {{{*/
-void PowerVariogram::Echo(void){
+void PowerVariogram::Echo(void){/*{{{*/
 	_printf_("PowerVariogram\n");
 	_printf_("   nugget: " << this->nugget << "\n");
@@ -54,8 +50,11 @@
 }
 /*}}}*/
+Object* PowerVariogram::copy(void){/*{{{*/
+	   return new PowerVariogram(*this);
+}
+/*}}}*/
 
 /*Variogram function*/
-/*FUNCTION PowerVariogram::Covariance{{{*/
-double PowerVariogram::Covariance(double deltax,double deltay){
+double PowerVariogram::Covariance(double deltax,double deltay){/*{{{*/
 	/*The covariance can be deduced from the variogram from the following
 	 * relationship:
@@ -74,6 +73,5 @@
 }
 /*}}}*/
-/*FUNCTION PowerVariogram::SemiVariogram{{{*/
-double PowerVariogram::SemiVariogram(double deltax,double deltay){
+double PowerVariogram::SemiVariogram(double deltax,double deltay){/*{{{*/
 	/*http://en.wikipedia.org/wiki/Variogram*/
 	double h,gamma;
Index: issm/trunk/src/c/classes/kriging/PowerVariogram.h
===================================================================
--- issm/trunk/src/c/classes/kriging/PowerVariogram.h	(revision 18081)
+++ issm/trunk/src/c/classes/kriging/PowerVariogram.h	(revision 18301)
@@ -26,5 +26,5 @@
 		int   Id(){_error_("Not implemented yet");}; 
 		int   ObjectEnum(){_error_("Not implemented yet");};
-		Object* copy(){_error_("Not implemented yet");};
+		Object* copy();
 
 		/*Variogram functions*/
Index: issm/trunk/src/c/classes/kriging/Quadtree.cpp
===================================================================
--- issm/trunk/src/c/classes/kriging/Quadtree.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/kriging/Quadtree.cpp	(revision 18301)
@@ -81,12 +81,10 @@
 
 	/*Constructors/Destructors*/
-/*FUNCTION Quadtree::Quadtree(){{{*/
-Quadtree::Quadtree(){
+Quadtree::Quadtree(){/*{{{*/
 	_error_("Constructor not supported");
 
 }
 /*}}}*/
-/*FUNCTION Quadtree::Quadtree(double xmin,double xmax,double ymin,double ymax,int maxdepth){{{*/
-Quadtree::Quadtree(double xmin,double xmax,double ymin,double ymax,int maxdepth){
+Quadtree::Quadtree(double xmin,double xmax,double ymin,double ymax,int maxdepth){/*{{{*/
 
 	/*Intermediaries*/
@@ -106,6 +104,5 @@
 }
 /*}}}*/
-	/*FUNCTION Quadtree::~Quadtree(){{{*/
-	Quadtree::~Quadtree(){
+	Quadtree::~Quadtree(){/*{{{*/
 
 		delete boxcontainer;
@@ -116,6 +113,5 @@
 
 	/*Methods*/
-/*FUNCTION Quadtree::Add{{{*/
-void  Quadtree::Add(Observation* observation){
+void  Quadtree::Add(Observation* observation){/*{{{*/
 
 	/*Intermediaries*/
@@ -199,6 +195,5 @@
 
 }/*}}}*/
-/*FUNCTION Quadtree::AddAndAverage{{{*/
-void Quadtree::AddAndAverage(double x,double y,double value){
+void Quadtree::AddAndAverage(double x,double y,double value){/*{{{*/
 
 	QuadtreeBox **pbox = NULL;
@@ -248,6 +243,5 @@
 	}
 }/*}}}*/
-/*FUNCTION Quadtree::ClosestObs{{{*/
-void Quadtree::ClosestObs(int *pindex,double x,double y){
+void Quadtree::ClosestObs(int *pindex,double x,double y){/*{{{*/
 
 	QuadtreeBox **pbox = NULL;
@@ -288,6 +282,5 @@
 	*pindex=index;
 }/*}}}*/
-/*FUNCTION Quadtree::Echo{{{*/
-void  Quadtree::Echo(void){
+void  Quadtree::Echo(void){/*{{{*/
 
 	_printf_("Quadtree:\n");
@@ -298,6 +291,5 @@
 
 }/*}}}*/
-/*FUNCTION Quadtree::DeepEcho{{{*/
-void  Quadtree::DeepEcho(void){
+void  Quadtree::DeepEcho(void){/*{{{*/
 
 	_printf_("Quadtree:\n");
@@ -309,6 +301,5 @@
 
 }/*}}}*/
-/*FUNCTION Quadtree::IntergerCoordinates{{{*/
-void  Quadtree::IntergerCoordinates(int *xi,int *yi,double x,double y){
+void  Quadtree::IntergerCoordinates(int *xi,int *yi,double x,double y){/*{{{*/
 
 	/*Intermediaries*/
@@ -333,6 +324,5 @@
 	*yi=int(coefficient*(y - ymin));
 }/*}}}*/
-/*FUNCTION Quadtree::NewQuadtreeBox(double xcenter,double ycenter,double length){{{*/
-Quadtree::QuadtreeBox* Quadtree::NewQuadtreeBox(double xcenter,double ycenter,double length){
+Quadtree::QuadtreeBox* Quadtree::NewQuadtreeBox(double xcenter,double ycenter,double length){/*{{{*/
 
 	/*Output*/
@@ -357,6 +347,5 @@
 	return newbox;
 }/*}}}*/
-/*FUNCTION Quadtree::NewQuadtreeBox(QuadtreeBox* master,int index) {{{*/
-Quadtree::QuadtreeBox* Quadtree::NewQuadtreeBox(QuadtreeBox* master,int index){
+Quadtree::QuadtreeBox* Quadtree::NewQuadtreeBox(QuadtreeBox* master,int index){/*{{{*/
 
 	/*Output*/
@@ -402,6 +391,5 @@
 	return newbox;
 }/*}}}*/
-/*FUNCTION Quadtree::QuadtreeDepth{{{*/
-void Quadtree::QuadtreeDepth(int* A,int xi,int yi){
+void Quadtree::QuadtreeDepth(int* A,int xi,int yi){/*{{{*/
 
 	QuadtreeBox **pbox = NULL;
@@ -430,6 +418,5 @@
 	*A=level;
 }/*}}}*/
-/*FUNCTION Quadtree::QuadtreeDepth2{{{*/
-void Quadtree::QuadtreeDepth2(int* A,int xi,int yi){
+void Quadtree::QuadtreeDepth2(int* A,int xi,int yi){/*{{{*/
 
 	QuadtreeBox **pbox = NULL;
@@ -483,6 +470,5 @@
 	*A=level;
 }/*}}}*/
-/*FUNCTION Quadtree::RangeSearch{{{*/
-void Quadtree::RangeSearch(int **pindices,int *pnobs,double x,double y,double range){
+void Quadtree::RangeSearch(int **pindices,int *pnobs,double x,double y,double range){/*{{{*/
 
 	/*Intermediaries*/
@@ -503,6 +489,5 @@
 
 /*QuadtreeBox methos*/
-/*FUNCTION QuadtreeBox::Echo{{{*/
-void  Quadtree::QuadtreeBox::Echo(void){
+void  Quadtree::QuadtreeBox::Echo(void){/*{{{*/
 
 	_printf_("QuadtreeBox:\n");
@@ -513,6 +498,25 @@
 
 }/*}}}*/
-/*FUNCTION QuadtreeBox::IsWithinRange{{{*/
-int Quadtree::QuadtreeBox::IsWithinRange(double x,double y,double range){
+Object* Quadtree::QuadtreeBox::copy(void){/*{{{*/
+
+	   QuadtreeBox* qtreebox = new QuadtreeBox(*this);
+
+		if (this->box){	
+			for (int i=0; i<4; ++i){
+				if(this->box[i]) qtreebox->box[i] = reinterpret_cast<QuadtreeBox*>(this->box[i]->copy());
+				else qtreebox->box[i] = NULL;
+			}
+		}
+		if (this->obs){
+			for (int i=0; i<4; ++i){
+				if(this->obs[i]) qtreebox->obs[i] = reinterpret_cast<Observation*>(this->obs[i]->copy());
+				else qtreebox->obs[i] = NULL;
+			}
+		}
+
+		return (Object*) qtreebox;
+}
+/*}}}*/
+int Quadtree::QuadtreeBox::IsWithinRange(double x,double y,double range){/*{{{*/
 
 	/*Return 0 if the 2 boxes do not overlap*/
@@ -532,6 +536,5 @@
 
 }/*}}}*/
-/*FUNCTION QuadtreeBox::RangeSearch{{{*/
-void Quadtree::QuadtreeBox::RangeSearch(int* indices,int *pnobs,double x,double y,double range){
+void Quadtree::QuadtreeBox::RangeSearch(int* indices,int *pnobs,double x,double y,double range){/*{{{*/
 
 	/*Intermediaries*/
@@ -574,6 +577,5 @@
 	*pnobs=nobs;
 }/*}}}*/
-/*FUNCTION QuadtreeBox::WriteObservations{{{*/
-void Quadtree::QuadtreeBox::WriteObservations(int* indices,int *pnobs){
+void Quadtree::QuadtreeBox::WriteObservations(int* indices,int *pnobs){/*{{{*/
 
 	/*Intermediaries*/
Index: issm/trunk/src/c/classes/kriging/Quadtree.h
===================================================================
--- issm/trunk/src/c/classes/kriging/Quadtree.h	(revision 18081)
+++ issm/trunk/src/c/classes/kriging/Quadtree.h	(revision 18301)
@@ -30,5 +30,5 @@
 				int     Id()        {_error_("not implemented yet"); };
 				int     ObjectEnum(){_error_("not implemented yet"); };
-				Object *copy()      {_error_("not implemented yet"); };
+				Object *copy();
 
 				/*Methods*/
Index: issm/trunk/src/c/classes/kriging/SphericalVariogram.cpp
===================================================================
--- issm/trunk/src/c/classes/kriging/SphericalVariogram.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/kriging/SphericalVariogram.cpp	(revision 18301)
@@ -13,6 +13,5 @@
 
 /*SphericalVariogram constructors and destructor*/
-/*FUNCTION SphericalVariogram::SphericalVariogram(){{{*/
-SphericalVariogram::SphericalVariogram(){
+SphericalVariogram::SphericalVariogram(){/*{{{*/
 	this->nugget = 0.2;
 	this->sill   = 1;
@@ -21,6 +20,5 @@
 }
 /*}}}*/
-/*FUNCTION SphericalVariogram::SphericalVariogram(Options* options){{{*/
-SphericalVariogram::SphericalVariogram(Options* options){
+SphericalVariogram::SphericalVariogram(Options* options){/*{{{*/
 
 	/*Defaults*/
@@ -38,6 +36,5 @@
 }
 /*}}}*/
-/*FUNCTION SphericalVariogram::~SphericalVariogram(){{{*/
-SphericalVariogram::~SphericalVariogram(){
+SphericalVariogram::~SphericalVariogram(){/*{{{*/
 	return;
 }
@@ -45,6 +42,5 @@
 
 /*Object virtual functions definitions:*/
-/*FUNCTION SphericalVariogram::Echo {{{*/
-void SphericalVariogram::Echo(void){
+void SphericalVariogram::Echo(void){/*{{{*/
 	_printf_("SphericalVariogram\n");
 	_printf_("   nugget: " << this->nugget << "\n");
@@ -53,8 +49,11 @@
 }
 /*}}}*/
+Object* SphericalVariogram::copy(void){/*{{{*/
+	return new SphericalVariogram(*this);
+}
+/*}}}*/
 
 /*Variogram function*/
-/*FUNCTION SphericalVariogram::Covariance{{{*/
-double SphericalVariogram::Covariance(double deltax,double deltay){
+double SphericalVariogram::Covariance(double deltax,double deltay){/*{{{*/
 	/*The covariance can be deduced from the variogram from the following
 	 * relationship:
@@ -76,6 +75,5 @@
 }
 /*}}}*/
-/*FUNCTION SphericalVariogram::SemiVariogram{{{*/
-double SphericalVariogram::SemiVariogram(double deltax,double deltay){
+double SphericalVariogram::SemiVariogram(double deltax,double deltay){/*{{{*/
 	/*http://en.wikipedia.org/wiki/Variogram*/
 	double h,gamma;
Index: issm/trunk/src/c/classes/kriging/SphericalVariogram.h
===================================================================
--- issm/trunk/src/c/classes/kriging/SphericalVariogram.h	(revision 18081)
+++ issm/trunk/src/c/classes/kriging/SphericalVariogram.h	(revision 18301)
@@ -26,5 +26,5 @@
 		int   Id(){_error_("Not implemented yet");}; 
 		int   ObjectEnum(){_error_("Not implemented yet");};
-		Object* copy(){_error_("Not implemented yet");};
+		Object* copy();
 
 		/*Variogram functions*/
Index: issm/trunk/src/c/classes/matrix/ElementMatrix.cpp
===================================================================
--- issm/trunk/src/c/classes/matrix/ElementMatrix.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/matrix/ElementMatrix.cpp	(revision 18301)
@@ -18,6 +18,5 @@
 
 /*ElementMatrix constructors and destructor*/
-/*FUNCTION ElementMatrix::ElementMatrix(){{{*/
-ElementMatrix::ElementMatrix(){
+ElementMatrix::ElementMatrix(){/*{{{*/
 
 	this->nrows=0;
@@ -42,6 +41,5 @@
 }
 /*}}}*/
-/*FUNCTION ElementMatrix::ElementMatrix(ElementMatrix* Ke){{{*/
-ElementMatrix::ElementMatrix(ElementMatrix* Ke){
+ElementMatrix::ElementMatrix(ElementMatrix* Ke){/*{{{*/
 
 	if(!Ke) _error_("Input Element Matrix is a NULL pointer");
@@ -50,6 +48,5 @@
 }
 /*}}}*/
-/*FUNCTION ElementMatrix::ElementMatrix(ElementMatrix* Ke1, ElementMatrix* Ke2){{{*/
-ElementMatrix::ElementMatrix(ElementMatrix* Ke1, ElementMatrix* Ke2){
+ElementMatrix::ElementMatrix(ElementMatrix* Ke1, ElementMatrix* Ke2){/*{{{*/
 
 	/*intermediaries*/
@@ -179,6 +176,5 @@
 }
 /*}}}*/
-/*FUNCTION ElementMatrix::ElementMatrix(ElementMatrix* Ke1, ElementMatrix* Ke2,ElementMatrix* Ke3){{{*/
-ElementMatrix::ElementMatrix(ElementMatrix* Ke1, ElementMatrix* Ke2,ElementMatrix* Ke3){
+ElementMatrix::ElementMatrix(ElementMatrix* Ke1, ElementMatrix* Ke2,ElementMatrix* Ke3){/*{{{*/
 
 	/*Concatenate all matrices*/
@@ -194,6 +190,5 @@
 }
 /*}}}*/
-/*FUNCTION ElementMatrix::ElementMatrix(Node** nodes,int numnodes,Parameters* parameters,int approximation){{{*/
-ElementMatrix::ElementMatrix(Node** nodes,int numnodes,Parameters* parameters,int approximation){
+ElementMatrix::ElementMatrix(Node** nodes,int numnodes,Parameters* parameters,int approximation){/*{{{*/
 
 	/*get Matrix size and properties*/
@@ -225,6 +220,5 @@
 }
 /*}}}*/
-/*FUNCTION ElementMatrix::~ElementMatrix(){{{*/
-ElementMatrix::~ElementMatrix(){
+ElementMatrix::~ElementMatrix(){/*{{{*/
 
 	xDelete<IssmDouble>(this->values);
@@ -242,6 +236,5 @@
 
 /*ElementMatrix specific routines: */
-/*FUNCTION ElementMatrix::AddToGlobal(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){{{*/
-void ElementMatrix::AddToGlobal(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){
+void ElementMatrix::AddToGlobal(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){/*{{{*/
 
 	int i,j;
@@ -300,6 +293,5 @@
 }
 /*}}}*/
-/*FUNCTION ElementMatrix::AddToGlobal(Matrix<IssmDouble>* Jff){{{*/
-void ElementMatrix::AddToGlobal(Matrix<IssmDouble>* Jff){
+void ElementMatrix::AddToGlobal(Matrix<IssmDouble>* Jff){/*{{{*/
 
 	int i,j;
@@ -337,6 +329,5 @@
 }
 /*}}}*/
-/*FUNCTION ElementMatrix::CheckConsistency{{{*/
-void ElementMatrix::CheckConsistency(void){
+void ElementMatrix::CheckConsistency(void){/*{{{*/
 	/*Check element matrix values, only in debugging mode*/
 	#ifdef _ISSM_DEBUG_ 
@@ -350,6 +341,5 @@
 }
 /*}}}*/
-/*FUNCTION ElementMatrix::Transpose{{{*/
-void ElementMatrix::Transpose(void){
+void ElementMatrix::Transpose(void){/*{{{*/
 
 	/*Intermediaries*/
@@ -373,6 +363,5 @@
 }
 /*}}}*/
-/*FUNCTION ElementMatrix::StaticCondensation{{{*/
-void ElementMatrix::StaticCondensation(int bsize,int* bindices){
+void ElementMatrix::StaticCondensation(int bsize,int* bindices){/*{{{*/
 	/* 
 	 * | Kii  Kib | | Ui |    |Fi|
@@ -477,6 +466,5 @@
 }
 /*}}}*/
-/*FUNCTION ElementMatrix::Echo{{{*/
-void ElementMatrix::Echo(void){
+void ElementMatrix::Echo(void){/*{{{*/
 
 	int i,j;
@@ -523,6 +511,5 @@
 }
 /*}}}*/
-/*FUNCTION ElementMatrix::Init{{{*/
-void ElementMatrix::Init(ElementMatrix* Ke){
+void ElementMatrix::Init(ElementMatrix* Ke){/*{{{*/
 
 	_assert_(Ke);
Index: issm/trunk/src/c/classes/matrix/ElementVector.cpp
===================================================================
--- issm/trunk/src/c/classes/matrix/ElementVector.cpp	(revision 18081)
+++ issm/trunk/src/c/classes/matrix/ElementVector.cpp	(revision 18301)
@@ -18,6 +18,5 @@
 
 /*ElementVector constructors and destructor*/
-/*FUNCTION ElementVector::ElementVector(){{{*/
-ElementVector::ElementVector(){
+ElementVector::ElementVector(){/*{{{*/
 
 	this->nrows=0;
@@ -29,6 +28,5 @@
 }
 /*}}}*/
-/*FUNCTION ElementVector::ElementVector(ElementVector* pe1, ElementVector* pe2){{{*/
-ElementVector::ElementVector(ElementVector* pe1, ElementVector* pe2){
+ElementVector::ElementVector(ElementVector* pe1, ElementVector* pe2){/*{{{*/
 
 	/*intermediaries*/
@@ -114,6 +112,5 @@
 }
 /*}}}*/
-/*FUNCTION ElementVector::ElementVector(ElementVector* pe1, ElementVector* pe2,ElementVector* pe3){{{*/
-ElementVector::ElementVector(ElementVector* pe1, ElementVector* pe2,ElementVector* pe3){
+ElementVector::ElementVector(ElementVector* pe1, ElementVector* pe2,ElementVector* pe3){/*{{{*/
 
 	/*Concatenate all matrices*/
@@ -129,6 +126,5 @@
 }
 /*}}}*/
-/*FUNCTION ElementVector::ElementVector(Node** nodes,int numnodes,Parameters* parameters,int approximation){{{*/
-ElementVector::ElementVector(Node** nodes,int numnodes,Parameters* parameters,int approximation){
+ElementVector::ElementVector(Node** nodes,int numnodes,Parameters* parameters,int approximation){/*{{{*/
 
 	/*get Vector size and properties*/
@@ -147,6 +143,5 @@
 }
 /*}}}*/
-/*FUNCTION ElementVector::~ElementVector(){{{*/
-ElementVector::~ElementVector(){
+ElementVector::~ElementVector(){/*{{{*/
 
 	xDelete<IssmDouble>(this->values);
@@ -158,6 +153,5 @@
 
 /*ElementVector specific routines: */
-/*FUNCTION ElementVector::AddToGlobal(Vector<IssmDouble>* pf){{{*/
-void ElementVector::AddToGlobal(Vector<IssmDouble>* pf){
+void ElementVector::AddToGlobal(Vector<IssmDouble>* pf){/*{{{*/
 
 	int i;
@@ -182,6 +176,5 @@
 }
 /*}}}*/
-/*FUNCTION ElementVector::InsertIntoGlobal(Vector<IssmDouble>* pf){{{*/
-void ElementVector::InsertIntoGlobal(Vector<IssmDouble>* pf){
+void ElementVector::InsertIntoGlobal(Vector<IssmDouble>* pf){/*{{{*/
 
 	int i;
@@ -203,6 +196,5 @@
 }
 /*}}}*/
-/*FUNCTION ElementVector::CheckConsistency{{{*/
-void ElementVector::CheckConsistency(void){
+void ElementVector::CheckConsistency(void){/*{{{*/
 	/*Check element matrix values, only in debugging mode*/
 #ifdef _ISSM_DEBUG_ 
@@ -214,6 +206,5 @@
 }
 /*}}}*/
-/*FUNCTION ElementVector::Echo{{{*/
-void ElementVector::Echo(void){
+void ElementVector::Echo(void){/*{{{*/
 
 	int i;
@@ -239,6 +230,5 @@
 }
 /*}}}*/
-/*FUNCTION ElementVector::Init{{{*/
-void ElementVector::Init(ElementVector* pe){
+void ElementVector::Init(ElementVector* pe){/*{{{*/
 
 	_assert_(pe);
@@ -265,6 +255,5 @@
 }
 /*}}}*/
-/*FUNCTION ElementVector::SetValue{{{*/
-void ElementVector::SetValue(IssmDouble scalar){
+void ElementVector::SetValue(IssmDouble scalar){/*{{{*/
 
 	int i;
@@ -274,6 +263,5 @@
 }
 /*}}}*/
-/*FUNCTION ElementVector::StaticCondensation{{{*/
-void ElementVector::StaticCondensation(ElementMatrix* Ke,int bsize,int* bindices){
+void ElementVector::StaticCondensation(ElementMatrix* Ke,int bsize,int* bindices){/*{{{*/
 	/* 
 	 * | Kii  Kib | | Ui |    |Fi|
Index: issm/trunk/src/c/cores/AnalysisConfiguration.cpp
===================================================================
--- issm/trunk/src/c/cores/AnalysisConfiguration.cpp	(revision 18081)
+++ issm/trunk/src/c/cores/AnalysisConfiguration.cpp	(revision 18301)
@@ -26,5 +26,5 @@
 
 		case StressbalanceSolutionEnum:
-			numanalyses=6;
+			numanalyses=7;
 			analyses=xNew<int>(numanalyses);
 			analyses[0]=StressbalanceAnalysisEnum;
@@ -34,4 +34,5 @@
 			analyses[4]=ExtrudeFromBaseAnalysisEnum;
 			analyses[5]=DepthAverageAnalysisEnum;
+			analyses[6]=UzawaPressureAnalysisEnum;
 			break;
 
Index: issm/trunk/src/c/cores/DakotaSpawnCore.cpp
===================================================================
--- issm/trunk/src/c/cores/DakotaSpawnCore.cpp	(revision 18081)
+++ issm/trunk/src/c/cores/DakotaSpawnCore.cpp	(revision 18301)
@@ -51,6 +51,7 @@
 	if(counter==-1)return 0;
 
-	/*cast void_femmodel to FemModel: */
-	femmodel=reinterpret_cast<FemModel*>(void_femmodel);
+	/*cast void_femmodel to FemModel, and at the same time, make a copy, so we start this new core run for this specific sample 
+	 *with a brand new copy of the model, which has not been tempered with by previous dakota runs: */
+	femmodel=(reinterpret_cast<FemModel*>(void_femmodel))->copy();
 
 	/*retrieve parameters: */
@@ -80,4 +81,7 @@
 	/*Free ressources:*/
 	DakotaFree(&d_variables,&d_variables_descriptors,&responses_descriptors, d_numvariables, numresponsedescriptors);
+
+	/*Avoid leaks here: */
+	delete femmodel;
 
 	return 1; //this is critical! do not return 0, otherwise, dakota_core will stop running!
Index: issm/trunk/src/c/cores/WrapperCorePointerFromSolutionEnum.cpp
===================================================================
--- issm/trunk/src/c/cores/WrapperCorePointerFromSolutionEnum.cpp	(revision 18081)
+++ issm/trunk/src/c/cores/WrapperCorePointerFromSolutionEnum.cpp	(revision 18301)
@@ -46,4 +46,5 @@
 			case 1: solutioncore=controltao_core; break;
 			case 2: solutioncore=controlm1qn3_core; break;
+			case 3: solutioncore=controlvalidation_core; break;
 			default: _error_("control type not supported");
 		}
Index: issm/trunk/src/c/cores/adjointbalancethickness2_core.cpp
===================================================================
--- issm/trunk/src/c/cores/adjointbalancethickness2_core.cpp	(revision 18081)
+++ issm/trunk/src/c/cores/adjointbalancethickness2_core.cpp	(revision 18301)
@@ -32,5 +32,5 @@
 
 	/*Save results*/
-	if(save_results){
+	if(save_results || true){
 		if(VerboseSolution()) _printf0_("   saving results\n");
 		int outputs[1] = {AdjointEnum};
Index: issm/trunk/src/c/cores/control_core.cpp
===================================================================
--- issm/trunk/src/c/cores/control_core.cpp	(revision 18081)
+++ issm/trunk/src/c/cores/control_core.cpp	(revision 18301)
@@ -11,33 +11,27 @@
 
 /*Local prototypes*/
-bool controlconvergence(IssmDouble J, IssmDouble tol_cm);
-IssmDouble objectivefunction(IssmDouble search_scalar,void* optargs);
-
-void control_core(FemModel* femmodel){
-
-	int     i;
+/*{{{*/
+IssmDouble FormFunction(IssmDouble* X,void* usr);
+IssmDouble FormFunctionGradient(IssmDouble** pG,IssmDouble* X,void* usr);
+typedef struct {
+	FemModel* femmodel;
+	int       nsize;
+} AppCtx;
+/*}}}*/
+
+void control_core(FemModel* femmodel){/*{{{*/
 
 	/*parameters: */
-	int        num_controls;
-	int        nsteps;
-	IssmDouble tol_cm;
-	int        solution_type;
-	bool       isFS;
-	bool       dakota_analysis = false;
-
-	int        *control_type   = NULL;
-	IssmDouble *maxiter        = NULL;
-	IssmDouble *cm_jump        = NULL;
-
-	/*intermediary: */
-	IssmDouble search_scalar = 1.;
-	OptPars    optpars;
+	int         num_controls,nsize,nsteps;
+	int         solution_type;
+	bool        isFS,dakota_analysis;
+	int        *control_type  = NULL;
+	int        *maxiter       = NULL;
+	IssmDouble *cm_jump       = NULL;
+	IssmDouble *J             = NULL;
 
 	/*Solution and Adjoint core pointer*/
 	void (*solutioncore)(FemModel*) = NULL;
 	void (*adjointcore)(FemModel*)  = NULL;
-
-	/*output: */
-	IssmDouble* J=NULL;
 
 	/*Recover parameters used throughout the solution*/
@@ -47,5 +41,4 @@
 	femmodel->parameters->FindParam(&maxiter,NULL,InversionMaxiterPerStepEnum);
 	femmodel->parameters->FindParam(&cm_jump,NULL,InversionStepThresholdEnum);
-	femmodel->parameters->FindParam(&tol_cm,InversionCostFunctionThresholdEnum);
 	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
 	femmodel->parameters->FindParam(&isFS,FlowequationIsFSEnum);
@@ -61,35 +54,40 @@
 	if(isFS) solutioncore(femmodel);
 
-	/*Initialize cost function: */
-	J=xNew<IssmDouble>(nsteps);
+	/*Get initial guess*/
+	Vector<IssmDouble> *Xpetsc = NULL;
+	GetVectorFromControlInputsx(&Xpetsc,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"value");
+	IssmDouble* X0 = Xpetsc->ToMPISerial();
+	Xpetsc->GetSize(&nsize);
+	delete Xpetsc;
 
 	/*Initialize some of the BrentSearch arguments: */
-	optpars.xmin=0; optpars.xmax=1;
-
-	/*Start looping: */
-	for(int n=0;n<nsteps;n++){
-
-		/*Display info*/
-		if(VerboseControl()) _printf0_("\n" << "   control method step " << n+1 << "/" << nsteps << "\n");
-
-
-		/*In steady state inversion, compute new temperature field now*/
-		if(solution_type==SteadystateSolutionEnum) solutioncore(femmodel);
-
-		if(VerboseControl()) _printf0_("   compute adjoint state:\n");
-		adjointcore(femmodel);
-		gradient_core(femmodel,n,search_scalar==0.);
-
-		if(VerboseControl()) _printf0_("   optimizing along gradient direction\n");
-		optpars.maxiter=reCast<int,IssmDouble>(maxiter[n]); optpars.cm_jump=cm_jump[n];
-		BrentSearch(&search_scalar,J+n,&optpars,&objectivefunction,(void*)femmodel);
-
-		if(VerboseControl()) _printf0_("   updating parameter using optimized search scalar\n"); //true means update save controls
-		InputControlUpdatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,search_scalar,true);
-
-		if(controlconvergence(J[n],tol_cm)) break;
-	}
+	OptPars optpars;
+	optpars.xmin    = 0; 
+	optpars.xmax    = 1;
+	optpars.nsteps  = nsteps;
+	optpars.nsize   = nsize;
+	optpars.maxiter = maxiter;
+	optpars.cm_jump = cm_jump;
+
+	/*Initialize function argument*/
+	AppCtx usr;
+	usr.femmodel = femmodel;
+	usr.nsize    = nsize;
+
+	/*Call Brent optimization*/
+	BrentSearch(&J,optpars,X0,&FormFunction,&FormFunctionGradient,(void*)&usr);
 
 	if(VerboseControl()) _printf0_("   preparing final solution\n");
+	IssmDouble  *XL = NULL;
+	IssmDouble  *XU = NULL;
+	GetVectorFromControlInputsx(&XL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
+	GetVectorFromControlInputsx(&XU,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
+	for(long i=0;i<nsize;i++){
+		if(X0[i]>XU[i]) X0[i]=XU[i];
+		if(X0[i]<XL[i]) X0[i]=XL[i];
+	}
+	xDelete<IssmDouble>(XU);
+	xDelete<IssmDouble>(XL);
+	SetControlInputsFromVectorx(femmodel,X0);
 	femmodel->parameters->SetParam(true,SaveResultsEnum);
 	solutioncore(femmodel);
@@ -101,5 +99,5 @@
 		#ifdef _HAVE_ADOLC_
 		IssmPDouble* J_passive=xNew<IssmPDouble>(nsteps);
-		for(i=0;i<nsteps;i++) J_passive[i]=reCast<IssmPDouble>(J[i]);
+		for(int i=0;i<nsteps;i++) J_passive[i]=reCast<IssmPDouble>(J[i]);
 		femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,JEnum,J_passive,nsteps,1,1,0));
 		xDelete<IssmPDouble>(J_passive);
@@ -111,22 +109,10 @@
 	/*Free ressources: */
 	xDelete<int>(control_type);
-	xDelete<IssmDouble>(maxiter);
+	xDelete<int>(maxiter);
 	xDelete<IssmDouble>(cm_jump);
 	xDelete<IssmDouble>(J);
-}
-bool controlconvergence(IssmDouble J, IssmDouble tol_cm){
-
-	bool converged=false;
-
-	/*Has convergence been reached?*/
-	if (!xIsNan<IssmDouble>(tol_cm) && J<tol_cm){
-		converged=true;
-		if(VerboseConvergence()) _printf0_("      Convergence criterion reached: J = " << J << " < " << tol_cm);
-	}
-
-	return converged;
-}
-
-IssmDouble objectivefunction(IssmDouble search_scalar,void* optargs){
+	xDelete<IssmDouble>(X0);
+}/*}}}*/
+IssmDouble FormFunction(IssmDouble* X,void* usrvoid){/*{{{*/
 
 	/*output: */
@@ -134,52 +120,146 @@
 
 	/*parameters: */
-	int        solution_type,analysis_type;
-	bool       isFS       = false;
+	int        solution_type,analysis_type,num_responses;
 	bool       conserve_loads = true;
-	FemModel  *femmodel       = (FemModel*)optargs;
+	AppCtx*    usr = (AppCtx*)usrvoid;
+	FemModel  *femmodel  = usr->femmodel;
+	int        nsize     = usr->nsize;
 
 	/*Recover parameters: */
-	femmodel->parameters->FindParam(&isFS,FlowequationIsFSEnum);
 	femmodel->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
 	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
-
-	/*set analysis type to compute velocity: */
-	if (solution_type==SteadystateSolutionEnum || solution_type==StressbalanceSolutionEnum){
-		femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
-	}
-	else if (solution_type==BalancethicknessSolutionEnum){
-		femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum);
-	}
-	else if (solution_type==BalancethicknessSoftSolutionEnum){
-		femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum);
-	}
-	else{
-		_error_("Solution " << EnumToStringx(solution_type) << " not implemented yet");
-	}
-
-	/*update parameter according to scalar: */ //false means: do not save control
-	InputControlUpdatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,search_scalar,false);
-
-	/*Run stressbalance with updated inputs: */
-	if (solution_type==SteadystateSolutionEnum){
-		stressbalance_core(femmodel);	//We need a 3D velocity!! (vz is required for the next thermal run)
-	}
-	else if (solution_type==StressbalanceSolutionEnum){
-		solutionsequence_nonlinear(femmodel,conserve_loads); 
-	}
-	else if (solution_type==BalancethicknessSolutionEnum){
-		solutionsequence_linear(femmodel); 
-	}
-	else if (solution_type==BalancethicknessSoftSolutionEnum){
-		/*Don't do anything*/
-	}
-	else{
-		_error_("Solution " << EnumToStringx(solution_type) << " not implemented yet");
+	femmodel->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+
+	/*Constrain input vector*/
+	IssmDouble  *XL = NULL;
+	IssmDouble  *XU = NULL;
+	GetVectorFromControlInputsx(&XL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
+	GetVectorFromControlInputsx(&XU,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
+	for(long i=0;i<nsize;i++){
+		if(X[i]>XU[i]) X[i]=XU[i];
+		if(X[i]<XL[i]) X[i]=XL[i];
+	}
+
+	/*Update control input*/
+	SetControlInputsFromVectorx(femmodel,X);
+
+	/*solve forward: */
+	switch(solution_type){
+		case SteadystateSolutionEnum:
+			femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
+			stressbalance_core(femmodel);	//We need a 3D velocity!! (vz is required for the next thermal run)
+			break;
+		case StressbalanceSolutionEnum:
+			femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
+			solutionsequence_nonlinear(femmodel,conserve_loads); 
+			break;
+		case BalancethicknessSolutionEnum:
+			femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum);
+			solutionsequence_linear(femmodel); 
+			break;
+		case BalancethicknessSoftSolutionEnum:
+			/*NOTHING*/
+			break;
+		case Balancethickness2SolutionEnum:
+			femmodel->SetCurrentConfiguration(Balancethickness2AnalysisEnum);
+			solutionsequence_linear(femmodel); 
+			break;
+		default:
+			_error_("Solution " << EnumToStringx(solution_type) << " not implemented yet");
 	}
 
 	/*Compute misfit for this velocity field.*/
-	femmodel->CostFunctionx(&J,NULL,NULL);
+	IssmDouble* Jlist = NULL;
+	femmodel->CostFunctionx(&J,&Jlist,NULL);
+	_printf0_("f(x) = "<<setw(12)<<setprecision(7)<<J<<"  |  ");
+	for(int i=0;i<num_responses;i++) _printf0_(" "<<setw(12)<<setprecision(7)<<Jlist[i]);
+	_printf0_("\n");
 
 	/*Free ressources:*/
+	xDelete<IssmDouble>(XU);
+	xDelete<IssmDouble>(XL);
+	xDelete<IssmDouble>(Jlist);
 	return J;
-}
+}/*}}}*/
+IssmDouble FormFunctionGradient(IssmDouble** pG,IssmDouble* X,void* usrvoid){/*{{{*/
+
+	/*output: */
+	IssmDouble J;
+
+	/*parameters: */
+	void (*adjointcore)(FemModel*)=NULL;
+	int         solution_type,analysis_type,num_responses,num_controls,numvertices;
+	bool        conserve_loads = true;
+	IssmDouble *scalar_list    = NULL;
+	IssmDouble *Jlist          = NULL;
+	IssmDouble *G              = NULL;
+	IssmDouble *norm_list      = NULL;
+	AppCtx     *usr            = (AppCtx*)usrvoid;
+	FemModel   *femmodel       = usr->femmodel;
+	int         nsize          = usr->nsize;
+
+	/*Recover parameters: */
+	femmodel->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	femmodel->parameters->FindParam(&scalar_list,NULL,NULL,InversionGradientScalingEnum);
+	femmodel->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);   _assert_(num_controls);
+	numvertices=femmodel->vertices->NumberOfVertices();
+
+	/*Constrain input vector*/
+	IssmDouble  *XL = NULL;
+	IssmDouble  *XU = NULL;
+	GetVectorFromControlInputsx(&XL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
+	GetVectorFromControlInputsx(&XU,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
+	for(long i=0;i<nsize;i++){
+		if(X[i]>XU[i]) X[i]=XU[i];
+		if(X[i]<XL[i]) X[i]=XL[i];
+	}
+
+	/*Update control input*/
+	SetControlInputsFromVectorx(femmodel,X);
+
+	/*Compute new temperature at this point*/
+	if(solution_type==SteadystateSolutionEnum) steadystate_core(femmodel);
+
+	/*Compute Adjoint*/
+	AdjointCorePointerFromSolutionEnum(&adjointcore,solution_type);
+	adjointcore(femmodel);
+
+	/*Compute gradient*/
+	Gradjx(&G,&norm_list,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+
+	/*Compute scaling factor*/
+	IssmDouble scalar = scalar_list[0]/norm_list[0];
+	for(int i=1;i<num_controls;i++) scalar=min(scalar,scalar_list[i]/norm_list[i]);
+
+	/*Constrain Gradient*/
+	for(int i=0;i<num_controls;i++){
+		for(int j=0;j<numvertices;j++){
+			G[i*numvertices+j] = scalar*G[i*numvertices+j];
+		}
+	}
+
+	for(long i=0;i<nsize;i++){
+		if(X[i]>=XU[i]) G[i]=0.;
+		if(X[i]<=XL[i]) G[i]=0.;
+	}
+
+	/*Needed for output results*/
+	ControlInputSetGradientx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,G);
+
+	/*Compute misfit for this velocity field.*/
+	femmodel->CostFunctionx(&J,&Jlist,NULL);
+	_printf0_("f(x) = "<<setw(12)<<setprecision(7)<<J<<"  |  ");
+	for(int i=0;i<num_responses;i++) _printf0_(" "<<setw(12)<<setprecision(7)<<Jlist[i]);
+	_printf0_("\n");
+
+	/*Clean-up and return*/
+	xDelete<IssmDouble>(XU);
+	xDelete<IssmDouble>(XL);
+	xDelete<IssmDouble>(norm_list);
+	xDelete<IssmDouble>(scalar_list);
+	xDelete<IssmDouble>(Jlist);
+	*pG = G;
+	return J;
+}/*}}}*/
Index: issm/trunk/src/c/cores/controlm1qn3_core.cpp
===================================================================
--- issm/trunk/src/c/cores/controlm1qn3_core.cpp	(revision 18081)
+++ issm/trunk/src/c/cores/controlm1qn3_core.cpp	(revision 18301)
@@ -106,5 +106,5 @@
 
 	/*Get solution*/
-	SetControlInputsFromVectorx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,X);
+	SetControlInputsFromVectorx(femmodel,X);
 	ControlInputSetGradientx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,G);
 	femmodel->OutputControlsx(&femmodel->results);
@@ -131,8 +131,7 @@
 	FemModel   *femmodel  = (FemModel*)dzs;
 
-	/*Recover responses*/
-	int         num_responses;
-	int        *responses = NULL;
-	femmodel->parameters->FindParam(&responses,&num_responses,InversionCostFunctionsEnum);
+	/*Recover number of cost functions responses*/
+	int num_responses;
+	femmodel->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
 
 	/*Constrain input vector*/
@@ -147,5 +146,5 @@
 
 	/*Update control input*/
-	SetControlInputsFromVectorx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,X);
+	SetControlInputsFromVectorx(femmodel,X);
 
 	/*Recover some parameters*/
@@ -170,5 +169,4 @@
 	if(indic==0){
 		/*dry run, no gradient required*/
-		xDelete<int>(responses);
 		xDelete<IssmDouble>(XU);
 		xDelete<IssmDouble>(XL);
@@ -193,5 +191,4 @@
 
 	/*Clean-up and return*/
-	xDelete<int>(responses);
 	xDelete<IssmDouble>(XU);
 	xDelete<IssmDouble>(XL);
Index: issm/trunk/src/c/cores/controltao_core.cpp
===================================================================
--- issm/trunk/src/c/cores/controltao_core.cpp	(revision 18081)
+++ issm/trunk/src/c/cores/controltao_core.cpp	(revision 18301)
@@ -10,10 +10,19 @@
 #include "../solutionsequences/solutionsequences.h"
 
-#if defined (_HAVE_TAO_) && defined (_HAVE_PETSC_) && (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ > 1)
+#if defined (_HAVE_TAO_)
+#if defined (_HAVE_PETSC_) && (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 5)
 #include <tao.h>
+#else
+#include <petsctao.h>
+#endif
 
 /*Local prototype*/
+#if defined (_HAVE_PETSC_) && (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 5)
 int FormFunctionGradient(TaoSolver,Vec,IssmDouble*,Vec,void*);
 int IssmMonitor(TaoSolver,void*);
+#else
+int FormFunctionGradient(Tao,Vec,IssmDouble*,Vec,void*);
+int IssmMonitor(Tao,void*);
+#endif
 typedef struct {
 	FemModel* femmodel;
@@ -29,5 +38,9 @@
 	IssmDouble          fatol,frtol,gatol,grtol,gttol;
 	AppCtx              user;
+	#if defined (_HAVE_PETSC_) && (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 5)
 	TaoSolver           tao = 0;
+	#else
+	Tao                 tao = 0;
+	#endif
 	int                *control_list = NULL;
 	char               *algorithm    = NULL;
@@ -38,8 +51,10 @@
 
 	/*Initialize TAO*/
+	#if defined (_HAVE_PETSC_) && (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 5)
 	int argc; char **args=NULL;
 	PetscGetArgs(&argc,&args);
 	ierr = TaoInitialize(&argc,&args,(char*)0,"");
 	if(ierr) _error_("Could not initialize Tao");
+	#endif
 
 	/*Recover some parameters*/
@@ -93,5 +108,5 @@
 	G=new Vector<IssmDouble>(0); VecFree(&G->pvector->vector);
 	TaoGetGradientVector(tao,&G->pvector->vector);
-	SetControlInputsFromVectorx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,X);
+	SetControlInputsFromVectorx(femmodel,X);
 	ControlInputSetGradientx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,G);
 	femmodel->OutputControlsx(&femmodel->results);
@@ -111,11 +126,18 @@
 	delete X;
 	TaoDestroy(&tao);
+	#if defined (_HAVE_PETSC_) && (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 5)
 	TaoFinalize();
-}
-int FormFunctionGradient(TaoSolver tao, Vec Xpetsc, IssmDouble *fcn,Vec G,void *userCtx){
+	#endif
+}
+
+#if defined (_HAVE_PETSC_) && (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 5)
+int FormFunctionGradient(TaoSolver tao, Vec Xpetsc, IssmDouble *fcn,Vec G,void *uservoid){
+#else
+int FormFunctionGradient(Tao tao, Vec Xpetsc, IssmDouble *fcn,Vec G,void *uservoid){
+#endif
 
 	/*Retreive arguments*/
 	int                  solution_type;
-	AppCtx              *user            = (AppCtx *)userCtx;
+	AppCtx              *user            = (AppCtx *)uservoid;
 	FemModel            *femmodel        = user->femmodel;
 	Vector<IssmDouble>  *gradient        = NULL;
@@ -127,5 +149,5 @@
 	/*Set new variable*/
 	//VecView(X,PETSC_VIEWER_STDOUT_WORLD);
-	SetControlInputsFromVectorx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,X);
+	SetControlInputsFromVectorx(femmodel,X);
 	delete X;
 
@@ -152,5 +174,9 @@
 	return 0;
 }
+#if defined (_HAVE_PETSC_) && (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 5)
 int IssmMonitor(TaoSolver tao, void *userCtx){
+#else
+int IssmMonitor(Tao tao, void *userCtx){
+#endif
 
 	int         its,num_responses;
Index: issm/trunk/src/c/cores/controlvalidation_core.cpp
===================================================================
--- issm/trunk/src/c/cores/controlvalidation_core.cpp	(revision 18301)
+++ issm/trunk/src/c/cores/controlvalidation_core.cpp	(revision 18301)
@@ -0,0 +1,102 @@
+/*!\file: controlvalidation_core.cpp
+ * \brief: core of the control solution 
+ */ 
+
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+void controlvalidation_core(FemModel* femmodel){
+
+	int         solution_type,n;
+	IssmDouble  j0,j;
+	IssmDouble  Ialpha,exponent,alpha;
+	IssmDouble *G = NULL;
+	IssmDouble *X = NULL;
+	IssmDouble *X0= NULL;
+
+	/*Solution and Adjoint core pointer*/
+	void (*solutioncore)(FemModel*) = NULL;
+	void (*adjointcore)(FemModel*)  = NULL;
+
+	/*Recover parameters used throughout the solution*/
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->SetParam(false,SaveResultsEnum);
+
+	/*Get initial guess*/
+	Vector<IssmDouble> *Xpetsc = NULL;
+	GetVectorFromControlInputsx(&Xpetsc,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"value");
+	Xpetsc->GetSize(&n);
+	X0 = Xpetsc->ToMPISerial();
+	delete Xpetsc;
+
+	/*Allocate Gradient and current vector*/
+	G = xNew<IssmDouble>(n);
+	X = xNew<IssmDouble>(n);
+
+	/*out of solution_type, figure out solution core and adjoint function pointer*/
+	CorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type);
+	AdjointCorePointerFromSolutionEnum(&adjointcore,solution_type);
+
+	if(VerboseControl()) _printf0_("   Compute Initial solution\n");
+	solutioncore(femmodel);
+	if(VerboseControl()) _printf0_("   Compute Adjoint\n");
+	adjointcore(femmodel);
+	if(VerboseControl()) _printf0_("   Compute Initial cost function\n");
+	femmodel->CostFunctionx(&j0,NULL,NULL);
+	if(VerboseControl()) _printf0_("   Compute Gradient\n");
+	Gradjx(&G,NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+	for(int i=0;i<n;i++) G[i] = -G[i];
+
+	/*Range of tests*/
+	IssmDouble exp0 = 0.;
+	IssmDouble incr = -0.2;
+	IssmDouble exp1 = -10.;
+	int        num  = reCast<int,IssmDouble>((exp1-exp0)/incr);
+
+	/*Allocate output*/
+	IssmDouble* output = xNew<IssmDouble>(2*num);
+
+	/*Start loop*/
+	_printf0_("       alpha      Ialpha \n");
+	_printf0_("_________________________\n");
+	for(int m=0;m<num;m++){
+
+		/*Calculate alpha = 10^-exponent*/
+		exponent = exp0+m*incr;
+		alpha    = pow(10.,exponent);
+
+		/*Create new vector*/
+		for(int i=0;i<n;i++) X[i] = X0[i] + alpha;
+
+		/*Calculate j(k+alpha delta k) */
+		SetControlInputsFromVectorx(femmodel,X);
+		solutioncore(femmodel);
+		femmodel->CostFunctionx(&j,NULL,NULL);
+
+		IssmDouble Den = 0.;
+		for(int i=0;i<n;i++) Den += alpha * G[i] * 1.;
+		Ialpha = fabs((j - j0)/Den - 1.);
+
+		_printf0_(" " << setw(11) << setprecision (5)<<alpha<<" " << setw(11) << setprecision (5)<<Ialpha<<"\n");
+		output[m*2+0] = alpha;
+		output[m*2+1] = Ialpha;
+	}
+
+	/*output*/
+	#ifdef _HAVE_ADOLC_
+	IssmPDouble* J_passive=xNew<IssmPDouble>(2*num);
+	for(int i=0;i<2*num;i++) J_passive[i]=reCast<IssmPDouble>(output[i]);
+	femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,JEnum,J_passive,num,2,1,0));
+	xDelete<IssmPDouble>(J_passive);
+	#else
+	femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,JEnum,output,num,2,1,0));
+	#endif
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(G);
+	xDelete<IssmDouble>(X);
+	xDelete<IssmDouble>(X0);
+}
Index: issm/trunk/src/c/cores/cores.h
===================================================================
--- issm/trunk/src/c/cores/cores.h	(revision 18081)
+++ issm/trunk/src/c/cores/cores.h	(revision 18301)
@@ -19,5 +19,4 @@
 void adjointbalancethickness_core(FemModel* femmodel);
 void adjointbalancethickness2_core(FemModel* femmodel);
-void gradient_core(FemModel* femmodel,int n=0,bool orthogonalize=false);
 void stressbalance_core(FemModel* femmodel);
 void hydrology_core(FemModel* femmodel);
@@ -30,4 +29,5 @@
 void controltao_core(FemModel* femmodel);
 void controlm1qn3_core(FemModel* femmodel);
+void controlvalidation_core(FemModel* femmodel);
 void masstransport_core(FemModel* femmodel);
 void depthaverage_core(FemModel* femmodel);
Index: issm/trunk/src/c/cores/damage_core.cpp
===================================================================
--- issm/trunk/src/c/cores/damage_core.cpp	(revision 18081)
+++ issm/trunk/src/c/cores/damage_core.cpp	(revision 18301)
@@ -22,13 +22,7 @@
 	//first recover parameters common to all solutions
 	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
-	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
 	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
 	femmodel->parameters->FindParam(&numoutputs,DamageEvolutionNumRequestedOutputsEnum);
 	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,DamageEvolutionRequestedOutputsEnum);
-
-	if(dakota_analysis && solution_type!=TransientSolutionEnum){
-		femmodel->SetCurrentConfiguration(DamageEvolutionAnalysisEnum);
-		ResetConstraintsx(femmodel);
-	}
 
 	if(VerboseSolution()) _printf0_("   computing damage\n");
Index: issm/trunk/src/c/cores/gradient_core.cpp
===================================================================
--- issm/trunk/src/c/cores/gradient_core.cpp	(revision 18081)
+++ 	(revision )
@@ -1,48 +1,0 @@
-/*!\file:  gradient_core.cpp
- * \brief compute inverse method gradient direction.
- */ 
-
-#include "./cores.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../modules/modules.h"
-#include "../solutionsequences/solutionsequences.h"
-
-void gradient_core(FemModel* femmodel,int step,bool orthogonalize){ 
-
-	/*Intermediaries*/
-	IssmDouble  norm_inf;
-	IssmDouble *norm_list    = NULL;
-	Vector<IssmDouble>*     new_gradient = NULL;
-	Vector<IssmDouble>*     gradient     = NULL;
-	Vector<IssmDouble>*     old_gradient = NULL;
-
-	/*Compute gradient*/
-	if(VerboseControl()) _printf0_("   compute cost function gradient\n");
-	Gradjx(&gradient,&norm_list,femmodel->elements,femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials,femmodel->parameters);
-
-	if (orthogonalize){
-		if(VerboseControl()) _printf0_("   orthogonalization\n");
-		ControlInputGetGradientx(&old_gradient,femmodel->elements,femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials,femmodel->parameters);
-		Orthx(&new_gradient,gradient,old_gradient); delete old_gradient; delete gradient;
-	}
-	else{ 
-		new_gradient=gradient;
-	}
-
-	/*Check that gradient is clean*/
-	norm_inf=new_gradient->Norm(NORM_INF);
-	if(norm_inf<=0)    _error_("||∂J/∂α||∞ = 0    gradient norm is zero");
-	if(xIsNan<IssmDouble>(norm_inf))_error_("||∂J/∂α||∞ = NaN  gradient norm is NaN");
-
-	/*plug back into inputs: */
-	ControlInputSetGradientx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,new_gradient);
-	delete new_gradient;
-
-	/*Scale Gradients*/
-	ControlInputScaleGradientx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,norm_list,step);
-
-	/*Clean up and return*/
-	xDelete<IssmDouble>(norm_list);
-}
Index: issm/trunk/src/c/cores/masstransport_core.cpp
===================================================================
--- issm/trunk/src/c/cores/masstransport_core.cpp	(revision 18081)
+++ issm/trunk/src/c/cores/masstransport_core.cpp	(revision 18301)
@@ -26,16 +26,8 @@
 	femmodel->parameters->FindParam(&isFS,FlowequationIsFSEnum);
 	femmodel->parameters->FindParam(&isfreesurface,MasstransportIsfreesurfaceEnum);
-	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
 	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
 	femmodel->parameters->FindParam(&domaintype,DomainTypeEnum);
 	femmodel->parameters->FindParam(&numoutputs,MasstransportNumRequestedOutputsEnum);
 	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,MasstransportRequestedOutputsEnum);
-
-	/*for qmu analysis, reinitialize velocity so that fake sensitivities do not show up as a result of a different restart of the convergence at each trial.*/
-	if(dakota_analysis && solution_type==MasstransportSolutionEnum){
-		InputDuplicatex(femmodel,QmuSurfaceEnum,SurfaceEnum);
-		InputDuplicatex(femmodel,QmuThicknessEnum,ThicknessEnum);
-		InputDuplicatex(femmodel,QmuBaseEnum,BaseEnum);
-	}
 
 	/*Calculate new Surface Mass Balance (SMB)*/
Index: issm/trunk/src/c/cores/stressbalance_core.cpp
===================================================================
--- issm/trunk/src/c/cores/stressbalance_core.cpp	(revision 18081)
+++ issm/trunk/src/c/cores/stressbalance_core.cpp	(revision 18301)
@@ -30,17 +30,8 @@
 	femmodel->parameters->FindParam(&isHO,FlowequationIsHOEnum);
 	femmodel->parameters->FindParam(&isFS,FlowequationIsFSEnum);
-	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
 	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
 	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
 	femmodel->parameters->FindParam(&numoutputs,StressbalanceNumRequestedOutputsEnum);
 	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,StressbalanceRequestedOutputsEnum);
-
-	/*for qmu analysis, reinitialize velocity so that fake sensitivities do not show up as a result of a different restart of the convergence at each trial.*/
-	if(dakota_analysis && solution_type==StressbalanceSolutionEnum){
-		InputDuplicatex(femmodel,QmuVxEnum,VxEnum);
-		InputDuplicatex(femmodel,QmuVyEnum,VyEnum);
-		if(domaintype==Domain3DEnum) InputDuplicatex(femmodel,QmuVzEnum,VzEnum);
-		if(isFS) InputDuplicatex(femmodel,QmuPressureEnum,PressureEnum);
-	}
 
 	/*Compute slopes if necessary */
Index: issm/trunk/src/c/cores/thermal_core.cpp
===================================================================
--- issm/trunk/src/c/cores/thermal_core.cpp	(revision 18081)
+++ issm/trunk/src/c/cores/thermal_core.cpp	(revision 18301)
@@ -22,20 +22,8 @@
 	/*first recover parameters common to all solutions*/
 	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
-	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
 	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
 	femmodel->parameters->FindParam(&isenthalpy,ThermalIsenthalpyEnum);
 	femmodel->parameters->FindParam(&numoutputs,ThermalNumRequestedOutputsEnum);
 	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,ThermalRequestedOutputsEnum);
-
-	if(dakota_analysis && solution_type!=TransientSolutionEnum){
-		InputDuplicatex(femmodel,QmuVxMeshEnum,VxMeshEnum);
-		InputDuplicatex(femmodel,QmuVyMeshEnum,VyMeshEnum);
-		InputDuplicatex(femmodel,QmuVzMeshEnum,VzMeshEnum);
-		InputDuplicatex(femmodel,QmuTemperatureEnum,TemperatureEnum);
-		InputDuplicatex(femmodel,QmuMeltingEnum,BasalforcingsMeltingRateEnum);
-		InputDuplicatex(femmodel,QmuMaterialsRheologyBEnum,MaterialsRheologyBEnum);
-		femmodel->SetCurrentConfiguration(ThermalAnalysisEnum);
-		ResetConstraintsx(femmodel);
-	}
 
 	if(isenthalpy){
Index: issm/trunk/src/c/cores/transient_core.cpp
===================================================================
--- issm/trunk/src/c/cores/transient_core.cpp	(revision 18081)
+++ issm/trunk/src/c/cores/transient_core.cpp	(revision 18301)
@@ -60,37 +60,4 @@
 	step=0;
 	time=starttime;
-
-	/*for qmu analysis, reinitialize velocity so that fake sensitivities do not show up as a result of a different restart of the convergence at each trial.*/
-	if(dakota_analysis){
-		if(isstressbalance){
-			InputDuplicatex(femmodel,QmuVxEnum,VxEnum);
-			InputDuplicatex(femmodel,QmuVyEnum,VyEnum);
-			if(domaintype==Domain3DEnum){
-				InputDuplicatex(femmodel,QmuVzEnum,VzEnum);
-				if(isFS)InputDuplicatex(femmodel,QmuPressureEnum,PressureEnum);
-			}
-		}
-		if(ismasstransport || isgroundingline){
-			InputDuplicatex(femmodel,QmuThicknessEnum,ThicknessEnum);
-			InputDuplicatex(femmodel,QmuSurfaceEnum,SurfaceEnum);
-			InputDuplicatex(femmodel,QmuBaseEnum,BaseEnum);
-			InputDuplicatex(femmodel,QmuMaskIceLevelsetEnum,MaskIceLevelsetEnum);
-		}
-		if(isgroundingline) InputDuplicatex(femmodel,QmuMaskGroundediceLevelsetEnum,MaskGroundediceLevelsetEnum);
-		if(isthermal && domaintype==Domain3DEnum){
-			//Update Vertex Position after updating Thickness and Bed
-			femmodel->SetCurrentConfiguration(MasstransportAnalysisEnum);
-			femmodel->UpdateVertexPositionsx();
-			InputDuplicatex(femmodel,QmuVxMeshEnum,VxMeshEnum);
-			InputDuplicatex(femmodel,QmuVyMeshEnum,VyMeshEnum);
-			InputDuplicatex(femmodel,QmuVzMeshEnum,VzMeshEnum);
-			InputDuplicatex(femmodel,QmuTemperatureEnum,TemperatureEnum);
-			InputDuplicatex(femmodel,QmuMeltingEnum,BasalforcingsMeltingRateEnum);
-			InputDuplicatex(femmodel,QmuMaterialsRheologyBEnum,MaterialsRheologyBEnum);
-			//Reset Thermal Constraints
-			femmodel->SetCurrentConfiguration(ThermalAnalysisEnum);
-			ResetConstraintsx(femmodel);
-		}
-	}
 
 	while(time < finaltime - (yts*DBL_EPSILON)){ //make sure we run up to finaltime.
@@ -183,4 +150,8 @@
 			}
 		}
+
+		/*Calculate new Basal melting on Floating ice*/
+		FloatingiceMeltingRatex(femmodel);
+		
 		if(isgia){
 			if(VerboseSolution()) _printf0_("   computing glacial isostatic adjustment\n");
Index: issm/trunk/src/c/datastructures/DataSet.cpp
===================================================================
--- issm/trunk/src/c/datastructures/DataSet.cpp	(revision 18081)
+++ issm/trunk/src/c/datastructures/DataSet.cpp	(revision 18301)
@@ -24,6 +24,15 @@
 
 /*Constructors/Destructors*/
-/*FUNCTION DataSet::DataSet(){{{*/
-DataSet::DataSet(){
+DataSet::DataSet(){/*{{{*/
+
+	sorted=0;
+	numsorted=0;
+	sorted_ids=NULL;
+	id_offsets=NULL;
+
+}
+/*}}}*/
+DataSet::DataSet(int dataset_enum){/*{{{*/
+	enum_type=dataset_enum;
 
 	sorted=0;
@@ -33,45 +42,41 @@
 }
 /*}}}*/
-/*FUNCTION DataSet::DataSet(int dataset_enum){{{*/
-DataSet::DataSet(int dataset_enum){
-	enum_type=dataset_enum;
-
-	sorted=0;
-	sorted_ids=NULL;
-	id_offsets=NULL;
-
-}
-/*}}}*/
-/*FUNCTION DataSet::Copy{{{*/
-DataSet*   DataSet::Copy(void){
-
-	vector<Object*>::iterator object;
+DataSet* DataSet::Copy(void){/*{{{*/
+
+	vector<Object*>::iterator obj;
 	Object* object_copy=NULL;
 
-	DataSet* copy=new DataSet(enum_type);
-
-	copy->sorted=sorted;
-	copy->presorted=presorted;
-	if(sorted_ids){
-		copy->sorted_ids=xNew<int>(objects.size());
-		xMemCpy<int>(copy->sorted_ids,sorted_ids,objects.size());
-	}
-	if(id_offsets){
-		copy->id_offsets=xNew<int>(objects.size());
-		xMemCpy<int>(copy->id_offsets,id_offsets,objects.size());
-	}
+	DataSet* copy=new DataSet(this->enum_type);
+
+	copy->sorted=this->sorted;
+	copy->numsorted=this->numsorted;
+	copy->presorted=this->presorted;
 
 	/*Now we need to deep copy the objects: */
-	for ( object=objects.begin() ; object < objects.end(); object++ ){
-
-		/*Call echo on object: */
-		object_copy = (*object)->copy();
+	for ( obj=this->objects.begin() ; obj < this->objects.end(); obj++ ){
+		/*Call copy on object: */
+		object_copy = (*obj)->copy();
 		copy->AddObject(object_copy);
 	}
+
+	/*Build id_offsets and sorted_ids*/
+	int objsize = this->numsorted;
+	if(this->sorted && objsize>0 && this->id_offsets){	
+		/*Allocate new ids*/
+		copy->id_offsets=xNew<int>(objsize);
+		xMemCpy<int>(copy->id_offsets,this->id_offsets,objsize);
+	}
+	else copy->id_offsets=NULL;
+	if(this->sorted && objsize>0 && this->sorted_ids){
+		/*Allocate new ids*/
+		copy->sorted_ids=xNew<int>(objsize);
+		xMemCpy<int>(copy->sorted_ids,this->sorted_ids,objsize);
+	}
+	else copy->sorted_ids=NULL;
+
 	return copy;
 }
 /*}}}*/
-/*FUNCTION DataSet::~DataSet{{{*/
-DataSet::~DataSet(){
+DataSet::~DataSet(){/*{{{*/
 	clear();
 	xDelete<int>(sorted_ids);
@@ -81,6 +86,5 @@
 
 /*Specific methods*/
-/*FUNCTION DataSet::AddObject{{{*/
-int  DataSet::AddObject(Object* object){
+int   DataSet::AddObject(Object* object){/*{{{*/
 
 	_assert_(this);
@@ -90,6 +94,5 @@
 }
 /*}}}*/
-/*FUNCTION DataSet::clear{{{*/
-void  DataSet::clear(){
+void  DataSet::clear(){/*{{{*/
 
 /*  use reverse_iterator for efficiency in matlab memory manager
@@ -108,6 +111,5 @@
 }
 /*}}}*/
-/*FUNCTION DataSet::DeleteObject{{{*/
-int  DataSet::DeleteObject(Object* object){
+int   DataSet::DeleteObject(Object* object){/*{{{*/
 
 	vector<Object*>::iterator iterator;
@@ -123,6 +125,5 @@
 }
 /*}}}*/
-/*FUNCTION DataSet::DeepEcho{{{*/
-void DataSet::DeepEcho(){
+void  DataSet::DeepEcho(){/*{{{*/
 
 	vector<Object*>::iterator object;
@@ -140,6 +141,5 @@
 }
 /*}}}*/
-/*FUNCTION DataSet::Echo{{{*/
-void DataSet::Echo(){
+void  DataSet::Echo(){/*{{{*/
 
 	vector<Object*>::iterator object;
@@ -158,11 +158,9 @@
 }
 /*}}}*/
-/*FUNCTION DataSet::GetEnum(){{{*/
-int  DataSet::GetEnum(){
+int   DataSet::GetEnum(){/*{{{*/
 	return enum_type;
 }
 /*}}}*/
-/*FUNCTION DataSet::GetEnum(int offset){{{*/
-int   DataSet::GetEnum(int offset){
+int   DataSet::GetEnum(int offset){/*{{{*/
 
 	return objects[offset]->ObjectEnum();
@@ -170,6 +168,5 @@
 }
 /*}}}*/
-/*FUNCTION DataSet::GetObjectByOffset{{{*/
-Object* DataSet::GetObjectByOffset(int offset){
+Object* DataSet::GetObjectByOffset(int offset){/*{{{*/
 
 	/*Check index in debugging mode*/
@@ -182,6 +179,5 @@
 }
 /*}}}*/
-/*FUNCTION DataSet::GetObjectById{{{*/
-Object* DataSet::GetObjectById(int* poffset,int eid){
+Object* DataSet::GetObjectById(int* poffset,int eid){/*{{{*/
 
 	int id_offset;
@@ -189,5 +185,5 @@
 
 	_assert_(this);
-	if(!sorted)_error_("trying to binary search on a non-sorted dataset!");
+	if(!sorted || objects.size()>numsorted)_error_("trying to binary search on a non-sorted dataset!");
 
 	/*Carry out a binary search on the sorted_ids: */
@@ -206,6 +202,5 @@
 }
 /*}}}*/
-/*FUNCTION DataSet::Presort{{{*/
-void DataSet::Presort(){
+void  DataSet::Presort(){/*{{{*/
 
 	/*vector of objects is already sorted, just allocate the sorted ids and their
@@ -214,6 +209,6 @@
 
 		/*Delete existing ids*/
-		xDelete<int>(sorted_ids);
-		xDelete<int>(id_offsets);
+		if(sorted_ids) xDelete<int>(sorted_ids);
+		if(id_offsets) xDelete<int>(id_offsets);
 
 		/*Allocate new ids*/
@@ -229,9 +224,9 @@
 
 	/*set sorted flag: */
+	numsorted=objects.size();
 	sorted=1;
 }
 /*}}}*/
-/*FUNCTION DataSet::Size{{{*/
-int  DataSet::Size(void){
+int   DataSet::Size(void){/*{{{*/
 	_assert_(this!=NULL);
 
@@ -239,6 +234,5 @@
 }
 /*}}}*/
-/*FUNCTION DataSet::Sort{{{*/
-void DataSet::Sort(){
+void  DataSet::Sort(){/*{{{*/
 
 	/*Only sort if we are not already sorted: */
Index: issm/trunk/src/c/datastructures/DataSet.h
===================================================================
--- issm/trunk/src/c/datastructures/DataSet.h	(revision 18081)
+++ issm/trunk/src/c/datastructures/DataSet.h	(revision 18301)
@@ -25,4 +25,5 @@
 		int             sorted;
 		int             presorted;
+		int             numsorted;
 		int*            sorted_ids;
 		int*            id_offsets;
Index: issm/trunk/src/c/kml/KMLFileReadUtils.cpp
===================================================================
--- issm/trunk/src/c/kml/KMLFileReadUtils.cpp	(revision 18081)
+++ issm/trunk/src/c/kml/KMLFileReadUtils.cpp	(revision 18301)
@@ -16,6 +16,5 @@
 /*}}}*/
 
-/*FUNCTION  KMLFileToken(FILE* fid,int* pncom=NULL,char*** ppcom=NULL) {{{*/
-char* KMLFileToken(FILE* fid,
+char* KMLFileToken(FILE* fid,/*{{{*/
 				   int* pncom=NULL,char*** ppcom=NULL){
 
@@ -144,6 +143,5 @@
 }
 /*}}}*/
-/*FUNCTION  KMLFileTokenComment(FILE* fid) {{{*/
-char* KMLFileTokenComment(FILE* fid){
+char* KMLFileTokenComment(FILE* fid){/*{{{*/
 
 /*  check for comment in the file and read it  */
@@ -208,6 +206,5 @@
 }
 /*}}}*/
-/*FUNCTION  KMLFileTokenBuffer {{{*/
-void KMLFileTokenBuffer(char** pbuffer,int* pibuf,int* pbuflen,
+void KMLFileTokenBuffer(char** pbuffer,int* pibuf,int* pbuflen,/*{{{*/
 						int c,
 						int bufblk){
@@ -237,6 +234,5 @@
 }
 /*}}}*/
-/*FUNCTION  KMLFileTagName {{{*/
-char* KMLFileTagName(char* pname,
+char* KMLFileTagName(char* pname,/*{{{*/
 					 char* ktag){
 
@@ -245,6 +241,5 @@
 }
 /*}}}*/
-/*FUNCTION  KMLFileTagName {{{*/
-char* KMLFileTagName(char* pname,int *m,int maxlen,
+char* KMLFileTagName(char* pname,int *m,int maxlen,/*{{{*/
 					 char* ktag){
 
@@ -290,6 +285,5 @@
 }
 /*}}}*/
-/*FUNCTION  KMLFileTagAttrib {{{*/
-int KMLFileTagAttrib(KML_Object* kobj,
+int KMLFileTagAttrib(KML_Object* kobj,/*{{{*/
 					 char* ktag){
 
@@ -339,6 +333,5 @@
 }
 /*}}}*/
-/*FUNCTION  KMLFileTokenParse {{{*/
-int KMLFileTokenParse(int* pival,
+int KMLFileTokenParse(int* pival,/*{{{*/
 					  char* ktag,
 					  FILE* fid){
@@ -375,6 +368,5 @@
 }
 /*}}}*/
-/*FUNCTION  KMLFileTokenParse {{{*/
-int KMLFileTokenParse(bool* pbval, char* ktag, FILE* fid){
+int KMLFileTokenParse(bool* pbval, char* ktag, FILE* fid){/*{{{*/
 
 	int     ival;
@@ -410,6 +402,5 @@
 }
 /*}}}*/
-/*FUNCTION  KMLFileTokenParse {{{*/
-char* KMLFileTokenParse(char* pstr,
+char* KMLFileTokenParse(char* pstr,/*{{{*/
 						char* ktag,
 						FILE* fid){
@@ -420,6 +411,5 @@
 }
 /*}}}*/
-/*FUNCTION  KMLFileTokenParse {{{*/
-char* KMLFileTokenParse(char* pstr,int *m,int maxlen,
+char* KMLFileTokenParse(char* pstr,int *m,int maxlen,/*{{{*/
 						char* ktag,
 						FILE* fid){
@@ -472,6 +462,5 @@
 }
 /*}}}*/
-/*FUNCTION  KMLFileTokenParse {{{*/
-int KMLFileTokenParse(float* pfval,
+int KMLFileTokenParse(float* pfval,/*{{{*/
 					  char* ktag,
 					  FILE* fid){
@@ -507,6 +496,5 @@
 }
 /*}}}*/
-/*FUNCTION  KMLFileTokenParse {{{*/
-int KMLFileTokenParse(double* pdval,
+int KMLFileTokenParse(double* pdval,/*{{{*/
 					  char* ktag,
 					  FILE* fid){
@@ -542,6 +530,5 @@
 }
 /*}}}*/
-/*FUNCTION  KMLFileTokenParse {{{*/
-int KMLFileTokenParse(double **pdval,int* m,int maxlen,
+int KMLFileTokenParse(double **pdval,int* m,int maxlen,/*{{{*/
 					  char* ktag,
 					  FILE* fid){
@@ -610,6 +597,5 @@
 }
 /*}}}*/
-/*FUNCTION  KMLFileTokenParse {{{*/
-int KMLFileTokenParse(double **pdval,int* m,int n,int maxlen,
+int KMLFileTokenParse(double **pdval,int* m,int n,int maxlen,/*{{{*/
 					  char* ktag,
 					  FILE* fid){
@@ -682,6 +668,5 @@
 }
 /*}}}*/
-/*FUNCTION  KMLFileTagSkip {{{*/
-int KMLFileTagSkip(char* ktag, FILE* fid){
+int KMLFileTagSkip(char* ktag, FILE* fid){/*{{{*/
 
 	char*   kstr;
Index: issm/trunk/src/c/kml/KML_Attribute.cpp
===================================================================
--- issm/trunk/src/c/kml/KML_Attribute.cpp	(revision 18081)
+++ issm/trunk/src/c/kml/KML_Attribute.cpp	(revision 18301)
@@ -16,6 +16,5 @@
 
 /*Constructors/destructor/copy*/
-/*FUNCTION KML_Attribute::KML_Attribute(){{{*/
-KML_Attribute::KML_Attribute(){
+KML_Attribute::KML_Attribute(){/*{{{*/
 
 	name      =NULL;
@@ -24,6 +23,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Attribute::~KML_Attribute(){{{*/
-KML_Attribute::~KML_Attribute(){
+KML_Attribute::~KML_Attribute(){/*{{{*/
 
 	if (name      ) xDelete<char>(name);
@@ -34,6 +32,5 @@
 
 /*Other*/
-/*FUNCTION KML_Attribute::Echo {{{*/
-void  KML_Attribute::Echo(){
+void  KML_Attribute::Echo(){/*{{{*/
 
 	int   i;
@@ -48,6 +45,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Attribute::DeepEcho {{{*/
-void  KML_Attribute::DeepEcho(){
+void  KML_Attribute::DeepEcho(){/*{{{*/
 
 	char  indent[81]="";
@@ -58,6 +54,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Attribute::DeepEcho {{{*/
-void  KML_Attribute::DeepEcho(const char* indent){
+void  KML_Attribute::DeepEcho(const char* indent){/*{{{*/
 
 	int   i;
@@ -72,6 +67,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Attribute::Write {{{*/
-void  KML_Attribute::Write(FILE* filout,const char* indent){
+void  KML_Attribute::Write(FILE* filout,const char* indent){/*{{{*/
 
 //  attributes always written in keyword line of kml_object
@@ -82,6 +76,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Attribute::Read {{{*/
-void  KML_Attribute::Read(FILE* fid,char* kstr){
+void  KML_Attribute::Read(FILE* fid,char* kstr){/*{{{*/
 
 //  attributes always read in keyword line of kml_object
@@ -92,6 +85,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Attribute::Alloc {{{*/
-void  KML_Attribute::Alloc(const char* namei,const char* valuei){
+void  KML_Attribute::Alloc(const char* namei,const char* valuei){/*{{{*/
 
 	name =xNew<char>(strlen(namei )+1);
@@ -104,6 +96,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Attribute::Add {{{*/
-void  KML_Attribute::Add(DataSet* attrib){
+void  KML_Attribute::Add(DataSet* attrib){/*{{{*/
 
 	attrib->AddObject((Object*)this);
@@ -112,6 +103,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Attribute::Get {{{*/
-void  KML_Attribute::Get(char** pvalueo,char* deflt){
+void  KML_Attribute::Get(char** pvalueo,char* deflt){/*{{{*/
 
 	if (!value || !strlen(value)) {
Index: issm/trunk/src/c/kml/KML_ColorStyle.cpp
===================================================================
--- issm/trunk/src/c/kml/KML_ColorStyle.cpp	(revision 18081)
+++ issm/trunk/src/c/kml/KML_ColorStyle.cpp	(revision 18301)
@@ -18,6 +18,5 @@
 
 /*Constructors/destructor/copy*/
-/*FUNCTION KML_ColorStyle::KML_ColorStyle(){{{*/
-KML_ColorStyle::KML_ColorStyle(){
+KML_ColorStyle::KML_ColorStyle(){/*{{{*/
 
 	strcpy(color     ,"ffffffff");
@@ -26,6 +25,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_ColorStyle::~KML_ColorStyle(){{{*/
-KML_ColorStyle::~KML_ColorStyle(){
+KML_ColorStyle::~KML_ColorStyle(){/*{{{*/
 
 	;
@@ -35,6 +33,5 @@
 
 /*Other*/
-/*FUNCTION KML_ColorStyle::Echo {{{*/
-void  KML_ColorStyle::Echo(){
+void  KML_ColorStyle::Echo(){/*{{{*/
 
 	bool  flag=true;
@@ -48,6 +45,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_ColorStyle::DeepEcho {{{*/
-void  KML_ColorStyle::DeepEcho(){
+void  KML_ColorStyle::DeepEcho(){/*{{{*/
 
 	char  indent[81]="";
@@ -58,6 +54,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_ColorStyle::DeepEcho {{{*/
-void  KML_ColorStyle::DeepEcho(const char* indent){
+void  KML_ColorStyle::DeepEcho(const char* indent){/*{{{*/
 
 	bool  flag=true;
@@ -69,6 +64,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_ColorStyle::Write {{{*/
-void  KML_ColorStyle::Write(FILE* filout,const char* indent){
+void  KML_ColorStyle::Write(FILE* filout,const char* indent){/*{{{*/
 
 	KML_SubStyle::Write(filout,indent);
@@ -82,6 +76,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_ColorStyle::Read {{{*/
-void  KML_ColorStyle::Read(FILE* fid,char* kstr){
+void  KML_ColorStyle::Read(FILE* fid,char* kstr){/*{{{*/
 
 /*  process field within opening and closing tags  */
Index: issm/trunk/src/c/kml/KML_Comment.cpp
===================================================================
--- issm/trunk/src/c/kml/KML_Comment.cpp	(revision 18081)
+++ issm/trunk/src/c/kml/KML_Comment.cpp	(revision 18301)
@@ -16,6 +16,5 @@
 
 /*Constructors/destructor/copy*/
-/*FUNCTION KML_Comment::KML_Comment(){{{*/
-KML_Comment::KML_Comment(){
+KML_Comment::KML_Comment(){/*{{{*/
 
 	value     =NULL;
@@ -23,6 +22,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Comment::~KML_Comment(){{{*/
-KML_Comment::~KML_Comment(){
+KML_Comment::~KML_Comment(){/*{{{*/
 
 	if (value     ) xDelete<char>(value);
@@ -32,6 +30,5 @@
 
 /*Other*/
-/*FUNCTION KML_Comment::Echo {{{*/
-void  KML_Comment::Echo(){
+void  KML_Comment::Echo(){/*{{{*/
 
 	bool  flag=true;
@@ -43,6 +40,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Comment::DeepEcho {{{*/
-void  KML_Comment::DeepEcho(){
+void  KML_Comment::DeepEcho(){/*{{{*/
 
 	char  indent[81]="";
@@ -53,6 +49,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Comment::DeepEcho {{{*/
-void  KML_Comment::DeepEcho(const char* indent){
+void  KML_Comment::DeepEcho(const char* indent){/*{{{*/
 
 	bool  flag=true;
@@ -64,6 +59,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Comment::Write {{{*/
-void  KML_Comment::Write(FILE* filout,const char* indent){
+void  KML_Comment::Write(FILE* filout,const char* indent){/*{{{*/
 
 	if (strncmp(&value[0]              ,"<!--",4))
@@ -76,6 +70,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Comment::Read {{{*/
-void  KML_Comment::Read(FILE* fid,char* kstr){
+void  KML_Comment::Read(FILE* fid,char* kstr){/*{{{*/
 
 //  comments always read as part of KMLFileToken
@@ -86,6 +79,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Comment::Alloc {{{*/
-void  KML_Comment::Alloc(const char* valuei){
+void  KML_Comment::Alloc(const char* valuei){/*{{{*/
 
 	value=xNew<char>(strlen(valuei)+1);
@@ -95,6 +87,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Comment::Add {{{*/
-void  KML_Comment::Add(DataSet* commnt){
+void  KML_Comment::Add(DataSet* commnt){/*{{{*/
 
 	commnt->AddObject((Object*)this);
@@ -103,6 +94,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Comment::Get {{{*/
-void  KML_Comment::Get(char** pvalueo){
+void  KML_Comment::Get(char** pvalueo){/*{{{*/
 
 	*pvalueo=xNew<char>(strlen(value)+1);
Index: issm/trunk/src/c/kml/KML_Container.cpp
===================================================================
--- issm/trunk/src/c/kml/KML_Container.cpp	(revision 18081)
+++ issm/trunk/src/c/kml/KML_Container.cpp	(revision 18301)
@@ -21,6 +21,5 @@
 
 /*Constructors/destructor/copy*/
-/*FUNCTION KML_Container::KML_Container(){{{*/
-KML_Container::KML_Container(){
+KML_Container::KML_Container(){/*{{{*/
 
 	feature   =new DataSet;
@@ -28,6 +27,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Container::~KML_Container(){{{*/
-KML_Container::~KML_Container(){
+KML_Container::~KML_Container(){/*{{{*/
 
 	if (feature) {
@@ -40,6 +38,5 @@
 
 /*Other*/
-/*FUNCTION KML_Container::Echo {{{*/
-void  KML_Container::Echo(){
+void  KML_Container::Echo(){/*{{{*/
 
 	bool  flag=true;
@@ -52,6 +49,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Container::DeepEcho {{{*/
-void  KML_Container::DeepEcho(){
+void  KML_Container::DeepEcho(){/*{{{*/
 
 	char  indent[81]="";
@@ -62,6 +58,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Container::DeepEcho {{{*/
-void  KML_Container::DeepEcho(const char* indent){
+void  KML_Container::DeepEcho(const char* indent){/*{{{*/
 
 	int   i;
@@ -88,6 +83,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Container::Write {{{*/
-void  KML_Container::Write(FILE* filout,const char* indent){
+void  KML_Container::Write(FILE* filout,const char* indent){/*{{{*/
 
 	int   i;
@@ -108,6 +102,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Container::Read {{{*/
-void  KML_Container::Read(FILE* fid,char* kstr){
+void  KML_Container::Read(FILE* fid,char* kstr){/*{{{*/
 
 	KML_Object*  kobj;
@@ -154,6 +147,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Container::WriteExp {{{*/
-void  KML_Container::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+void  KML_Container::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){/*{{{*/
 
 	int   i;
Index: issm/trunk/src/c/kml/KML_Document.cpp
===================================================================
--- issm/trunk/src/c/kml/KML_Document.cpp	(revision 18081)
+++ issm/trunk/src/c/kml/KML_Document.cpp	(revision 18301)
@@ -17,6 +17,5 @@
 
 /*Constructors/destructor/copy*/
-/*FUNCTION KML_Document::KML_Document(){{{*/
-KML_Document::KML_Document(){
+KML_Document::KML_Document(){/*{{{*/
 
 	;
@@ -24,6 +23,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Document::~KML_Document(){{{*/
-KML_Document::~KML_Document(){
+KML_Document::~KML_Document(){/*{{{*/
 
 	;
@@ -33,6 +31,5 @@
 
 /*Other*/
-/*FUNCTION KML_Document::Echo {{{*/
-void  KML_Document::Echo(){
+void  KML_Document::Echo(){/*{{{*/
 
 	bool  flag=true;
@@ -44,6 +41,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Document::DeepEcho {{{*/
-void  KML_Document::DeepEcho(){
+void  KML_Document::DeepEcho(){/*{{{*/
 
 	char  indent[81]="";
@@ -54,6 +50,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Document::DeepEcho {{{*/
-void  KML_Document::DeepEcho(const char* indent){
+void  KML_Document::DeepEcho(const char* indent){/*{{{*/
 
 	bool  flag=true;
@@ -65,6 +60,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Document::Write {{{*/
-void  KML_Document::Write(FILE* filout,const char* indent){
+void  KML_Document::Write(FILE* filout,const char* indent){/*{{{*/
 
 	fprintf(filout,"%s<Document",indent);
@@ -80,6 +74,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Document::Read {{{*/
-void  KML_Document::Read(FILE* fid,char* kstr){
+void  KML_Document::Read(FILE* fid,char* kstr){/*{{{*/
 
 	char*        kstri;
Index: issm/trunk/src/c/kml/KML_Feature.cpp
===================================================================
--- issm/trunk/src/c/kml/KML_Feature.cpp	(revision 18081)
+++ issm/trunk/src/c/kml/KML_Feature.cpp	(revision 18301)
@@ -27,6 +27,5 @@
 
 /*Constructors/destructor/copy*/
-/*FUNCTION KML_Feature::KML_Feature(){{{*/
-KML_Feature::KML_Feature(){
+KML_Feature::KML_Feature(){/*{{{*/
 
 	memcpy(name,"",(strlen("")+1)*sizeof(char));
@@ -41,6 +40,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Feature::~KML_Feature(){{{*/
-KML_Feature::~KML_Feature(){
+KML_Feature::~KML_Feature(){/*{{{*/
 
 	if (style) {
@@ -53,6 +51,5 @@
 
 /*Other*/
-/*FUNCTION KML_Feature::Echo {{{*/
-void  KML_Feature::Echo(){
+void  KML_Feature::Echo(){/*{{{*/
 
 	bool  flag=true;
@@ -71,6 +68,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Feature::DeepEcho {{{*/
-void  KML_Feature::DeepEcho(){
+void  KML_Feature::DeepEcho(){/*{{{*/
 
 	char  indent[81]="";
@@ -81,6 +77,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Feature::DeepEcho {{{*/
-void  KML_Feature::DeepEcho(const char* indent){
+void  KML_Feature::DeepEcho(const char* indent){/*{{{*/
 
 	int   i;
@@ -114,6 +109,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Feature::Write {{{*/
-void  KML_Feature::Write(FILE* filout,const char* indent){
+void  KML_Feature::Write(FILE* filout,const char* indent){/*{{{*/
 
 	int   i;
@@ -145,6 +139,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Feature::Read {{{*/
-void  KML_Feature::Read(FILE* fid,char* kstr){
+void  KML_Feature::Read(FILE* fid,char* kstr){/*{{{*/
 
 	KML_Object*  kobj;
Index: issm/trunk/src/c/kml/KML_File.cpp
===================================================================
--- issm/trunk/src/c/kml/KML_File.cpp	(revision 18081)
+++ issm/trunk/src/c/kml/KML_File.cpp	(revision 18301)
@@ -18,6 +18,5 @@
 
 /*Constructors/destructor/copy*/
-/*FUNCTION KML_File::KML_File(){{{*/
-KML_File::KML_File(){
+KML_File::KML_File(){/*{{{*/
 
 	;
@@ -25,6 +24,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_File::~KML_File(){{{*/
-KML_File::~KML_File(){
+KML_File::~KML_File(){/*{{{*/
 
 	;
@@ -34,6 +32,5 @@
 
 /*Other*/
-/*FUNCTION KML_File::Echo {{{*/
-void  KML_File::Echo(){
+void  KML_File::Echo(){/*{{{*/
 
 	bool  flag=true;
@@ -45,6 +42,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_File::DeepEcho {{{*/
-void  KML_File::DeepEcho(){
+void  KML_File::DeepEcho(){/*{{{*/
 
 	char  indent[81]="";
@@ -55,6 +51,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_File::DeepEcho {{{*/
-void  KML_File::DeepEcho(const char* indent){
+void  KML_File::DeepEcho(const char* indent){/*{{{*/
 
 	bool  flag=true;
@@ -66,6 +61,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_File::Write {{{*/
-void  KML_File::Write(FILE* filout,const char* indent){
+void  KML_File::Write(FILE* filout,const char* indent){/*{{{*/
 
 	fprintf(filout,"%s<kml",indent);
@@ -81,6 +75,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_File::Read {{{*/
-void  KML_File::Read(FILE* fid,char* kstr){
+void  KML_File::Read(FILE* fid,char* kstr){/*{{{*/
 
 	char*        kstri;
@@ -120,6 +113,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_File::WriteExp {{{*/
-void  KML_File::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+void  KML_File::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){/*{{{*/
 
 	int   i;
Index: issm/trunk/src/c/kml/KML_Folder.cpp
===================================================================
--- issm/trunk/src/c/kml/KML_Folder.cpp	(revision 18081)
+++ issm/trunk/src/c/kml/KML_Folder.cpp	(revision 18301)
@@ -17,6 +17,5 @@
 
 /*Constructors/destructor/copy*/
-/*FUNCTION KML_Folder::KML_Folder(){{{*/
-KML_Folder::KML_Folder(){
+KML_Folder::KML_Folder(){/*{{{*/
 
 	;
@@ -24,6 +23,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Folder::~KML_Folder(){{{*/
-KML_Folder::~KML_Folder(){
+KML_Folder::~KML_Folder(){/*{{{*/
 
 	;
@@ -33,6 +31,5 @@
 
 /*Other*/
-/*FUNCTION KML_Folder::Echo {{{*/
-void  KML_Folder::Echo(){
+void  KML_Folder::Echo(){/*{{{*/
 
 	bool  flag=true;
@@ -44,6 +41,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Folder::DeepEcho {{{*/
-void  KML_Folder::DeepEcho(){
+void  KML_Folder::DeepEcho(){/*{{{*/
 
 	char  indent[81]="";
@@ -54,6 +50,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Folder::DeepEcho {{{*/
-void  KML_Folder::DeepEcho(const char* indent){
+void  KML_Folder::DeepEcho(const char* indent){/*{{{*/
 
 	bool  flag=true;
@@ -65,6 +60,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Folder::Write {{{*/
-void  KML_Folder::Write(FILE* filout,const char* indent){
+void  KML_Folder::Write(FILE* filout,const char* indent){/*{{{*/
 
 	fprintf(filout,"%s<Folder",indent);
@@ -80,6 +74,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Folder::Read {{{*/
-void  KML_Folder::Read(FILE* fid,char* kstr){
+void  KML_Folder::Read(FILE* fid,char* kstr){/*{{{*/
 
 	char*        kstri;
Index: issm/trunk/src/c/kml/KML_Geometry.cpp
===================================================================
--- issm/trunk/src/c/kml/KML_Geometry.cpp	(revision 18081)
+++ issm/trunk/src/c/kml/KML_Geometry.cpp	(revision 18301)
@@ -17,6 +17,5 @@
 
 /*Constructors/destructor/copy*/
-/*FUNCTION KML_Geometry::KML_Geometry(){{{*/
-KML_Geometry::KML_Geometry(){
+KML_Geometry::KML_Geometry(){/*{{{*/
 
 	;
@@ -24,6 +23,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Geometry::~KML_Geometry(){{{*/
-KML_Geometry::~KML_Geometry(){
+KML_Geometry::~KML_Geometry(){/*{{{*/
 
 	;
@@ -33,6 +31,5 @@
 
 /*Other*/
-/*FUNCTION KML_Geometry::Echo {{{*/
-void  KML_Geometry::Echo(){
+void  KML_Geometry::Echo(){/*{{{*/
 
 	this->KML_Object::Echo();
@@ -41,6 +38,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Geometry::DeepEcho {{{*/
-void  KML_Geometry::DeepEcho(){
+void  KML_Geometry::DeepEcho(){/*{{{*/
 
 	char  indent[81]="";
@@ -51,6 +47,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Geometry::DeepEcho {{{*/
-void  KML_Geometry::DeepEcho(const char* indent){
+void  KML_Geometry::DeepEcho(const char* indent){/*{{{*/
 
 	this->KML_Object::DeepEcho(indent);
@@ -59,6 +54,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Geometry::Write {{{*/
-void  KML_Geometry::Write(FILE* filout,const char* indent){
+void  KML_Geometry::Write(FILE* filout,const char* indent){/*{{{*/
 
 	KML_Object::Write(filout,indent);
@@ -67,6 +61,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Geometry::Read {{{*/
-void  KML_Geometry::Read(FILE* fid,char* kstr){
+void  KML_Geometry::Read(FILE* fid,char* kstr){/*{{{*/
 
 /*  process field within opening and closing tags  */
Index: issm/trunk/src/c/kml/KML_GroundOverlay.cpp
===================================================================
--- issm/trunk/src/c/kml/KML_GroundOverlay.cpp	(revision 18081)
+++ issm/trunk/src/c/kml/KML_GroundOverlay.cpp	(revision 18301)
@@ -19,6 +19,5 @@
 
 /*Constructors/destructor/copy*/
-/*FUNCTION KML_GroundOverlay::KML_GroundOverlay(){{{*/
-KML_GroundOverlay::KML_GroundOverlay(){
+KML_GroundOverlay::KML_GroundOverlay(){/*{{{*/
 
 	altitude  = 0.;
@@ -29,6 +28,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_GroundOverlay::~KML_GroundOverlay(){{{*/
-KML_GroundOverlay::~KML_GroundOverlay(){
+KML_GroundOverlay::~KML_GroundOverlay(){/*{{{*/
 
 	if (llbox) {
@@ -41,6 +39,5 @@
 
 /*Other*/
-/*FUNCTION KML_GroundOverlay::Echo {{{*/
-void  KML_GroundOverlay::Echo(){
+void  KML_GroundOverlay::Echo(){/*{{{*/
 
 	_printf_("KML_GroundOverlay:\n");
@@ -52,6 +49,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_GroundOverlay::DeepEcho {{{*/
-void  KML_GroundOverlay::DeepEcho(){
+void  KML_GroundOverlay::DeepEcho(){/*{{{*/
 
 	char  indent[81]="";
@@ -62,6 +58,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_GroundOverlay::DeepEcho {{{*/
-void  KML_GroundOverlay::DeepEcho(const char* indent){
+void  KML_GroundOverlay::DeepEcho(const char* indent){/*{{{*/
 
 	char  indent2[81];
@@ -81,6 +76,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_GroundOverlay::Write {{{*/
-void  KML_GroundOverlay::Write(FILE* filout,const char* indent){
+void  KML_GroundOverlay::Write(FILE* filout,const char* indent){/*{{{*/
 
 	char  indent2[81];
@@ -107,6 +101,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_GroundOverlay::Read {{{*/
-void  KML_GroundOverlay::Read(FILE* fid,char* kstr){
+void  KML_GroundOverlay::Read(FILE* fid,char* kstr){/*{{{*/
 
 	char*        kstri;
Index: issm/trunk/src/c/kml/KML_Icon.cpp
===================================================================
--- issm/trunk/src/c/kml/KML_Icon.cpp	(revision 18081)
+++ issm/trunk/src/c/kml/KML_Icon.cpp	(revision 18301)
@@ -17,6 +17,5 @@
 
 /*Constructors/destructor/copy*/
-/*FUNCTION KML_Icon::KML_Icon(){{{*/
-KML_Icon::KML_Icon(){
+KML_Icon::KML_Icon(){/*{{{*/
 
 	strcpy(href      ,"");
@@ -31,6 +30,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Icon::~KML_Icon(){{{*/
-KML_Icon::~KML_Icon(){
+KML_Icon::~KML_Icon(){/*{{{*/
 
 	;
@@ -40,6 +38,5 @@
 
 /*Other*/
-/*FUNCTION KML_Icon::Echo {{{*/
-void  KML_Icon::Echo(){
+void  KML_Icon::Echo(){/*{{{*/
 
 	bool  flag=true;
@@ -60,6 +57,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Icon::DeepEcho {{{*/
-void  KML_Icon::DeepEcho(){
+void  KML_Icon::DeepEcho(){/*{{{*/
 
 	char  indent[81]="";
@@ -70,6 +66,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Icon::DeepEcho {{{*/
-void  KML_Icon::DeepEcho(const char* indent){
+void  KML_Icon::DeepEcho(const char* indent){/*{{{*/
 
 	bool  flag=true;
@@ -90,6 +85,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Icon::Write {{{*/
-void  KML_Icon::Write(FILE* filout,const char* indent){
+void  KML_Icon::Write(FILE* filout,const char* indent){/*{{{*/
 
 	fprintf(filout,"%s<Icon",indent);
@@ -119,6 +113,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Icon::Read {{{*/
-void  KML_Icon::Read(FILE* fid,char* kstr){
+void  KML_Icon::Read(FILE* fid,char* kstr){/*{{{*/
 
 	char*        kstri;
Index: issm/trunk/src/c/kml/KML_LatLonBox.cpp
===================================================================
--- issm/trunk/src/c/kml/KML_LatLonBox.cpp	(revision 18081)
+++ issm/trunk/src/c/kml/KML_LatLonBox.cpp	(revision 18301)
@@ -17,6 +17,5 @@
 
 /*Constructors/destructor/copy*/
-/*FUNCTION KML_LatLonBox::KML_LatLonBox(){{{*/
-KML_LatLonBox::KML_LatLonBox(){
+KML_LatLonBox::KML_LatLonBox(){/*{{{*/
 
 	north     = 0.;
@@ -28,6 +27,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_LatLonBox::~KML_LatLonBox(){{{*/
-KML_LatLonBox::~KML_LatLonBox(){
+KML_LatLonBox::~KML_LatLonBox(){/*{{{*/
 
 	;
@@ -37,6 +35,5 @@
 
 /*Other*/
-/*FUNCTION KML_LatLonBox::Echo {{{*/
-void  KML_LatLonBox::Echo(){
+void  KML_LatLonBox::Echo(){/*{{{*/
 
 	_printf_("KML_LatLonBox:\n");
@@ -50,6 +47,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_LatLonBox::DeepEcho {{{*/
-void  KML_LatLonBox::DeepEcho(){
+void  KML_LatLonBox::DeepEcho(){/*{{{*/
 
 	char  indent[81]="";
@@ -60,6 +56,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_LatLonBox::DeepEcho {{{*/
-void  KML_LatLonBox::DeepEcho(const char* indent){
+void  KML_LatLonBox::DeepEcho(const char* indent){/*{{{*/
 
 	_printf_(indent << "KML_LatLonBox:\n");
@@ -73,6 +68,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_LatLonBox::Write {{{*/
-void  KML_LatLonBox::Write(FILE* filout,const char* indent){
+void  KML_LatLonBox::Write(FILE* filout,const char* indent){/*{{{*/
 
 	fprintf(filout,"%s<LatLonBox",indent);
@@ -94,6 +88,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_LatLonBox::Read {{{*/
-void  KML_LatLonBox::Read(FILE* fid,char* kstr){
+void  KML_LatLonBox::Read(FILE* fid,char* kstr){/*{{{*/
 
 	char*        kstri;
Index: issm/trunk/src/c/kml/KML_LineString.cpp
===================================================================
--- issm/trunk/src/c/kml/KML_LineString.cpp	(revision 18081)
+++ issm/trunk/src/c/kml/KML_LineString.cpp	(revision 18301)
@@ -17,6 +17,5 @@
 
 /*Constructors/destructor/copy*/
-/*FUNCTION KML_LineString::KML_LineString(){{{*/
-KML_LineString::KML_LineString(){
+KML_LineString::KML_LineString(){/*{{{*/
 
 	extrude   =false;
@@ -29,6 +28,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_LineString::~KML_LineString(){{{*/
-KML_LineString::~KML_LineString(){
+KML_LineString::~KML_LineString(){/*{{{*/
 
 	if (coords) xDelete<double>(coords);
@@ -41,6 +39,5 @@
 
 /*Other*/
-/*FUNCTION KML_LineString::Echo {{{*/
-void  KML_LineString::Echo(){
+void  KML_LineString::Echo(){/*{{{*/
 
 	bool  flag=true;
@@ -57,6 +54,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_LineString::DeepEcho {{{*/
-void  KML_LineString::DeepEcho(){
+void  KML_LineString::DeepEcho(){/*{{{*/
 
 	char  indent[81]="";
@@ -67,6 +63,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_LineString::DeepEcho {{{*/
-void  KML_LineString::DeepEcho(const char* indent){
+void  KML_LineString::DeepEcho(const char* indent){/*{{{*/
 
 	int   i;
@@ -86,6 +81,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_LineString::Write {{{*/
-void  KML_LineString::Write(FILE* filout,const char* indent){
+void  KML_LineString::Write(FILE* filout,const char* indent){/*{{{*/
 
 	int   i;
@@ -114,6 +108,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_LineString::Read {{{*/
-void  KML_LineString::Read(FILE* fid,char* kstr){
+void  KML_LineString::Read(FILE* fid,char* kstr){/*{{{*/
 
 	char*        kstri;
@@ -171,6 +164,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_LineString::WriteExp {{{*/
-void  KML_LineString::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+void  KML_LineString::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){/*{{{*/
 
 	int     i;
Index: issm/trunk/src/c/kml/KML_LineStyle.cpp
===================================================================
--- issm/trunk/src/c/kml/KML_LineStyle.cpp	(revision 18081)
+++ issm/trunk/src/c/kml/KML_LineStyle.cpp	(revision 18301)
@@ -17,6 +17,5 @@
 
 /*Constructors/destructor/copy*/
-/*FUNCTION KML_LineStyle::KML_LineStyle(){{{*/
-KML_LineStyle::KML_LineStyle(){
+KML_LineStyle::KML_LineStyle(){/*{{{*/
 
 	width     =1.;
@@ -24,6 +23,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_LineStyle::~KML_LineStyle(){{{*/
-KML_LineStyle::~KML_LineStyle(){
+KML_LineStyle::~KML_LineStyle(){/*{{{*/
 
 	;
@@ -33,6 +31,5 @@
 
 /*Other*/
-/*FUNCTION KML_LineStyle::Echo {{{*/
-void  KML_LineStyle::Echo(){
+void  KML_LineStyle::Echo(){/*{{{*/
 
 	bool  flag=true;
@@ -46,6 +43,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_LineStyle::DeepEcho {{{*/
-void  KML_LineStyle::DeepEcho(){
+void  KML_LineStyle::DeepEcho(){/*{{{*/
 
 	char  indent[81]="";
@@ -56,6 +52,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_LineStyle::DeepEcho {{{*/
-void  KML_LineStyle::DeepEcho(const char* indent){
+void  KML_LineStyle::DeepEcho(const char* indent){/*{{{*/
 
 	bool  flag=true;
@@ -69,6 +64,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_LineStyle::Write {{{*/
-void  KML_LineStyle::Write(FILE* filout,const char* indent){
+void  KML_LineStyle::Write(FILE* filout,const char* indent){/*{{{*/
 
 	fprintf(filout,"%s<LineStyle",indent);
@@ -86,6 +80,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_LineStyle::Read {{{*/
-void  KML_LineStyle::Read(FILE* fid,char* kstr){
+void  KML_LineStyle::Read(FILE* fid,char* kstr){/*{{{*/
 
 	char*        kstri;
Index: issm/trunk/src/c/kml/KML_LinearRing.cpp
===================================================================
--- issm/trunk/src/c/kml/KML_LinearRing.cpp	(revision 18081)
+++ issm/trunk/src/c/kml/KML_LinearRing.cpp	(revision 18301)
@@ -17,6 +17,5 @@
 
 /*Constructors/destructor/copy*/
-/*FUNCTION KML_LinearRing::KML_LinearRing(){{{*/
-KML_LinearRing::KML_LinearRing(){
+KML_LinearRing::KML_LinearRing(){/*{{{*/
 
 	extrude   =false;
@@ -29,6 +28,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_LinearRing::~KML_LinearRing(){{{*/
-KML_LinearRing::~KML_LinearRing(){
+KML_LinearRing::~KML_LinearRing(){/*{{{*/
 
 	if (coords) xDelete<double>(coords);
@@ -41,6 +39,5 @@
 
 /*Other*/
-/*FUNCTION KML_LinearRing::Echo {{{*/
-void  KML_LinearRing::Echo(){
+void  KML_LinearRing::Echo(){/*{{{*/
 
 	bool  flag=true;
@@ -57,6 +54,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_LinearRing::DeepEcho {{{*/
-void  KML_LinearRing::DeepEcho(){
+void  KML_LinearRing::DeepEcho(){/*{{{*/
 
 	char  indent[81]="";
@@ -67,6 +63,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_LinearRing::DeepEcho {{{*/
-void  KML_LinearRing::DeepEcho(const char* indent){
+void  KML_LinearRing::DeepEcho(const char* indent){/*{{{*/
 
 	int   i;
@@ -86,6 +81,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_LinearRing::Write {{{*/
-void  KML_LinearRing::Write(FILE* filout,const char* indent){
+void  KML_LinearRing::Write(FILE* filout,const char* indent){/*{{{*/
 
 	int   i;
@@ -114,6 +108,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_LinearRing::Read {{{*/
-void  KML_LinearRing::Read(FILE* fid,char* kstr){
+void  KML_LinearRing::Read(FILE* fid,char* kstr){/*{{{*/
 
 	char  *kstri = NULL;
@@ -160,6 +153,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_LinearRing::WriteExp {{{*/
-void  KML_LinearRing::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+void  KML_LinearRing::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){/*{{{*/
 
 	int     i;
Index: issm/trunk/src/c/kml/KML_MultiGeometry.cpp
===================================================================
--- issm/trunk/src/c/kml/KML_MultiGeometry.cpp	(revision 18081)
+++ issm/trunk/src/c/kml/KML_MultiGeometry.cpp	(revision 18301)
@@ -22,6 +22,5 @@
 
 /*Constructors/destructor/copy*/
-/*FUNCTION KML_MultiGeometry::KML_MultiGeometry(){{{*/
-KML_MultiGeometry::KML_MultiGeometry(){
+KML_MultiGeometry::KML_MultiGeometry(){/*{{{*/
 
 	geometry  =new DataSet;
@@ -29,6 +28,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_MultiGeometry::~KML_MultiGeometry(){{{*/
-KML_MultiGeometry::~KML_MultiGeometry(){
+KML_MultiGeometry::~KML_MultiGeometry(){/*{{{*/
 
 	if (geometry) {
@@ -41,6 +39,5 @@
 
 /*Other*/
-/*FUNCTION KML_MultiGeometry::Echo {{{*/
-void  KML_MultiGeometry::Echo(){
+void  KML_MultiGeometry::Echo(){/*{{{*/
 
 	bool  flag=true;
@@ -54,6 +51,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_MultiGeometry::DeepEcho {{{*/
-void  KML_MultiGeometry::DeepEcho(){
+void  KML_MultiGeometry::DeepEcho(){/*{{{*/
 
 	char  indent[81]="";
@@ -64,6 +60,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_MultiGeometry::DeepEcho {{{*/
-void  KML_MultiGeometry::DeepEcho(const char* indent){
+void  KML_MultiGeometry::DeepEcho(const char* indent){/*{{{*/
 
 	int   i;
@@ -91,6 +86,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_MultiGeometry::Write {{{*/
-void  KML_MultiGeometry::Write(FILE* filout,const char* indent){
+void  KML_MultiGeometry::Write(FILE* filout,const char* indent){/*{{{*/
 
 	int   i;
@@ -118,6 +112,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_MultiGeometry::Read {{{*/
-void  KML_MultiGeometry::Read(FILE* fid,char* kstr){
+void  KML_MultiGeometry::Read(FILE* fid,char* kstr){/*{{{*/
 
 	char*        kstri;
@@ -189,6 +182,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_MultiGeometry::WriteExp {{{*/
-void  KML_MultiGeometry::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+void  KML_MultiGeometry::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){/*{{{*/
 
 	int   i;
Index: issm/trunk/src/c/kml/KML_Object.cpp
===================================================================
--- issm/trunk/src/c/kml/KML_Object.cpp	(revision 18081)
+++ issm/trunk/src/c/kml/KML_Object.cpp	(revision 18301)
@@ -32,6 +32,5 @@
 
 /*Constructors/destructor/copy*/
-/*FUNCTION KML_Object::KML_Object(){{{*/
-KML_Object::KML_Object(){
+KML_Object::KML_Object(){/*{{{*/
 
 	attrib    =new DataSet;
@@ -41,6 +40,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Object::~KML_Object(){{{*/
-KML_Object::~KML_Object(){
+KML_Object::~KML_Object(){/*{{{*/
 
 	if (attrib) {
@@ -61,6 +59,5 @@
 
 /*Other*/
-/*FUNCTION KML_Object::Echo {{{*/
-void  KML_Object::Echo(){
+void  KML_Object::Echo(){/*{{{*/
 
 	bool  flag=true;
@@ -73,6 +70,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Object::DeepEcho {{{*/
-void  KML_Object::DeepEcho(){
+void  KML_Object::DeepEcho(){/*{{{*/
 
 	char  indent[81]="";
@@ -83,6 +79,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Object::DeepEcho {{{*/
-void  KML_Object::DeepEcho(const char* indent){
+void  KML_Object::DeepEcho(const char* indent){/*{{{*/
 
 	int   i;
@@ -125,6 +120,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Object::Write {{{*/
-void  KML_Object::Write(FILE* filout,const char* indent){
+void  KML_Object::Write(FILE* filout,const char* indent){/*{{{*/
 
 	int   i;
@@ -147,6 +141,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Object::Read {{{*/
-void  KML_Object::Read(FILE* fid,char* kstr){
+void  KML_Object::Read(FILE* fid,char* kstr){/*{{{*/
 
 	KML_Object*  kobj;
@@ -275,6 +268,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Object::WriteExp {{{*/
-void  KML_Object::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+void  KML_Object::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){/*{{{*/
 
 	;
@@ -283,6 +275,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Object::AddAttrib {{{*/
-void  KML_Object::AddAttrib(const char* name,const char* value){
+void  KML_Object::AddAttrib(const char* name,const char* value){/*{{{*/
 
 	KML_Attribute* katt=NULL;
@@ -295,6 +286,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Object::WriteAttrib {{{*/
-void  KML_Object::WriteAttrib(FILE* filout,const char* indent){
+void  KML_Object::WriteAttrib(FILE* filout,const char* indent){/*{{{*/
 
 //  attributes always written in keyword line of kml_object
@@ -309,6 +299,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Object::AddCommnt {{{*/
-void  KML_Object::AddCommnt(int ncom,char** pcom){
+void  KML_Object::AddCommnt(int ncom,char** pcom){/*{{{*/
 
 	int   i;
@@ -324,6 +313,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Object::AddCommnt {{{*/
-void  KML_Object::AddCommnt(char* value){
+void  KML_Object::AddCommnt(char* value){/*{{{*/
 
 	KML_Comment* kcom=NULL;
@@ -336,6 +324,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Object::WriteCommnt {{{*/
-void  KML_Object::WriteCommnt(FILE* filout,const char* indent){
+void  KML_Object::WriteCommnt(FILE* filout,const char* indent){/*{{{*/
 
 	int   i;
Index: issm/trunk/src/c/kml/KML_Overlay.cpp
===================================================================
--- issm/trunk/src/c/kml/KML_Overlay.cpp	(revision 18081)
+++ issm/trunk/src/c/kml/KML_Overlay.cpp	(revision 18301)
@@ -18,6 +18,5 @@
 
 /*Constructors/destructor/copy*/
-/*FUNCTION KML_Overlay::KML_Overlay(){{{*/
-KML_Overlay::KML_Overlay(){
+KML_Overlay::KML_Overlay(){/*{{{*/
 
 	strcpy(color     ,"ffffffff");
@@ -29,6 +28,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Overlay::~KML_Overlay(){{{*/
-KML_Overlay::~KML_Overlay(){
+KML_Overlay::~KML_Overlay(){/*{{{*/
 
 	if (icon) {
@@ -41,6 +39,5 @@
 
 /*Other*/
-/*FUNCTION KML_Overlay::Echo {{{*/
-void  KML_Overlay::Echo(){
+void  KML_Overlay::Echo(){/*{{{*/
 
 	KML_Feature::Echo();
@@ -50,6 +47,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Overlay::DeepEcho {{{*/
-void  KML_Overlay::DeepEcho(){
+void  KML_Overlay::DeepEcho(){/*{{{*/
 
 	char  indent[81]="";
@@ -60,6 +56,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Overlay::DeepEcho {{{*/
-void  KML_Overlay::DeepEcho(const char* indent){
+void  KML_Overlay::DeepEcho(const char* indent){/*{{{*/
 
 	char  indent2[81];
@@ -77,6 +72,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Overlay::Write {{{*/
-void  KML_Overlay::Write(FILE* filout,const char* indent){
+void  KML_Overlay::Write(FILE* filout,const char* indent){/*{{{*/
 
 	char  indent2[81];
@@ -97,6 +91,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Overlay::Read {{{*/
-void  KML_Overlay::Read(FILE* fid,char* kstr){
+void  KML_Overlay::Read(FILE* fid,char* kstr){/*{{{*/
 
 /*  process field within opening and closing tags  */
Index: issm/trunk/src/c/kml/KML_Placemark.cpp
===================================================================
--- issm/trunk/src/c/kml/KML_Placemark.cpp	(revision 18081)
+++ issm/trunk/src/c/kml/KML_Placemark.cpp	(revision 18301)
@@ -23,6 +23,5 @@
 
 /*Constructors/destructor/copy*/
-/*FUNCTION KML_Placemark::KML_Placemark(){{{*/
-KML_Placemark::KML_Placemark(){
+KML_Placemark::KML_Placemark(){/*{{{*/
 
 	geometry  =new DataSet;
@@ -30,6 +29,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Placemark::~KML_Placemark(){{{*/
-KML_Placemark::~KML_Placemark(){
+KML_Placemark::~KML_Placemark(){/*{{{*/
 
 	if (geometry) {
@@ -42,6 +40,5 @@
 
 /*Other*/
-/*FUNCTION KML_Placemark::Echo {{{*/
-void  KML_Placemark::Echo(){
+void  KML_Placemark::Echo(){/*{{{*/
 
 	bool  flag=true;
@@ -55,6 +52,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Placemark::DeepEcho {{{*/
-void  KML_Placemark::DeepEcho(){
+void  KML_Placemark::DeepEcho(){/*{{{*/
 
 	char  indent[81]="";
@@ -65,6 +61,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Placemark::DeepEcho {{{*/
-void  KML_Placemark::DeepEcho(const char* indent){
+void  KML_Placemark::DeepEcho(const char* indent){/*{{{*/
 
 	int   i;
@@ -92,6 +87,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Placemark::Write {{{*/
-void  KML_Placemark::Write(FILE* filout,const char* indent){
+void  KML_Placemark::Write(FILE* filout,const char* indent){/*{{{*/
 
 	int   i;
@@ -119,6 +113,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Placemark::Read {{{*/
-void  KML_Placemark::Read(FILE* fid,char* kstr){
+void  KML_Placemark::Read(FILE* fid,char* kstr){/*{{{*/
 
 	char*        kstri;
@@ -190,6 +183,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Placemark::WriteExp {{{*/
-void  KML_Placemark::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+void  KML_Placemark::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){/*{{{*/
 
 	int   i;
Index: issm/trunk/src/c/kml/KML_Point.cpp
===================================================================
--- issm/trunk/src/c/kml/KML_Point.cpp	(revision 18081)
+++ issm/trunk/src/c/kml/KML_Point.cpp	(revision 18301)
@@ -17,6 +17,5 @@
 
 /*Constructors/destructor/copy*/
-/*FUNCTION KML_Point::KML_Point(){{{*/
-KML_Point::KML_Point(){
+KML_Point::KML_Point(){/*{{{*/
 
 	extrude   =false;
@@ -29,6 +28,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Point::~KML_Point(){{{*/
-KML_Point::~KML_Point(){
+KML_Point::~KML_Point(){/*{{{*/
 
 	;
@@ -38,6 +36,5 @@
 
 /*Other*/
-/*FUNCTION KML_Point::Echo {{{*/
-void  KML_Point::Echo(){
+void  KML_Point::Echo(){/*{{{*/
 
 	bool  flag=true;
@@ -53,6 +50,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Point::DeepEcho {{{*/
-void  KML_Point::DeepEcho(){
+void  KML_Point::DeepEcho(){/*{{{*/
 
 	char  indent[81]="";
@@ -63,6 +59,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Point::DeepEcho {{{*/
-void  KML_Point::DeepEcho(const char* indent){
+void  KML_Point::DeepEcho(const char* indent){/*{{{*/
 
 	bool  flag=true;
@@ -78,6 +73,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Point::Write {{{*/
-void  KML_Point::Write(FILE* filout,const char* indent){
+void  KML_Point::Write(FILE* filout,const char* indent){/*{{{*/
 
 	fprintf(filout,"%s<Point",indent);
@@ -98,6 +92,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Point::Read {{{*/
-void  KML_Point::Read(FILE* fid,char* kstr){
+void  KML_Point::Read(FILE* fid,char* kstr){/*{{{*/
 
 	double*      pcoords=&coords[0];
@@ -146,6 +139,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Point::WriteExp {{{*/
-void  KML_Point::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+void  KML_Point::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){/*{{{*/
 
 	int     i;
Index: issm/trunk/src/c/kml/KML_PolyStyle.cpp
===================================================================
--- issm/trunk/src/c/kml/KML_PolyStyle.cpp	(revision 18081)
+++ issm/trunk/src/c/kml/KML_PolyStyle.cpp	(revision 18301)
@@ -19,6 +19,5 @@
 
 /*Constructors/destructor/copy*/
-/*FUNCTION KML_PolyStyle::KML_PolyStyle(){{{*/
-KML_PolyStyle::KML_PolyStyle(){
+KML_PolyStyle::KML_PolyStyle(){/*{{{*/
 
 	fill      =true;
@@ -27,6 +26,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_PolyStyle::~KML_PolyStyle(){{{*/
-KML_PolyStyle::~KML_PolyStyle(){
+KML_PolyStyle::~KML_PolyStyle(){/*{{{*/
 
 	;
@@ -36,6 +34,5 @@
 
 /*Other*/
-/*FUNCTION KML_PolyStyle::Echo {{{*/
-void  KML_PolyStyle::Echo(){
+void  KML_PolyStyle::Echo(){/*{{{*/
 
 	bool  flag=true;
@@ -50,6 +47,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_PolyStyle::DeepEcho {{{*/
-void  KML_PolyStyle::DeepEcho(){
+void  KML_PolyStyle::DeepEcho(){/*{{{*/
 
 	char  indent[81]="";
@@ -60,6 +56,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_PolyStyle::DeepEcho {{{*/
-void  KML_PolyStyle::DeepEcho(const char* indent){
+void  KML_PolyStyle::DeepEcho(const char* indent){/*{{{*/
 
 	bool  flag=true;
@@ -74,6 +69,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_PolyStyle::Write {{{*/
-void  KML_PolyStyle::Write(FILE* filout,const char* indent){
+void  KML_PolyStyle::Write(FILE* filout,const char* indent){/*{{{*/
 
 	fprintf(filout,"%s<PolyStyle",indent);
@@ -92,6 +86,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_PolyStyle::Read {{{*/
-void  KML_PolyStyle::Read(FILE* fid,char* kstr){
+void  KML_PolyStyle::Read(FILE* fid,char* kstr){/*{{{*/
 
 	char*        kstri;
Index: issm/trunk/src/c/kml/KML_Polygon.cpp
===================================================================
--- issm/trunk/src/c/kml/KML_Polygon.cpp	(revision 18081)
+++ issm/trunk/src/c/kml/KML_Polygon.cpp	(revision 18301)
@@ -18,6 +18,5 @@
 
 /*Constructors/destructor/copy*/
-/*FUNCTION KML_Polygon::KML_Polygon(){{{*/
-KML_Polygon::KML_Polygon(){
+KML_Polygon::KML_Polygon(){/*{{{*/
 
 	extrude   =false;
@@ -30,6 +29,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Polygon::~KML_Polygon(){{{*/
-KML_Polygon::~KML_Polygon(){
+KML_Polygon::~KML_Polygon(){/*{{{*/
 
 	if (inner) {
@@ -47,6 +45,5 @@
 
 /*Other*/
-/*FUNCTION KML_Polygon::Echo {{{*/
-void  KML_Polygon::Echo(){
+void  KML_Polygon::Echo(){/*{{{*/
 
 	bool  flag=true;
@@ -64,6 +61,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Polygon::DeepEcho {{{*/
-void  KML_Polygon::DeepEcho(){
+void  KML_Polygon::DeepEcho(){/*{{{*/
 
 	char  indent[81]="";
@@ -74,6 +70,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Polygon::DeepEcho {{{*/
-void  KML_Polygon::DeepEcho(const char* indent){
+void  KML_Polygon::DeepEcho(const char* indent){/*{{{*/
 
 	int   i;
@@ -112,6 +107,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Polygon::Write {{{*/
-void  KML_Polygon::Write(FILE* filout,const char* indent){
+void  KML_Polygon::Write(FILE* filout,const char* indent){/*{{{*/
 
 	int   i;
@@ -152,6 +146,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Polygon::Read {{{*/
-void  KML_Polygon::Read(FILE* fid,char* kstr){
+void  KML_Polygon::Read(FILE* fid,char* kstr){/*{{{*/
 
 	char*        kstri;
@@ -259,6 +252,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Polygon::WriteExp {{{*/
-void  KML_Polygon::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+void  KML_Polygon::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){/*{{{*/
 
 	int   i;
Index: issm/trunk/src/c/kml/KML_Style.cpp
===================================================================
--- issm/trunk/src/c/kml/KML_Style.cpp	(revision 18081)
+++ issm/trunk/src/c/kml/KML_Style.cpp	(revision 18301)
@@ -19,6 +19,5 @@
 
 /*Constructors/destructor/copy*/
-/*FUNCTION KML_Style::KML_Style(){{{*/
-KML_Style::KML_Style(){
+KML_Style::KML_Style(){/*{{{*/
 
 	icon      =NULL;
@@ -31,6 +30,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Style::~KML_Style(){{{*/
-KML_Style::~KML_Style(){
+KML_Style::~KML_Style(){/*{{{*/
 
 	if (list) {
@@ -63,6 +61,5 @@
 
 /*Other*/
-/*FUNCTION KML_Style::Echo {{{*/
-void  KML_Style::Echo(){
+void  KML_Style::Echo(){/*{{{*/
 
 	bool  flag=true;
@@ -81,6 +78,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Style::DeepEcho {{{*/
-void  KML_Style::DeepEcho(){
+void  KML_Style::DeepEcho(){/*{{{*/
 
 	char  indent[81]="";
@@ -91,6 +87,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Style::DeepEcho {{{*/
-void  KML_Style::DeepEcho(const char* indent){
+void  KML_Style::DeepEcho(const char* indent){/*{{{*/
 
 	char  indent2[81];
@@ -131,6 +126,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Style::Write {{{*/
-void  KML_Style::Write(FILE* filout,const char* indent){
+void  KML_Style::Write(FILE* filout,const char* indent){/*{{{*/
 
 	char  indent2[81];
@@ -165,6 +159,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Style::Read {{{*/
-void  KML_Style::Read(FILE* fid,char* kstr){
+void  KML_Style::Read(FILE* fid,char* kstr){/*{{{*/
 
 	char*        kstri;
Index: issm/trunk/src/c/kml/KML_StyleSelector.cpp
===================================================================
--- issm/trunk/src/c/kml/KML_StyleSelector.cpp	(revision 18081)
+++ issm/trunk/src/c/kml/KML_StyleSelector.cpp	(revision 18301)
@@ -17,6 +17,5 @@
 
 /*Constructors/destructor/copy*/
-/*FUNCTION KML_StyleSelector::KML_StyleSelector(){{{*/
-KML_StyleSelector::KML_StyleSelector(){
+KML_StyleSelector::KML_StyleSelector(){/*{{{*/
 
 	;
@@ -24,6 +23,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_StyleSelector::~KML_StyleSelector(){{{*/
-KML_StyleSelector::~KML_StyleSelector(){
+KML_StyleSelector::~KML_StyleSelector(){/*{{{*/
 
 	;
@@ -33,6 +31,5 @@
 
 /*Other*/
-/*FUNCTION KML_StyleSelector::Echo {{{*/
-void  KML_StyleSelector::Echo(){
+void  KML_StyleSelector::Echo(){/*{{{*/
 
 	KML_Object::Echo();
@@ -41,6 +38,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_StyleSelector::DeepEcho {{{*/
-void  KML_StyleSelector::DeepEcho(){
+void  KML_StyleSelector::DeepEcho(){/*{{{*/
 
 	char  indent[81]="";
@@ -51,6 +47,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_StyleSelector::DeepEcho {{{*/
-void  KML_StyleSelector::DeepEcho(const char* indent){
+void  KML_StyleSelector::DeepEcho(const char* indent){/*{{{*/
 
 	KML_Object::DeepEcho(indent);
@@ -59,6 +54,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_StyleSelector::Write {{{*/
-void  KML_StyleSelector::Write(FILE* filout,const char* indent){
+void  KML_StyleSelector::Write(FILE* filout,const char* indent){/*{{{*/
 
 	KML_Object::Write(filout,indent);
@@ -67,6 +61,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_StyleSelector::Read {{{*/
-void  KML_StyleSelector::Read(FILE* fid,char* kstr){
+void  KML_StyleSelector::Read(FILE* fid,char* kstr){/*{{{*/
 
 /*  process field within opening and closing tags  */
Index: issm/trunk/src/c/kml/KML_SubStyle.cpp
===================================================================
--- issm/trunk/src/c/kml/KML_SubStyle.cpp	(revision 18081)
+++ issm/trunk/src/c/kml/KML_SubStyle.cpp	(revision 18301)
@@ -17,6 +17,5 @@
 
 /*Constructors/destructor/copy*/
-/*FUNCTION KML_SubStyle::KML_SubStyle(){{{*/
-KML_SubStyle::KML_SubStyle(){
+KML_SubStyle::KML_SubStyle(){/*{{{*/
 
 	;
@@ -24,6 +23,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_SubStyle::~KML_SubStyle(){{{*/
-KML_SubStyle::~KML_SubStyle(){
+KML_SubStyle::~KML_SubStyle(){/*{{{*/
 
 	;
@@ -33,6 +31,5 @@
 
 /*Other*/
-/*FUNCTION KML_SubStyle::Echo {{{*/
-void  KML_SubStyle::Echo(){
+void  KML_SubStyle::Echo(){/*{{{*/
 
 	KML_Object::Echo();
@@ -41,6 +38,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_SubStyle::DeepEcho {{{*/
-void  KML_SubStyle::DeepEcho(){
+void  KML_SubStyle::DeepEcho(){/*{{{*/
 
 	char  indent[81]="";
@@ -51,6 +47,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_SubStyle::DeepEcho {{{*/
-void  KML_SubStyle::DeepEcho(const char* indent){
+void  KML_SubStyle::DeepEcho(const char* indent){/*{{{*/
 
 	KML_Object::DeepEcho(indent);
@@ -59,6 +54,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_SubStyle::Write {{{*/
-void  KML_SubStyle::Write(FILE* filout,const char* indent){
+void  KML_SubStyle::Write(FILE* filout,const char* indent){/*{{{*/
 
 	KML_Object::Write(filout,indent);
@@ -67,6 +61,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_SubStyle::Read {{{*/
-void  KML_SubStyle::Read(FILE* fid,char* kstr){
+void  KML_SubStyle::Read(FILE* fid,char* kstr){/*{{{*/
 
 /*  process field within opening and closing tags  */
Index: issm/trunk/src/c/kml/KML_Unknown.cpp
===================================================================
--- issm/trunk/src/c/kml/KML_Unknown.cpp	(revision 18081)
+++ issm/trunk/src/c/kml/KML_Unknown.cpp	(revision 18301)
@@ -17,6 +17,5 @@
 
 /*Constructors/destructor/copy*/
-/*FUNCTION KML_Unknown::KML_Unknown(){{{*/
-KML_Unknown::KML_Unknown(){
+KML_Unknown::KML_Unknown(){/*{{{*/
 
 	name      =NULL;
@@ -25,6 +24,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Unknown::~KML_Unknown(){{{*/
-KML_Unknown::~KML_Unknown(){
+KML_Unknown::~KML_Unknown(){/*{{{*/
 
 	if (name      ) xDelete<char>(name);
@@ -35,6 +33,5 @@
 
 /*Other*/
-/*FUNCTION KML_Unknown::Echo {{{*/
-void  KML_Unknown::Echo(){
+void  KML_Unknown::Echo(){/*{{{*/
 
 	bool  flag=true;
@@ -53,6 +50,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Unknown::DeepEcho {{{*/
-void  KML_Unknown::DeepEcho(){
+void  KML_Unknown::DeepEcho(){/*{{{*/
 
 	char  indent[81]="";
@@ -63,6 +59,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Unknown::DeepEcho {{{*/
-void  KML_Unknown::DeepEcho(const char* indent){
+void  KML_Unknown::DeepEcho(const char* indent){/*{{{*/
 
 	char*        valuei;
@@ -93,6 +88,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Unknown::Write {{{*/
-void  KML_Unknown::Write(FILE* filout,const char* indent){
+void  KML_Unknown::Write(FILE* filout,const char* indent){/*{{{*/
 
 	char*        valuei;
@@ -125,6 +119,5 @@
 }
 /*}}}*/
-/*FUNCTION KML_Unknown::Read {{{*/
-void  KML_Unknown::Read(FILE* fid,char* kstr){
+void  KML_Unknown::Read(FILE* fid,char* kstr){/*{{{*/
 
 	char*        kstri;
Index: issm/trunk/src/c/main/issm.cpp
===================================================================
--- issm/trunk/src/c/main/issm.cpp	(revision 18081)
+++ issm/trunk/src/c/main/issm.cpp	(revision 18301)
@@ -23,4 +23,7 @@
 
 	/*Wrap up: */
+	femmodel->CleanUp();
+
+	/*Delete Model: */
 	delete femmodel;
 
Index: issm/trunk/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.h
===================================================================
--- issm/trunk/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.h	(revision 18081)
+++ issm/trunk/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.h	(revision 18301)
@@ -7,5 +7,5 @@
 #include "../../classes/classes.h"
 
-void	ControlInputSetGradientx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,double* gradient);
+void	ControlInputSetGradientx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,IssmDouble* gradient);
 void	ControlInputSetGradientx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,Vector<IssmDouble>* gradient);
 
Index: issm/trunk/src/c/modules/FloatingiceMeltingRatex/FloatingiceMeltingRatex.cpp
===================================================================
--- issm/trunk/src/c/modules/FloatingiceMeltingRatex/FloatingiceMeltingRatex.cpp	(revision 18301)
+++ issm/trunk/src/c/modules/FloatingiceMeltingRatex/FloatingiceMeltingRatex.cpp	(revision 18301)
@@ -0,0 +1,39 @@
+/*!\file FloatingiceMeltingRatex
+ * \brief: calculates Floating ice melting rate
+ */
+
+#include "./FloatingiceMeltingRatex.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void FloatingiceMeltingRatex(FemModel* femmodel){/*{{{*/
+
+	/*Intermediaties*/
+	int  basalforcing_model;
+
+	/*First, get SMB model from parameters*/
+	femmodel->parameters->FindParam(&basalforcing_model,BasalforcingsEnum);
+
+	/*branch to correct module*/
+	switch(basalforcing_model){
+		case FloatingMeltRateEnum:
+			/*Nothing to be done*/
+			break;
+		case LinearFloatingMeltRateEnum:
+			if(VerboseSolution())_printf_("	call Linear Floating melting rate module\n");
+			LinearFloatingiceMeltingRatex(femmodel);
+			break;
+		default:
+			_error_("Basal forcing model "<<EnumToStringx(basalforcing_model)<<" not supported yet");
+	}
+
+}/*}}}*/
+
+void LinearFloatingiceMeltingRatex(FemModel* femmodel){/*{{{*/
+
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element->LinearFloatingiceMeltingRate();
+	}
+
+}/*}}}*/
Index: issm/trunk/src/c/modules/FloatingiceMeltingRatex/FloatingiceMeltingRatex.h
===================================================================
--- issm/trunk/src/c/modules/FloatingiceMeltingRatex/FloatingiceMeltingRatex.h	(revision 18301)
+++ issm/trunk/src/c/modules/FloatingiceMeltingRatex/FloatingiceMeltingRatex.h	(revision 18301)
@@ -0,0 +1,14 @@
+/*!\file:  FloatingiceMeltingRatex.h
+ * \brief header file for Floatingice melting rate
+ */ 
+
+#ifndef _FloatingiceMeltingRatex_H
+#define _FloatingiceMeltingRatex_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void FloatingiceMeltingRatex(FemModel* femmodel);
+void LinearFloatingiceMeltingRatex(FemModel* femmodel);
+
+#endif  /* _FloatingiceMeltingRatex_H*/
Index: issm/trunk/src/c/modules/Gradjx/Gradjx.cpp
===================================================================
--- issm/trunk/src/c/modules/Gradjx/Gradjx.cpp	(revision 18081)
+++ issm/trunk/src/c/modules/Gradjx/Gradjx.cpp	(revision 18301)
@@ -9,6 +9,6 @@
 void Gradjx(Vector<IssmDouble>** pgradient,IssmDouble** pnorm_list, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters){
 
-	int     i,j,numberofvertices;
-	int     num_controls;
+	int          numberofvertices;
+	int          num_controls,analysisenum;
 	IssmDouble   norm_inf;
 	IssmDouble  *norm_list     = NULL;
@@ -17,4 +17,7 @@
 	Vector<IssmDouble> **gradient_list = NULL;
 
+	/*Display message*/
+	if(VerboseModule()) _printf0_("   Computing cost function gradient\n");
+
 	/*retrieve some parameters: */
 	parameters->FindParam(&num_controls,InversionNumControlParametersEnum);   _assert_(num_controls);
@@ -22,8 +25,12 @@
 	numberofvertices=vertices->NumberOfVertices();
 
+	/*Get current analysis*/
+	parameters->FindParam(&analysisenum,AnalysisTypeEnum);
+	Analysis* analysis = EnumToAnalysis(analysisenum);
+
 	/*Allocate gradient_list */
 	gradient_list = xNew<Vector<IssmDouble>*>(num_controls);
 	norm_list = xNew<IssmDouble>(num_controls);
-	for(i=0;i<num_controls;i++){
+	for(int i=0;i<num_controls;i++){
 		gradient_list[i]=new Vector<IssmDouble>(num_controls*numberofvertices);
 	}
@@ -31,19 +38,15 @@
 
 	/*Compute all gradient_list*/
-	for(i=0;i<num_controls;i++){
-
-		for(j=0;j<elements->Size();j++){
-
+	for(int i=0;i<num_controls;i++){
+		for(int j=0;j<elements->Size();j++){
 			Element* element=(Element*)elements->GetObjectByOffset(j);
-			element->Gradj(gradient_list[i],control_type[i],i);
+			analysis->GradientJ(gradient_list[i],element,control_type[i],i);
 		}
-
 		gradient_list[i]->Assemble();
-
 		norm_list[i]=gradient_list[i]->Norm(NORM_INF);
 	}
 
 	/*Add all gradient_list together*/
-	for(i=0;i<num_controls;i++){
+	for(int i=0;i<num_controls;i++){
 		gradient->AXPY(gradient_list[i],1.0);
 		delete gradient_list[i];
@@ -52,8 +55,11 @@
 	/*Check that gradient is clean*/
 	norm_inf=gradient->Norm(NORM_INF);
-	if(norm_inf<=0)    _error_("||∂J/∂α||∞ = 0    gradient norm is zero");
-	if(xIsNan<IssmDouble>(norm_inf))_error_("||∂J/∂α||∞ = NaN  gradient norm is NaN");
+	if(norm_inf<=0)                 _error_("||dJ/dk|| = 0    gradient norm is zero");
+	if(xIsNan<IssmDouble>(norm_inf))_error_("||dJ/dk|| = NaN  gradient norm is NaN");
 
 	/*Clean-up and assign output pointer*/
+	delete analysis;
+	xDelete<Vector<IssmDouble>*>(gradient_list);
+	xDelete<int>(control_type);
 	if(pnorm_list){
 		*pnorm_list=norm_list;
@@ -63,6 +69,5 @@
 	}
 	if(pgradient)  *pgradient=gradient;
-	xDelete<Vector<IssmDouble>*>(gradient_list);
-	xDelete<int>(control_type);
+
 }
 void Gradjx(IssmDouble** pgradient,IssmDouble** pnorm_list, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters){
Index: issm/trunk/src/c/modules/Gradjx/Gradjx.h
===================================================================
--- issm/trunk/src/c/modules/Gradjx/Gradjx.h	(revision 18081)
+++ issm/trunk/src/c/modules/Gradjx/Gradjx.h	(revision 18301)
@@ -7,4 +7,5 @@
 
 #include "../../classes/classes.h"
+#include "../../analyses/analyses.h"
 
 /* local prototypes: */
Index: issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp
===================================================================
--- issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp	(revision 18081)
+++ issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp	(revision 18301)
@@ -56,6 +56,5 @@
 }
 
-/*FUNCTION ContactFSLevelset{{{*/
-IssmDouble*    ContactFSLevelset(Elements* elements,Vertices* vertices){ 
+IssmDouble*    ContactFSLevelset(Elements* elements,Vertices* vertices){ /*{{{*/
 
 	Vector<IssmDouble>* vertexgrounded = NULL;
@@ -108,6 +107,5 @@
 }
 /*}}}*/
-/*FUNCTION PotentialUngrounding {{{*/
-IssmDouble*    PotentialUngrounding(Elements* elements,Vertices* vertices,Parameters* parameters){ 
+IssmDouble*    PotentialUngrounding(Elements* elements,Vertices* vertices,Parameters* parameters){ /*{{{*/
 
 	int                 i,numberofvertices;
@@ -135,6 +133,5 @@
 }
 /*}}}*/
-/*FUNCTION PropagateFloatingiceToGroundedNeighbors {{{*/
-IssmDouble*    PropagateFloatingiceToGroundedNeighbors(Elements* elements,Nodes* nodes,Vertices* vertices,Parameters* parameters,IssmDouble* vertices_potentially_ungrounding){ 
+IssmDouble*    PropagateFloatingiceToGroundedNeighbors(Elements* elements,Nodes* nodes,Vertices* vertices,Parameters* parameters,IssmDouble* vertices_potentially_ungrounding){ /*{{{*/
 	int                 i,analysis_type;
 	int                 nflipped,local_nflipped;
Index: issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp
===================================================================
--- issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp	(revision 18081)
+++ issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp	(revision 18301)
@@ -25,4 +25,7 @@
 	femmodel->parameters->FindParam(&analysisenum,AnalysisTypeEnum);
 
+	/*Display message*/
+	if(VerboseModule()) _printf0_("   Updating inputs from solution\n");
+
 	Analysis* analysis = EnumToAnalysis(analysisenum);
 	for(int i=0;i<femmodel->elements->Size();i++){
Index: issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp
===================================================================
--- issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp	(revision 18081)
+++ issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp	(revision 18301)
@@ -75,4 +75,17 @@
 			}
 			EdgeOnBoundaryFlags(&boundaryedge,iomodel);
+			break;
+		case P2bubbleEnum:
+			EdgesPartitioning(&my_edges,iomodel);
+			if(iomodel->meshelementtype==PentaEnum){
+				FacesPartitioning(&my_faces,iomodel);
+			}
+			EdgeOnBoundaryFlags(&boundaryedge,iomodel);
+			switch(iomodel->meshelementtype){
+				case TriaEnum:  elementnbv = 3; break;
+				case TetraEnum: elementnbv = 4; break;
+				case PentaEnum: elementnbv = 6; break;
+				default: _error_("mesh type not supported yet");
+			}
 			break;
 		case P2xP4Enum:
@@ -138,4 +151,60 @@
 				}
 				break;
+			case P2bubbleEnum:
+				for(i=0;i<iomodel->numberofvertices;i++){
+					if((iomodel->my_vertices[i])){
+						if (!xIsNan<IssmDouble>(spcdata[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,dof,spcdata[i],analysis_type));
+							count++;
+						}
+					}
+				}
+				for(i=0;i<iomodel->numberofedges;i++){
+					if(my_edges[i] && boundaryedge[i]){
+						v1 = iomodel->edges[3*i+0]-1;
+						v2 = iomodel->edges[3*i+1]-1;
+						if(!xIsNan<IssmDouble>(spcdata[v1]) && !xIsNan<IssmDouble>(spcdata[v2])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+iomodel->numberofvertices+i+1,
+											dof,(spcdata[v1]+spcdata[v2])/2.,analysis_type));
+							count++;
+						}
+					}
+				}
+				if(iomodel->meshelementtype==PentaEnum){
+					for(i=0;i<iomodel->numberoffaces;i++){
+						if(iomodel->faces[i*iomodel->facescols+2]==2){/*Vertical quads*/
+							if(my_faces[i]){
+								numfacevertices = iomodel->faces[i*iomodel->facescols+3];
+								value=0.;
+								for(j=0;j<numfacevertices;j++){
+									value += spcdata[iomodel->faces[i*iomodel->facescols+4+j] -1];
+								}
+								value = value/reCast<IssmDouble>(numfacevertices);
+								if(!xIsNan<IssmDouble>(value)){
+									constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,
+													iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+i+1,
+													dof,value,analysis_type));
+									count++;
+								}
+							}
+						}
+					}
+				}
+				for(i=0;i<iomodel->numberofelements;i++){
+					if(iomodel->my_elements[i]){
+						value = spcdata[iomodel->elements[i*elementnbv+0]-1];
+						for(j=1;j<elementnbv;j++) value += spcdata[iomodel->elements[i*elementnbv+j]-1];
+						value = value/reCast<IssmDouble,int>(elementnbv+0);
+						if(!xIsNan<IssmDouble>(value)){
+							int nodeid = iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+i+1;
+							if(iomodel->meshelementtype==PentaEnum){
+								nodeid += iomodel->numberoffaces;
+							}
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,nodeid,dof,value,analysis_type));
+							count++;
+						}
+					}
+				}
+				break;
 			case P2xP4Enum:
 				for(i=0;i<iomodel->numberofvertices;i++){
Index: issm/trunk/src/c/modules/Krigingx/Krigingx.cpp
===================================================================
--- issm/trunk/src/c/modules/Krigingx/Krigingx.cpp	(revision 18081)
+++ issm/trunk/src/c/modules/Krigingx/Krigingx.cpp	(revision 18301)
@@ -11,6 +11,5 @@
 #include <gsl/gsl_linalg.h>
 #endif
-/*FUNCTION Krigingx{{{*/
-int Krigingx(double** ppredictions,double **perror,double* obs_x, double* obs_y, double* obs_list, int obs_length,double* x_interp,double* y_interp,int n_interp,Options* options){
+int   Krigingx(double** ppredictions,double **perror,double* obs_x, double* obs_y, double* obs_list, int obs_length,double* x_interp,double* y_interp,int n_interp,Options* options){/*{{{*/
 
 	/*output*/
@@ -189,6 +188,5 @@
 	return 1;
 }/*}}}*/
-/*FUNCTION Krigingxt{{{*/
-void* Krigingxt(void* vpthread_handle){
+void* Krigingxt(void* vpthread_handle){/*{{{*/
 
 	/*gate variables :*/
@@ -236,6 +234,5 @@
 	return NULL;
 }/*}}}*/
-/*FUNCTION NearestNeighbort{{{*/
-void* NearestNeighbort(void* vpthread_handle){
+void* NearestNeighbort(void* vpthread_handle){/*{{{*/
 
 	/*gate variables :*/
@@ -282,6 +279,5 @@
 	return NULL;
 }/*}}}*/
-/*FUNCTION idwt{{{*/
-void* idwt(void* vpthread_handle){
+void* idwt(void* vpthread_handle){/*{{{*/
 
 	/*gate variables :*/
@@ -328,6 +324,5 @@
 	return NULL;
 }/*}}}*/
-/*FUNCTION v4t{{{*/
-void* v4t(void* vpthread_handle){
+void* v4t(void* vpthread_handle){/*{{{*/
 
 	/*gate variables :*/
@@ -373,6 +368,5 @@
 	return NULL;
 }/*}}}*/
-/*FUNCTION Distancest{{{*/
-void* Distancest(void* vpthread_handle){
+void* Distancest(void* vpthread_handle){/*{{{*/
 
 	/*gate variables :*/
Index: issm/trunk/src/c/modules/Krigingx/Krigingx.h
===================================================================
--- issm/trunk/src/c/modules/Krigingx/Krigingx.h	(revision 18081)
+++ issm/trunk/src/c/modules/Krigingx/Krigingx.h	(revision 18301)
@@ -15,4 +15,5 @@
 int  pKrigingx(double** ppredictions,double **perror,double* x, double* y, double* observations, int n_obs,double* x_interp,double* y_interp,int n_interp,Options* options);
 void ProcessVariogram(Variogram **pvariogram,Options* options);
+void ProcessVariogram2(Variogram **pvariogram,Options* options);
 
 /*threading: */
Index: issm/trunk/src/c/modules/Krigingx/pKrigingx.cpp
===================================================================
--- issm/trunk/src/c/modules/Krigingx/pKrigingx.cpp	(revision 18081)
+++ issm/trunk/src/c/modules/Krigingx/pKrigingx.cpp	(revision 18301)
@@ -9,6 +9,5 @@
 #include "../../shared/io/io.h"
 
-/*FUNCTION pKrigingx{{{*/
-int pKrigingx(double** ppredictions,double **perror,double* obs_x, double* obs_y, double* obs_list, int obs_length,double* x_interp,double* y_interp,int n_interp,Options* options){
+int pKrigingx(double** ppredictions,double **perror,double* obs_x, double* obs_y, double* obs_list, int obs_length,double* x_interp,double* y_interp,int n_interp,Options* options){/*{{{*/
 
 #ifdef _HAVE_MPI_
@@ -66,5 +65,5 @@
 
 		/*Process Variogram*/
-		ProcessVariogram(&variogram,options);
+		ProcessVariogram2(&variogram,options);
 
 		/*partition loop across threads: */
@@ -157,5 +156,5 @@
 #endif
 }/*}}}*/
-void ProcessVariogram(Variogram **pvariogram,Options* options){/*{{{*/
+void ProcessVariogram2(Variogram **pvariogram,Options* options){/*{{{*/
 
 	/*Intermediaries*/
Index: issm/trunk/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp
===================================================================
--- issm/trunk/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp	(revision 18081)
+++ issm/trunk/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp	(revision 18301)
@@ -16,8 +16,8 @@
 	int         num_cm_responses;
 	int        *control_type     = NULL;
+	int        *maxiter          = NULL;
 	int        *cm_responses     = NULL;
 	IssmDouble *cm_jump          = NULL;
 	IssmDouble *optscal          = NULL;
-	IssmDouble *maxiter          = NULL;
 
 	/*retrieve some parameters: */
@@ -56,5 +56,5 @@
 				parameters->AddObject(new DoubleMatParam(InversionGradientScalingEnum,optscal,nsteps,num_control_type));
 				parameters->AddObject(new DoubleVecParam(InversionStepThresholdEnum,cm_jump,nsteps));
-				parameters->AddObject(new DoubleVecParam(InversionMaxiterPerStepEnum,maxiter,nsteps));
+				parameters->AddObject(new IntVecParam(InversionMaxiterPerStepEnum,maxiter,nsteps));
 				break;
 			case 1:/*TAO*/
@@ -74,4 +74,6 @@
 				parameters->AddObject(iomodel->CopyConstantObject(InversionMaxiterEnum));
 				break;
+			case 3:/*Validation*/
+				break;
 			default:
 				_error_("not supported");
@@ -81,7 +83,7 @@
 		xDelete<int>(control_type);
 		xDelete<int>(cm_responses);
+		xDelete<int>(maxiter);
 		iomodel->DeleteData(cm_jump,InversionStepThresholdEnum);
 		iomodel->DeleteData(optscal,InversionGradientScalingEnum);
-		iomodel->DeleteData(maxiter,InversionMaxiterPerStepEnum);
 	}
 }
Index: issm/trunk/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp
===================================================================
--- issm/trunk/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp	(revision 18081)
+++ issm/trunk/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp	(revision 18301)
@@ -12,6 +12,5 @@
 
 	/*Intermediary*/
-	int       i;
-	int       counter;
+	int       control;
 	Element  *element = NULL;
 	Material *material = NULL;
@@ -33,6 +32,6 @@
 	iomodel->FetchData(5,InversionControlParametersEnum,InversionCostFunctionsEnum,InversionCostFunctionsCoefficientsEnum,InversionMinParametersEnum,InversionMaxParametersEnum);
 
-	for(i=0;i<num_control_type;i++){
-		int control = reCast<int,IssmDouble>(iomodel->Data(InversionControlParametersEnum)[i]);
+	for(int i=0;i<num_control_type;i++){
+		control = reCast<int,IssmDouble>(iomodel->Data(InversionControlParametersEnum)[i]);
 		switch(control){
 			/*List of supported controls*/
@@ -44,4 +43,5 @@
 			case BalancethicknessNuxEnum:
 			case BalancethicknessNuyEnum:
+			case BalancethicknessApparentMassbalanceEnum:
 				iomodel->FetchData(1,control); 
 				break;
@@ -56,6 +56,6 @@
 
 	/*Update elements: */
-	counter=0;
-	for (i=0;i<iomodel->numberofelements;i++){
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
 		if(iomodel->my_elements[i]){
 			element=(Element*)elements->GetObjectByOffset(counter);
@@ -66,4 +66,14 @@
 
 	/*Free data: */
-	iomodel->DeleteData(5+7,InversionControlParametersEnum,InversionCostFunctionsCoefficientsEnum,InversionCostFunctionsEnum,InversionMinParametersEnum,InversionMaxParametersEnum,BalancethicknessThickeningRateEnum,VxEnum,VyEnum,ThicknessEnum,FrictionCoefficientEnum,MaterialsRheologyBEnum,DamageDEnum);
+	for(int i=0;i<num_control_type;i++){
+		control = reCast<int,IssmDouble>(iomodel->Data(InversionControlParametersEnum)[i]);
+		switch(control){
+			case MaterialsRheologyBbarEnum: iomodel->DeleteData(1,MaterialsRheologyBEnum); break;
+			case DamageDbarEnum:            iomodel->DeleteData(1,DamageDEnum);            break;
+			default:                        iomodel->DeleteData(1,control); 
+		}
+	}
+	iomodel->DeleteData(5,InversionControlParametersEnum,InversionCostFunctionsCoefficientsEnum,InversionCostFunctionsEnum,InversionMinParametersEnum,InversionMaxParametersEnum);
+
+
 }
Index: issm/trunk/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp
===================================================================
--- issm/trunk/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp	(revision 18081)
+++ issm/trunk/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp	(revision 18301)
@@ -56,8 +56,6 @@
 				case 2:
 					elements->InputDuplicate(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum);
-					if(dakota_analysis) elements->InputDuplicate(MaterialsRheologyBbarEnum,QmuMaterialsRheologyBEnum);
 					break;
 				case 3:
-					if(dakota_analysis) elements->InputDuplicate(MaterialsRheologyBEnum,QmuMaterialsRheologyBEnum); 
 					break;
 				default:
@@ -74,8 +72,6 @@
 					elements->InputDuplicate(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum);
 					elements->InputDuplicate(DamageDEnum,DamageDbarEnum);
-					if(dakota_analysis) elements->InputDuplicate(MaterialsRheologyBbarEnum,QmuMaterialsRheologyBEnum);
 					break;
 				case 3:
-					if(dakota_analysis) elements->InputDuplicate(MaterialsRheologyBEnum,QmuMaterialsRheologyBEnum); 
 					break;
 				default:
Index: issm/trunk/src/c/modules/ModelProcessorx/CreateFaces.cpp
===================================================================
--- issm/trunk/src/c/modules/ModelProcessorx/CreateFaces.cpp	(revision 18081)
+++ issm/trunk/src/c/modules/ModelProcessorx/CreateFaces.cpp	(revision 18301)
@@ -164,4 +164,5 @@
 			elementfaces_markers[1] = 1;
 			elementfaces_markers[2] = 1;
+			elementfaces_markers[3] = 1;
 			elementfaces[cols*0+0] = 3; elementfaces[cols*0+1] = 0;  elementfaces[cols*0+2] = 1; elementfaces[cols*0+3] = 2;
 			elementfaces[cols*1+0] = 3; elementfaces[cols*1+1] = 0;  elementfaces[cols*1+2] = 3; elementfaces[cols*1+3] = 1;
Index: issm/trunk/src/c/modules/ModelProcessorx/CreateNodes.cpp
===================================================================
--- issm/trunk/src/c/modules/ModelProcessorx/CreateNodes.cpp	(revision 18081)
+++ issm/trunk/src/c/modules/ModelProcessorx/CreateNodes.cpp	(revision 18301)
@@ -13,5 +13,5 @@
 	/*Intermediaries*/
 	int   i,j,counter,vnodes,lid=0;
-	int   numberoffaces;
+	int   numberoffaces,elementnbv;
 	int   id0 = iomodel->nodecounter;
 	bool *my_faces = NULL;
@@ -162,4 +162,41 @@
 			}
 			break;
+		case P2bubbleEnum:
+			EdgesPartitioning(&my_edges,iomodel);
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(id0+i+1,i,lid++,i,iomodel,analysis,approximation));
+				}
+			}
+			for(i=0;i<iomodel->numberofedges;i++){
+				if(my_edges[i]){
+					nodes->AddObject(new Node(id0+iomodel->numberofvertices+i+1,iomodel->numberofvertices+i,lid++,0,iomodel,analysis,approximation));
+				}
+			}
+			id0 = id0+iomodel->numberofvertices+iomodel->numberofedges;
+			if(iomodel->meshelementtype==PentaEnum){
+				FacesPartitioning(&my_faces,iomodel);
+				for(i=0;i<iomodel->numberoffaces;i++){
+					if(iomodel->faces[i*iomodel->facescols+2]==2){/*Vertical quads*/
+						if(my_faces[i]){
+							node = new Node(id0+i+1,iomodel->numberofvertices+iomodel->numberofedges+i,lid++,0,iomodel,analysis,approximation);
+							nodes->AddObject(node);
+						}
+					}
+					else if(iomodel->faces[i*iomodel->facescols+2]==1){/*Triangular base/top*/
+						/*Nothing*/
+					}
+					else{
+						_error_("not supported");
+					}
+				}
+				id0 = id0+iomodel->numberoffaces;
+			}
+			for(i=0;i<iomodel->numberofelements;i++){
+				if(iomodel->my_elements[i]){
+					nodes->AddObject(new Node(id0+i+1,id0-iomodel->nodecounter+i,lid++,0,iomodel,analysis,approximation));
+				}
+			}
+			break;
 		case P2xP4Enum:
 			EdgesPartitioning(&my_edges,iomodel);
@@ -341,4 +378,39 @@
 			}
 			break;
+		case LATaylorHoodEnum:
+			_assert_(approximation==FSApproximationEnum);
+			/*P2 velocity*/
+			EdgesPartitioning(&my_edges,iomodel);
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(id0+i+1,i,lid++,i,iomodel,analysis,FSvelocityEnum));
+				}
+			}
+			for(i=0;i<iomodel->numberofedges;i++){
+				if(my_edges[i]){
+					nodes->AddObject(new Node(id0+iomodel->numberofvertices+i+1,iomodel->numberofvertices+i,lid++,0,iomodel,analysis,FSvelocityEnum));
+				}
+			}
+			id0 = id0+iomodel->numberofvertices+iomodel->numberofedges;
+	      if(iomodel->meshelementtype==PentaEnum){
+				FacesPartitioning(&my_faces,iomodel);
+				for(i=0;i<iomodel->numberoffaces;i++){
+					if(iomodel->faces[i*iomodel->facescols+2]==2){/*Vertical quads*/
+						if(my_faces[i]){
+							node = new Node(id0+i+1,iomodel->numberofvertices+iomodel->numberofedges+i,lid++,0,iomodel,analysis,FSvelocityEnum);
+							nodes->AddObject(node);
+						}
+					}
+					else if(iomodel->faces[i*iomodel->facescols+2]==1){/*Triangular base/top*/
+						/*Nothing*/
+					}
+					else{
+						_error_("not supported");
+					}
+				}
+			}
+
+			/*No pressure*/
+			break;
 		case OneLayerP4zEnum:
 			_assert_(approximation==FSApproximationEnum);
@@ -405,4 +477,60 @@
 			}
 			break;
+		case CrouzeixRaviartEnum:
+			_assert_(approximation==FSApproximationEnum);
+			/*P2b velocity*/
+			EdgesPartitioning(&my_edges,iomodel);
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(id0+i+1,i,lid++,i,iomodel,analysis,FSvelocityEnum));
+				}
+			}
+			for(i=0;i<iomodel->numberofedges;i++){
+				if(my_edges[i]){
+					nodes->AddObject(new Node(id0+iomodel->numberofvertices+i+1,iomodel->numberofvertices+i,lid++,0,iomodel,analysis,FSvelocityEnum));
+				}
+			}
+			id0 = id0+iomodel->numberofvertices+iomodel->numberofedges;
+			if(iomodel->meshelementtype==PentaEnum){
+				FacesPartitioning(&my_faces,iomodel);
+				for(i=0;i<iomodel->numberoffaces;i++){
+					if(iomodel->faces[i*iomodel->facescols+2]==2){/*Vertical quads*/
+						if(my_faces[i]){
+							node = new Node(id0+i+1,iomodel->numberofvertices+iomodel->numberofedges+i,lid++,0,iomodel,analysis,FSvelocityEnum);
+							nodes->AddObject(node);
+						}
+					}
+					else if(iomodel->faces[i*iomodel->facescols+2]==1){/*Triangular base/top*/
+						/*Nothing*/
+					}
+					else{
+						_error_("not supported");
+					}
+				}
+				id0 = id0+iomodel->numberoffaces;
+			}
+			for(i=0;i<iomodel->numberofelements;i++){
+				if(iomodel->my_elements[i]){
+					nodes->AddObject(new Node(id0+i+1,id0-iomodel->nodecounter+i,lid++,0,iomodel,analysis,FSvelocityEnum));
+				}
+			}
+
+			/*P1 DG pressure*/
+			vnodes = id0+iomodel->numberofelements;
+			switch(iomodel->meshelementtype){
+				case TriaEnum:  elementnbv = 3; break;
+				case TetraEnum: elementnbv = 4; break;
+				case PentaEnum: elementnbv = 6; break;
+				default:        _error_("mesh dimension not supported yet");
+			}
+			for(i=0;i<iomodel->numberofelements;i++){
+				if(iomodel->my_elements[i]){
+					for(j=0;j<elementnbv;j++){
+						nodes->AddObject(new Node(vnodes+elementnbv*i+j+1,vnodes-iomodel->nodecounter+elementnbv*i+j,lid++,iomodel->elements[+elementnbv*i+j]-1,iomodel,analysis,FSpressureEnum));
+
+					}
+				}
+			}
+			break;
 
 		default:
Index: issm/trunk/src/c/modules/ModelProcessorx/CreateParameters.cpp
===================================================================
--- issm/trunk/src/c/modules/ModelProcessorx/CreateParameters.cpp	(revision 18081)
+++ issm/trunk/src/c/modules/ModelProcessorx/CreateParameters.cpp	(revision 18301)
@@ -19,5 +19,5 @@
 
 	int         i,j,m,k;
-	int         numoutputs,materialtype,smb_model;
+	int         numoutputs,materialtype,smb_model,basalforcing_model;
 	char**      requestedoutputs = NULL;
 	IssmDouble  time;
@@ -53,9 +53,9 @@
 	parameters->AddObject(iomodel->CopyConstantObject(TimesteppingTimeStepEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(TimesteppingCflCoefficientEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(TimesteppingInterpForcingsEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(SettingsLowmemEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(DebugProfilingEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(MeshAverageVertexConnectivityEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(ConstantsReferencetemperatureEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(GroundinglineMeltingRateEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(SettingsWaitonlockEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(MeshNumberofelementsEnum));
@@ -123,6 +123,28 @@
 			/*Nothing to add to parameters*/
 			break;
+		case SMBcomponentsEnum:
+			/*Nothing to add to parameters*/
+			break;
+		case SMBmeltcomponentsEnum:
+			/*Nothing to add to parameters*/
+			break;
 		default:
 			_error_("Surface mass balance model "<<EnumToStringx(smb_model)<<" not supported yet");
+	}
+
+	/*Basal forcing parameters*/
+	parameters->AddObject(iomodel->CopyConstantObject(BasalforcingsEnum));
+	iomodel->Constant(&basalforcing_model,BasalforcingsEnum);
+	switch(basalforcing_model){
+		case FloatingMeltRateEnum:
+			/*Nothing to add to parameters*/
+			break;
+		case LinearFloatingMeltRateEnum:
+			parameters->AddObject(iomodel->CopyConstantObject(BasalforcingsDeepwaterMeltingRateEnum));
+			parameters->AddObject(iomodel->CopyConstantObject(BasalforcingsDeepwaterElevationEnum));
+			parameters->AddObject(iomodel->CopyConstantObject(BasalforcingsUpperwaterElevationEnum));
+			break;
+		default:
+			_error_("Basal forcing model "<<EnumToStringx(smb_model)<<" not supported yet");
 	}
 
Index: issm/trunk/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp
===================================================================
--- issm/trunk/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp	(revision 18081)
+++ issm/trunk/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp	(revision 18301)
@@ -7,5 +7,5 @@
 #include "../../toolkits/toolkits.h"
 
-void SetControlInputsFromVectorx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,IssmDouble* vector){
+void SetControlInputsFromVectorx(FemModel* femmodel,IssmDouble* vector){
 
 	int  num_controls;
@@ -13,10 +13,10 @@
 
 	/*Retrieve some parameters*/
-	parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
-	parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+	femmodel->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+	femmodel->parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
 
 	for(int i=0;i<num_controls;i++){
-		for(int j=0;j<elements->Size();j++){
-			Element* element=(Element*)elements->GetObjectByOffset(j);
+		for(int j=0;j<femmodel->elements->Size();j++){
+			Element* element=(Element*)femmodel->elements->GetObjectByOffset(j);
 			element->SetControlInputsFromVector(vector,control_type[i],i);
 		}
@@ -26,13 +26,8 @@
 }
 
-void SetControlInputsFromVectorx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,Vector<IssmDouble>* vector){
+void SetControlInputsFromVectorx(FemModel* femmodel,Vector<IssmDouble>* vector){
 
-	IssmDouble* serial_vector=NULL;
-
-	serial_vector=vector->ToMPISerial();
-
-	SetControlInputsFromVectorx(elements,nodes, vertices, loads, materials, parameters,serial_vector);
-
-	/*Free ressources:*/
+	IssmDouble* serial_vector=vector->ToMPISerial();
+	SetControlInputsFromVectorx(femmodel,serial_vector);
 	xDelete<IssmDouble>(serial_vector);
 }
Index: issm/trunk/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.h
===================================================================
--- issm/trunk/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.h	(revision 18081)
+++ issm/trunk/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.h	(revision 18301)
@@ -8,6 +8,6 @@
 
 /* local prototypes: */
-void SetControlInputsFromVectorx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,Vector<IssmDouble>* vector);
-void SetControlInputsFromVectorx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,IssmDouble* vector);
+void SetControlInputsFromVectorx(FemModel* femmodel,Vector<IssmDouble>* vector);
+void SetControlInputsFromVectorx(FemModel* femmodel,IssmDouble* vector);
 
 #endif 
Index: issm/trunk/src/c/modules/SurfaceMassBalancex/SurfaceMassBalancex.cpp
===================================================================
--- issm/trunk/src/c/modules/SurfaceMassBalancex/SurfaceMassBalancex.cpp	(revision 18081)
+++ issm/trunk/src/c/modules/SurfaceMassBalancex/SurfaceMassBalancex.cpp	(revision 18301)
@@ -38,4 +38,12 @@
 			SmbHenningx(femmodel);
 			break;
+		case SMBcomponentsEnum:
+			if(VerboseSolution())_printf_("  call smb Components module\n");
+			SmbComponentsx(femmodel);
+			break;
+		case SMBmeltcomponentsEnum:
+			if(VerboseSolution())_printf_("  call smb Melt Components module\n");
+			SmbMeltComponentsx(femmodel);
+			break;
 		default:
 			_error_("Surface mass balance model "<<EnumToStringx(smb_model)<<" not supported yet");
@@ -50,8 +58,53 @@
 	//    INPUT: surface elevation (m): hd(NA)
 	//    OUTPUT: mass-balance (m/yr ice): agd(NA)
-
-	for(int i=0;i<femmodel->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
-		element->SmbGradients();
+	int v;
+	IssmDouble rho_water;                   // density of fresh water
+	IssmDouble rho_ice;                     // density of ice
+
+	/*Loop over all the elements of this partition*/
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+
+		/*Allocate all arrays*/
+		int         numvertices = element->GetNumberOfVertices();
+		IssmDouble* Href        = xNew<IssmDouble>(numvertices); // reference elevation from which deviations are used to calculate the SMB adjustment
+		IssmDouble* Smbref      = xNew<IssmDouble>(numvertices); // reference SMB to which deviations are added
+		IssmDouble* b_pos       = xNew<IssmDouble>(numvertices); // Hs-SMB relation parameter
+		IssmDouble* b_neg       = xNew<IssmDouble>(numvertices); // Hs-SMB relation paremeter
+		IssmDouble* s           = xNew<IssmDouble>(numvertices); // surface elevation (m)
+		IssmDouble* smb         = xNew<IssmDouble>(numvertices);
+
+		/*Recover SmbGradients*/
+		element->GetInputListOnVertices(Href,SurfaceforcingsHrefEnum);
+		element->GetInputListOnVertices(Smbref,SurfaceforcingsSmbrefEnum);
+		element->GetInputListOnVertices(b_pos,SurfaceforcingsBPosEnum);
+		element->GetInputListOnVertices(b_neg,SurfaceforcingsBNegEnum);
+
+		/*Recover surface elevation at vertices: */
+		element->GetInputListOnVertices(s,SurfaceEnum);
+
+		/*Get material parameters :*/
+		rho_ice=element->matpar->GetRhoIce();
+		rho_water=element->matpar->GetRhoFreshwater();
+
+		// loop over all vertices
+		for(v=0;v<numvertices;v++){
+			if(Smbref[v]>0){
+				smb[v]=Smbref[v]+b_pos[v]*(s[v]-Href[v]);
+			}
+			else{
+				smb[v]=Smbref[v]+b_neg[v]*(s[v]-Href[v]);
+			}
+			smb[v]=smb[v]/1000*rho_water/rho_ice;      // SMB in m/y ice
+		}  //end of the loop over the vertices
+
+		/*Add input to element and Free memory*/
+		element->AddInput(SurfaceforcingsMassBalanceEnum,smb,P1Enum);
+		xDelete<IssmDouble>(Href);
+		xDelete<IssmDouble>(Smbref);
+		xDelete<IssmDouble>(b_pos);
+		xDelete<IssmDouble>(b_neg);
+		xDelete<IssmDouble>(s);
+		xDelete<IssmDouble>(smb);
 	}
 
@@ -227,2 +280,86 @@
 
 }/*}}}*/
+void SmbComponentsx(FemModel* femmodel){/*{{{*/
+
+	// void SmbComponentsx(acc,evap,runoff,ni){
+	//    INPUT parameters: ni: working size of arrays
+	//    INPUT: surface accumulation (m/yr water equivalent): acc
+	//    surface evaporation (m/yr water equivalent): evap
+	//    surface runoff (m/yr water equivalent): runoff
+	//    OUTPUT: mass-balance (m/yr ice): agd(NA)
+	int v;
+
+	/*Loop over all the elements of this partition*/
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+
+		/*Allocate all arrays*/
+		int         numvertices = element->GetNumberOfVertices();
+		IssmDouble* acc         = xNew<IssmDouble>(numvertices); 
+		IssmDouble* evap        = xNew<IssmDouble>(numvertices);
+		IssmDouble* runoff      = xNew<IssmDouble>(numvertices); 
+		IssmDouble* smb         = xNew<IssmDouble>(numvertices);
+
+		/*Recover Smb Components*/
+		element->GetInputListOnVertices(acc,SurfaceforcingsAccumulationEnum);
+		element->GetInputListOnVertices(evap,SurfaceforcingsEvaporationEnum);
+		element->GetInputListOnVertices(runoff,SurfaceforcingsRunoffEnum);
+
+		// loop over all vertices
+		for(v=0;v<numvertices;v++){
+			smb[v]=acc[v]-evap[v]-runoff[v];
+		}  //end of the loop over the vertices
+
+		/*Add input to element and Free memory*/
+		element->AddInput(SurfaceforcingsMassBalanceEnum,smb,P1Enum);
+		xDelete<IssmDouble>(acc);
+		xDelete<IssmDouble>(evap);
+		xDelete<IssmDouble>(runoff);
+		xDelete<IssmDouble>(smb);
+	}
+
+}/*}}}*/
+void SmbMeltComponentsx(FemModel* femmodel){/*{{{*/
+
+	// void SmbMeltComponentsx(acc,evap,melt,refreeze,ni){
+	//    INPUT parameters: ni: working size of arrays
+	//    INPUT: surface accumulation (m/yr water equivalent): acc
+	//    surface evaporation (m/yr water equivalent): evap
+	//    surface melt (m/yr water equivalent): melt
+	//    refreeze of surface melt (m/yr water equivalent): refreeze
+	//    OUTPUT: mass-balance (m/yr ice): agd(NA)
+	int v;
+
+	/*Loop over all the elements of this partition*/
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+
+		/*Allocate all arrays*/
+		int         numvertices = element->GetNumberOfVertices();
+		IssmDouble* acc         = xNew<IssmDouble>(numvertices);
+		IssmDouble* evap        = xNew<IssmDouble>(numvertices); 
+		IssmDouble* melt        = xNew<IssmDouble>(numvertices);
+		IssmDouble* refreeze    = xNew<IssmDouble>(numvertices);
+		IssmDouble* smb         = xNew<IssmDouble>(numvertices);
+
+		/*Recover Smb Components*/
+		element->GetInputListOnVertices(acc,SurfaceforcingsAccumulationEnum);
+		element->GetInputListOnVertices(evap,SurfaceforcingsEvaporationEnum);
+		element->GetInputListOnVertices(melt,SurfaceforcingsMeltEnum);
+		element->GetInputListOnVertices(refreeze,SurfaceforcingsRefreezeEnum);
+
+		// loop over all vertices
+		for(v=0;v<numvertices;v++){
+			smb[v]=acc[v]-evap[v]-melt[v]+refreeze[v];
+		}  //end of the loop over the vertices
+
+		/*Add input to element and Free memory*/
+		element->AddInput(SurfaceforcingsMassBalanceEnum,smb,P1Enum);
+		xDelete<IssmDouble>(acc);
+		xDelete<IssmDouble>(evap);
+		xDelete<IssmDouble>(melt);
+		xDelete<IssmDouble>(refreeze);
+		xDelete<IssmDouble>(smb);
+	}
+
+}/*}}}*/
Index: issm/trunk/src/c/modules/SurfaceMassBalancex/SurfaceMassBalancex.h
===================================================================
--- issm/trunk/src/c/modules/SurfaceMassBalancex/SurfaceMassBalancex.h	(revision 18081)
+++ issm/trunk/src/c/modules/SurfaceMassBalancex/SurfaceMassBalancex.h	(revision 18301)
@@ -14,4 +14,6 @@
 void PositiveDegreeDayx(FemModel* femmodel);
 void SmbHenningx(FemModel* femmodel);
+void SmbComponentsx(FemModel* femmodel);
+void SmbMeltComponentsx(FemModel* femmodel);
 
 #endif  /* _SurfaceMassBalancex_H*/
Index: issm/trunk/src/c/modules/modules.h
===================================================================
--- issm/trunk/src/c/modules/modules.h	(revision 18081)
+++ issm/trunk/src/c/modules/modules.h	(revision 18301)
@@ -8,5 +8,4 @@
 /*Modules: */
 #include "./AllocateSystemMatricesx/AllocateSystemMatricesx.h"
-#include "./AverageFilterx/AverageFilterx.h"
 #include "./AverageOntoPartitionx/AverageOntoPartitionx.h"
 #include "./Bamgx/Bamgx.h"
@@ -17,12 +16,9 @@
 #include "./ContourToMeshx/ContourToMeshx.h"
 #include "./ContourToNodesx/ContourToNodesx.h"
-#include "./ControlInputGetGradientx/ControlInputGetGradientx.h"
 #include "./ControlInputSetGradientx/ControlInputSetGradientx.h"
-#include "./ControlInputScaleGradientx/ControlInputScaleGradientx.h"
 #include "./CreateNodalConstraintsx/CreateNodalConstraintsx.h"
 #include "./CreateJacobianMatrixx/CreateJacobianMatrixx.h"
 #include "./DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h"
 #include "./ElementConnectivityx/ElementConnectivityx.h"
-#include "./EdgeDetectionx/EdgeDetectionx.h"
 #include "./GetSolutionFromInputsx/GetSolutionFromInputsx.h"
 #include "./GetVectorFromInputsx/GetVectorFromInputsx.h"
@@ -33,5 +29,4 @@
 #include "./Gradjx/Gradjx.h"
 #include "./GroundinglineMigrationx/GroundinglineMigrationx.h"
-#include "./HoleFillerx/HoleFillerx.h"
 #include "./InputControlUpdatex/InputControlUpdatex.h"
 #include "./InputDepthAverageAtBasex/InputDepthAverageAtBasex.h"
@@ -57,4 +52,5 @@
 #include "./Kml2Expx/Kml2Expx.h"
 #include "./Krigingx/Krigingx.h"
+#include "./FloatingiceMeltingRatex/FloatingiceMeltingRatex.h"
 #include "./Mergesolutionfromftogx/Mergesolutionfromftogx.h"
 #include "./MeshPartitionx/MeshPartitionx.h"
@@ -70,5 +66,4 @@
 #include "./NodeConnectivityx/NodeConnectivityx.h"
 #include "./NodesDofx/NodesDofx.h"
-#include "./Orthx/Orthx.h"
 #include "./OutputDefinitionsResponsex/OutputDefinitionsResponsex.h"
 #include "./OutputResultsx/OutputResultsx.h"
Index: issm/trunk/src/c/shared/Elements/DrainageFunctionWaterfraction.cpp
===================================================================
--- issm/trunk/src/c/shared/Elements/DrainageFunctionWaterfraction.cpp	(revision 18081)
+++ issm/trunk/src/c/shared/Elements/DrainageFunctionWaterfraction.cpp	(revision 18301)
@@ -7,5 +7,4 @@
 #include "../Exceptions/exceptions.h"
 
-/*FUNCTION IssmDouble DrainageFunctionWaterfraction()*/
 IssmDouble DrainageFunctionWaterfraction(IssmDouble waterfraction, IssmDouble dt=0.){
 	/* DrainageFunctionWaterfraction returns how much of the waterfraction is drained per year */
Index: issm/trunk/src/c/shared/Enum/EnumDefinitions.h
===================================================================
--- issm/trunk/src/c/shared/Enum/EnumDefinitions.h	(revision 18081)
+++ issm/trunk/src/c/shared/Enum/EnumDefinitions.h	(revision 18301)
@@ -38,7 +38,13 @@
 	BalancethicknessStabilizationEnum,
 	BalancethicknessThickeningRateEnum,
+	BasalforcingsEnum,
 	BasalforcingsGeothermalfluxEnum,
-	BasalforcingsMeltingRateCorrectionEnum,
-	BasalforcingsMeltingRateEnum,
+	BasalforcingsGroundediceMeltingRateEnum,
+	BasalforcingsFloatingiceMeltingRateEnum,
+	BasalforcingsDeepwaterMeltingRateEnum,
+	BasalforcingsDeepwaterElevationEnum,
+	BasalforcingsUpperwaterElevationEnum,
+	FloatingMeltRateEnum,
+	LinearFloatingMeltRateEnum,
 	BedEnum,
 	BaseEnum,
@@ -161,5 +167,4 @@
 	InversionVzObsEnum,
 	MaskIceLevelsetEnum,
-	QmuMaskIceLevelsetEnum,
 	MaterialsBetaEnum,
 	MaterialsHeatcapacityEnum,
@@ -174,5 +179,4 @@
 	DamageDEnum,
 	DamageFEnum,
-	QmuDamageDEnum,
 	DamageDbarEnum,
 	DamageLawEnum,
@@ -194,4 +198,5 @@
 	DamageEvolutionNumRequestedOutputsEnum,
 	DamageEvolutionRequestedOutputsEnum,
+	NewDamageEnum,
 	MaterialsRhoIceEnum,
 	MaterialsRhoSeawaterEnum,
@@ -247,5 +252,4 @@
 	QmuResponsedescriptorsEnum,
 	QmuVariabledescriptorsEnum,
-	QmuMaterialsRheologyBEnum,
 	RiftsNumriftsEnum,
 	RiftsRiftstructEnum,
@@ -324,4 +328,11 @@
 	SurfaceforcingsBNegEnum,
 	SMBhenningEnum,
+	SMBcomponentsEnum,
+	SurfaceforcingsAccumulationEnum,
+	SurfaceforcingsEvaporationEnum,
+	SurfaceforcingsRunoffEnum,
+	SMBmeltcomponentsEnum,
+	SurfaceforcingsMeltEnum,
+	SurfaceforcingsRefreezeEnum,
 	/*TO BE REMOVED*/
 	SurfaceforcingsIspddEnum,
@@ -377,4 +388,5 @@
 	ThermalSolutionEnum,
 	TransientSolutionEnum,
+	UzawaPressureAnalysisEnum,
 	GiaSolutionEnum,
 	GiaAnalysisEnum,
@@ -492,5 +504,4 @@
 	FractionIncrementEnum,
 	FrictionEnum,
-	GroundinglineMeltingRateEnum,
 	InternalEnum,
 	MassFluxEnum,
@@ -499,15 +510,4 @@
 	PressureEnum,
 	PressurePicardEnum,
-	QmuPressureEnum,
-	QmuVxEnum,
-	QmuVyEnum,
-	QmuVzEnum,
-	QmuThicknessEnum,
-	QmuBaseEnum,
-	QmuSurfaceEnum,
-	QmuMeltingEnum,
-	QmuVxMeshEnum,
-	QmuVyMeshEnum,
-	QmuVzMeshEnum,
 	AndroidFrictionCoefficientEnum,
 	ResetPenaltiesEnum,
@@ -553,5 +553,4 @@
 	BasalFrictionEnum,
 	ViscousHeatingEnum,
-	QmuTemperatureEnum,
 	HydrologyWaterVxEnum,
 	HydrologyWaterVyEnum,
@@ -590,4 +589,6 @@
 	P1bubblecondensedEnum,
 	P2Enum,
+	P2bubbleEnum,
+	P2bubblecondensedEnum,
 	P2xP1Enum,
 	P1xP2Enum,
@@ -599,6 +600,8 @@
 	MINIcondensedEnum,
 	TaylorHoodEnum,
+	LATaylorHoodEnum,
 	XTaylorHoodEnum,
 	OneLayerP4zEnum,
+	CrouzeixRaviartEnum,
 	/*}}}*/
 	/*Results{{{*/
@@ -650,4 +653,7 @@
 	IncrementalEnum,
 	AugmentedLagrangianREnum,
+	AugmentedLagrangianRhopEnum,
+	AugmentedLagrangianRlambdaEnum,
+	AugmentedLagrangianRholambdaEnum,
 	AugmentedLagrangianThetaEnum,
 	/*}}}*/
@@ -660,5 +666,4 @@
 	ContactEnum,
 	MaskGroundediceLevelsetEnum,
-	QmuMaskGroundediceLevelsetEnum,
 	/*}}}*/
 	/*Gauss{{{*/
Index: issm/trunk/src/c/shared/Enum/EnumToStringx.cpp
===================================================================
--- issm/trunk/src/c/shared/Enum/EnumToStringx.cpp	(revision 18081)
+++ issm/trunk/src/c/shared/Enum/EnumToStringx.cpp	(revision 18301)
@@ -46,7 +46,13 @@
 		case BalancethicknessStabilizationEnum : return "BalancethicknessStabilization";
 		case BalancethicknessThickeningRateEnum : return "BalancethicknessThickeningRate";
+		case BasalforcingsEnum : return "Basalforcings";
 		case BasalforcingsGeothermalfluxEnum : return "BasalforcingsGeothermalflux";
-		case BasalforcingsMeltingRateCorrectionEnum : return "BasalforcingsMeltingRateCorrection";
-		case BasalforcingsMeltingRateEnum : return "BasalforcingsMeltingRate";
+		case BasalforcingsGroundediceMeltingRateEnum : return "BasalforcingsGroundediceMeltingRate";
+		case BasalforcingsFloatingiceMeltingRateEnum : return "BasalforcingsFloatingiceMeltingRate";
+		case BasalforcingsDeepwaterMeltingRateEnum : return "BasalforcingsDeepwaterMeltingRate";
+		case BasalforcingsDeepwaterElevationEnum : return "BasalforcingsDeepwaterElevation";
+		case BasalforcingsUpperwaterElevationEnum : return "BasalforcingsUpperwaterElevation";
+		case FloatingMeltRateEnum : return "FloatingMeltRate";
+		case LinearFloatingMeltRateEnum : return "LinearFloatingMeltRate";
 		case BedEnum : return "Bed";
 		case BaseEnum : return "Base";
@@ -169,5 +175,4 @@
 		case InversionVzObsEnum : return "InversionVzObs";
 		case MaskIceLevelsetEnum : return "MaskIceLevelset";
-		case QmuMaskIceLevelsetEnum : return "QmuMaskIceLevelset";
 		case MaterialsBetaEnum : return "MaterialsBeta";
 		case MaterialsHeatcapacityEnum : return "MaterialsHeatcapacity";
@@ -182,5 +187,4 @@
 		case DamageDEnum : return "DamageD";
 		case DamageFEnum : return "DamageF";
-		case QmuDamageDEnum : return "QmuDamageD";
 		case DamageDbarEnum : return "DamageDbar";
 		case DamageLawEnum : return "DamageLaw";
@@ -202,4 +206,5 @@
 		case DamageEvolutionNumRequestedOutputsEnum : return "DamageEvolutionNumRequestedOutputs";
 		case DamageEvolutionRequestedOutputsEnum : return "DamageEvolutionRequestedOutputs";
+		case NewDamageEnum : return "NewDamage";
 		case MaterialsRhoIceEnum : return "MaterialsRhoIce";
 		case MaterialsRhoSeawaterEnum : return "MaterialsRhoSeawater";
@@ -255,5 +260,4 @@
 		case QmuResponsedescriptorsEnum : return "QmuResponsedescriptors";
 		case QmuVariabledescriptorsEnum : return "QmuVariabledescriptors";
-		case QmuMaterialsRheologyBEnum : return "QmuMaterialsRheologyB";
 		case RiftsNumriftsEnum : return "RiftsNumrifts";
 		case RiftsRiftstructEnum : return "RiftsRiftstruct";
@@ -330,4 +334,11 @@
 		case SurfaceforcingsBNegEnum : return "SurfaceforcingsBNeg";
 		case SMBhenningEnum : return "SMBhenning";
+		case SMBcomponentsEnum : return "SMBcomponents";
+		case SurfaceforcingsAccumulationEnum : return "SurfaceforcingsAccumulation";
+		case SurfaceforcingsEvaporationEnum : return "SurfaceforcingsEvaporation";
+		case SurfaceforcingsRunoffEnum : return "SurfaceforcingsRunoff";
+		case SMBmeltcomponentsEnum : return "SMBmeltcomponents";
+		case SurfaceforcingsMeltEnum : return "SurfaceforcingsMelt";
+		case SurfaceforcingsRefreezeEnum : return "SurfaceforcingsRefreeze";
 		case SurfaceforcingsIspddEnum : return "SurfaceforcingsIspdd";
 		case SurfaceforcingsIssmbgradientsEnum : return "SurfaceforcingsIssmbgradients";
@@ -380,4 +391,5 @@
 		case ThermalSolutionEnum : return "ThermalSolution";
 		case TransientSolutionEnum : return "TransientSolution";
+		case UzawaPressureAnalysisEnum : return "UzawaPressureAnalysis";
 		case GiaSolutionEnum : return "GiaSolution";
 		case GiaAnalysisEnum : return "GiaAnalysis";
@@ -483,5 +495,4 @@
 		case FractionIncrementEnum : return "FractionIncrement";
 		case FrictionEnum : return "Friction";
-		case GroundinglineMeltingRateEnum : return "GroundinglineMeltingRate";
 		case InternalEnum : return "Internal";
 		case MassFluxEnum : return "MassFlux";
@@ -490,15 +501,4 @@
 		case PressureEnum : return "Pressure";
 		case PressurePicardEnum : return "PressurePicard";
-		case QmuPressureEnum : return "QmuPressure";
-		case QmuVxEnum : return "QmuVx";
-		case QmuVyEnum : return "QmuVy";
-		case QmuVzEnum : return "QmuVz";
-		case QmuThicknessEnum : return "QmuThickness";
-		case QmuBaseEnum : return "QmuBase";
-		case QmuSurfaceEnum : return "QmuSurface";
-		case QmuMeltingEnum : return "QmuMelting";
-		case QmuVxMeshEnum : return "QmuVxMesh";
-		case QmuVyMeshEnum : return "QmuVyMesh";
-		case QmuVzMeshEnum : return "QmuVzMesh";
 		case AndroidFrictionCoefficientEnum : return "AndroidFrictionCoefficient";
 		case ResetPenaltiesEnum : return "ResetPenalties";
@@ -544,5 +544,4 @@
 		case BasalFrictionEnum : return "BasalFriction";
 		case ViscousHeatingEnum : return "ViscousHeating";
-		case QmuTemperatureEnum : return "QmuTemperature";
 		case HydrologyWaterVxEnum : return "HydrologyWaterVx";
 		case HydrologyWaterVyEnum : return "HydrologyWaterVy";
@@ -579,4 +578,6 @@
 		case P1bubblecondensedEnum : return "P1bubblecondensed";
 		case P2Enum : return "P2";
+		case P2bubbleEnum : return "P2bubble";
+		case P2bubblecondensedEnum : return "P2bubblecondensed";
 		case P2xP1Enum : return "P2xP1";
 		case P1xP2Enum : return "P1xP2";
@@ -588,6 +589,8 @@
 		case MINIcondensedEnum : return "MINIcondensed";
 		case TaylorHoodEnum : return "TaylorHood";
+		case LATaylorHoodEnum : return "LATaylorHood";
 		case XTaylorHoodEnum : return "XTaylorHood";
 		case OneLayerP4zEnum : return "OneLayerP4z";
+		case CrouzeixRaviartEnum : return "CrouzeixRaviart";
 		case SaveResultsEnum : return "SaveResults";
 		case BoolExternalResultEnum : return "BoolExternalResult";
@@ -631,4 +634,7 @@
 		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";
@@ -639,5 +645,4 @@
 		case ContactEnum : return "Contact";
 		case MaskGroundediceLevelsetEnum : return "MaskGroundediceLevelset";
-		case QmuMaskGroundediceLevelsetEnum : return "QmuMaskGroundediceLevelset";
 		case GaussSegEnum : return "GaussSeg";
 		case GaussTriaEnum : return "GaussTria";
Index: issm/trunk/src/c/shared/Enum/StringToEnumx.cpp
===================================================================
--- issm/trunk/src/c/shared/Enum/StringToEnumx.cpp	(revision 18081)
+++ issm/trunk/src/c/shared/Enum/StringToEnumx.cpp	(revision 18301)
@@ -46,7 +46,13 @@
 	      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,"BasalforcingsMeltingRateCorrection")==0) return BasalforcingsMeltingRateCorrectionEnum;
-	      else if (strcmp(name,"BasalforcingsMeltingRate")==0) return BasalforcingsMeltingRateEnum;
+	      else if (strcmp(name,"BasalforcingsGroundediceMeltingRate")==0) return BasalforcingsGroundediceMeltingRateEnum;
+	      else if (strcmp(name,"BasalforcingsFloatingiceMeltingRate")==0) return BasalforcingsFloatingiceMeltingRateEnum;
+	      else if (strcmp(name,"BasalforcingsDeepwaterMeltingRate")==0) return BasalforcingsDeepwaterMeltingRateEnum;
+	      else if (strcmp(name,"BasalforcingsDeepwaterElevation")==0) return BasalforcingsDeepwaterElevationEnum;
+	      else if (strcmp(name,"BasalforcingsUpperwaterElevation")==0) return BasalforcingsUpperwaterElevationEnum;
+	      else if (strcmp(name,"FloatingMeltRate")==0) return FloatingMeltRateEnum;
+	      else if (strcmp(name,"LinearFloatingMeltRate")==0) return LinearFloatingMeltRateEnum;
 	      else if (strcmp(name,"Bed")==0) return BedEnum;
 	      else if (strcmp(name,"Base")==0) return BaseEnum;
@@ -131,5 +137,8 @@
 	      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 stage=2;
+   }
+   if(stage==2){
+	      if (strcmp(name,"HydrologydcLeakageFactor")==0) return HydrologydcLeakageFactorEnum;
 	      else if (strcmp(name,"HydrologydcPenaltyFactor")==0) return HydrologydcPenaltyFactorEnum;
 	      else if (strcmp(name,"HydrologydcPenaltyLock")==0) return HydrologydcPenaltyLockEnum;
@@ -137,8 +146,5 @@
 	      else if (strcmp(name,"HydrologyLayer")==0) return HydrologyLayerEnum;
 	      else if (strcmp(name,"HydrologySediment")==0) return HydrologySedimentEnum;
-         else stage=2;
-   }
-   if(stage==2){
-	      if (strcmp(name,"HydrologyEfficient")==0) return HydrologyEfficientEnum;
+	      else if (strcmp(name,"HydrologyEfficient")==0) return HydrologyEfficientEnum;
 	      else if (strcmp(name,"HydrologySedimentKmax")==0) return HydrologySedimentKmaxEnum;
 	      else if (strcmp(name,"IndependentObject")==0) return IndependentObjectEnum;
@@ -172,5 +178,4 @@
 	      else if (strcmp(name,"InversionVzObs")==0) return InversionVzObsEnum;
 	      else if (strcmp(name,"MaskIceLevelset")==0) return MaskIceLevelsetEnum;
-	      else if (strcmp(name,"QmuMaskIceLevelset")==0) return QmuMaskIceLevelsetEnum;
 	      else if (strcmp(name,"MaterialsBeta")==0) return MaterialsBetaEnum;
 	      else if (strcmp(name,"MaterialsHeatcapacity")==0) return MaterialsHeatcapacityEnum;
@@ -185,5 +190,4 @@
 	      else if (strcmp(name,"DamageD")==0) return DamageDEnum;
 	      else if (strcmp(name,"DamageF")==0) return DamageFEnum;
-	      else if (strcmp(name,"QmuDamageD")==0) return QmuDamageDEnum;
 	      else if (strcmp(name,"DamageDbar")==0) return DamageDbarEnum;
 	      else if (strcmp(name,"DamageLaw")==0) return DamageLawEnum;
@@ -205,4 +209,5 @@
 	      else if (strcmp(name,"DamageEvolutionNumRequestedOutputs")==0) return DamageEvolutionNumRequestedOutputsEnum;
 	      else if (strcmp(name,"DamageEvolutionRequestedOutputs")==0) return DamageEvolutionRequestedOutputsEnum;
+	      else if (strcmp(name,"NewDamage")==0) return NewDamageEnum;
 	      else if (strcmp(name,"MaterialsRhoIce")==0) return MaterialsRhoIceEnum;
 	      else if (strcmp(name,"MaterialsRhoSeawater")==0) return MaterialsRhoSeawaterEnum;
@@ -255,13 +260,12 @@
 	      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,"QmuMaterialsRheologyB")==0) return QmuMaterialsRheologyBEnum;
-	      else if (strcmp(name,"RiftsNumrifts")==0) return RiftsNumriftsEnum;
          else stage=3;
    }
    if(stage==3){
-	      if (strcmp(name,"RiftsRiftstruct")==0) return RiftsRiftstructEnum;
+	      if (strcmp(name,"QmuPartition")==0) return QmuPartitionEnum;
+	      else if (strcmp(name,"QmuResponsedescriptors")==0) return QmuResponsedescriptorsEnum;
+	      else if (strcmp(name,"QmuVariabledescriptors")==0) return QmuVariabledescriptorsEnum;
+	      else if (strcmp(name,"RiftsNumrifts")==0) return RiftsNumriftsEnum;
+	      else if (strcmp(name,"RiftsRiftstruct")==0) return RiftsRiftstructEnum;
 	      else if (strcmp(name,"SettingsResultsOnNodes")==0) return SettingsResultsOnNodesEnum;
 	      else if (strcmp(name,"SettingsIoGather")==0) return SettingsIoGatherEnum;
@@ -336,4 +340,11 @@
 	      else if (strcmp(name,"SurfaceforcingsBNeg")==0) return SurfaceforcingsBNegEnum;
 	      else if (strcmp(name,"SMBhenning")==0) return SMBhenningEnum;
+	      else if (strcmp(name,"SMBcomponents")==0) return SMBcomponentsEnum;
+	      else if (strcmp(name,"SurfaceforcingsAccumulation")==0) return SurfaceforcingsAccumulationEnum;
+	      else if (strcmp(name,"SurfaceforcingsEvaporation")==0) return SurfaceforcingsEvaporationEnum;
+	      else if (strcmp(name,"SurfaceforcingsRunoff")==0) return SurfaceforcingsRunoffEnum;
+	      else if (strcmp(name,"SMBmeltcomponents")==0) return SMBmeltcomponentsEnum;
+	      else if (strcmp(name,"SurfaceforcingsMelt")==0) return SurfaceforcingsMeltEnum;
+	      else if (strcmp(name,"SurfaceforcingsRefreeze")==0) return SurfaceforcingsRefreezeEnum;
 	      else if (strcmp(name,"SurfaceforcingsIspdd")==0) return SurfaceforcingsIspddEnum;
 	      else if (strcmp(name,"SurfaceforcingsIssmbgradients")==0) return SurfaceforcingsIssmbgradientsEnum;
@@ -372,5 +383,8 @@
 	      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 stage=4;
+   }
+   if(stage==4){
+	      if (strcmp(name,"MasstransportSolution")==0) return MasstransportSolutionEnum;
 	      else if (strcmp(name,"FreeSurfaceBaseAnalysis")==0) return FreeSurfaceBaseAnalysisEnum;
 	      else if (strcmp(name,"FreeSurfaceTopAnalysis")==0) return FreeSurfaceTopAnalysisEnum;
@@ -383,10 +397,8 @@
 	      else if (strcmp(name,"SmoothedSurfaceSlopeXAnalysis")==0) return SmoothedSurfaceSlopeXAnalysisEnum;
 	      else if (strcmp(name,"SmoothedSurfaceSlopeYAnalysis")==0) return SmoothedSurfaceSlopeYAnalysisEnum;
-         else stage=4;
-   }
-   if(stage==4){
-	      if (strcmp(name,"ThermalAnalysis")==0) return ThermalAnalysisEnum;
+	      else if (strcmp(name,"ThermalAnalysis")==0) return ThermalAnalysisEnum;
 	      else if (strcmp(name,"ThermalSolution")==0) return ThermalSolutionEnum;
 	      else if (strcmp(name,"TransientSolution")==0) return TransientSolutionEnum;
+	      else if (strcmp(name,"UzawaPressureAnalysis")==0) return UzawaPressureAnalysisEnum;
 	      else if (strcmp(name,"GiaSolution")==0) return GiaSolutionEnum;
 	      else if (strcmp(name,"GiaAnalysis")==0) return GiaAnalysisEnum;
@@ -492,25 +504,13 @@
 	      else if (strcmp(name,"FractionIncrement")==0) return FractionIncrementEnum;
 	      else if (strcmp(name,"Friction")==0) return FrictionEnum;
-	      else if (strcmp(name,"GroundinglineMeltingRate")==0) return GroundinglineMeltingRateEnum;
 	      else if (strcmp(name,"Internal")==0) return InternalEnum;
 	      else if (strcmp(name,"MassFlux")==0) return MassFluxEnum;
-	      else if (strcmp(name,"MeltingOffset")==0) return MeltingOffsetEnum;
+         else stage=5;
+   }
+   if(stage==5){
+	      if (strcmp(name,"MeltingOffset")==0) return MeltingOffsetEnum;
 	      else if (strcmp(name,"Misfit")==0) return MisfitEnum;
 	      else if (strcmp(name,"Pressure")==0) return PressureEnum;
 	      else if (strcmp(name,"PressurePicard")==0) return PressurePicardEnum;
-	      else if (strcmp(name,"QmuPressure")==0) return QmuPressureEnum;
-	      else if (strcmp(name,"QmuVx")==0) return QmuVxEnum;
-	      else if (strcmp(name,"QmuVy")==0) return QmuVyEnum;
-	      else if (strcmp(name,"QmuVz")==0) return QmuVzEnum;
-	      else if (strcmp(name,"QmuThickness")==0) return QmuThicknessEnum;
-	      else if (strcmp(name,"QmuBase")==0) return QmuBaseEnum;
-	      else if (strcmp(name,"QmuSurface")==0) return QmuSurfaceEnum;
-         else stage=5;
-   }
-   if(stage==5){
-	      if (strcmp(name,"QmuMelting")==0) return QmuMeltingEnum;
-	      else if (strcmp(name,"QmuVxMesh")==0) return QmuVxMeshEnum;
-	      else if (strcmp(name,"QmuVyMesh")==0) return QmuVyMeshEnum;
-	      else if (strcmp(name,"QmuVzMesh")==0) return QmuVzMeshEnum;
 	      else if (strcmp(name,"AndroidFrictionCoefficient")==0) return AndroidFrictionCoefficientEnum;
 	      else if (strcmp(name,"ResetPenalties")==0) return ResetPenaltiesEnum;
@@ -556,5 +556,4 @@
 	      else if (strcmp(name,"BasalFriction")==0) return BasalFrictionEnum;
 	      else if (strcmp(name,"ViscousHeating")==0) return ViscousHeatingEnum;
-	      else if (strcmp(name,"QmuTemperature")==0) return QmuTemperatureEnum;
 	      else if (strcmp(name,"HydrologyWaterVx")==0) return HydrologyWaterVxEnum;
 	      else if (strcmp(name,"HydrologyWaterVy")==0) return HydrologyWaterVyEnum;
@@ -591,4 +590,6 @@
 	      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;
@@ -600,6 +601,8 @@
 	      else if (strcmp(name,"MINIcondensed")==0) return MINIcondensedEnum;
 	      else if (strcmp(name,"TaylorHood")==0) return TaylorHoodEnum;
+	      else if (strcmp(name,"LATaylorHood")==0) return LATaylorHoodEnum;
 	      else if (strcmp(name,"XTaylorHood")==0) return XTaylorHoodEnum;
 	      else if (strcmp(name,"OneLayerP4z")==0) return OneLayerP4zEnum;
+	      else if (strcmp(name,"CrouzeixRaviart")==0) return CrouzeixRaviartEnum;
 	      else if (strcmp(name,"SaveResults")==0) return SaveResultsEnum;
 	      else if (strcmp(name,"BoolExternalResult")==0) return BoolExternalResultEnum;
@@ -626,11 +629,11 @@
 	      else if (strcmp(name,"SurfaceObservation")==0) return SurfaceObservationEnum;
 	      else if (strcmp(name,"WeightsSurfaceObservation")==0) return WeightsSurfaceObservationEnum;
-	      else if (strcmp(name,"MinVel")==0) return MinVelEnum;
-	      else if (strcmp(name,"MaxVel")==0) return MaxVelEnum;
-	      else if (strcmp(name,"MinVx")==0) return MinVxEnum;
          else stage=6;
    }
    if(stage==6){
-	      if (strcmp(name,"MaxVx")==0) return MaxVxEnum;
+	      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;
@@ -646,4 +649,7 @@
 	      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;
@@ -654,5 +660,4 @@
 	      else if (strcmp(name,"Contact")==0) return ContactEnum;
 	      else if (strcmp(name,"MaskGroundediceLevelset")==0) return MaskGroundediceLevelsetEnum;
-	      else if (strcmp(name,"QmuMaskGroundediceLevelset")==0) return QmuMaskGroundediceLevelsetEnum;
 	      else if (strcmp(name,"GaussSeg")==0) return GaussSegEnum;
 	      else if (strcmp(name,"GaussTria")==0) return GaussTriaEnum;
Index: issm/trunk/src/c/shared/FSanalyticals/fsanalyticals.cpp
===================================================================
--- issm/trunk/src/c/shared/FSanalyticals/fsanalyticals.cpp	(revision 18081)
+++ issm/trunk/src/c/shared/FSanalyticals/fsanalyticals.cpp	(revision 18301)
@@ -25,5 +25,5 @@
 			z=y;
 			return  4*pow(x, 2)*z*pow(x - 1, 2) + 4*pow(x, 2)*z*(z - 1)*(2*z - 1) + 4*pow(x, 2)*pow(x - 1, 2)*(z - 1) + 2*pow(x, 2)*pow(x - 1, 2)*(2*z - 1) + 16*x*z*(x - 1)*(z - 1)*(2*z - 1) - 4*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) + 6*pow(z, 2)*(6*pow(x, 2) - 6*x + 1) + 4*z*pow(x - 1, 2)*(z - 1)*(2*z - 1) - 2*z*(6*pow(x, 2) - 6*x + 1) + z - 1.0L/2.0L;
-		case 2: case 11:
+		case 2:
 			z=y;
 			return 10*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 3)*pow(sin(PI*p*z), 2)*cos(PI*p*z) - 2*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 3)*pow(cos(PI*p*z), 3) - 6*pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*pow(sin(PI*p*z), 2)*pow(cos(PI*p*x), 2)*cos(PI*p*z) + PI*q*sin(PI*q*z)*cos(PI*q*x);
@@ -45,4 +45,10 @@
 		case 10:
 			return 4*pow(PI, 2)*pow(p, 2)*(cos(PI*p*x) - 1)*sin(PI*p*y)*sin(PI*p*z) + 2*pow(PI, 2)*pow(p, 2)*sin(PI*p*y)*sin(PI*p*z)*cos(PI*p*x) + PI*q*pow(z, a)*sin(PI*q*y)*cos(PI*q*x);
+		case 11:
+			z=y;
+			return 32.0/5.0*pow(PI, 2)*sin(8*PI*z) + 8*PI*cos(8*PI*x + 1.0/3.0*PI);
+		case 12:
+			z=y;
+			return 32.0/5.0*pow(PI, 2)*sin(8*PI*z);
 		case 21:
 			z=y;
@@ -67,5 +73,5 @@
 			z=y;
 			return -8*pow(x, 3) + 4*pow(x, 2)*z*(x - 1)*(z - 1) + 2*pow(x, 2)*z*(x - 1)*(2*z - 1) + 2*pow(x, 2)*(x - 1)*(z - 1)*(2*z - 1) + 12*pow(x, 2) + 4*x*z*pow(x - 1, 2)*(z - 1) + 2*x*z*pow(x - 1, 2)*(2*z - 1) + 2*x*pow(x - 1, 2)*(z - 1)*(2*z - 1) - 3*x - 6*pow(z, 4)*(2*x - 1) + 12*pow(z, 3)*(2*x - 1) - 6*pow(z, 2)*(2*x - 1) - 24*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + 24*z*(2*pow(x, 3) - 3*pow(x, 2) + x) - 1.0L/2.0L;
-		case 2: case 11:
+		case 2: 
 			z=y;
 			return -10*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*z), 3)*cos(PI*p*x) + 6*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*sin(PI*p*z)*cos(PI*p*x)*pow(cos(PI*p*z), 2) + 2*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*z), 3)*pow(cos(PI*p*x), 3) + PI*q*sin(PI*q*x)*cos(PI*q*z);
@@ -87,4 +93,10 @@
 		case 10:
 			return -2*pow(PI, 2)*pow(p, 2)*(cos(PI*p*y) - 1)*sin(PI*p*x)*sin(PI*p*z) - pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*z)*cos(PI*p*y) + PI*q*pow(z, a)*sin(PI*q*x)*cos(PI*q*y);
+		case 11:
+			z=y;
+			return 32.0/5.0*pow(PI, 2)*sin(8*PI*x) - 10.;
+		case 12:
+			z=y;
+			return 32.0/5.0*pow(PI, 2)*sin(8*PI*x) - 100;
 		case 21:
 			z=y;
@@ -106,5 +118,5 @@
 
 	switch(testid){
-		case 1: case 2: case 7: case 8: case 11: case 18: case 21:
+		case 1: case 2: case 7: case 8: case 11:  case 12: case 18: case 21:
 			return 0.;
 		case 3: 
@@ -132,9 +144,6 @@
 
 	switch(testid){
-		case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 21:
+		case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 21:
 			return 0.;
-		case 11:
-			z=y;
-			return -10*PI*p*sqrt((9.0L/25.0L)*pow(PI, 2)*pow(p, 2)*pow(cos(2*PI*p*x), 2) + 1)*(9*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(cos(2*PI*p*x), 2)*pow(cos(PI*p*z), 2) - 9*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*z), 2)*pow(cos(PI*p*x), 2)*pow(cos(2*PI*p*x), 2) + 90*PI*p*sin(PI*p*x)*sin(PI*p*z)*cos(PI*p*x)*cos(2*PI*p*x)*cos(PI*p*z) - 25*pow(sin(PI*p*x), 2)*pow(cos(PI*p*z), 2) + 25*pow(sin(PI*p*z), 2)*pow(cos(PI*p*x), 2))/((9*pow(PI, 2)*pow(p, 2)*pow(cos(2*PI*p*x), 2) + 25)*(3*PI*p*sin(PI*p*z)*cos(PI*p*x)*cos(2*PI*p*x) - 5*sin(PI*p*x)*cos(PI*p*z))*sin(PI*p*x)*sin(PI*p*z));
 		case 18:
 			return (120.0L/109.0L)*sqrt(109.)/(10*x - 3*z);
Index: issm/trunk/src/c/shared/Matrix/MatrixUtils.cpp
===================================================================
--- issm/trunk/src/c/shared/Matrix/MatrixUtils.cpp	(revision 18081)
+++ issm/trunk/src/c/shared/Matrix/MatrixUtils.cpp	(revision 18301)
@@ -15,6 +15,5 @@
 /*}}}*/
 
-/*FUNCTION TripleMultiply {{{*/
-int TripleMultiply(IssmDouble* a, int nrowa, int ncola, int itrna, IssmDouble* b, int nrowb, int ncolb, int itrnb, IssmDouble* c, int nrowc, int ncolc, int itrnc, IssmDouble* d, int iaddd){
+int TripleMultiply(IssmDouble* a, int nrowa, int ncola, int itrna, IssmDouble* b, int nrowb, int ncolb, int itrnb, IssmDouble* c, int nrowc, int ncolc, int itrnc, IssmDouble* d, int iaddd){/*{{{*/
 	/*TripleMultiply    Perform triple matrix product a*b*c+d.*/
 
@@ -77,6 +76,5 @@
 	return 1;
 }/*}}}*/
-/*FUNCTION MatrixMuliply {{{*/
-int MatrixMultiply(IssmDouble* a, int nrowa, int ncola, int itrna, IssmDouble* b, int nrowb, int ncolb, int itrnb, IssmDouble* c, int iaddc ){
+int MatrixMultiply(IssmDouble* a, int nrowa, int ncola, int itrna, IssmDouble* b, int nrowb, int ncolb, int itrnb, IssmDouble* c, int iaddc ){/*{{{*/
 	/*MatrixMultiply    Perform matrix multiplication a*b+c.*/
 	int noerr=1;
@@ -139,6 +137,5 @@
 	return noerr;
 }/*}}}*/
-/*FUNCTION MatrixInverse {{{*/
-int MatrixInverse( IssmDouble* a, int ndim, int nrow, IssmDouble* b, int nvec, IssmDouble* pdet ){
+int MatrixInverse( IssmDouble* a, int ndim, int nrow, IssmDouble* b, int nvec, IssmDouble* pdet ){/*{{{*/
 	/* MatrixInverse    Perform matrix inversion and linear equation solution.
 
@@ -312,6 +309,6 @@
 	return noerr;
 }/*}}}*/
-/*FUNCTION Matrix2x2Determinant(IssmDouble* Adet,IssmDouble* A) {{{*/
-void Matrix2x2Determinant(IssmDouble* Adet,IssmDouble* A){
+
+void Matrix2x2Determinant(IssmDouble* Adet,IssmDouble* A){/*{{{*/
 	/*Compute determinant of a 2x2 matrix*/
 
@@ -320,6 +317,5 @@
 }
 /*}}}*/
-/*FUNCTION Matrix2x2Invert(IssmDouble* Ainv,IssmDouble* A) {{{*/
-void Matrix2x2Invert(IssmDouble* Ainv,IssmDouble* A){
+void Matrix2x2Invert(IssmDouble* Ainv,IssmDouble* A){/*{{{*/
 
 	/*Intermediaries*/
@@ -337,6 +333,6 @@
 
 }/*}}}*/
-/*FUNCTION Matrix3x3Determinant(IssmDouble* Adet,IssmDouble* A) {{{*/
-void Matrix3x3Determinant(IssmDouble* Adet,IssmDouble* A){
+
+void Matrix3x3Determinant(IssmDouble* Adet,IssmDouble* A){/*{{{*/
 	/*Compute determinant of a 3x3 matrix*/
 
@@ -345,6 +341,15 @@
 }
 /*}}}*/
-/*FUNCTION Matrix3x3Invert(IssmDouble* Ainv,IssmDouble* A) {{{*/
-void Matrix3x3Invert(IssmDouble* Ainv,IssmDouble* A){
+IssmDouble Matrix3x3Determinant(IssmDouble a1,IssmDouble a2,IssmDouble a3, IssmDouble b1,IssmDouble b2,IssmDouble b3, IssmDouble c1,IssmDouble c2,IssmDouble c3){/*{{{*/
+	/*Compute determinant of a 3x3 matrix*/
+
+	/*det = a*(e*i-f*h)-b*(d*i-f*g)+c*(d*h-e*g)
+	 * a b c   a1 a2 a3
+	 * d e f   b1 b2 b3
+	 * g h i   c1 c2 c3 */
+	return a1*b2*c3-a1*b3*c2-b1*a2*c3+b1*a3*c2+c1*a2*b3-c1*a3*b2;
+}
+/*}}}*/
+void Matrix3x3Invert(IssmDouble* Ainv,IssmDouble* A){/*{{{*/
 
 	/*Intermediaries*/
@@ -367,6 +372,5 @@
 
 }/*}}}*/
-/*FUNCTION Matrix3x3Solve(IssmDouble* X,IssmDouble* A,IssmDouble* B) {{{*/
-void Matrix3x3Solve(IssmDouble* X,IssmDouble* A,IssmDouble* B){
+void Matrix3x3Solve(IssmDouble* X,IssmDouble* A,IssmDouble* B){/*{{{*/
 
 	IssmDouble Ainv[3][3];
@@ -376,6 +380,96 @@
 
 }/*}}}*/
-/*FUNCTION Matrix4x4Solve(IssmDouble* X,IssmDouble* A,IssmDouble *B) {{{*/
-void Matrix4x4Solve(IssmDouble* X,IssmDouble* A,IssmDouble *B){
-	_error_("STOP");
-}/*}}}*/
+
+void Matrix4x4Determinant(IssmDouble* Adet,IssmDouble* A){/*{{{*/
+	/*Compute determinant of a 4x4 matrix*/
+
+	IssmDouble a1 = A[0*4+0];
+	IssmDouble b1 = A[0*4+1]; 
+	IssmDouble c1 = A[0*4+2];
+	IssmDouble d1 = A[0*4+3];
+
+	IssmDouble a2 = A[1*4+0];
+	IssmDouble b2 = A[1*4+1]; 
+	IssmDouble c2 = A[1*4+2];
+	IssmDouble d2 = A[1*4+3];
+
+	IssmDouble a3 = A[2*4+0]; 
+	IssmDouble b3 = A[2*4+1];
+	IssmDouble c3 = A[2*4+2];
+	IssmDouble d3 = A[2*4+3];
+
+	IssmDouble a4 = A[3*4+0];
+	IssmDouble b4 = A[3*4+1]; 
+	IssmDouble c4 = A[3*4+2];
+	IssmDouble d4 = A[3*4+3];
+
+	*Adet= a1 * Matrix3x3Determinant(b2, b3, b4, c2, c3, c4, d2, d3, d4)
+		  - b1 * Matrix3x3Determinant(a2, a3, a4, c2, c3, c4, d2, d3, d4)
+		  + c1 * Matrix3x3Determinant(a2, a3, a4, b2, b3, b4, d2, d3, d4)
+		  - d1 * Matrix3x3Determinant(a2, a3, a4, b2, b3, b4, c2, c3, c4);
+}
+/*}}}*/
+void Matrix4x4Adjoint(IssmDouble* Aadj,IssmDouble* A){/*{{{*/
+
+    IssmDouble a1 = A[0*4+0];
+    IssmDouble b1 = A[0*4+1]; 
+    IssmDouble c1 = A[0*4+2];
+    IssmDouble d1 = A[0*4+3];
+
+    IssmDouble a2 = A[1*4+0];
+    IssmDouble b2 = A[1*4+1]; 
+    IssmDouble c2 = A[1*4+2];
+    IssmDouble d2 = A[1*4+3];
+
+    IssmDouble a3 = A[2*4+0];
+    IssmDouble b3 = A[2*4+1];
+    IssmDouble c3 = A[2*4+2];
+    IssmDouble d3 = A[2*4+3];
+
+    IssmDouble a4 = A[3*4+0];
+    IssmDouble b4 = A[3*4+1]; 
+    IssmDouble c4 = A[3*4+2];
+    IssmDouble d4 = A[3*4+3];
+
+    /* Row column labeling reversed since we transpose rows & columns*/
+    Aadj[0*4+0]  =   Matrix3x3Determinant(b2, b3, b4, c2, c3, c4, d2, d3, d4);
+    Aadj[1*4+0]  = - Matrix3x3Determinant(a2, a3, a4, c2, c3, c4, d2, d3, d4);
+    Aadj[2*4+0]  =   Matrix3x3Determinant(a2, a3, a4, b2, b3, b4, d2, d3, d4);
+    Aadj[3*4+0]  = - Matrix3x3Determinant(a2, a3, a4, b2, b3, b4, c2, c3, c4);
+
+    Aadj[0*4+1]  = - Matrix3x3Determinant(b1, b3, b4, c1, c3, c4, d1, d3, d4);
+    Aadj[1*4+1]  =   Matrix3x3Determinant(a1, a3, a4, c1, c3, c4, d1, d3, d4);
+    Aadj[2*4+1]  = - Matrix3x3Determinant(a1, a3, a4, b1, b3, b4, d1, d3, d4);
+    Aadj[3*4+1]  =   Matrix3x3Determinant(a1, a3, a4, b1, b3, b4, c1, c3, c4);
+
+    Aadj[0*4+2]  =   Matrix3x3Determinant(b1, b2, b4, c1, c2, c4, d1, d2, d4);
+    Aadj[1*4+2]  = - Matrix3x3Determinant(a1, a2, a4, c1, c2, c4, d1, d2, d4);
+    Aadj[2*4+2]  =   Matrix3x3Determinant(a1, a2, a4, b1, b2, b4, d1, d2, d4);
+    Aadj[3*4+2]  = - Matrix3x3Determinant(a1, a2, a4, b1, b2, b4, c1, c2, c4);
+
+    Aadj[0*4+3]  = - Matrix3x3Determinant(b1, b2, b3, c1, c2, c3, d1, d2, d3);
+    Aadj[1*4+3]  =   Matrix3x3Determinant(a1, a2, a3, c1, c2, c3, d1, d2, d3);
+    Aadj[2*4+3]  = - Matrix3x3Determinant(a1, a2, a3, b1, b2, b3, d1, d2, d3);
+    Aadj[3*4+3]  =   Matrix3x3Determinant(a1, a2, a3, b1, b2, b3, c1, c2, c3);
+}/*}}}*/
+void Matrix4x4Invert(IssmDouble* Ainv,IssmDouble* A){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble det;
+
+	/*Compute determinant*/
+	Matrix4x4Determinant(&det,A);
+	//if(fabs(det) < DBL_EPSILON) _error_("Determinant smaller than machine epsilon");
+
+	/*Compute adjoint matrix*/
+	Matrix4x4Adjoint(Ainv,A);
+
+	/*Scalte adjoint matrix to get inverse*/
+	for(int i=0;i<4*4;i++) Ainv[i] = Ainv[i]/det;
+}/*}}}*/
+void Matrix4x4Solve(IssmDouble* X,IssmDouble* A,IssmDouble *B){/*{{{*/
+	IssmDouble Ainv[4][4];
+
+	Matrix4x4Invert(&Ainv[0][0],A);
+	for(int i=0;i<4;i++) X[i]=Ainv[i][0]*B[0] + Ainv[i][1]*B[1] + Ainv[i][2]*B[2] + Ainv[i][3]*B[3];
+}/*}}}*/
Index: issm/trunk/src/c/shared/Matrix/matrix.h
===================================================================
--- issm/trunk/src/c/shared/Matrix/matrix.h	(revision 18081)
+++ issm/trunk/src/c/shared/Matrix/matrix.h	(revision 18301)
@@ -11,9 +11,16 @@
 int  MatrixMultiply( IssmDouble* a, int nrowa, int ncola, int itrna, IssmDouble* b, int nrowb, int ncolb, int itrnb, IssmDouble* c, int iaddc );
 int  MatrixInverse( IssmDouble* a, int ndim, int nrow, IssmDouble* b, int nvec, IssmDouble* pdet );
+
 void Matrix2x2Invert(IssmDouble* Ainv, IssmDouble* A);
 void Matrix2x2Determinant(IssmDouble* Adet,IssmDouble* A);
+
 void Matrix3x3Invert(IssmDouble* Ainv, IssmDouble* A);
 void Matrix3x3Determinant(IssmDouble* Adet,IssmDouble* A);
+IssmDouble Matrix3x3Determinant( IssmDouble a1,IssmDouble a2,IssmDouble a3, IssmDouble b1,IssmDouble b2,IssmDouble b3, IssmDouble c1,IssmDouble c2,IssmDouble c3);
 void Matrix3x3Solve(IssmDouble* X,IssmDouble* A,IssmDouble* B);
+
+void Matrix4x4Adjoint(IssmDouble* Aadj, IssmDouble* A);
+void Matrix4x4Invert(IssmDouble* Ainv, IssmDouble* A);
+void Matrix4x4Determinant(IssmDouble* Adet,IssmDouble* A);
 void Matrix4x4Solve(IssmDouble* X,IssmDouble* A,IssmDouble* B);
 
Index: issm/trunk/src/c/shared/Numerics/BrentSearch.cpp
===================================================================
--- issm/trunk/src/c/shared/Numerics/BrentSearch.cpp	(revision 18081)
+++ issm/trunk/src/c/shared/Numerics/BrentSearch.cpp	(revision 18301)
@@ -20,5 +20,5 @@
 #include "./isnan.h"
 
-void BrentSearch(IssmDouble* psearch_scalar,IssmDouble* pJ,OptPars* optpars,IssmDouble (*f)(IssmDouble,void*),void* optargs){
+void BrentSearch(IssmDouble** pJ,OptPars optpars,IssmDouble* X0,IssmDouble (*f)(IssmDouble*,void*),IssmDouble (*g)(IssmDouble**,IssmDouble*,void*),void* usr){
 
 	/* This routine is optimizing a given function using Brent's method
@@ -26,198 +26,225 @@
 
 	/*Intermediary*/
+	int        iter;
 	IssmDouble si,gold,intervalgold,oldintervalgold;
-	IssmDouble parab_num,parab_den;
-	IssmDouble distance,cm_jump;
+	IssmDouble parab_num,parab_den,distance;
 	IssmDouble fxmax,fxmin,fxbest;
 	IssmDouble fx,fx1,fx2;
-	IssmDouble xmax,xmin,xbest;
-	IssmDouble x,x1,x2,xm;
+	IssmDouble x,x1,x2,xm,xbest;
 	IssmDouble tol1,tol2,seps;
 	IssmDouble tolerance = 1.e-4;
-	int        maxiter ,iter;
-	bool       loop= true,goldenflag;
 
 	/*Recover parameters:*/
-	xmin=optpars->xmin;
-	xmax=optpars->xmax;
-	maxiter=optpars->maxiter;
-	cm_jump=optpars->cm_jump;
-
-	/*initialize counter and get response at the boundaries*/
-	iter=0;
-	fxmin = (*f)(xmin,optargs);
-	if (xIsNan<IssmDouble>(fxmin)) _error_("Function evaluation returned NaN");
-	cout<<setprecision(5);
-	if(VerboseControl()) _printf0_("\n");
-	if(VerboseControl()) _printf0_("       Iteration         x           f(x)       Tolerance         Procedure\n");
-	if(VerboseControl()) _printf0_("\n");
-	if(VerboseControl()) _printf0_("           N/A    "<<setw(12)<<xmin<<"  "<<setw(12)<<fxmin<<"           N/A         boundary\n");
-	fxmax = (*f)(xmax,optargs);
-	if (xIsNan<IssmDouble>(fxmax)) _error_("Function evaluation returned NaN");
-	if(VerboseControl()) _printf0_("           N/A    "<<setw(12)<<xmax<<"  "<<setw(12)<<fxmax<<"           N/A         boundary\n");
-
-	/*test if jump option activated and xmin==0*/
-	if (!xIsNan<IssmDouble>(cm_jump) && (xmin==0) && (fxmax/fxmin)<cm_jump){
-		*psearch_scalar=xmax;
-		*pJ=fxmax;
-		return;
+	int         nsteps  = optpars.nsteps;
+	int         nsize   = optpars.nsize;
+	IssmDouble  xmin    = optpars.xmin;
+	IssmDouble  xmax    = optpars.xmax;
+	int        *maxiter = optpars.maxiter;
+	IssmDouble *cm_jump = optpars.cm_jump;
+
+	/*Initialize gradient and controls*/
+	IssmDouble* G = NULL;
+	IssmDouble* J = xNew<IssmDouble>(nsteps);
+	IssmDouble* X = xNew<IssmDouble>(nsize);
+
+	/*Header of printf*/
+	_printf0_("\n");
+	_printf0_("       x       |  Cost function f(x)  |  List of contributions\n");
+
+	/*start iterations*/
+	for(int n=0;n<nsteps;n++){
+
+		/*Print iteration number*/
+		_printf0_("====================== step "<< n+1 << "/" << nsteps <<" ===============================\n");
+
+		/*Reset some variables*/
+		iter = 0;
+		xmin = 0.;
+		xmax = 1.;
+		bool loop = true;
+		cout<<setprecision(5);
+
+		/*Get current Gradient at xmin=0*/
+		_printf0_(" x = "<<setw(9)<<xmin<<" | ");
+		fxmin = (*g)(&G,X0,usr); if(xIsNan<IssmDouble>(fxmin)) _error_("Function evaluation returned NaN");
+		
+		/*Get f(xmax)*/
+		_printf0_(" x = "<<setw(9)<<xmax<<" | ");
+		for(int i=0;i<nsize;i++) X[i]=X0[i]+xmax*G[i];
+		fxmax = (*f)(X,usr); if (xIsNan<IssmDouble>(fxmax)) _error_("Function evaluation returned NaN");
+		//if(VerboseControl()) _printf0_("           N/A    "<<setw(12)<<xmax<<"  "<<setw(12)<<fxmax<<"           N/A         boundary\n");
+
+		/*test if jump option activated and xmin==0*/
+		if(!xIsNan<IssmDouble>(cm_jump[n]) && (xmin==0) && (fxmax/fxmin)<cm_jump[n]){
+			for(int i=0;i<nsize;i++) X0[i]=X0[i]+xmax*G[i];
+			xDelete<IssmDouble>(G);
+			J[n]=fxmax;
+			continue;
+		}
+
+		/*initialize optimization variables*/
+		seps=sqrt(DBL_EPSILON);    //precision of a IssmDouble
+		distance=0.0;              //new_x=old_x + distance
+		gold=0.5*(3.0-sqrt(5.0));  //gold = 1 - golden ratio
+		intervalgold=0.0;          //distance used by Golden procedure
+
+		/*1: initialize the values of the 4 x needed (x1,x2,x,xbest)*/
+		x1=xmin+gold*(xmax-xmin);
+		x2=x1;
+		xbest=x1;
+		x=xbest;
+
+		/*2: call the function to be evaluated*/
+		_printf0_(" x = "<<setw(9)<<x<<" | ");
+		for(int i=0;i<nsize;i++) X[i]=X0[i]+x*G[i];
+		fxbest = (*f)(X,usr); if(xIsNan<IssmDouble>(fxbest)) _error_("Function evaluation returned NaN");
+		iter++;
+
+		/*3: update the other variables*/
+		fx1=fxbest;
+		fx2=fxbest;
+		/*xm is always in the middle of a and b*/
+		xm=0.5*(xmin+xmax);                           
+		/*update tolerances*/
+		tol1=seps*sqrt(pow(xbest,2))+tolerance/3.0;
+		tol2=2.0*tol1;
+
+		/*4: print result*/
+		//if(VerboseControl())
+		 //_printf0_("         "<<setw(5)<<iter<<"    "<<setw(12)<<xbest<<"  "<<setw(12)<<fxbest<<"  "<<setw(12)<<pow(pow(xbest-xm,2),0.5)<<"         initial\n");
+		if (!xIsNan<IssmDouble>(cm_jump[n]) && (xmin==0) && ((fxbest/fxmin)<cm_jump[n])){
+			//if(VerboseControl()) _printf0_("      optimization terminated: current x satisfies criteria 'cm_jump'=" << cm_jump[n] << "\n");
+			loop=false;
+		}
+
+		while(loop){
+
+			bool goldenflag=true;
+
+			// Is a parabolic fit possible ?
+			if (sqrt(pow(intervalgold,2))>tol1){
+
+				// Yes, so fit parabola
+				goldenflag=false;
+				parab_num=(xbest-x1)*(xbest-x1)*(fxbest-fx2)-(xbest-x2)*(xbest-x2)*(fxbest-fx1);;
+				parab_den=2.0*(xbest-x1)*(fxbest-fx2)-2.0*(xbest-x2)*(fxbest-fx1);
+
+				//reverse p if necessary
+				if(parab_den>0.0){ 
+					parab_num=-parab_num;
+				}
+				parab_den=sqrt(pow(parab_den,2));
+				oldintervalgold=intervalgold;
+				intervalgold=distance;
+
+				// Is the parabola acceptable (we use seps here because in some configuration parab_num==parab_den*(xmax-xbest)
+				// and the result is not repeatable anymore
+				if (( sqrt(pow(parab_num,2)) < sqrt(pow(0.5*parab_den*oldintervalgold,2))) &&
+							(parab_num>parab_den*(xmin-xbest)+seps) && 
+							(parab_num<parab_den*(xmax-xbest)-seps)){
+
+					// Yes, parabolic interpolation step
+					distance=parab_num/parab_den;
+					x=xbest+distance;
+
+					// f must not be evaluated too close to min_x or max_x
+					if (((x-xmin)<tol2) || ((xmax-x)<tol2)){
+						if ((xm-xbest)<0.0) si=-1;
+						else                si=1;
+						//compute new distance
+						distance=tol1*si;
+					}
+				}
+				else{
+					// Not acceptable, must do a golden section step
+					goldenflag=true;
+				}
+			}
+
+			//Golden procedure
+			if(goldenflag){
+				// compute the new distance d
+				if(xbest>=xm){
+					intervalgold=xmin-xbest;    
+				}
+				else{ 
+					intervalgold=xmax-xbest;  
+				}
+				distance=gold*intervalgold;
+			}
+
+			// The function must not be evaluated too close to xbest
+			if(distance<0) si=-1;
+			else           si=1;
+			if(sqrt(pow(distance,2))>tol1) x=xbest+si*sqrt(pow(distance,2));
+			else                           x=xbest+si*tol1;
+
+			//evaluate function on x
+			_printf0_(" x = "<<setw(9)<<x<<" | ");
+			for(int i=0;i<nsize;i++) X[i]=X0[i]+x*G[i];
+			fx = (*f)(X,usr); if(xIsNan<IssmDouble>(fx)) _error_("Function evaluation returned NaN");
+			iter++;
+
+			// Update a, b, xm, x1, x2, tol1, tol2
+			if (fx<=fxbest){
+				if (x>=xbest) xmin=xbest;
+				else          xmax=xbest;
+				x1=x2;    fx1=fx2;
+				x2=xbest; fx2=fxbest;
+				xbest=x;  fxbest=fx;
+			}
+			else{ // fx > fxbest
+				if (x<xbest) xmin=x;
+				else         xmax=x;
+				if ((fx<=fx2) || (x2==xbest)){
+					x1=x2; fx1=fx2;
+					x2=x;  fx2=fx;
+				}
+				else if ( (fx <= fx1) || (x1 == xbest) || (x1 == x2) ){
+					x1=x;  fx1=fx;
+				}
+			}
+			xm = 0.5*(xmin+xmax);
+			tol1=seps*pow(pow(xbest,2),0.5)+tolerance/3.0;
+			tol2=2.0*tol1;
+			//if(VerboseControl())
+			// _printf0_("         "<<setw(5)<<iter<<"    "<<setw(12)<<x<<"  "<<setw(12)<<fx<<"  "<<setw(12)<<pow(pow(xbest-xm,2),0.5)<<
+			//			 "         "<<(goldenflag?"golden":"parabolic")<<"\n");
+
+			/*Stop the optimization?*/
+			if (sqrt(pow(xbest-xm,2)) < (tol2-0.5*(xmax-xmin))){
+				//if(VerboseControl()) _printf0_("      optimization terminated: current x satisfies criteria 'tolx'=" << tolerance << "\n");
+				loop=false;
+			}
+			else if (iter>=maxiter[n]){
+				//if(VerboseControl()) _printf0_("      exiting: Maximum number of iterations has been exceeded  ('maxiter'=" << maxiter[n] << ")\n");
+				loop=false;
+			}
+			else if (!xIsNan<IssmDouble>(cm_jump[n]) && (xmin==0) && ((fxbest/fxmin)<cm_jump[n])){
+				//if(VerboseControl()) _printf0_("      optimization terminated: current x satisfies criteria 'cm_jump'=" << cm_jump[n] << "\n");
+				loop=false;
+			}
+			else{
+				//continue
+				loop=true;
+			}
+		}//end while
+
+		//Now, check that the value on the boundaries are not better than current fxbest
+		if (fxbest>fxmin){
+			xbest=optpars.xmin; fxbest=fxmin;
+		}
+		if (fxbest>fxmax){
+			xbest=optpars.xmax; fxbest=fxmax;
+		}
+
+		/*Assign output pointers: */
+		for(int i=0;i<nsize;i++) X0[i]=X0[i]+xbest*G[i];
+		xDelete<IssmDouble>(G);
+		J[n]=fxbest;
 	}
-
-	/*initialize optimization variables*/
-	seps=sqrt(DBL_EPSILON);    //precision of a IssmDouble
-	distance=0.0;              //new_x=old_x + distance
-	gold=0.5*(3.0-sqrt(5.0));  //gold = 1 - golden ratio
-	intervalgold=0.0;          //distance used by Golden procedure
-
-	/*1: initialize the values of the 4 x needed (x1,x2,x,xbest)*/
-	x1=xmin+gold*(xmax-xmin);
-	x2=x1;
-	xbest=x1;
-	x=xbest;
-
-	/*2: call the function to be evaluated*/
-	fxbest = (*f)(x,optargs);
-	if(xIsNan<IssmDouble>(fxbest)) _error_("Function evaluation returned NaN");
-	iter=iter+1;
-
-	/*3: update the other variables*/
-	fx1=fxbest;
-	fx2=fxbest;
-	/*xm is always in the middle of a and b*/
-	xm=0.5*(xmin+xmax);                           
-	/*update tolerances*/
-	tol1=seps*sqrt(pow(xbest,2))+tolerance/3.0;
-	tol2=2.0*tol1;
-
-	/*4: print result*/
-	if(VerboseControl())
-	 _printf0_("         "<<setw(5)<<iter<<"    "<<setw(12)<<xbest<<"  "<<setw(12)<<fxbest<<"  "<<setw(12)<<pow(pow(xbest-xm,2),0.5)<<"         initial\n");
-	if (!xIsNan<IssmDouble>(cm_jump) && (xmin==0) && ((fxbest/fxmin)<cm_jump)){
-		if(VerboseControl()) _printf0_("      optimization terminated: current x satisfies criteria 'cm_jump'=" << cm_jump << "\n");
-		loop=false;
-	}
-
-	while(loop){
-
-		goldenflag=true;
-
-		// Is a parabolic fit possible ?
-		if (sqrt(pow(intervalgold,2))>tol1){
-
-			// Yes, so fit parabola
-			goldenflag=false;
-			parab_num=(xbest-x1)*(xbest-x1)*(fxbest-fx2)-(xbest-x2)*(xbest-x2)*(fxbest-fx1);;
-			parab_den=2.0*(xbest-x1)*(fxbest-fx2)-2.0*(xbest-x2)*(fxbest-fx1);
-
-			//reverse p if necessary
-			if(parab_den>0.0){ 
-				parab_num=-parab_num;
-			}
-			parab_den=sqrt(pow(parab_den,2));
-			oldintervalgold=intervalgold;
-			intervalgold=distance;
-
-			// Is the parabola acceptable (we use seps here because in some configuration parab_num==parab_den*(xmax-xbest)
-			// and the result is not repeatable anymore
-			if (( sqrt(pow(parab_num,2)) < sqrt(pow(0.5*parab_den*oldintervalgold,2))) &&
-						(parab_num>parab_den*(xmin-xbest)+seps) && 
-						(parab_num<parab_den*(xmax-xbest)-seps)){
-
-				// Yes, parabolic interpolation step
-				distance=parab_num/parab_den;
-				x=xbest+distance;
-
-				// f must not be evaluated too close to min_x or max_x
-				if (((x-xmin)<tol2) || ((xmax-x)<tol2)){
-					if ((xm-xbest)<0.0) si=-1;
-					else                si=1;
-					//compute new distance
-					distance=tol1*si;
-				}
-			}
-			else{
-				// Not acceptable, must do a golden section step
-				goldenflag=true;
-			}
-		}
-
-		//Golden procedure
-		if(goldenflag){
-			// compute the new distance d
-			if(xbest>=xm){
-				intervalgold=xmin-xbest;    
-			}
-			else{ 
-				intervalgold=xmax-xbest;  
-			}
-			distance=gold*intervalgold;
-		}
-
-		// The function must not be evaluated too close to xbest
-		if(distance<0) si=-1;
-		else           si=1;
-		if(sqrt(pow(distance,2))>tol1) x=xbest+si*sqrt(pow(distance,2));
-		else                           x=xbest+si*tol1;
-
-		//evaluate function on x
-		fx = (*f)(x,optargs);
-		if(xIsNan<IssmDouble>(fx)) _error_("Function evaluation returned NaN");
-		iter=iter+1;
-
-		// Update a, b, xm, x1, x2, tol1, tol2
-		if (fx<=fxbest){
-			if (x>=xbest) xmin=xbest;
-			else          xmax=xbest;
-			x1=x2;    fx1=fx2;
-			x2=xbest; fx2=fxbest;
-			xbest=x;  fxbest=fx;
-		}
-		else{ // fx > fxbest
-			if (x<xbest) xmin=x;
-			else         xmax=x;
-			if ((fx<=fx2) || (x2==xbest)){
-				x1=x2; fx1=fx2;
-				x2=x;  fx2=fx;
-			}
-			else if ( (fx <= fx1) || (x1 == xbest) || (x1 == x2) ){
-				x1=x;  fx1=fx;
-			}
-		}
-		xm = 0.5*(xmin+xmax);
-		tol1=seps*pow(pow(xbest,2),0.5)+tolerance/3.0;
-		tol2=2.0*tol1;
-		if(VerboseControl())
-		 _printf0_("         "<<setw(5)<<iter<<"    "<<setw(12)<<x<<"  "<<setw(12)<<fx<<"  "<<setw(12)<<pow(pow(xbest-xm,2),0.5)<<
-					 "         "<<(goldenflag?"golden":"parabolic")<<"\n");
-
-		/*Stop the optimization?*/
-		if (sqrt(pow(xbest-xm,2)) < (tol2-0.5*(xmax-xmin))){
-			if(VerboseControl()) _printf0_("      optimization terminated: current x satisfies criteria 'tolx'=" << tolerance << "\n");
-			loop=false;
-		}
-		else if (iter>=maxiter){
-			if(VerboseControl()) _printf0_("      exiting: Maximum number of iterations has been exceeded  ('maxiter'=" << maxiter << ")\n");
-			loop=false;
-		}
-		else if (!xIsNan<IssmDouble>(cm_jump) && (xmin==0) && ((fxbest/fxmin)<cm_jump)){
-			if(VerboseControl()) _printf0_("      optimization terminated: current x satisfies criteria 'cm_jump'=" << cm_jump << "\n");
-			loop=false;
-		}
-		else{
-			//continue
-			loop=true;
-		}
-	}//end while
-
-	//Now, check that the value on the boundaries are not better than current fxbest
-	if (fxbest>fxmin){
-		xbest=optpars->xmin; fxbest=fxmin;
-	}
-	if (fxbest>fxmax){
-		xbest=optpars->xmax; fxbest=fxmax;
-	}
-
-	/*Assign output pointers: */
-	*psearch_scalar=xbest;
-	*pJ=fxbest;
+	
+	/*return*/
+	xDelete<IssmDouble>(X);
+	*pJ=J;
 }
Index: issm/trunk/src/c/shared/Numerics/GaussPoints.cpp
===================================================================
--- issm/trunk/src/c/shared/Numerics/GaussPoints.cpp	(revision 18081)
+++ issm/trunk/src/c/shared/Numerics/GaussPoints.cpp	(revision 18301)
@@ -9,6 +9,5 @@
 
 /*General Gauss points*/
-/*FUNCTION GaussLegendreLinear {{{*/
-void GaussLegendreLinear( IssmPDouble** pxgaus, IssmPDouble** pxwgt, int ngaus){
+void GaussLegendreLinear( IssmPDouble** pxgaus, IssmPDouble** pxwgt, int ngaus){/*{{{*/
 	/* Gauss-Legendre quadrature points.
 
@@ -93,6 +92,5 @@
 	}
 }/*}}}*/
-/*FUNCTION GaussLegendreTria{{{*/
-void GaussLegendreTria( int* pngaus, IssmDouble** pl1, IssmDouble** pl2, IssmDouble** pl3, IssmDouble** pwgt, int iord ) {
+void GaussLegendreTria( int* pngaus, IssmDouble** pl1, IssmDouble** pl2, IssmDouble** pl3, IssmDouble** pwgt, int iord ) {/*{{{*/
 	/*Gauss quadrature points for the triangle.
 
@@ -1210,6 +1208,5 @@
 	return;
 }/*}}}*/
-/*FUNCTION GaussLegendreTetra{{{*/
-void GaussLegendreTetra( int* pngaus, IssmDouble** pl1, IssmDouble** pl2, IssmDouble** pl3, IssmDouble** pl4, IssmDouble** pwgt, int iord ) {
+void GaussLegendreTetra( int* pngaus, IssmDouble** pl1, IssmDouble** pl2, IssmDouble** pl3, IssmDouble** pl4, IssmDouble** pwgt, int iord ) {/*{{{*/
 	/* Gauss quadrature points for the tetrahedron.
 
@@ -1473,6 +1470,5 @@
 	}
 }/*}}}*/
-/*FUNCTION GaussLobatto{{{*/
-void GaussLobatto( IssmPDouble** pxgaus, IssmPDouble** pxwgt, int ngaus ) {
+void GaussLobatto( IssmPDouble** pxgaus, IssmPDouble** pxwgt, int ngaus ) {/*{{{*/
 	/*Gauss-Lobatto quadrature points.
 
@@ -1575,6 +1571,5 @@
 
 }/*}}}*/
-/*FUNCTION GaussRecur{{{*/
-void GaussRecur( IssmPDouble* zero, IssmPDouble* weight, int n, IssmPDouble* alpha, IssmPDouble* beta ) {
+void GaussRecur( IssmPDouble* zero, IssmPDouble* weight, int n, IssmPDouble* alpha, IssmPDouble* beta ) {/*{{{*/
 	/*Gauss quadrature points from recursion coefficients.
 	 *
@@ -1698,6 +1693,5 @@
 
 /*Element Gauss points TO BE REMOVED*/
-/*FUNCTION gaussQuad{{{*/
-void gaussQuad( IssmPDouble** pxgaus, IssmPDouble** pxwgt, IssmPDouble** pegaus, IssmPDouble** pewgt, int nigaus, int njgaus ) {
+void gaussQuad( IssmPDouble** pxgaus, IssmPDouble** pxwgt, IssmPDouble** pegaus, IssmPDouble** pewgt, int nigaus, int njgaus ) {/*{{{*/
 	/*Gauss quadrature points for the quadrilaterial.*/
 
@@ -1706,6 +1700,5 @@
 	GaussLegendreLinear(pegaus, pewgt, njgaus);
 }/*}}}*/
-/*FUNCTION gaussHexa{{{*/
-void gaussHexa( IssmPDouble** pxgaus, IssmPDouble** pxwgt, IssmPDouble** pegaus, IssmPDouble** pewgt, IssmPDouble** pzgaus, IssmPDouble ** pzwgt, int nigaus, int njgaus, int nkgaus ) {
+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.*/
 
Index: issm/trunk/src/c/shared/Numerics/OptPars.h
===================================================================
--- issm/trunk/src/c/shared/Numerics/OptPars.h	(revision 18081)
+++ issm/trunk/src/c/shared/Numerics/OptPars.h	(revision 18301)
@@ -10,8 +10,10 @@
 struct OptPars{
 
-	IssmDouble xmin;
-	IssmDouble xmax;
-	IssmDouble cm_jump;
-	int maxiter;
+	IssmDouble  xmin;
+	IssmDouble  xmax;
+	IssmDouble *cm_jump;
+	int* maxiter;
+	int  nsteps;
+	int  nsize;
 
 };
Index: issm/trunk/src/c/shared/Numerics/Synchronize.sh
===================================================================
--- issm/trunk/src/c/shared/Numerics/Synchronize.sh	(revision 18081)
+++ issm/trunk/src/c/shared/Numerics/Synchronize.sh	(revision 18301)
@@ -116,6 +116,5 @@
 /*Verbosity Setup*/
 static int verbositylevel=-1;
-/*FUNCTION SetVerbosityLevel {{{*/
-void SetVerbosityLevel(int level){
+void SetVerbosityLevel(int level){/*{{{*/
 
 	if(level<0) _error_("vebosity level should be a positive integer (user provided " << level << ")");
@@ -124,6 +123,5 @@
 
 }/*}}}*/
-/*FUNCTION GetVerbosityLevel {{{*/
-int  GetVerbosityLevel(void){
+int  GetVerbosityLevel(void){/*{{{*/
 	_assert_(verbositylevel>=0);
 	return verbositylevel;
Index: issm/trunk/src/c/shared/Numerics/Verbosity.cpp
===================================================================
--- issm/trunk/src/c/shared/Numerics/Verbosity.cpp	(revision 18081)
+++ issm/trunk/src/c/shared/Numerics/Verbosity.cpp	(revision 18301)
@@ -31,6 +31,5 @@
 /*Verbosity Setup*/
 static int verbositylevel=-1;
-/*FUNCTION SetVerbosityLevel {{{*/
-void SetVerbosityLevel(int level){
+void SetVerbosityLevel(int level){/*{{{*/
 
 	if(level<0) _error_("vebosity level should be a positive integer (user provided " << level << ")");
@@ -39,6 +38,5 @@
 
 }/*}}}*/
-/*FUNCTION GetVerbosityLevel {{{*/
-int  GetVerbosityLevel(void){
+int  GetVerbosityLevel(void){/*{{{*/
 	_assert_(verbositylevel>=0);
 	return verbositylevel;
Index: issm/trunk/src/c/shared/Numerics/numerics.h
===================================================================
--- issm/trunk/src/c/shared/Numerics/numerics.h	(revision 18081)
+++ issm/trunk/src/c/shared/Numerics/numerics.h	(revision 18301)
@@ -30,5 +30,5 @@
 int         min(int a,int b);
 int         max(int a,int b);
-void        BrentSearch(IssmDouble *psearch_scalar,IssmDouble*pJ,OptPars*optpars,IssmDouble (*f)(IssmDouble,void*),void* optargs);
+void        BrentSearch(IssmDouble** pJ,OptPars optpars,IssmDouble* X0,IssmDouble (*f)(IssmDouble*,void*),IssmDouble (*g)(IssmDouble**,IssmDouble*,void*),void* usr);
 void        cross(IssmDouble *result,IssmDouble*vector1,IssmDouble*vector2);
 void        XZvectorsToCoordinateSystem(IssmDouble *T,IssmDouble*xzvectors);
Index: issm/trunk/src/c/shared/TriMesh/TriMeshUtils.cpp
===================================================================
--- issm/trunk/src/c/shared/TriMesh/TriMeshUtils.cpp	(revision 18081)
+++ issm/trunk/src/c/shared/TriMesh/TriMeshUtils.cpp	(revision 18301)
@@ -10,6 +10,5 @@
 
 #define RIFTPENALTYPAIRSWIDTH 8
-/*FUNCTION IsGridOnRift{{{*/
-int IsGridOnRift(int* riftsegments, int nriftsegs, int node){
+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, 
@@ -33,6 +32,5 @@
 	}
 }/*}}}*/
-/*FUNCTION GridElementsList{{{*/
-int GridElementsList(int** pGridElements, int* pNumGridElements,int node,int* index,int nel){
+int GridElementsList(int** pGridElements, int* pNumGridElements,int node,int* index,int nel){/*{{{*/
 
 	/*From a node, recover all the elements that are connected to it: */
@@ -87,6 +85,5 @@
 	return noerr;
 }/*}}}*/
-/*FUNCTION IsNeighbor{{{*/
-int IsNeighbor(int el1,int el2,int* index){
+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;
@@ -104,6 +101,5 @@
 	}
 }/*}}}*/
-/*FUNCTION IsOnRift{{{*/
-int IsOnRift(int el,int nriftsegs,int* riftsegments){
+int IsOnRift(int el,int nriftsegs,int* riftsegments){/*{{{*/
 	/*From a list of elements segments, figure out if el belongs to it: */
 	int i;
@@ -115,6 +111,5 @@
 	return 0;
 }/*}}}*/
-/*FUNCTION RiftSegmentsFromSegments{{{*/
-void RiftSegmentsFromSegments(int* pnriftsegs, int** priftsegments, int nel,int* index,int nsegs,int* segments){
+void RiftSegmentsFromSegments(int* pnriftsegs, int** priftsegments, int nel,int* index,int nsegs,int* segments){/*{{{*/
 
 	int i,counter;
@@ -181,6 +176,5 @@
 	*pnriftsegs=nriftsegs;
 }/*}}}*/
-/*FUNCTION DetermineGridElementListOnOneSideOfRift{{{*/
-int DetermineGridElementListOnOneSideOfRift(int* pNumGridElementListOnOneSideOfRift, int** pGridElementListOnOneSideOfRift, int segmentnumber, int nriftsegs, int* riftsegments, int node,int* index,int nel){
+int DetermineGridElementListOnOneSideOfRift(int* pNumGridElementListOnOneSideOfRift, int** pGridElementListOnOneSideOfRift, int segmentnumber, int nriftsegs, int* riftsegments, int node,int* index,int nel){/*{{{*/
 
 	int noerr=1;
@@ -245,6 +239,5 @@
 	return noerr;
 }/*}}}*/
-/*FUNCTION UpdateSegments{{{*/
-int UpdateSegments(int** psegments,int** psegmentmarkerlist, int* pnsegs,int* index, double* x,double* y,int* riftsegments,int nriftsegs,int nods,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 noerr=1;
@@ -344,6 +337,5 @@
 	return noerr;
 }/*}}}*/
-/*FUNCTION FindElement{{{*/
-int FindElement(int A,int B,int* index,int nel){
+int FindElement(int A,int B,int* index,int nel){/*{{{*/
 
 	int el=-1;
@@ -356,6 +348,5 @@
 	return el;
 }/*}}}*/
-/*FUNCTION SplitRiftSegments{{{*/
-int SplitRiftSegments(int** psegments,int** psegmentmarkerlist, int* pnumsegs, int* pnumrifts,int** priftsnumsegs,int*** priftssegments,int numrifts,int nods,int nel){
+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 
@@ -443,6 +434,5 @@
 	return noerr;
 }/*}}}*/
-/*FUNCTION PairRiftElements{{{*/
-int PairRiftElements(int** priftsnumpairs,int*** priftspairs,int numrifts,int* riftsnumsegments,int** riftssegments,double* x,double* y){
+int PairRiftElements(int** priftsnumpairs,int*** priftspairs,int numrifts,int* riftsnumsegments,int** riftssegments,double* x,double* y){/*{{{*/
 
 	int noerr=1;
@@ -490,6 +480,5 @@
 	return noerr;
 }/*}}}*/
-/*FUNCTION IsRiftPresent{{{*/
-int IsRiftPresent(int* priftflag,int* pnumrifts,int* segmentmarkerlist,int nsegs){
+int IsRiftPresent(int* priftflag,int* pnumrifts,int* segmentmarkerlist,int nsegs){/*{{{*/
 
 	int i;
@@ -517,6 +506,5 @@
 	return noerr;
 }/*}}}*/
-/*FUNCTION OrderRifts{{{*/
-int OrderRifts(int** priftstips,int** riftssegments,int** riftspairs,int numrifts,int* riftsnumsegments,double* x,double* y,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 noerr=1;
@@ -672,6 +660,5 @@
 	return noerr;
 }/*}}}*/
-/*FUNCTION PenaltyPairs{{{*/
-int PenaltyPairs(double*** priftspenaltypairs,int** priftsnumpenaltypairs,int numrifts,int** riftssegments,
+int PenaltyPairs(double*** priftspenaltypairs,int** priftsnumpenaltypairs,int numrifts,int** riftssegments,/*{{{*/
 		int* riftsnumsegs,int** riftspairs,int* riftstips,double* x,double* y){
 
Index: issm/trunk/src/c/solutionsequences/solutionsequence_la.cpp
===================================================================
--- issm/trunk/src/c/solutionsequences/solutionsequence_la.cpp	(revision 18301)
+++ issm/trunk/src/c/solutionsequences/solutionsequence_la.cpp	(revision 18301)
@@ -0,0 +1,123 @@
+/*!\file: solutionsequence_la.cpp
+ * \brief: numerical core of la solutions
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+void solutionsequence_la(FemModel* femmodel){
+
+	/*intermediary: */
+	Matrix<IssmDouble>*  Kff     = NULL;
+	Matrix<IssmDouble>*  Kfs     = NULL;
+	Vector<IssmDouble>*  ug      = NULL;
+	Vector<IssmDouble>*  uf      = NULL;
+	Vector<IssmDouble>*  pf      = NULL;
+	Vector<IssmDouble>*  df      = NULL;
+	Vector<IssmDouble>*  ys      = NULL;
+	Vector<IssmDouble>*  pug     = NULL;
+	Vector<IssmDouble>*  pug_old = NULL;
+	IssmDouble           eps_rel,r,theta; // 0<theta<.5   -> .15<theta<.45
+	int                  configuration_type,max_nonlinear_iterations;
+	bool                 vel_converged      = false;
+	bool                 pressure_converged = false;
+
+	/*Create analysis*/
+	StressbalanceAnalysis* stressanalysis   = new StressbalanceAnalysis();
+	UzawaPressureAnalysis* pressureanalysis = new UzawaPressureAnalysis();
+	femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
+
+	/*Recover parameters: */
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	femmodel->parameters->FindParam(&eps_rel,StressbalanceReltolEnum);
+	femmodel->parameters->FindParam(&max_nonlinear_iterations,StressbalanceMaxiterEnum);
+
+	/*Update constraints*/
+	femmodel->UpdateConstraintsx();
+
+	/*Convergence criterion*/
+	int  count = 0;
+	Vector<IssmDouble>* vel     = NULL;
+	Vector<IssmDouble>* vel_old = NULL;
+	GetVectorFromInputsx(&vel,femmodel,VxEnum,VertexEnum);
+	GetVectorFromInputsx(&pug,femmodel,PressureEnum,VertexEnum);
+
+	while(true){
+		count++;
+
+		/*save pointer to old velocity*/
+		delete vel_old;vel_old=vel;
+		delete pug_old;pug_old=pug; 
+		pressure_converged=false; vel_converged=false;
+
+		/*Solve KU=F*/
+		femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
+		femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+		SystemMatricesx(&Kff,&Kfs,&pf,&df,NULL,femmodel);
+		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
+		Reduceloadx(pf, Kfs, ys); delete Kfs;
+		Solverx(&uf, Kff, pf, NULL, df, femmodel->parameters); 
+		delete Kff; delete pf; delete df;
+		Mergesolutionfromftogx(&ug, uf,ys,femmodel->nodes,femmodel->parameters);delete uf; delete ys;
+
+		/*Update solution*/
+		InputUpdateFromSolutionx(femmodel,ug); delete ug;
+		GetVectorFromInputsx(&vel,femmodel,VxEnum,VertexEnum);
+
+		femmodel->SetCurrentConfiguration(UzawaPressureAnalysisEnum);
+		femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+		SystemMatricesx(&Kff,&Kfs,&pf,&df,NULL,femmodel);
+		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
+		Reduceloadx(pf, Kfs, ys); delete Kfs;
+		Solverx(&uf, Kff, pf, NULL, df, femmodel->parameters); 
+		delete Kff; delete pf; delete df;
+		Mergesolutionfromftogx(&pug, uf,ys,femmodel->nodes,femmodel->parameters); delete uf; delete ys;
+
+		/*Update solution*/
+		InputUpdateFromSolutionx(femmodel,pug); delete pug;
+		GetVectorFromInputsx(&pug,femmodel,PressureEnum,VertexEnum);
+
+		/*Check for convergence*/
+		Vector<IssmDouble>* dvel=vel_old->Duplicate(); vel_old->Copy(dvel); dvel->AYPX(vel,-1.0);
+		IssmDouble ndu=dvel->Norm(NORM_TWO);   delete dvel;
+		IssmDouble nu =vel_old->Norm(NORM_TWO);
+		if (xIsNan<IssmDouble>(ndu) || xIsNan<IssmDouble>(nu)) _error_("convergence criterion is NaN!");
+		if((ndu/nu)<eps_rel){
+			if(VerboseConvergence()) _printf0_(setw(50) << left << "   Convergence criterion: norm(du)/norm(u)" << ndu/nu*100 << " < " << eps_rel*100 << " %\n");
+			vel_converged=true;
+		}
+		else{ 
+			if(VerboseConvergence()) _printf0_(setw(50) << left << "   Convergence criterion: norm(du)/norm(u)" << ndu/nu*100 << " > " << eps_rel*100 << " %\n");
+			vel_converged=false;
+		}
+		Vector<IssmDouble>* dup=pug_old->Duplicate(); pug_old->Copy(dup); dup->AYPX(pug,-1.0);
+		IssmDouble ndp=dup->Norm(NORM_TWO);   delete dup;
+		IssmDouble np =pug_old->Norm(NORM_TWO);
+		if (xIsNan<IssmDouble>(ndp) || xIsNan<IssmDouble>(np)) _error_("convergence criterion is NaN!");
+		if((ndp/np)<eps_rel){
+			if(VerboseConvergence()) _printf0_(setw(50) << left << "   Convergence criterion: norm(dp)/norm(p)" << ndp/np*100 << " < " << eps_rel*100 << " %\n");
+			pressure_converged=true;
+		}
+		else{ 
+			if(VerboseConvergence()) _printf0_(setw(50) << left << "   Convergence criterion: norm(dp/)/norm(p)" << ndp/np*100 << " > " << eps_rel*100 << " %\n");
+			pressure_converged=false;
+		}
+
+		if(pressure_converged && vel_converged) break;
+		if(count>=max_nonlinear_iterations){
+			_printf0_("   maximum number of nonlinear iterations (" << max_nonlinear_iterations << ") exceeded\n"); 
+			break;
+		}
+	}
+
+	if(VerboseConvergence()) _printf0_("\n   total number of iterations: " << count-1 << "\n");
+
+	delete pug;  
+	delete pug_old;  
+	delete vel;  
+	delete vel_old;  
+	delete stressanalysis;
+	delete pressureanalysis;
+}
Index: issm/trunk/src/c/solutionsequences/solutionsequences.h
===================================================================
--- issm/trunk/src/c/solutionsequences/solutionsequences.h	(revision 18081)
+++ issm/trunk/src/c/solutionsequences/solutionsequences.h	(revision 18301)
@@ -18,4 +18,5 @@
 void solutionsequence_FScoupling_nonlinear(FemModel* femmodel,bool conserve_loads);
 void solutionsequence_linear(FemModel* femmodel);
+void solutionsequence_la(FemModel* femmodel);
 void solutionsequence_la_theta(FemModel* femmodel);
 void solutionsequence_adjoint_linear(FemModel* femmodel);
Index: issm/trunk/src/c/toolkits/issm/Bucket.h
===================================================================
--- issm/trunk/src/c/toolkits/issm/Bucket.h	(revision 18081)
+++ issm/trunk/src/c/toolkits/issm/Bucket.h	(revision 18301)
@@ -125,5 +125,7 @@
 		} /*}}}*/
 		Object *copy()        {/*{{{*/
-			_error_("Not implemented yet (similar to Elements)"); };
+			if (this->type==MATRIX_BUCKET) return new Bucket(this->m,this->idxm,this->n,this->idxn,this->values,this->mode);
+			else if (this->type==VECTOR_BUCKET) return new Bucket(this->m,this->idxm,this->values,this->mode);
+			else _error_("No Copy of Bucket because its type is invalid."); };
 		/*}}}*/
 
Index: issm/trunk/src/c/toolkits/issm/IssmMpiDenseMat.h
===================================================================
--- issm/trunk/src/c/toolkits/issm/IssmMpiDenseMat.h	(revision 18081)
+++ issm/trunk/src/c/toolkits/issm/IssmMpiDenseMat.h	(revision 18301)
@@ -45,6 +45,5 @@
 
 		/*IssmMpiDenseMat constructors, destructors*/
-		/*FUNCTION IssmMpiDenseMat(){{{*/
-		IssmMpiDenseMat(){
+		IssmMpiDenseMat(){/*{{{*/
 			this->M=0;
 			this->N=0;
@@ -54,17 +53,14 @@
 		}
 		/*}}}*/
-		/*FUNCTION IssmMpiDenseMat(int M,int N){{{*/
-		IssmMpiDenseMat(int Min,int Nin){
+		IssmMpiDenseMat(int Min,int Nin){/*{{{*/
 			this->Init(Min,Nin);
 		}
 		/*}}}*/
-		/*FUNCTION IssmMpiDenseMat(int M,int N, doubletype sparsity){{{*/
-		IssmMpiDenseMat(int pM,int pN, doubletype sparsity){
+		IssmMpiDenseMat(int pM,int pN, doubletype sparsity){/*{{{*/
 			/*no sparsity involved here, we are fully dense, so just use the previous constructor: */
 			this->Init(pM,pN);
 		}
 		/*}}}*/
-		/*FUNCTION IssmMpiDenseMat(int m,int n,int M,int N,int* d_nnz,int* o_nnz){{{*/
-		IssmMpiDenseMat(int min,int nin,int Min,int Nin,int* d_nnz,int* o_nnz){
+		IssmMpiDenseMat(int min,int nin,int Min,int Nin,int* d_nnz,int* o_nnz){/*{{{*/
 			/*not needed, we are fully dense!: */
 
@@ -82,6 +78,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION IssmMpiDenseMat(doubletype* serial_mat,int M,int N,doubletype sparsity){{{*/
-		IssmMpiDenseMat(doubletype* serial_mat,int Min,int Nin,doubletype sparsity){
+		IssmMpiDenseMat(doubletype* serial_mat,int Min,int Nin,doubletype sparsity){/*{{{*/
 
 			/*Here, we assume that the serial_mat is local to the local cpu, and that it has 
@@ -99,12 +94,10 @@
 		}
 		/*}}}*/
-		/*FUNCTION IssmMpiDenseMat(int M,int N, int connectivity, int numberofdofspernode){{{*/
-		IssmMpiDenseMat(int pM,int pN, int connectivity,int numberofdofspernode){
+		IssmMpiDenseMat(int pM,int pN, int connectivity,int numberofdofspernode){/*{{{*/
 			/*not needed, we are fully dense!: */
 			this->Init(pM,pN);
 		}
 		/*}}}*/
-		/*FUNCTION ~IssmMpiDenseMat(){{{*/
-		~IssmMpiDenseMat(){
+		~IssmMpiDenseMat(){/*{{{*/
 			xDelete<doubletype>(this->matrix);
 			M=0;
@@ -114,6 +107,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION IssmMpiDenseMat::Init(int Min,int Nin){{{*/
-		void Init(int Min,int Nin){
+		void Init(int Min,int Nin){/*{{{*/
 
 			this->buckets=new DataSet();
@@ -134,6 +126,5 @@
 
 		/*IssmMpiDenseMat specific routines */
-		/*FUNCTION Echo{{{*/
-		void Echo(void){
+		void Echo(void){/*{{{*/
 
 			int my_rank;
@@ -158,6 +149,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Assemble{{{*/
-		void Assemble(){
+		void Assemble(){/*{{{*/
 
 			int           i,j;
@@ -313,6 +303,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Norm{{{*/
-		doubletype Norm(NormMode mode){
+		doubletype Norm(NormMode mode){/*{{{*/
 
 			doubletype norm,local_norm;
@@ -352,18 +341,15 @@
 		}
 		/*}}}*/
-		/*FUNCTION GetSize{{{*/
-		void GetSize(int* pM,int* pN){
+		void GetSize(int* pM,int* pN){/*{{{*/
 			*pM=M;
 			*pN=N;
 		}
 		/*}}}*/
-		/*FUNCTION GetLocalSize{{{*/
-		void GetLocalSize(int* pM,int* pN){
+		void GetLocalSize(int* pM,int* pN){/*{{{*/
 			*pM=m;
 			*pN=N;
 		}
 		/*}}}*/
-		/*FUNCTION MatMult{{{*/
-		void MatMult(IssmAbsVec<doubletype>* Xin,IssmAbsVec<doubletype>* AXin){
+		void MatMult(IssmAbsVec<doubletype>* Xin,IssmAbsVec<doubletype>* AXin){/*{{{*/
 
 			int         i,j;
@@ -392,6 +378,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Duplicate{{{*/
-		IssmMpiDenseMat<doubletype>* Duplicate(void){
+		IssmMpiDenseMat<doubletype>* Duplicate(void){/*{{{*/
 
 			IssmMpiDenseMat<doubletype>* dup=new IssmMpiDenseMat<doubletype>(this->matrix,this->M,this->N,0);
@@ -400,11 +385,9 @@
 		}
 		/*}}}*/
-		/*FUNCTION ToSerial{{{*/
-		doubletype* ToSerial(void){
+		doubletype* ToSerial(void){/*{{{*/
 			_error_("not supported yet!");
 		}
 		/*}}}*/
-		/*FUNCTION SetValues{{{*/
-		void SetValues(int min,int* idxm,int nin,int* idxn,doubletype* values,InsMode mode){
+		void SetValues(int min,int* idxm,int nin,int* idxn,doubletype* values,InsMode mode){/*{{{*/
 
 			/*we need to store all the values we collect here in order to Assemble later. 
@@ -417,11 +400,9 @@
 		}
 		/*}}}*/
-		/*FUNCTION Convert{{{*/
-		void Convert(MatrixType type){
+		void Convert(MatrixType type){/*{{{*/
 			_error_("not supported yet!");
 		}
 		/*}}}*/		
-		/*FUNCTION BucketsBuildScatterBuffers{{{*/
-		void BucketsBuildScatterBuffers(int** pnumvalues_forcpu,int** prow_indices_forcpu,int** pcol_indices_forcpu,doubletype** pvalues_forcpu,int** pmodes_forcpu,DataSet** bucketsforcpu,int num_procs){
+		void BucketsBuildScatterBuffers(int** pnumvalues_forcpu,int** prow_indices_forcpu,int** pcol_indices_forcpu,doubletype** pvalues_forcpu,int** pmodes_forcpu,DataSet** bucketsforcpu,int num_procs){/*{{{*/
 
 			/*intermediary: */
Index: issm/trunk/src/c/toolkits/issm/IssmMpiSparseMat.h
===================================================================
--- issm/trunk/src/c/toolkits/issm/IssmMpiSparseMat.h	(revision 18081)
+++ issm/trunk/src/c/toolkits/issm/IssmMpiSparseMat.h	(revision 18301)
@@ -45,6 +45,5 @@
 		DataSet*    buckets;  /*here, we store buckets of values that we will Assemble into a global matrix.*/
 		/*IssmMpiSparseMat constructors, destructors*/
-		/*FUNCTION IssmMpiSparseMat(){{{*/
-		IssmMpiSparseMat(){
+		IssmMpiSparseMat(){/*{{{*/
 			this->M=0;
 			this->N=0;
@@ -54,17 +53,14 @@
 		}
 		/*}}}*/
-		/*FUNCTION IssmMpiSparseMat(int M,int N){{{*/
-		IssmMpiSparseMat(int Min,int Nin){
+		IssmMpiSparseMat(int Min,int Nin){/*{{{*/
 			this->Init(Min,Nin);
 		}
 		/*}}}*/
-		/*FUNCTION IssmMpiSparseMat(int M,int N, doubletype sparsity){{{*/
-		IssmMpiSparseMat(int pM,int pN, doubletype sparsity){
+		IssmMpiSparseMat(int pM,int pN, doubletype sparsity){/*{{{*/
 			/*no sparsity involved here, the sparsity pattern is resolve during the assemble phase: */
 			this->Init(pM,pN);
 		}
 		/*}}}*/
-		/*FUNCTION IssmMpiSparseMat(int m,int n,int M,int N,int* d_nnz,int* o_nnz){{{*/
-		IssmMpiSparseMat(int min,int nin,int Min,int Nin,int* d_nnz,int* o_nnz){
+		IssmMpiSparseMat(int min,int nin,int Min,int Nin,int* d_nnz,int* o_nnz){/*{{{*/
 
 			int i;
@@ -89,12 +85,10 @@
 		}
 		/*}}}*/
-		/*FUNCTION IssmMpiSparseMat(int M,int N, int connectivity, int numberofdofspernode){{{*/
-		IssmMpiSparseMat(int pM,int pN, int connectivity,int numberofdofspernode){
+		IssmMpiSparseMat(int pM,int pN, int connectivity,int numberofdofspernode){/*{{{*/
 			/*this is not needed, sparsity pattern is resolved at assemble phase: */
 			this->Init(pM,pN);
 		}
 		/*}}}*/
-		/*FUNCTION IssmMpiSparseMat::Init(int Min,int Nin){{{*/
-		void Init(int Min,int Nin){
+		void Init(int Min,int Nin){/*{{{*/
 			
 			int i;
@@ -120,6 +114,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION ~IssmMpiSparseMat(){{{*/
-		~IssmMpiSparseMat(){
+		~IssmMpiSparseMat(){/*{{{*/
 			int i;
 
@@ -138,6 +131,5 @@
 
 		/*IssmMpiSparseMat specific routines */
-		/*FUNCTION Echo{{{*/
-		void Echo(void){
+		void Echo(void){/*{{{*/
 
 			/*Do a synchronized dump across all the rows: */
@@ -157,6 +149,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Assemble{{{*/
-		void Assemble(){
+		void Assemble(){/*{{{*/
 
 			int           i,j;
@@ -369,6 +360,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Norm{{{*/
-		doubletype Norm(NormMode mode){
+		doubletype Norm(NormMode mode){/*{{{*/
 
 			doubletype norm,local_norm;
@@ -402,18 +392,15 @@
 		}
 		/*}}}*/
-		/*FUNCTION GetSize{{{*/
-		void GetSize(int* pM,int* pN){
+		void GetSize(int* pM,int* pN){/*{{{*/
 			*pM=M;
 			*pN=N;
 		}
 		/*}}}*/
-		/*FUNCTION GetLocalSize{{{*/
-		void GetLocalSize(int* pM,int* pN){
+		void GetLocalSize(int* pM,int* pN){/*{{{*/
 			*pM=m;
 			*pN=N;
 		}
 		/*}}}*/
-		/*FUNCTION MatMult{{{*/
-		void MatMult(IssmAbsVec<doubletype>* Xin,IssmAbsVec<doubletype>* AXin){
+		void MatMult(IssmAbsVec<doubletype>* Xin,IssmAbsVec<doubletype>* AXin){/*{{{*/
 
 			/*A check on the types: */
@@ -437,6 +424,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Duplicate{{{*/
-		IssmMpiSparseMat<doubletype>* Duplicate(void){
+		IssmMpiSparseMat<doubletype>* Duplicate(void){/*{{{*/
 
 			_error_("not supported yet!");
@@ -444,11 +430,9 @@
 		}
 		/*}}}*/
-		/*FUNCTION ToSerial{{{*/
-		doubletype* ToSerial(void){
+		doubletype* ToSerial(void){/*{{{*/
 			_error_("not supported yet!");
 		}
 		/*}}}*/
-		/*FUNCTION SetValues{{{*/
-		void SetValues(int min,int* idxm,int nin,int* idxn,doubletype* values,InsMode mode){
+		void SetValues(int min,int* idxm,int nin,int* idxn,doubletype* values,InsMode mode){/*{{{*/
 
 			/*we need to store all the values we collect here in order to Assemble later. 
@@ -461,11 +445,9 @@
 		}
 		/*}}}*/
-		/*FUNCTION Convert{{{*/
-		void Convert(MatrixType type){
+		void Convert(MatrixType type){/*{{{*/
 			_error_("not supported yet!");
 		}
 		/*}}}*/		
-		/*FUNCTION BucketsBuildScatterBuffers{{{*/
-		void BucketsBuildScatterBuffers(int** pnumvalues_forcpu,int** prow_indices_forcpu,int** pcol_indices_forcpu,doubletype** pvalues_forcpu,int** pmodes_forcpu,DataSet** bucketsforcpu,int num_procs){
+		void BucketsBuildScatterBuffers(int** pnumvalues_forcpu,int** prow_indices_forcpu,int** pcol_indices_forcpu,doubletype** pvalues_forcpu,int** pmodes_forcpu,DataSet** bucketsforcpu,int num_procs){/*{{{*/
 
 			/*intermediary: */
Index: issm/trunk/src/c/toolkits/issm/IssmMpiVec.h
===================================================================
--- issm/trunk/src/c/toolkits/issm/IssmMpiVec.h	(revision 18081)
+++ issm/trunk/src/c/toolkits/issm/IssmMpiVec.h	(revision 18301)
@@ -42,6 +42,5 @@
 
 		/*IssmMpiVec constructors, destructors*/
-		/*FUNCTION IssmMpiVec(){{{*/
-		IssmMpiVec(){
+		IssmMpiVec(){/*{{{*/
 
 			this->M=0;
@@ -51,21 +50,17 @@
 		}
 		/*}}}*/
-		/*FUNCTION IssmMpiVec(int M){{{*/
-		IssmMpiVec(int Min){
+		IssmMpiVec(int Min){/*{{{*/
 			this->Init(Min,false);
 		}
 		/*}}}*/
-		/*FUNCTION IssmMpiVec(int m,int M){{{*/
-		IssmMpiVec(int min, int Min){
+		IssmMpiVec(int min, int Min){/*{{{*/
 			this->Init(min,true);
 		}
 		/*}}}*/
-		/*FUNCTION IssmMpiVec(int M,bool fromlocalsize){{{*/
-		IssmMpiVec(int Min, bool fromlocalsize){
+		IssmMpiVec(int Min, bool fromlocalsize){/*{{{*/
 			this->Init(Min,fromlocalsize);
 		}
 		/*}}}*/
-		/*FUNCTION IssmMpiVec(doubletype* serial_vec,int M){{{*/
-		IssmMpiVec(doubletype* buffer,int Min){
+		IssmMpiVec(doubletype* buffer,int Min){/*{{{*/
 
 			this->Init(Min,false);
@@ -77,6 +72,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION IssmMpiVec(doubletype* serial_vec,int M,int m){{{*/
-		IssmMpiVec(doubletype* buffer,int Min,int min){
+		IssmMpiVec(doubletype* buffer,int Min,int min){/*{{{*/
 
 			this->vector=NULL;
@@ -91,6 +85,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION IssmMpiVec::Init(int Min,bool fromlocalsize){{{*/
-		void Init(int Min,bool fromlocalsize){
+		void Init(int Min,bool fromlocalsize){/*{{{*/
 
 			this->buckets=new DataSet();
@@ -112,6 +105,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION ~IssmMpiVec(){{{*/
-		~IssmMpiVec(){
+		~IssmMpiVec(){/*{{{*/
 			xDelete<doubletype>(this->vector);
 			this->M=0;
@@ -122,6 +114,5 @@
 
 		/*IssmMpiVec specific routines*/
-		/*FUNCTION Echo{{{*/
-		void Echo(void){
+		void Echo(void){/*{{{*/
 
 			int i,j;
@@ -140,6 +131,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Assemble{{{*/
-		void Assemble(){
+		void Assemble(){/*{{{*/
 
 			int           i,j;
@@ -285,6 +275,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION SetValues{{{*/
-		void SetValues(int ssize, int* list, doubletype* values, InsMode mode){
+		void SetValues(int ssize, int* list, doubletype* values, InsMode mode){/*{{{*/
 
 			/*we need to store all the values we collect here in order to Assemble later. 
@@ -297,6 +286,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION SetValue{{{*/
-		void SetValue(int dof, doubletype value, InsMode mode){
+		void SetValue(int dof, doubletype value, InsMode mode){/*{{{*/
 
 			/*we need to store the value we collect here in order to Assemble later. 
@@ -308,11 +296,9 @@
 		}
 		/*}}}*/
-		/*FUNCTION GetValue{{{*/
-		void GetValue(doubletype* pvalue,int dof){
+		void GetValue(doubletype* pvalue,int dof){/*{{{*/
 			_error_("Get value on a MpiVec vector not implemented yet!");
 		}
 		/*}}}*/
-		/*FUNCTION GetSize{{{*/
-		void GetSize(int* pM){
+		void GetSize(int* pM){/*{{{*/
 
 			*pM=this->M;
@@ -320,6 +306,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION GetLocalSize{{{*/
-		void GetLocalSize(int* pM){
+		void GetLocalSize(int* pM){/*{{{*/
 
 			*pM=this->m;
@@ -327,6 +312,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Duplicate{{{*/
-		IssmMpiVec<doubletype>* Duplicate(void){
+		IssmMpiVec<doubletype>* Duplicate(void){/*{{{*/
 
 			return new IssmMpiVec<doubletype>(this->vector,this->M,this->m);
@@ -334,6 +318,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Set{{{*/
-		void Set(doubletype value){
+		void Set(doubletype value){/*{{{*/
 
 			int i;
@@ -342,6 +325,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION AXPY{{{*/
-		void AXPY(IssmAbsVec<doubletype>* Xin, doubletype a){
+		void AXPY(IssmAbsVec<doubletype>* Xin, doubletype a){/*{{{*/
 
 			int i;
@@ -357,6 +339,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION AYPX{{{*/
-		void AYPX(IssmAbsVec<doubletype>* Xin, doubletype a){
+		void AYPX(IssmAbsVec<doubletype>* Xin, doubletype a){/*{{{*/
 			int i;
 
@@ -371,6 +352,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION ToMPISerial{{{*/
-		doubletype* ToMPISerial(void){
+		doubletype* ToMPISerial(void){/*{{{*/
 
 			/*communicator info: */
@@ -416,6 +396,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Copy{{{*/
-		void Copy(IssmAbsVec<doubletype>* toin){
+		void Copy(IssmAbsVec<doubletype>* toin){/*{{{*/
 
 			int i;
@@ -431,6 +410,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Norm{{{*/
-		doubletype Norm(NormMode mode){
+		doubletype Norm(NormMode mode){/*{{{*/
 
 			doubletype local_norm;
@@ -459,6 +437,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Scale{{{*/
-		void Scale(doubletype scale_factor){
+		void Scale(doubletype scale_factor){/*{{{*/
 
 			int i;
@@ -467,6 +444,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Dot{{{*/
-		doubletype Dot(IssmAbsVec<doubletype>* inputin){
+		doubletype Dot(IssmAbsVec<doubletype>* inputin){/*{{{*/
 
 			int i;
@@ -488,6 +464,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION PointwiseDivide{{{*/
-		void PointwiseDivide(IssmAbsVec<doubletype>* xin,IssmAbsVec<doubletype>* yin){
+		void PointwiseDivide(IssmAbsVec<doubletype>* xin,IssmAbsVec<doubletype>* yin){/*{{{*/
 
 			int i;
@@ -504,6 +479,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION BucketsBuildScatterBuffers{{{*/
-		void BucketsBuildScatterBuffers(int** pnumvalues_forcpu,int** prow_indices_forcpu,doubletype** pvalues_forcpu,int** pmodes_forcpu,DataSet** bucketsforcpu,int num_procs){
+		void BucketsBuildScatterBuffers(int** pnumvalues_forcpu,int** prow_indices_forcpu,doubletype** pvalues_forcpu,int** pmodes_forcpu,DataSet** bucketsforcpu,int num_procs){/*{{{*/
 
 			/*intermediary: */
Index: issm/trunk/src/c/toolkits/issm/IssmSeqVec.h
===================================================================
--- issm/trunk/src/c/toolkits/issm/IssmSeqVec.h	(revision 18081)
+++ issm/trunk/src/c/toolkits/issm/IssmSeqVec.h	(revision 18301)
@@ -37,6 +37,5 @@
 
 		/*IssmSeqVec constructors, destructors*/
-		/*FUNCTION IssmSeqVec(){{{*/
-		IssmSeqVec(){
+		IssmSeqVec(){/*{{{*/
 
 			this->M=0;
@@ -44,6 +43,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION IssmSeqVec(int M){{{*/
-		IssmSeqVec(int pM){
+		IssmSeqVec(int pM){/*{{{*/
 
 			this->M=pM;
@@ -52,6 +50,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION IssmSeqVec(int m,int M){{{*/
-		IssmSeqVec(int pm,int pM){
+		IssmSeqVec(int pm,int pM){/*{{{*/
 
 			this->M=pM;
@@ -60,6 +57,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION IssmSeqVec(int M,bool fromlocalsize){{{*/
-		IssmSeqVec(int pM,bool fromlocalsize){
+		IssmSeqVec(int pM,bool fromlocalsize){/*{{{*/
 
 			this->M=pM;
@@ -68,6 +64,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION IssmSeqVec(doubletype* serial_vec,int M){{{*/
-		IssmSeqVec(doubletype* buffer,int pM){
+		IssmSeqVec(doubletype* buffer,int pM){/*{{{*/
 
 			this->M=pM;
@@ -79,6 +74,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION ~IssmSeqVec(){{{*/
-		~IssmSeqVec(){
+		~IssmSeqVec(){/*{{{*/
 			if(this->M)xDelete<doubletype>(this->vector);
 			M=0;
@@ -87,6 +81,5 @@
 
 		/*IssmSeqVec specific routines*/
-		/*FUNCTION Echo{{{*/
-		void Echo(void){
+		void Echo(void){/*{{{*/
 
 			int i;
@@ -97,6 +90,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Assemble{{{*/
-		void Assemble(void){
+		void Assemble(void){/*{{{*/
 
 			/*do nothing*/
@@ -104,6 +96,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION SetValues{{{*/
-		void SetValues(int ssize, int* list, doubletype* values, InsMode mode){
+		void SetValues(int ssize, int* list, doubletype* values, InsMode mode){/*{{{*/
 
 			int i;
@@ -122,6 +113,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION SetValue{{{*/
-		void SetValue(int dof, doubletype value, InsMode mode){
+		void SetValue(int dof, doubletype value, InsMode mode){/*{{{*/
 
 			switch(mode){
@@ -138,6 +128,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION GetValue{{{*/
-		void GetValue(doubletype* pvalue,int dof){
+		void GetValue(doubletype* pvalue,int dof){/*{{{*/
 
 			*pvalue=this->vector[dof];
@@ -145,6 +134,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION GetSize{{{*/
-		void GetSize(int* pM){
+		void GetSize(int* pM){/*{{{*/
 
 			*pM=this->M;
@@ -152,6 +140,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION GetLocalSize{{{*/
-		void GetLocalSize(int* pM){
+		void GetLocalSize(int* pM){/*{{{*/
 
 			*pM=this->M;
@@ -159,6 +146,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Duplicate{{{*/
-		IssmSeqVec<doubletype>* Duplicate(void){
+		IssmSeqVec<doubletype>* Duplicate(void){/*{{{*/
 
 			return new IssmSeqVec<doubletype>(this->vector,this->M);
@@ -166,6 +152,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Set{{{*/
-		void Set(doubletype value){
+		void Set(doubletype value){/*{{{*/
 
 			int i;
@@ -174,6 +159,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION AXPY{{{*/
-		void AXPY(IssmAbsVec<doubletype>* Xin, doubletype a){
+		void AXPY(IssmAbsVec<doubletype>* Xin, doubletype a){/*{{{*/
 
 			int i;
@@ -189,6 +173,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION AYPX{{{*/
-		void AYPX(IssmAbsVec<doubletype>* Xin, doubletype a){
+		void AYPX(IssmAbsVec<doubletype>* Xin, doubletype a){/*{{{*/
 
 			int i;
@@ -204,6 +187,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION ToMPISerial{{{*/
-		doubletype* ToMPISerial(void){
+		doubletype* ToMPISerial(void){/*{{{*/
 
 			doubletype* buffer=NULL;
@@ -217,6 +199,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Copy{{{*/
-		void Copy(IssmAbsVec<doubletype>* toin){
+		void Copy(IssmAbsVec<doubletype>* toin){/*{{{*/
 
 			int i;
@@ -232,6 +213,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Norm{{{*/
-		doubletype Norm(NormMode mode){
+		doubletype Norm(NormMode mode){/*{{{*/
 
 			doubletype norm;
@@ -255,6 +235,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Scale{{{*/
-		void Scale(doubletype scale_factor){
+		void Scale(doubletype scale_factor){/*{{{*/
 
 			int i;
@@ -263,6 +242,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Dot{{{*/
-		doubletype Dot(IssmAbsVec<doubletype>* inputin){
+		doubletype Dot(IssmAbsVec<doubletype>* inputin){/*{{{*/
 
 			int i;
@@ -279,6 +257,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION PointwiseDivide{{{*/
-		void PointwiseDivide(IssmAbsVec<doubletype>* xin,IssmAbsVec<doubletype>* yin){
+		void PointwiseDivide(IssmAbsVec<doubletype>* xin,IssmAbsVec<doubletype>* yin){/*{{{*/
 
 			int i;
Index: issm/trunk/src/c/toolkits/objects/Matrix.h
===================================================================
--- issm/trunk/src/c/toolkits/objects/Matrix.h	(revision 18081)
+++ issm/trunk/src/c/toolkits/objects/Matrix.h	(revision 18301)
@@ -36,11 +36,9 @@
 
 		/*Matrix constructors, destructors*/
-		/*FUNCTION Matrix(){{{*/
-		Matrix(){
-			InitCheckAndSetType();
-		}
-		/*}}}*/
-		/*FUNCTION Matrix(int M,int N){{{*/
-		Matrix(int M,int N){
+		Matrix(){/*{{{*/
+			InitCheckAndSetType();
+		}
+		/*}}}*/
+		Matrix(int M,int N){/*{{{*/
 
 			InitCheckAndSetType();
@@ -57,6 +55,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Matrix(int m,int n,int M,int N,int* d_nnz,int* o_nnz){{{*/
-		Matrix(int m,int n,int M,int N,int* d_nnz,int* o_nnz){
+		Matrix(int m,int n,int M,int N,int* d_nnz,int* o_nnz){/*{{{*/
 
 			InitCheckAndSetType();
@@ -73,6 +70,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Matrix(int M,int N,IssmDouble sparsity){{{*/
-		Matrix(int M,int N,double sparsity){
+		Matrix(int M,int N,double sparsity){/*{{{*/
 
 			InitCheckAndSetType();
@@ -88,6 +84,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Matrix(IssmDouble* serial_mat, int M,int N,IssmDouble sparsity){{{*/
-		Matrix(IssmPDouble* serial_mat,int M,int N,IssmPDouble sparsity){
+		Matrix(IssmPDouble* serial_mat,int M,int N,IssmPDouble sparsity){/*{{{*/
 
 			InitCheckAndSetType();
@@ -104,6 +99,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Matrix(int M,int N,int connectivity,int numberofdofspernode){{{*/
-		Matrix(int M,int N,int connectivity,int numberofdofspernode){
+		Matrix(int M,int N,int connectivity,int numberofdofspernode){/*{{{*/
 
 			InitCheckAndSetType();
@@ -120,6 +114,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION ~Matrix(){{{*/
-		~Matrix(){
+		~Matrix(){/*{{{*/
 
 			if(type==PetscMatType){
@@ -132,6 +125,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION InitCheckAndSetType(){{{*/
-		void InitCheckAndSetType(void){
+		void InitCheckAndSetType(void){/*{{{*/
 
 			char* toolkittype=NULL;
@@ -165,6 +157,5 @@
 
 		/*Matrix specific routines:*/
-		/*FUNCTION Echo{{{*/
-		void Echo(void){
+		void Echo(void){/*{{{*/
 			_assert_(this);
 
@@ -180,6 +171,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION AllocationInfo{{{*/
-		void AllocationInfo(void){
+		void AllocationInfo(void){/*{{{*/
 			_assert_(this);
 			if(type==PetscMatType){
@@ -193,6 +183,5 @@
 			}
 		}/*}}}*/
-		/*FUNCTION Assemble{{{*/
-		void Assemble(void){
+		void Assemble(void){/*{{{*/
 
 			if(type==PetscMatType){
@@ -206,6 +195,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Norm{{{*/
-		IssmDouble Norm(NormMode norm_type){
+		IssmDouble Norm(NormMode norm_type){/*{{{*/
 
 			IssmDouble norm=0;
@@ -223,6 +211,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION GetSize{{{*/
-		void GetSize(int* pM,int* pN){
+		void GetSize(int* pM,int* pN){/*{{{*/
 
 			if(type==PetscMatType){
@@ -237,6 +224,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION GetLocalSize{{{*/
-		void GetLocalSize(int* pM,int* pN){
+		void GetLocalSize(int* pM,int* pN){/*{{{*/
 
 			if(type==PetscMatType){
@@ -251,6 +237,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION MatMult{{{*/
-		void MatMult(Vector<doubletype>* X,Vector<doubletype>* AX){
+		void MatMult(Vector<doubletype>* X,Vector<doubletype>* AX){/*{{{*/
 
 			if(type==PetscMatType){
@@ -265,6 +250,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Duplicate{{{*/
-		Matrix<doubletype>* Duplicate(void){
+		Matrix<doubletype>* Duplicate(void){/*{{{*/
 
 			Matrix<doubletype>* output=new Matrix<doubletype>();
@@ -282,6 +266,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION ToSerial{{{*/
-		doubletype* ToSerial(void){
+		doubletype* ToSerial(void){/*{{{*/
 
 			doubletype* output=NULL;
@@ -299,6 +282,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION SetValues{{{*/
-		void SetValues(int m,int* idxm,int n,int* idxn,IssmDouble* values,InsMode mode){
+		void SetValues(int m,int* idxm,int n,int* idxn,IssmDouble* values,InsMode mode){/*{{{*/
 
 			if(type==PetscMatType){
@@ -312,6 +294,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Convert{{{*/
-		void Convert(MatrixType newtype){
+		void Convert(MatrixType newtype){/*{{{*/
 
 			if(type==PetscMatType){
Index: issm/trunk/src/c/toolkits/objects/Vector.h
===================================================================
--- issm/trunk/src/c/toolkits/objects/Vector.h	(revision 18081)
+++ issm/trunk/src/c/toolkits/objects/Vector.h	(revision 18301)
@@ -128,6 +128,5 @@
 
 		/*Vector specific routines*/
-		/*FUNCTION Echo{{{*/
-		void Echo(void){_assert_(this);
+		void Echo(void){_assert_(this);/*{{{*/
 
 			if(type==PetscVecType){
@@ -140,6 +139,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Assemble{{{*/
-		void Assemble(void){_assert_(this);
+		void Assemble(void){_assert_(this);/*{{{*/
 
 			if(type==PetscVecType){
@@ -152,6 +150,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION SetValues{{{*/
-		void SetValues(int ssize, int* list, doubletype* values, InsMode mode){ _assert_(this);
+		void SetValues(int ssize, int* list, doubletype* values, InsMode mode){ _assert_(this);/*{{{*/
 			if(type==PetscVecType){
 				#ifdef _HAVE_PETSC_
@@ -163,6 +160,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION SetValue{{{*/
-		void SetValue(int dof, doubletype value, InsMode mode){_assert_(this);
+		void SetValue(int dof, doubletype value, InsMode mode){_assert_(this);/*{{{*/
 
 			if(type==PetscVecType){
@@ -175,6 +171,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION GetValue{{{*/
-		void GetValue(doubletype* pvalue,int dof){_assert_(this);
+		void GetValue(doubletype* pvalue,int dof){_assert_(this);/*{{{*/
 
 			if(type==PetscVecType){
@@ -187,6 +182,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION GetSize{{{*/
-		void GetSize(int* pM){_assert_(this);
+		void GetSize(int* pM){_assert_(this);/*{{{*/
 
 			if(type==PetscVecType){
@@ -199,6 +193,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION IsEmpty{{{*/
-		bool IsEmpty(void){
+		bool IsEmpty(void){/*{{{*/
 			int M;
 
@@ -212,6 +205,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION GetLocalSize{{{*/
-		void GetLocalSize(int* pM){_assert_(this);
+		void GetLocalSize(int* pM){_assert_(this);/*{{{*/
 
 			if(type==PetscVecType){
@@ -224,6 +216,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Duplicate{{{*/
-		Vector<doubletype>* Duplicate(void){_assert_(this);
+		Vector<doubletype>* Duplicate(void){_assert_(this);/*{{{*/
 
 			Vector<doubletype>* output=NULL;
@@ -242,6 +233,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Set{{{*/
-		void Set(doubletype value){_assert_(this);
+		void Set(doubletype value){_assert_(this);/*{{{*/
 
 			if(type==PetscVecType){
@@ -254,6 +244,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION AXPY{{{*/
-		void AXPY(Vector* X, doubletype a){_assert_(this);
+		void AXPY(Vector* X, doubletype a){_assert_(this);/*{{{*/
 
 			if(type==PetscVecType){
@@ -266,6 +255,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION AYPX{{{*/
-		void AYPX(Vector* X, doubletype a){_assert_(this);
+		void AYPX(Vector* X, doubletype a){_assert_(this);/*{{{*/
 
 			if(type==PetscVecType){
@@ -277,6 +265,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION ToMPISerial{{{*/
-		doubletype* ToMPISerial(void){
+		doubletype* ToMPISerial(void){/*{{{*/
 
 			doubletype* vec_serial=NULL;
@@ -294,6 +281,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Copy{{{*/
-		void Copy(Vector* to){_assert_(this);
+		void Copy(Vector* to){_assert_(this);/*{{{*/
 
 			if(type==PetscVecType){
@@ -305,6 +291,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Max{{{*/
-		doubletype Max(void){_assert_(this);
+		doubletype Max(void){_assert_(this);/*{{{*/
 
 			doubletype max=0;
@@ -319,6 +304,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Norm{{{*/
-		doubletype Norm(NormMode norm_type){_assert_(this);
+		doubletype Norm(NormMode norm_type){_assert_(this);/*{{{*/
 
 			doubletype norm=0;
@@ -333,6 +317,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Scale{{{*/
-		void Scale(doubletype scale_factor){_assert_(this);
+		void Scale(doubletype scale_factor){_assert_(this);/*{{{*/
 
 			if(type==PetscVecType){
@@ -344,6 +327,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Dot{{{*/
-		doubletype Dot(Vector* vector){_assert_(this);
+		doubletype Dot(Vector* vector){_assert_(this);/*{{{*/
 
 			doubletype dot;
@@ -358,6 +340,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION PointwiseDivide{{{*/
-		void PointwiseDivide(Vector* x,Vector* y){_assert_(this);
+		void PointwiseDivide(Vector* x,Vector* y){_assert_(this);/*{{{*/
 
 			if(type==PetscVecType){
Index: issm/trunk/src/c/toolkits/petsc/objects/PetscMat.cpp
===================================================================
--- issm/trunk/src/c/toolkits/petsc/objects/PetscMat.cpp	(revision 18081)
+++ issm/trunk/src/c/toolkits/petsc/objects/PetscMat.cpp	(revision 18301)
@@ -19,6 +19,5 @@
 
 /*PetscMat constructors and destructor*/
-/*FUNCTION PetscMat::PetscMat(){{{*/
-PetscMat::PetscMat(){
+PetscMat::PetscMat(){/*{{{*/
 	this->matrix=NULL;
 	#ifdef _HAVE_ADOLC_
@@ -28,29 +27,26 @@
 }
 /*}}}*/
-/*FUNCTION PetscMat::PetscMat(int M,int N){{{*/
-PetscMat::PetscMat(int M,int N){
+PetscMat::PetscMat(int M,int N){/*{{{*/
 
 	this->matrix=NewMat(M,N,IssmComm::GetComm());
 }
 /*}}}*/
-/*FUNCTION PetscMat::PetscMat(int M,int N, IssmDouble sparsity){{{*/
-PetscMat::PetscMat(int M,int N, IssmDouble sparsity){
+PetscMat::PetscMat(int M,int N, IssmDouble sparsity){/*{{{*/
 
 	this->matrix=NewMat(M,N,sparsity,IssmComm::GetComm());
 }
 /*}}}*/
-/*FUNCTION PetscMat::PetscMat(int m,int n,int M,int N,int* d_nnz,int* o_nnz){{{*/
-PetscMat::PetscMat(int m,int n,int M,int N,int* d_nnz,int* o_nnz){
+PetscMat::PetscMat(int m,int n,int M,int N,int* d_nnz,int* o_nnz){/*{{{*/
 
 	MatCreate(IssmComm::GetComm(),&this->matrix);
 	MatSetSizes(this->matrix,m,n,M,N);
 	MatSetFromOptions(this->matrix);
-	MatMPIAIJSetPreallocation(this->matrix,0,d_nnz,0,o_nnz);
+	PetscErrorCode ierr = MatMPIAIJSetPreallocation(this->matrix,0,d_nnz,0,o_nnz);
+	if(ierr) _error_("PETSc could not allocate matrix (probably not enough memory)");
 //	MatSetOption(this->matrix,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE);
 
 }
 /*}}}*/
-/*FUNCTION PetscMat::PetscMat(IssmDouble* serial_mat,int M,int N,IssmDouble sparsity){{{*/
-PetscMat::PetscMat(IssmDouble* serial_mat,int M,int N,IssmDouble sparsity){
+PetscMat::PetscMat(IssmDouble* serial_mat,int M,int N,IssmDouble sparsity){/*{{{*/
 
 	int     i;
@@ -74,6 +70,5 @@
 }
 /*}}}*/
-/*FUNCTION PetscMat::PetscMat(int M,int N, int connectivity, int numberofdofspernode){{{*/
-PetscMat::PetscMat(int M,int N, int connectivity,int numberofdofspernode){
+PetscMat::PetscMat(int M,int N, int connectivity,int numberofdofspernode){/*{{{*/
 
 	this->matrix=NewMat(M,N,connectivity,numberofdofspernode,IssmComm::GetComm());
@@ -81,6 +76,5 @@
 }
 /*}}}*/
-/*FUNCTION PetscMat::~PetscMat(){{{*/
-PetscMat::~PetscMat(){
+PetscMat::~PetscMat(){/*{{{*/
 	MatFree(&this->matrix);
 }
@@ -88,6 +82,5 @@
 
 /*PetscMat specific routines: */
-/*FUNCTION PetscMat::AllocationInfo{{{*/
-void PetscMat::AllocationInfo(void){
+void PetscMat::AllocationInfo(void){/*{{{*/
 
 	MatInfo info;
@@ -103,12 +96,10 @@
 }
 /*}}}*/
-/*FUNCTION PetscMat::Echo{{{*/
-void PetscMat::Echo(void){
+void PetscMat::Echo(void){/*{{{*/
 
 	MatView(this->matrix,PETSC_VIEWER_STDOUT_WORLD);
 }
 /*}}}*/
-/*FUNCTION PetscMat::Assemble{{{*/
-void PetscMat::Assemble(void){
+void PetscMat::Assemble(void){/*{{{*/
 
 	_assert_(this->matrix);
@@ -118,6 +109,5 @@
 }
 /*}}}*/
-/*FUNCTION PetscMat::Norm{{{*/
-IssmDouble PetscMat::Norm(NormMode mode){
+IssmDouble PetscMat::Norm(NormMode mode){/*{{{*/
 
 	IssmDouble norm=0;
@@ -129,6 +119,5 @@
 }
 /*}}}*/
-/*FUNCTION PetscMat::GetSize{{{*/
-void PetscMat::GetSize(int* pM,int* pN){
+void PetscMat::GetSize(int* pM,int* pN){/*{{{*/
 
 	_assert_(this->matrix);
@@ -136,6 +125,5 @@
 }
 /*}}}*/
-/*FUNCTION PetscMat::GetLocalSize{{{*/
-void PetscMat::GetLocalSize(int* pM,int* pN){
+void PetscMat::GetLocalSize(int* pM,int* pN){/*{{{*/
 
 	_assert_(this->matrix);
@@ -144,6 +132,5 @@
 }
 /*}}}*/
-/*FUNCTION PetscMat::MatMult{{{*/
-void PetscMat::MatMult(PetscVec* X,PetscVec* AX){
+void PetscMat::MatMult(PetscVec* X,PetscVec* AX){/*{{{*/
 
 	_assert_(this->matrix);
@@ -153,6 +140,5 @@
 }
 /*}}}*/
-/*FUNCTION PetscMat::Duplicate{{{*/
-PetscMat* PetscMat::Duplicate(void){
+PetscMat* PetscMat::Duplicate(void){/*{{{*/
 
 	PetscMat* output=new PetscMat();
@@ -164,6 +150,5 @@
 }
 /*}}}*/
-/*FUNCTION PetscMat::ToSerial{{{*/
-IssmDouble* PetscMat::ToSerial(void){
+IssmDouble* PetscMat::ToSerial(void){/*{{{*/
 
 	 IssmDouble* output=NULL;
@@ -174,15 +159,12 @@
 }
 /*}}}*/
-/*FUNCTION PetscMat::SetValues{{{*/
-void PetscMat::SetValues(int m,int* idxm,int n,int* idxn,IssmDouble* values,InsMode mode){
+void PetscMat::SetValues(int m,int* idxm,int n,int* idxn,IssmDouble* values,InsMode mode){/*{{{*/
 
-	PetscErrorCode ierr;
-	ierr = MatSetValues(this->matrix,m,idxm,n,idxn,values,ISSMToPetscInsertMode(mode));
-	if(ierr) _error_("PETSC's MatSetValues reported an error");
+	PetscErrorCode ierr = MatSetValues(this->matrix,m,idxm,n,idxn,values,ISSMToPetscInsertMode(mode));
+	if(ierr) _error_("PETSc's MatSetValues reported an error");
 
 }
 /*}}}*/
-/*FUNCTION PetscMat::Convert{{{*/
-void PetscMat::Convert(MatrixType type){
+void PetscMat::Convert(MatrixType type){/*{{{*/
 
 	MatConvert(this->matrix,ISSMToPetscMatrixType(type),MAT_REUSE_MATRIX,&this->matrix);
Index: issm/trunk/src/c/toolkits/petsc/objects/PetscSolver.cpp
===================================================================
--- issm/trunk/src/c/toolkits/petsc/objects/PetscSolver.cpp	(revision 18081)
+++ issm/trunk/src/c/toolkits/petsc/objects/PetscSolver.cpp	(revision 18301)
@@ -104,5 +104,9 @@
 	/*Prepare solver*/
 	KSPCreate(IssmComm::GetComm(),&ksp);
-	KSPSetOperators(ksp,Kff,Kff,DIFFERENT_NONZERO_PATTERN);
+	#if (_PETSC_MAJOR_==3) && (_PETSC_MINOR_>=5)
+		KSPSetOperators(ksp,Kff,Kff);
+	#else
+		KSPSetOperators(ksp,Kff,Kff,DIFFERENT_NONZERO_PATTERN);
+	#endif
 	KSPSetFromOptions(ksp);
 
Index: issm/trunk/src/c/toolkits/petsc/objects/PetscVec.cpp
===================================================================
--- issm/trunk/src/c/toolkits/petsc/objects/PetscVec.cpp	(revision 18081)
+++ issm/trunk/src/c/toolkits/petsc/objects/PetscVec.cpp	(revision 18301)
@@ -19,6 +19,5 @@
 
 /*PetscVec constructors and destructor*/
-/*FUNCTION PetscVec::PetscVec(){{{*/
-PetscVec::PetscVec(){
+PetscVec::PetscVec(){/*{{{*/
 	this->vector=NULL;
 	#ifdef _HAVE_ADOLC_
@@ -27,6 +26,5 @@
 }
 /*}}}*/
-/*FUNCTION PetscVec::PetscVec(int M,bool fromlocalsize){{{*/
-PetscVec::PetscVec(int M,bool fromlocalsize){
+PetscVec::PetscVec(int M,bool fromlocalsize){/*{{{*/
 
 	this->vector=NewVec(M,IssmComm::GetComm(),fromlocalsize);
@@ -34,6 +32,5 @@
 }
 /*}}}*/
-/*FUNCTION PetscVec::PetscVec(int m,int M){{{*/
-PetscVec::PetscVec(int m,int M){
+PetscVec::PetscVec(int m,int M){/*{{{*/
 
 	VecCreate(IssmComm::GetComm(),&this->vector);
@@ -44,6 +41,5 @@
 }
 /*}}}*/
-/*FUNCTION PetscVec::PetscVec(Vec petsc_vec){{{*/
-PetscVec::PetscVec(Vec petsc_vec){
+PetscVec::PetscVec(Vec petsc_vec){/*{{{*/
 
 	if(petsc_vec==NULL){
@@ -58,6 +54,5 @@
 }
 /*}}}*/
-/*FUNCTION PetscVec::PetscVec(IssmDouble* serial_vec,int M){{{*/
-PetscVec::PetscVec(IssmDouble* serial_vec,int M){
+PetscVec::PetscVec(IssmDouble* serial_vec,int M){/*{{{*/
 
 	int* idxm=NULL;
@@ -73,6 +68,5 @@
 }
 /*}}}*/
-/*FUNCTION PetscVec::~PetscVec(){{{*/
-PetscVec::~PetscVec(){
+PetscVec::~PetscVec(){/*{{{*/
     VecFree(&this->vector);
 }
@@ -80,6 +74,5 @@
 
 /*PetscVec specific routines: */
-/*FUNCTION PetscVec::Echo{{{*/
-void PetscVec::Echo(void){
+void PetscVec::Echo(void){/*{{{*/
 
 	_assert_(this->vector);
@@ -87,6 +80,5 @@
 }
 /*}}}*/
-/*FUNCTION PetscVec::Assemble{{{*/
-void PetscVec::Assemble(void){
+void PetscVec::Assemble(void){/*{{{*/
 
 	_assert_(this->vector);
@@ -96,6 +88,5 @@
 }
 /*}}}*/
-/*FUNCTION PetscVec::SetValues{{{*/
-void PetscVec::SetValues(int ssize, int* list, IssmDouble* values, InsMode mode){
+void PetscVec::SetValues(int ssize, int* list, IssmDouble* values, InsMode mode){/*{{{*/
 
 	_assert_(this->vector);
@@ -104,6 +95,5 @@
 }
 /*}}}*/
-/*FUNCTION PetscVec::SetValue{{{*/
-void PetscVec::SetValue(int dof, IssmDouble value, InsMode mode){
+void PetscVec::SetValue(int dof, IssmDouble value, InsMode mode){/*{{{*/
 
 	_assert_(this->vector);
@@ -112,6 +102,5 @@
 }
 /*}}}*/
-/*FUNCTION PetscVec::GetValue{{{*/
-void PetscVec::GetValue(IssmDouble* pvalue,int dof){
+void PetscVec::GetValue(IssmDouble* pvalue,int dof){/*{{{*/
 
 	_assert_(this->vector);
@@ -120,6 +109,5 @@
 }
 /*}}}*/
-/*FUNCTION PetscVec::GetSize{{{*/
-void PetscVec::GetSize(int* pM){
+void PetscVec::GetSize(int* pM){/*{{{*/
 
 	_assert_(this->vector);
@@ -128,6 +116,5 @@
 }
 /*}}}*/
-/*FUNCTION PetscVec::GetLocalSize{{{*/
-void PetscVec::GetLocalSize(int* pM){
+void PetscVec::GetLocalSize(int* pM){/*{{{*/
 
 	_assert_(this->vector);
@@ -136,6 +123,5 @@
 }
 /*}}}*/
-/*FUNCTION PetscVec::Duplicate{{{*/
-PetscVec* PetscVec::Duplicate(void){
+PetscVec* PetscVec::Duplicate(void){/*{{{*/
 
 	_assert_(this->vector);
@@ -148,6 +134,5 @@
 }
 /*}}}*/
-/*FUNCTION PetscVec::Set{{{*/
-void PetscVec::Set(IssmDouble value){
+void PetscVec::Set(IssmDouble value){/*{{{*/
 
 	_assert_(this->vector);
@@ -156,6 +141,5 @@
 }
 /*}}}*/
-/*FUNCTION PetscVec::AXPY{{{*/
-void PetscVec::AXPY(PetscVec* X, IssmDouble a){
+void PetscVec::AXPY(PetscVec* X, IssmDouble a){/*{{{*/
 
 	_assert_(this->vector);
@@ -164,6 +148,5 @@
 }
 /*}}}*/
-/*FUNCTION PetscVec::AYPX{{{*/
-void PetscVec::AYPX(PetscVec* X, IssmDouble a){
+void PetscVec::AYPX(PetscVec* X, IssmDouble a){/*{{{*/
 
 	_assert_(this->vector);
@@ -172,6 +155,5 @@
 }
 /*}}}*/
-/*FUNCTION PetscVec::ToMPISerial{{{*/
-IssmDouble* PetscVec::ToMPISerial(void){
+IssmDouble* PetscVec::ToMPISerial(void){/*{{{*/
 
 	IssmDouble* vec_serial=NULL;
@@ -181,6 +163,5 @@
 }
 /*}}}*/
-/*FUNCTION PetscVec::Copy{{{*/
-void PetscVec::Copy(PetscVec* to){
+void PetscVec::Copy(PetscVec* to){/*{{{*/
 
 	if(this->vector) VecCopy(this->vector,to->vector);
@@ -188,6 +169,5 @@
 }
 /*}}}*/
-/*FUNCTION PetscVec::Max{{{*/
-IssmDouble PetscVec::Max(void){
+IssmDouble PetscVec::Max(void){/*{{{*/
 
 	_assert_(this->vector);
@@ -199,6 +179,5 @@
 }
 /*}}}*/
-/*FUNCTION PetscVec::Norm{{{*/
-IssmDouble PetscVec::Norm(NormMode mode){
+IssmDouble PetscVec::Norm(NormMode mode){/*{{{*/
 
 	IssmDouble norm=0;
@@ -209,6 +188,5 @@
 }
 /*}}}*/
-/*FUNCTION PetscVec::Scale{{{*/
-void PetscVec::Scale(IssmDouble scale_factor){
+void PetscVec::Scale(IssmDouble scale_factor){/*{{{*/
 
 	_assert_(this->vector);
@@ -217,6 +195,5 @@
 }
 /*}}}*/
-/*FUNCTION PetscVec::Dot{{{*/
-IssmDouble PetscVec::Dot(PetscVec* input){
+IssmDouble PetscVec::Dot(PetscVec* input){/*{{{*/
 
 	IssmDouble dot;
@@ -227,6 +204,5 @@
 }
 /*}}}*/
-/*FUNCTION PetscVec::PointwiseDivide{{{*/
-void PetscVec::PointwiseDivide(PetscVec* x,PetscVec* y){
+void PetscVec::PointwiseDivide(PetscVec* x,PetscVec* y){/*{{{*/
 
 	_assert_(this->vector);
Index: issm/trunk/src/dox/issm.dox
===================================================================
--- issm/trunk/src/dox/issm.dox	(revision 18081)
+++ issm/trunk/src/dox/issm.dox	(revision 18301)
@@ -87,4 +87,4 @@
 </table>
 
-	<I> Copyright (C) 2013 </I>
+	<I> Copyright (C) 2014 </I>
   */
Index: issm/trunk/src/m/classes/SMBcomponents.m
===================================================================
--- issm/trunk/src/m/classes/SMBcomponents.m	(revision 18301)
+++ issm/trunk/src/m/classes/SMBcomponents.m	(revision 18301)
@@ -0,0 +1,80 @@
+%SMBcomponents Class definition
+%
+%   Usage:
+%      SMBcomponents=SMBcomponents();
+
+classdef SMBcomponents
+	properties (SetAccess=public) 
+		accumulation = NaN;
+		runoff = NaN;
+		evaporation = NaN;
+	end
+	methods
+		function obj = SMBcomponents(varargin) % {{{
+			switch nargin
+				case 0
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function self = extrude(self,md) % {{{
+
+			self.accumulation=project3d(md,'vector',self.accumulation,'type','node');
+			self.runoff=project3d(md,'vector',self.runoff,'type','node');
+			self.evaporation=project3d(md,'vector',self.evaporation,'type','node');
+
+		end % }}}
+		function self = initialize(self,md) % {{{
+
+			if isnan(self.accumulation)
+				self.accumulation=zeros(md.mesh.numberofvertices,1);
+				disp('      no surfaceforcings.accumulation specified: values set as zero');
+			end
+			if isnan(self.evaporation)
+				self.evaporation=zeros(md.mesh.numberofvertices,1);
+				disp('      no surfaceforcings.evaporation specified: values set as zero');
+			end
+			if isnan(self.runoff)
+				self.runoff=zeros(md.mesh.numberofvertices,1);
+				disp('      no surfaceforcings.runoff specified: values set as zero');
+			end
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			if ismember(MasstransportAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.accumulation','forcing',1,'NaN',1);
+			end
+			if ismember(BalancethicknessAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.accumulation','size',[md.mesh.numberofvertices 1],'NaN',1);
+			end
+			if ismember(MasstransportAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.runoff','forcing',1,'NaN',1);
+			end
+			if ismember(BalancethicknessAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.runoff','size',[md.mesh.numberofvertices 1],'NaN',1);
+			end
+			if ismember(MasstransportAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.evaporation','forcing',1,'NaN',1);
+			end
+			if ismember(BalancethicknessAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.evaporation','size',[md.mesh.numberofvertices 1],'NaN',1);
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   surface forcings parameters (SMB=accumulation-runoff-evaporation) :'));
+			fielddisplay(obj,'accumulation','accumulated snow [m/yr ice eq]');
+			fielddisplay(obj,'runoff','amount of ice melt lost from the ice column [m/yr ice eq]');
+			fielddisplay(obj,'evaporation','amount of ice lost to evaporative processes [m/yr ice eq]');
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+
+			yts=365.0*24.0*3600.0;
+
+			WriteData(fid,'enum',SurfaceforcingsEnum(),'data',SMBcomponentsEnum(),'format','Integer');
+			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','accumulation','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','runoff','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','evaporation','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+		end % }}}
+	end
+end
Index: issm/trunk/src/m/classes/SMBcomponents.py
===================================================================
--- issm/trunk/src/m/classes/SMBcomponents.py	(revision 18301)
+++ issm/trunk/src/m/classes/SMBcomponents.py	(revision 18301)
@@ -0,0 +1,80 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from project3d import *
+from WriteData import *
+
+class SMBcomponents(object):
+	"""
+	SMBcomponents Class definition
+
+	   Usage:
+	      SMBcomponents=SMBcomponents();
+	"""
+
+	def __init__(self): # {{{
+		self.accumulation = float('NaN')
+		self.runoff = float('NaN')
+		self.evaporation = float('NaN')
+		#}}}
+	def __repr__(self): # {{{
+		string="   surface forcings parameters (SMB=accumulation-runoff-evaporation) :"
+		string="%s\n%s"%(string,fielddisplay(self,'accumulation','accumulated snow [m/yr ice eq]'))
+		string="%s\n%s"%(string,fielddisplay(self,'runoff','amount of ice melt lost from the ice column [m/yr ice eq]'))
+		string="%s\n%s"%(string,fielddisplay(self,'evaporation','mount of ice lost to evaporative processes [m/yr ice eq]'))
+		return string
+		#}}}
+	def extrude(self,md): # {{{
+
+		self.mass_balance=project3d(md,'vector',self.accumulation,'type','node');
+		self.mass_balance=project3d(md,'vector',self.runoff,'type','node');
+		self.mass_balance=project3d(md,'vector',self.evaporation,'type','node');
+		return self
+	#}}}
+	def initialize(self,md): # {{{
+
+		if numpy.all(numpy.isnan(self.accumulation)):
+			self.accumulation=numpy.zeros((md.mesh.numberofvertices,1))
+			print "      no SMB.accumulation specified: values set as zero"
+
+		if numpy.all(numpy.isnan(self.runoff)):
+			self.runoff=numpy.zeros((md.mesh.numberofvertices,1))
+			print "      no SMB.runoff specified: values set as zero"
+
+		if numpy.all(numpy.isnan(self.evaporation)):
+			self.evaporation=numpy.zeros((md.mesh.numberofvertices,1))
+			print "      no SMB.evaporation specified: values set as zero"
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		if MasstransportAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.accumulation','forcing',1,'NaN',1)
+
+		if BalancethicknessAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.accumulation','size',[md.mesh.numberofvertices],'NaN',1)
+
+		if MasstransportAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.runoff','forcing',1,'NaN',1)
+
+		if BalancethicknessAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.runoff','size',[md.mesh.numberofvertices],'NaN',1)
+
+		if MasstransportAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.evaporation','forcing',1,'NaN',1)
+
+		if BalancethicknessAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.evaporation','size',[md.mesh.numberofvertices],'NaN',1)
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+
+		yts=365.0*24.0*3600.0
+
+		WriteData(fid,'enum',SurfaceforcingsEnum(),'data',SMBcomponentsEnum(),'format','Integer');
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','accumulation','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','runoff','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','evaporation','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+	# }}}
Index: issm/trunk/src/m/classes/SMBgradients.m
===================================================================
--- issm/trunk/src/m/classes/SMBgradients.m	(revision 18081)
+++ issm/trunk/src/m/classes/SMBgradients.m	(revision 18301)
@@ -48,6 +48,6 @@
 
 			disp(sprintf('\n   SMB gradients parameters:'));
-			fielddisplay(obj,'href',' reference elevation from which deviation is used to calculate SMB adjustment in smb gradients method');
-			fielddisplay(obj,'smbref',' reference smb from which deviation is calculated in smb gradients method');
+			fielddisplay(obj,'href',' reference elevation from which deviation is used to calculate SMB adjustment in smb gradients method [m]');
+			fielddisplay(obj,'smbref',' reference smb from which deviation is calculated in smb gradients method [mm/yr water equiv]');
 			fielddisplay(obj,'b_pos',' slope of hs - smb regression line for accumulation regime required if smb gradients is activated');
 			fielddisplay(obj,'b_neg',' slope of hs - smb regression line for ablation regime required if smb gradients is activated');
Index: issm/trunk/src/m/classes/SMBmeltcomponents.m
===================================================================
--- issm/trunk/src/m/classes/SMBmeltcomponents.m	(revision 18301)
+++ issm/trunk/src/m/classes/SMBmeltcomponents.m	(revision 18301)
@@ -0,0 +1,94 @@
+%SMBmeltcomponents Class definition
+%
+%   Usage:
+%      SMBmeltcomponents=SMBmeltcomponents();
+
+classdef SMBmeltcomponents
+	properties (SetAccess=public) 
+		accumulation = NaN;
+		evaporation = NaN;
+		melt = NaN;
+		refreeze = NaN;
+	end
+	methods
+		function obj = SMBmeltcomponents(varargin) % {{{
+			switch nargin
+				case 0
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function self = extrude(self,md) % {{{
+
+			self.accumulation=project3d(md,'vector',self.accumulation,'type','node');
+			self.evaporation=project3d(md,'vector',self.evaporation,'type','node');
+			self.melt=project3d(md,'vector',self.melt,'type','node');
+			self.refreeze=project3d(md,'vector',self.refreeze,'type','node');
+
+		end % }}}
+		function self = initialize(self,md) % {{{
+
+			if isnan(self.accumulation)
+				self.accumulation=zeros(md.mesh.numberofvertices,1);
+				disp('      no surfaceforcings.accumulation specified: values set as zero');
+			end
+			if isnan(self.evaporation)
+				self.evaporation=zeros(md.mesh.numberofvertices,1);
+				disp('      no surfaceforcings.evaporation specified: values set as zero');
+			end
+			if isnan(self.refreeze)
+				self.refreeze=zeros(md.mesh.numberofvertices,1);
+				disp('      no surfaceforcings.refreeze specified: values set as zero');
+			end
+			if isnan(self.melt)
+				self.melt=zeros(md.mesh.numberofvertices,1);
+				disp('      no surfaceforcings.melt specified: values set as zero');
+			end
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			if ismember(MasstransportAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.accumulation','forcing',1,'NaN',1);
+			end
+			if ismember(BalancethicknessAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.accumulation','size',[md.mesh.numberofvertices 1],'NaN',1);
+			end
+			if ismember(MasstransportAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.evaporation','forcing',1,'NaN',1);
+			end
+			if ismember(BalancethicknessAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.evaporation','size',[md.mesh.numberofvertices 1],'NaN',1);
+			end
+			if ismember(MasstransportAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.refreeze','forcing',1,'NaN',1);
+			end
+			if ismember(BalancethicknessAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.refreeze','size',[md.mesh.numberofvertices 1],'NaN',1);
+			end
+			if ismember(MasstransportAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.melt','forcing',1,'NaN',1);
+			end
+			if ismember(BalancethicknessAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','surfaceforcings.melt','size',[md.mesh.numberofvertices 1],'NaN',1);
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   surface forcings parameters with melt (SMB=accumulation-evaporation-melt+refreeze) :'));
+			fielddisplay(obj,'accumulation','accumulated snow [m/yr ice eq]');
+			fielddisplay(obj,'evaporation','amount of ice lost to evaporative processes [m/yr ice eq]');
+			fielddisplay(obj,'melt','amount of ice melt in ice column [m/yr ice eq]');
+			fielddisplay(obj,'refreeze','amount of ice melt refrozen in ice column [m/yr ice eq]');
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+
+			yts=365.0*24.0*3600.0;
+
+			WriteData(fid,'enum',SurfaceforcingsEnum(),'data',SMBmeltcomponentsEnum(),'format','Integer');
+			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','accumulation','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','evaporation','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','melt','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','refreeze','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+		end % }}}
+	end
+end
Index: issm/trunk/src/m/classes/SMBmeltcomponents.py
===================================================================
--- issm/trunk/src/m/classes/SMBmeltcomponents.py	(revision 18301)
+++ issm/trunk/src/m/classes/SMBmeltcomponents.py	(revision 18301)
@@ -0,0 +1,93 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from project3d import *
+from WriteData import *
+
+class SMBmeltcomponents(object):
+	"""
+	SMBmeltcomponents Class definition
+
+	   Usage:
+	      SMBmeltcomponents=SMBmeltcomponents();
+	"""
+
+	def __init__(self): # {{{
+		self.accumulation = float('NaN')
+		self.runoff = float('NaN')
+		self.evaporation = float('NaN')
+		#}}}
+	def __repr__(self): # {{{
+		string="   surface forcings parameters with melt (SMB=accumulation-evaporation-melt+refreeze) :"
+		string="%s\n%s"%(string,fielddisplay(self,'accumulation','accumulated snow [m/yr ice eq]'))
+		string="%s\n%s"%(string,fielddisplay(self,'evaporation','mount of ice lost to evaporative processes [m/yr ice eq]'))
+		string="%s\n%s"%(string,fielddisplay(self,'melt','amount of ice melt in the ice column [m/yr ice eq]'))
+		string="%s\n%s"%(string,fielddisplay(self,'refreeze','amount of ice melt refrozen in the ice column [m/yr ice eq]'))
+		return string
+		#}}}
+	def extrude(self,md): # {{{
+
+		self.mass_balance=project3d(md,'vector',self.accumulation,'type','node');
+		self.mass_balance=project3d(md,'vector',self.evaporation,'type','node');
+		self.mass_balance=project3d(md,'vector',self.melt,'type','node');
+		self.mass_balance=project3d(md,'vector',self.refreeze,'type','node');
+		return self
+	#}}}
+	def initialize(self,md): # {{{
+
+		if numpy.all(numpy.isnan(self.accumulation)):
+			self.accumulation=numpy.zeros((md.mesh.numberofvertices,1))
+			print "      no SMB.accumulation specified: values set as zero"
+
+		if numpy.all(numpy.isnan(self.evaporation)):
+			self.evaporation=numpy.zeros((md.mesh.numberofvertices,1))
+			print "      no SMB.evaporation specified: values set as zero"
+
+		if numpy.all(numpy.isnan(self.melt)):
+			self.melt=numpy.zeros((md.mesh.numberofvertices,1))
+			print "      no SMB.melt specified: values set as zero"
+
+		if numpy.all(numpy.isnan(self.refreeze)):
+			self.refreeze=numpy.zeros((md.mesh.numberofvertices,1))
+			print "      no SMB.refreeze specified: values set as zero"
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		if MasstransportAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.accumulation','forcing',1,'NaN',1)
+
+		if BalancethicknessAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.accumulation','size',[md.mesh.numberofvertices],'NaN',1)
+
+		if MasstransportAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.melt','forcing',1,'NaN',1)
+
+		if BalancethicknessAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.melt','size',[md.mesh.numberofvertices],'NaN',1)
+
+		if MasstransportAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.refreeze','forcing',1,'NaN',1)
+
+		if BalancethicknessAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.refreeze','size',[md.mesh.numberofvertices],'NaN',1)
+
+		if MasstransportAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.evaporation','forcing',1,'NaN',1)
+
+		if BalancethicknessAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','surfaceforcings.evaporation','size',[md.mesh.numberofvertices],'NaN',1)
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+
+		yts=365.0*24.0*3600.0
+
+		WriteData(fid,'enum',SurfaceforcingsEnum(),'data',SMBmeltcomponentsEnum(),'format','Integer');
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','accumulation','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','evaporation','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','melt','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','refreeze','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+	# }}}
Index: issm/trunk/src/m/classes/balancethickness2.m
===================================================================
--- issm/trunk/src/m/classes/balancethickness2.m	(revision 18081)
+++ issm/trunk/src/m/classes/balancethickness2.m	(revision 18301)
@@ -43,4 +43,9 @@
 			fielddisplay(obj,'spcpotential','potential constraints (NaN means no constraint)');
 			fielddisplay(obj,'apparent_massbalance','Apparent mass balance [m/yr]');
+			fielddisplay(obj,'nux','vx_bar = nux vx_s (in ]0 1])');
+			fielddisplay(obj,'nuy','vy_bar = nuy vy_s (in ]0 1])');
+			fielddisplay(obj,'vx_obs','observed vx');
+			fielddisplay(obj,'vy_obs','observed vy');
+			fielddisplay(obj,'thickness_obs','observed H');
 
 		end % }}}
Index: issm/trunk/src/m/classes/basalforcings.m
===================================================================
--- issm/trunk/src/m/classes/basalforcings.m	(revision 18081)
+++ issm/trunk/src/m/classes/basalforcings.m	(revision 18301)
@@ -6,7 +6,7 @@
 classdef basalforcings
 	properties (SetAccess=public) 
-		melting_rate             = NaN;
-		melting_rate_correction  = NaN;
-		geothermalflux           = NaN;
+		groundedice_melting_rate  = NaN;
+		floatingice_melting_rate  = NaN;
+		geothermalflux            = NaN;
 	end
 	methods
@@ -15,5 +15,4 @@
             fprintf(fid, '%s\n', '<!-- basalforcings -->');
 			 fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="melting_rate" type="',            class(obj.melting_rate),'" default="',              num2str(obj.melting_rate),'">',              '     <section name="basalforcings" />','     <help> basal melting rate (positive if melting) [m/yr] </help>','</parameter>');
-             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="melting_rate_correction" type="', class(obj.melting_rate_correction),'" default="',   num2str(obj.melting_rate_correction),'">',   '     <section name="basalforcings" />','     <help> additional melting applied to compensate for dh/dt [m/yr] </help>','</parameter>');
              fprintf(fid,'%s%s%s%s%s\n%s\n%s\n',        '<parameter key ="geothermalflux" type="',          class(obj.geothermalflux),'" default="',            num2str(obj.geothermalflux),'">',            '     <section name="basalforcings" />','     <help> geothermal heat flux [W/m^2] </help>','</parameter>');
              
@@ -29,7 +28,12 @@
 		function self = initialize(self,md) % {{{
 
-			if isnan(self.melting_rate),
-				self.melting_rate=zeros(md.mesh.numberofvertices,1);
-				disp('      no basalforcings.melting_rate specified: values set as zero');
+			if isnan(self.groundedice_melting_rate),
+				self.groundedice_melting_rate=zeros(md.mesh.numberofvertices,1);
+				disp('      no basalforcings.groundedice_melting_rate specified: values set as zero');
+			end
+
+			if isnan(self.floatingice_melting_rate),
+				self.floatingice_melting_rate=zeros(md.mesh.numberofvertices,1);
+				disp('      no basalforcings.floatingice_melting_rate specified: values set as zero');
 			end
 
@@ -41,11 +45,14 @@
 
 			if ismember(MasstransportAnalysisEnum(),analyses) & ~(solution==TransientSolutionEnum() & md.transient.ismasstransport==0),
-				md = checkfield(md,'fieldname','basalforcings.melting_rate','NaN',1,'forcing',1);
+				md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'forcing',1);
+				md = checkfield(md,'fieldname','basalforcings.floatingice_melting_rate','NaN',1,'forcing',1);
 			end
 			if ismember(BalancethicknessAnalysisEnum(),analyses),
-				md = checkfield(md,'fieldname','basalforcings.melting_rate','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				md = checkfield(md,'fieldname','basalforcings.floatingice_melting_rate','NaN',1,'size',[md.mesh.numberofvertices 1]);
 			end
 			if ismember(ThermalAnalysisEnum(),analyses) & ~(solution==TransientSolutionEnum() & md.transient.isthermal==0),
-				md = checkfield(md,'fieldname','basalforcings.melting_rate','NaN',1,'forcing',1);
+				md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'forcing',1);
+				md = checkfield(md,'fieldname','basalforcings.floatingice_melting_rate','NaN',1,'forcing',1);
 				md = checkfield(md,'fieldname','basalforcings.geothermalflux','NaN',1,'forcing',1,'>=',0);
 			end
@@ -54,6 +61,6 @@
 			disp(sprintf('   basal forcings parameters:'));
 
-			fielddisplay(obj,'melting_rate','basal melting rate (positive if melting) [m/yr]');
-			fielddisplay(obj,'melting_rate_correction','additional melting applied to compensate for dh/dt [m/yr]');
+			fielddisplay(obj,'groundedice_melting_rate','basal melting rate (positive if melting) [m/yr]');
+			fielddisplay(obj,'floatingice_melting_rate','basal melting rate (positive if melting) [m/yr]');
 			fielddisplay(obj,'geothermalflux','geothermal heat flux [W/m^2]');
 
@@ -63,6 +70,7 @@
 			yts=365.0*24.0*3600.0;
 
-			WriteData(fid,'object',obj,'fieldname','melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
-			WriteData(fid,'object',obj,'fieldname','melting_rate_correction','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,'enum',BasalforcingsEnum(),'data',FloatingMeltRateEnum(),'format','Integer');
+			WriteData(fid,'object',obj,'fieldname','groundedice_melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+			WriteData(fid,'object',obj,'fieldname','floatingice_melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
 			WriteData(fid,'object',obj,'fieldname','geothermalflux','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
 		end % }}}
Index: issm/trunk/src/m/classes/basalforcings.py
===================================================================
--- issm/trunk/src/m/classes/basalforcings.py	(revision 18081)
+++ issm/trunk/src/m/classes/basalforcings.py	(revision 18301)
@@ -14,7 +14,7 @@
 
 	def __init__(self): # {{{
-		self.melting_rate             = float('NaN')
-		self.melting_rate_correction  = float('NaN')
-		self.geothermalflux           = float('NaN')
+		self.groundedice_melting_rate  = float('NaN')
+		self.floatingice_melting_rate  = float('NaN')
+		self.geothermalflux            = float('NaN')
 
 		#set defaults
@@ -25,6 +25,6 @@
 		string="   basal forcings parameters:"
 
-		string="%s\n%s"%(string,fielddisplay(self,"melting_rate","basal melting rate (positive if melting) [m/yr]"))
-		string="%s\n%s"%(string,fielddisplay(self,"melting_rate_correction","additional melting applied to compensate for dh/dt [m/yr]"))
+		string="%s\n%s"%(string,fielddisplay(self,"groundedice_melting_rate","basal melting rate (positive if melting) [m/yr]"))
+		string="%s\n%s"%(string,fielddisplay(self,"floatingice_melting_rate","basal melting rate (positive if melting) [m/yr]"))
 		string="%s\n%s"%(string,fielddisplay(self,"geothermalflux","geothermal heat flux [W/m^2]"))
 		return string
@@ -32,7 +32,11 @@
 	def initialize(self,md): # {{{
 
-		if numpy.all(numpy.isnan(self.melting_rate)):
-			self.melting_rate=numpy.zeros((md.mesh.numberofvertices,1))
-			print "      no basalforcings.melting_rate specified: values set as zero"
+		if numpy.all(numpy.isnan(self.groundedice_melting_rate)):
+			self.groundedice_melting_rate=numpy.zeros((md.mesh.numberofvertices,1))
+			print "      no basalforcings.groundedice_melting_rate specified: values set as zero"
+
+		if numpy.all(numpy.isnan(self.floatingice_melting_rate)):
+			self.floatingice_melting_rate=numpy.zeros((md.mesh.numberofvertices,1))
+			print "      no basalforcings.floatingice_melting_rate specified: values set as zero"
 
 		return self
@@ -44,11 +48,14 @@
 
 		if MasstransportAnalysisEnum() in analyses and not (solution==TransientSolutionEnum() and not md.transient.ismasstransport):
-			md = checkfield(md,'fieldname','basalforcings.melting_rate','NaN',1,'forcing',1)
+			md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'forcing',1)
+			md = checkfield(md,'fieldname','basalforcings.floatingice_melting_rate','NaN',1,'forcing',1)
 
 		if BalancethicknessAnalysisEnum() in analyses:
-			md = checkfield(md,'fieldname','basalforcings.melting_rate','NaN',1,'size',[md.mesh.numberofvertices])
+			md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'size',[md.mesh.numberofvertices])
+			md = checkfield(md,'fieldname','basalforcings.floatingice_melting_rate','NaN',1,'size',[md.mesh.numberofvertices])
 
 		if ThermalAnalysisEnum() in analyses and not (solution==TransientSolutionEnum() and not md.transient.isthermal):
-			md = checkfield(md,'fieldname','basalforcings.melting_rate','NaN',1,'forcing',1)
+			md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'forcing',1)
+			md = checkfield(md,'fieldname','basalforcings.floatingice_melting_rate','NaN',1,'forcing',1)
 			md = checkfield(md,'fieldname','basalforcings.geothermalflux','NaN',1,'forcing',1,'>=',0)
 
@@ -59,6 +66,7 @@
 		yts=365.0*24.0*3600.0
 
-		WriteData(fid,'object',self,'fieldname','melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
-		WriteData(fid,'object',self,'fieldname','melting_rate_correction','format','DoubleMat','mattype',1,'scale',1./yts)
+		WriteData(fid,'enum',BasalforcingsEnum(),'data',FloatingMeltRateEnum(),'format','Integer');
+		WriteData(fid,'object',self,'fieldname','groundedice_melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'fieldname','floatingice_melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
 		WriteData(fid,'object',self,'fieldname','geothermalflux','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
 	# }}}
Index: issm/trunk/src/m/classes/clusters/generic.m
===================================================================
--- issm/trunk/src/m/classes/clusters/generic.m	(revision 18081)
+++ issm/trunk/src/m/classes/clusters/generic.m	(revision 18301)
@@ -20,4 +20,5 @@
 		valgrindsup=[issmdir() '/externalpackages/valgrind/issm.supp'];
 		verbose=1;
+		shell='/bin/sh';
 		%}}}
 	end
@@ -70,4 +71,5 @@
 			disp(sprintf('    valgrindsup: %s',cluster.valgrindsup));
 			disp(sprintf('    verbose: %s',cluster.verbose));
+			disp(sprintf('    shell: %s',cluster.shell));
 		end
 		%}}}
@@ -87,9 +89,9 @@
 
 				fid=fopen([modelname '.queue'],'w');
-				fprintf(fid,'#!/bin/sh\n');
+				fprintf(fid,'#!%s\n',cluster.shell);
 				if ~isvalgrind,
 					if cluster.interactive
 						if IssmConfig('_HAVE_MPI_'),
-							fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s ',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
+							fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s \n',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
 						else
 							fprintf(fid,'%s/issm.exe %s %s %s ',cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
@@ -202,4 +204,12 @@
 
 			if ~ispc,
+
+				%figure out what shell extension we will use:
+				if isempty(strfind(cluster.shell,'csh')),
+					shellext='sh';
+				else
+					shellext='csh';
+				end
+
 				%compress the files into one zip.
 				compressstring=['tar -zcf ' dirname '.tar.gz '];
@@ -216,5 +226,5 @@
 
 				if cluster.verbose, disp('launching solution sequence on remote cluster'); end
-				launchcommand=['source ' cluster.etcpath '/environment.sh && cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
+				launchcommand=['source ' cluster.etcpath '/environment.' shellext ' && cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
 					' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && source  ' modelname '.queue '];
 				issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
Index: issm/trunk/src/m/classes/damage.m
===================================================================
--- issm/trunk/src/m/classes/damage.m	(revision 18081)
+++ issm/trunk/src/m/classes/damage.m	(revision 18301)
@@ -9,80 +9,80 @@
 		isdamage            = 0;
 		D                   = NaN;
-		law                 = '';
+		law                 = 0;
 		spcdamage           = NaN; 
-		max_damage          = NaN;
+		max_damage          = 0;
 	
 		%numerical
-		stabilization       = NaN;
-		maxiter             = NaN;
+		stabilization       = 0;
+		maxiter             = 0;
 		elementinterp       = '';
-		penalty_threshold   = NaN;
-		penalty_lock        = NaN;
-		penalty_factor      = NaN;
+		penalty_threshold   = 0;
+		penalty_lock        = 0;
+		penalty_factor      = 0;
 		
 		%general parameters for evolution law: 
-		stress_threshold    = NaN;
-		c1                  = NaN;
-		c2                  = NaN;
-		c3                  = NaN;
-		c4                  = NaN;
-		healing             = NaN;
-		equiv_stress		  = NaN;
+		stress_threshold    = 0;
+		c1                  = 0;
+		c2                  = 0;
+		c3                  = 0;
+		c4                  = 0;
+		healing             = 0;
+		equiv_stress		  = 0;
 		requested_outputs   = {};
 	end
 	methods
-        function createxml(obj,fid) % {{{
-            fprintf(fid, '\n\n');
-            fprintf(fid, '%s\n', '<!-- damage -->');
-            fprintf(fid, '%s\n', '<!-- Note: this class depends on different input of law -->');
-            
-            %fprintf(fid,'%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="law" type="logical"',           '" default="',                num2str(obj.law),'">',   '     <section name="damage" />','     <help> damage law (string) from {"undamaged","pralong"} </help>','</parameter>');
-            % drop-down 
-            fprintf(fid,'%s%s%s%s%s\n\t%s\n','<parameter key ="law" type="','alternative','" optional="','false','">','<section name="damage" />');
-            
-            % law = 'undamage'
-            fprintf(fid,'\t%s%s%s%s%s\n\t\t%s\n','<option value="undamage" type="','string','" default="','true','">','<help> law = undamage </help>');
-            % footer for option
-            fprintf(fid,'\t%s\n%s\n','</option>');
-            
-            % law = 'pralong'
-            fprintf(fid,'\t%s%s%s%s%s\n\t\t%s\n','<option value="pralong" type="','string','" default="','false','">','<help> law = pralong </help>');
-                
-            fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',   '<parameter key ="stress_threshold" type="',class(obj.stress_threshold),'" default="',num2str(obj.stress_threshold),'">','<help> damage stress threshold [Pa] </help>','</parameter>');
-            fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',	'<parameter key ="c1" type="', class(obj.c1),'" default="',   num2str(obj.c1),'">',   '<help> damage parameter 1 </help>','</parameter>');
-            fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',  	'<parameter key ="c2" type="',          class(obj.c2),'" default="',            num2str(obj.c2),'">','<help> damage parameter 2 </help>','</parameter>');
-            fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',  	'<parameter key ="c3" type="',          class(obj.c3),'" default="',            num2str(obj.c3),'">','<help> damage parameter 3 [W/m^2] </help>','</parameter>');
-            fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',  	'<parameter key ="c4" type="',            class(obj.c4),'" default="',              num2str(obj.c4),'">','<help> damage parameter 4 </help>','</parameter>');
-            fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',  	'<parameter key ="healing" type="', class(obj.healing),'" default="',   num2str(obj.healing),'">','<help> damage healing parameter 1 </help>','</parameter>');
-            fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',  	'<parameter key ="equiv_stress" type="',          class(obj.equiv_stress),'" default="',convert2str(obj.equiv_stress),'">','<help> 0: von Mises </help>','</parameter>');
-            fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',  	'<parameter key ="requested_outputs" type="',          class(obj.requested_outputs),'" default="',convert2str(obj.requested_outputs),'">','<help> additional outputs requested </help>','</parameter>');
-             
-                
-            % footer for option
-            fprintf(fid,'\t%s\n%s\n','</option>');
-                 
-            
-            % footer for drop-down
-            fprintf(fid,'\t%s\n%s\n%s','<help> damage law (string) from {"undamaged","pralong"} </help>','</parameter>');
-            
-            
+		function createxml(obj,fid) % {{{
+			fprintf(fid, '\n\n');
+			fprintf(fid, '%s\n', '<!-- damage -->');
+			fprintf(fid, '%s\n', '<!-- Note: this class depends on different input of law -->');
+
+			%fprintf(fid,'%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="law" type="logical"',           '" default="',                num2str(obj.law),'">',   '     <section name="damage" />','     <help> damage law (string) from {"undamaged","pralong"} </help>','</parameter>');
+			% drop-down 
+			fprintf(fid,'%s%s%s%s%s\n\t%s\n','<parameter key ="law" type="','alternative','" optional="','false','">','<section name="damage" />');
+
+			% law = 'undamage'
+			fprintf(fid,'\t%s%s%s%s%s\n\t\t%s\n','<option value="undamage" type="','string','" default="','true','">','<help> law = undamage </help>');
+			% footer for option
+			fprintf(fid,'\t%s\n%s\n','</option>');
+
+			% law = 'pralong'
+			fprintf(fid,'\t%s%s%s%s%s\n\t\t%s\n','<option value="pralong" type="','string','" default="','false','">','<help> law = pralong </help>');
+
+			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',   '<parameter key ="stress_threshold" type="',class(obj.stress_threshold),'" default="',num2str(obj.stress_threshold),'">','<help> damage stress threshold [Pa] </help>','</parameter>');
+			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',	'<parameter key ="c1" type="', class(obj.c1),'" default="',   num2str(obj.c1),'">',   '<help> damage parameter 1 </help>','</parameter>');
+			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',  	'<parameter key ="c2" type="',          class(obj.c2),'" default="',            num2str(obj.c2),'">','<help> damage parameter 2 </help>','</parameter>');
+			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',  	'<parameter key ="c3" type="',          class(obj.c3),'" default="',            num2str(obj.c3),'">','<help> damage parameter 3 [W/m^2] </help>','</parameter>');
+			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',  	'<parameter key ="c4" type="',            class(obj.c4),'" default="',              num2str(obj.c4),'">','<help> damage parameter 4 </help>','</parameter>');
+			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',  	'<parameter key ="healing" type="', class(obj.healing),'" default="',   num2str(obj.healing),'">','<help> damage healing parameter 1 </help>','</parameter>');
+			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',  	'<parameter key ="equiv_stress" type="',          class(obj.equiv_stress),'" default="',convert2str(obj.equiv_stress),'">','<help> 0: von Mises </help>','</parameter>');
+			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',  	'<parameter key ="requested_outputs" type="',          class(obj.requested_outputs),'" default="',convert2str(obj.requested_outputs),'">','<help> additional outputs requested </help>','</parameter>');
+
+
+			% footer for option
+			fprintf(fid,'\t%s\n%s\n','</option>');
+
+
+			% footer for drop-down
+			fprintf(fid,'\t%s\n%s\n%s','<help> damage law (string) from {"undamaged","pralong"} </help>','</parameter>');
+
+
 			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="D" type="',              class(obj.D),'" default="',                  num2str(obj.D),'">',              '     <section name="damage" />','     <help> damage tensor (scalar) </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="law" type="',            class(obj.law),'" default="',                num2str(obj.law),'">',   '     <section name="damage" />','     <help> damage law (string) from {"undamaged","pralong"} </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="spcdamage" type="',      class(obj.spcdamage),'" default="',          num2str(obj.spcdamage),'">',            '     <section name="damage" />','     <help> damage constraints (NaN means no constraint) </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="max_damage" type="',     class(obj.max_damage),'" default="',         num2str(obj.max_damage),'">',            '     <section name="damage" />','     <help> maximum possible damage (0&amp;lt;=max_damage&amp;lt;1) </help>','</parameter>');
-             
-            % stabilization (0,1, or 2) drop-down
-            fprintf(fid,'%s\n%s\n%s\n%s\n',    '<parameter key ="stabilization" type="alternative" optional="false">','     <section name="damage" />','     <help> 0: no, 1: artificial_diffusivity, 2: SUPG </help>');
-            fprintf(fid, '%s\n', '       <option value="0" type="string" default="true"></option>');
-            fprintf(fid, '%s\n', '       <option value="1" type="string" default="false"></option>');
-            fprintf(fid, '%s\n', '       <option value="2" type="string" default="false"></option>');
-            fprintf(fid, '%s\n','</parameter>');
-            
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="maxiter" type="',             class(obj.maxiter),'" default="',   num2str(obj.maxiter),'">',   '     <section name="damage" />','     <help> maximum number of non linear iterations </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="penalty_lock" type="',        class(obj.penalty_lock),'" default="',            num2str(obj.penalty_lock),'">',            '     <section name="damage" />','     <help> stabilize unstable damage constraints that keep zigzagging after n iteration (default is 0, no stabilization) </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="penalty_threshold" type="',   class(obj.penalty_threshold),'" default="',            num2str(obj.penalty_threshold),'">',            '     <section name="damage" />','     <help> threshold to declare convergence of damage evolution solution (default is 0) </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="penalty_factor" type="',      class(obj.penalty_factor),'" default="',            num2str(obj.penalty_factor),'">',            '     <section name="damage" />','     <help> scaling exponent (default is 3) </help>','</parameter>');
- 
-        end % }}}
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="law" type="',            class(obj.law),'" default="',                num2str(obj.law),'">',   '     <section name="damage" />','     <help> damage law (string) from {"undamaged","pralong"} </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="spcdamage" type="',      class(obj.spcdamage),'" default="',          num2str(obj.spcdamage),'">',            '     <section name="damage" />','     <help> damage constraints (NaN means no constraint) </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="max_damage" type="',     class(obj.max_damage),'" default="',         num2str(obj.max_damage),'">',            '     <section name="damage" />','     <help> maximum possible damage (0&amp;lt;=max_damage&amp;lt;1) </help>','</parameter>');
+
+			% stabilization (0,1, or 2) drop-down
+			fprintf(fid,'%s\n%s\n%s\n%s\n',    '<parameter key ="stabilization" type="alternative" optional="false">','     <section name="damage" />','     <help> 0: no, 1: artificial_diffusivity, 2: SUPG </help>');
+			fprintf(fid, '%s\n', '       <option value="0" type="string" default="true"></option>');
+			fprintf(fid, '%s\n', '       <option value="1" type="string" default="false"></option>');
+			fprintf(fid, '%s\n', '       <option value="2" type="string" default="false"></option>');
+			fprintf(fid, '%s\n','</parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="maxiter" type="',             class(obj.maxiter),'" default="',   num2str(obj.maxiter),'">',   '     <section name="damage" />','     <help> maximum number of non linear iterations </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="penalty_lock" type="',        class(obj.penalty_lock),'" default="',            num2str(obj.penalty_lock),'">',            '     <section name="damage" />','     <help> stabilize unstable damage constraints that keep zigzagging after n iteration (default is 0, no stabilization) </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="penalty_threshold" type="',   class(obj.penalty_threshold),'" default="',            num2str(obj.penalty_threshold),'">',            '     <section name="damage" />','     <help> threshold to declare convergence of damage evolution solution (default is 0) </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="penalty_factor" type="',      class(obj.penalty_factor),'" default="',            num2str(obj.penalty_factor),'">',            '     <section name="damage" />','     <help> scaling exponent (default is 3) </help>','</parameter>');
+
+		end % }}}
         
 		function obj = damage(varargin) % {{{
@@ -109,5 +109,5 @@
 			obj.isdamage=0;
 			obj.D=0;
-			obj.law='undamaged';
+			obj.law=0;
 			
 			obj.max_damage=1-1e-5; %if damage reaches 1, solve becomes singular, as viscosity becomes nil
@@ -148,5 +148,5 @@
 			md = checkfield(md,'fieldname','damage.isdamage','values',[1,0]);
 			if obj.isdamage,
-				md = checkfield(md,'fieldname','damage.law','values',{'undamaged','pralong'});
+				md = checkfield(md,'fieldname','damage.law','numel',[1],'values',[0,1,2]);
 				md = checkfield(md,'fieldname','damage.D','>=',0,'<=',obj.max_damage,'size',[md.mesh.numberofvertices 1]);
 				md = checkfield(md,'fieldname','damage.spcdamage','forcing',1);
@@ -155,10 +155,7 @@
 				md = checkfield(md,'fieldname','damage.maxiter','>=0',0);
 				md = checkfield(md,'fieldname','damage.elementinterp','values',{'P1','P2'});
-				md = checkfield(md,'fieldname','damage.penalty_factor','>=0',0);
-				md = checkfield(md,'fieldname','damage.penalty_lock','>=0',0);
-				md = checkfield(md,'fieldname','damage.penalty_threshold','>=0',0);
-			end
-
-			if strcmpi(obj.law,'pralong'),
+				md = checkfield(md,'fieldname','damage.penalty_factor','>=',0);
+				md = checkfield(md,'fieldname','damage.penalty_lock','>=',0);
+				md = checkfield(md,'fieldname','damage.penalty_threshold','>=',0);
 				md = checkfield(md,'fieldname','damage.healing','>=',0);
 				md = checkfield(md,'fieldname','damage.c1','>=',0);
@@ -169,12 +166,9 @@
 				md = checkfield(md,'fieldname','damage.equiv_stress','numel',[1],'values',[0 1]);
 				md = checkfield(md,'fieldname','damage.requested_outputs','stringrow',1);
-			elseif strcmpi(obj.law,'undamaged'),
+			elseif (obj.law~=0),
 				if (solution==DamageEvolutionSolutionEnum),
 					error('Invalid evolution law (md.damage.law) for a damage solution');
 				end
-			else 
-				error('invalid damage evolution law');
-			end
-
+			end
 		end % }}}
 		function list=defaultoutputs(self,md) % {{{
@@ -191,5 +185,5 @@
 			fielddisplay(obj,'isdamage','is damage mechanics being used? {true,false}');
 			if obj.isdamage,
-				fielddisplay(obj,'law','damage law (string) from {''undamaged'',''pralong''}');
+				fielddisplay(obj,'law','damage law {''0: undamaged'',''1: pralong''}');
 				fielddisplay(obj,'D','damage tensor (scalar)');
 				fielddisplay(obj,'spcdamage','damage constraints (NaN means no constraint)');
@@ -202,7 +196,4 @@
 				fielddisplay(obj,'penalty_threshold','threshold to declare convergence of damage evolution solution (default is 0)');
 				fielddisplay(obj,'penalty_factor','scaling exponent (default is 3)');
-			end
-
-			if strcmpi(obj.law,'pralong'),
 				fielddisplay(obj,'c1','damage parameter 1');
 				fielddisplay(obj,'c2','damage parameter 2');
@@ -220,5 +211,5 @@
 			WriteData(fid,'object',obj,'fieldname','isdamage','format','Boolean');
 			if obj.isdamage,
-				WriteData(fid,'object',obj,'fieldname','law','format','String');
+				WriteData(fid,'object',obj,'fieldname','law','format','Integer');
 				WriteData(fid,'object',obj,'fieldname','D','format','DoubleMat','mattype',1);
 				WriteData(fid,'object',obj,'fieldname','spcdamage','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
@@ -227,11 +218,8 @@
 				WriteData(fid,'object',obj,'fieldname','stabilization','format','Integer');
 				WriteData(fid,'object',obj,'fieldname','maxiter','format','Integer');
-				WriteData(fid,'object',obj,'fieldname','elementinterp','format','String');
+				WriteData(fid,'enum',DamageElementinterpEnum(),'data',StringToEnum(obj.elementinterp),'format','Integer');
 				WriteData(fid,'object',obj,'fieldname','penalty_threshold','format','Integer');
 				WriteData(fid,'object',obj,'fieldname','penalty_lock','format','Integer');
 				WriteData(fid,'object',obj,'fieldname','penalty_factor','format','Double');
-			end
-	
-			if strcmpi(obj.law,'pralong'),
 				WriteData(fid,'object',obj,'fieldname','c1','format','Double');
 				WriteData(fid,'object',obj,'fieldname','c2','format','Double');
Index: issm/trunk/src/m/classes/damage.py
===================================================================
--- issm/trunk/src/m/classes/damage.py	(revision 18081)
+++ issm/trunk/src/m/classes/damage.py	(revision 18301)
@@ -19,5 +19,5 @@
 		self.isdamage           = 0.
 		self.D						= float('NaN')
-		self.law						= ''
+		self.law						= float('NaN')
 		self.spcdamage				= float('NaN')
 		self.max_damage			= float('NaN')
@@ -53,5 +53,5 @@
 		if self.isdamage:
 			s+="%s\n" % fielddisplay(self,"D","damage tensor (scalar for now)")
-			s+="%s\n" % fielddisplay(self,"law","damage law (string) from ['undamaged','pralong']")
+			s+="%s\n" % fielddisplay(self,"law","damage law ['0: undamaged','1: pralong']")
 			s+="%s\n" % fielddisplay(self,"spcdamage","damage constraints (NaN means no constraint)")
 			s+="%s\n" % fielddisplay(self,"max_damage","maximum possible damage (0<=max_damage<1)")
@@ -63,6 +63,4 @@
 			s+="%s\n" % fielddisplay(self,"penalty_threshold","threshold to declare convergence of damage evolution solution (default is 0)")
 			s+="%s\n" % fielddisplay(self,"penalty_factor","scaling exponent (default is 3)")
-
-		if (self.law=='pralong'):
 			s+="%s\n" % fielddisplay(self,"c1","damage parameter 1 ")
 			s+="%s\n" % fielddisplay(self,"c2","damage parameter 2 ")
@@ -81,5 +79,5 @@
 		self.isdamage=0
 		self.D=0
-		self.law='undamaged'
+		self.law=0
 
 		self.max_damage=1-1e-5 #if damage reaches 1, solve becomes singular, as viscosity becomes nil
@@ -132,5 +130,5 @@
 			md = checkfield(md,'fieldname','damage.D','>=',0,'<=',self.max_damage,'size',[md.mesh.numberofvertices])
 			md = checkfield(md,'fieldname','damage.max_damage','<',1,'>=',0)
-			md = checkfield(md,'fieldname','damage.law','values',['undamaged','pralong'])
+			md = checkfield(md,'fieldname','damage.law','numel',[1],'values',[0,1,2,3])
 			md = checkfield(md,'fieldname','damage.spcdamage','forcing',1)
 			md = checkfield(md,'fieldname','damage.stabilization','numel',[1],'values',[0,1,2])
@@ -140,6 +138,4 @@
 			md = checkfield(md,'fieldname','damage.penalty_lock','>=0',0)
 			md = checkfield(md,'fieldname','damage.penalty_threshold','>=0',0)
-
-		if self.law == 'pralong':
 			md = checkfield(md,'fieldname','damage.healing','>=',0)
 			md = checkfield(md,'fieldname','damage.c1','>=',0)
@@ -151,5 +147,5 @@
 			md = checkfield(md,'fieldname','damage.equiv_stress','numel',[1],'values',[0,1])
 			md = checkfield(md,'fieldname','damage.requested_outputs','stringrow',1)
-		elif m.strcmpi(self.law,'undamaged'):
+		elif self.law != 0:
 			if (solution==DamageEvolutionSolutionEnum):
 				raise RuntimeError('Invalid evolution law (md.damage.law) for a damage solution')
@@ -162,15 +158,13 @@
 		if self.isdamage:
 			WriteData(fid,'object',self,'fieldname','D','format','DoubleMat','mattype',1)
-			WriteData(fid,'object',self,'fieldname','law','format','String')
+			WriteData(fid,'object',self,'fieldname','law','format','Integer')
 			WriteData(fid,'object',self,'fieldname','spcdamage','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
 			WriteData(fid,'object',self,'fieldname','max_damage','format','Double')
 			WriteData(fid,'object',self,'fieldname','stabilization','format','Integer')
-			WriteData(fid,'object',self,'fieldname','elementinterp','format','String')
+			WriteData(fid,'object',self,'fieldname','maxiter','format','Integer')
+			WriteData(fid,'enum',DamageElementinterpEnum(),'data',StringToEnum(self.elementinterp)[0],'format','Integer')
 			WriteData(fid,'object',self,'fieldname','penalty_threshold','format','Integer')
-			WriteData(fid,'object',self,'fieldname','maxiter','format','Integer')
 			WriteData(fid,'object',self,'fieldname','penalty_lock','format','Integer')
 			WriteData(fid,'object',self,'fieldname','penalty_factor','format','Double')
-
-		if self.law=='pralong':
 			WriteData(fid,'object',self,'fieldname','c1','format','Double')
 			WriteData(fid,'object',self,'fieldname','c2','format','Double')
Index: issm/trunk/src/m/classes/flowequation.m
===================================================================
--- issm/trunk/src/m/classes/flowequation.m	(revision 18081)
+++ issm/trunk/src/m/classes/flowequation.m	(revision 18301)
@@ -6,19 +6,22 @@
 classdef flowequation
 	properties (SetAccess=public) 
-		isSIA            = 0;
-		isSSA            = 0;
-		isL1L2           = 0;
-		isHO             = 0;
-		isFS             = 0;
-		fe_SSA           = '';
-		fe_HO            = '';
-		fe_FS            = '';
-		XTH_r            = 1.;
-		XTH_theta        = 0.;
-		vertex_equation  = NaN;
-		element_equation = NaN;
-		borderSSA        = NaN;
-		borderHO         = NaN;
-		borderFS         = NaN;
+		isSIA                          = 0;
+		isSSA                          = 0;
+		isL1L2                         = 0;
+		isHO                           = 0;
+		isFS                           = 0;
+		fe_SSA                         = '';
+		fe_HO                          = '';
+		fe_FS                          = '';
+		augmented_lagrangian_r         = 1.;
+		augmented_lagrangian_rhop      = 1.;
+		augmented_lagrangian_rlambda   = 1.;
+		augmented_lagrangian_rholambda = 1.;
+		XTH_theta                      = 0.;
+		vertex_equation                = NaN;
+		element_equation               = NaN;
+		borderSSA                      = NaN;
+		borderHO                       = NaN;
+		borderFS                       = NaN;
 	end
 	methods (Static)
@@ -59,49 +62,49 @@
 	end
 	methods
-        function createxml(obj,fid) % {{{
-            fprintf(fid, '\n\n');
-            fprintf(fid, '%s\n', '<!-- flowequation -->');
-            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Flow equation parameters">','<section name="flowequation" />');                    
-            
+		function createxml(obj,fid) % {{{
+			fprintf(fid, '\n\n');
+			fprintf(fid, '%s\n', '<!-- flowequation -->');
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Flow equation parameters">','<section name="flowequation" />');                    
+
 			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="isSIA" type="',              class(obj.isSIA),'" default="',                  convert2str(obj.isSIA),'">',              '     <section name="flowequation" />','     <help> is the Shallow Ice Approximation (SIA) used ? </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="isSSA" type="',            class(obj.isSSA),'" default="',                convert2str(obj.isSSA),'">',   '     <section name="flowequation" />','     <help> is the Shelfy-Stream Approximation (SSA) used ? </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="isL1L2" type="',      class(obj.isL1L2),'" default="',          convert2str(obj.isL1L2),'">',            '     <section name="flowequation" />','     <help> is the L1L2 approximation used ? </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="isHO" type="',     class(obj.isHO),'" default="',         convert2str(obj.isHO),'">',            '     <section name="flowequation" />','     <help> is the Higher-Order (HO) approximation used ? </help>','</parameter>');
-            
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="isFS" type="',       class(obj.isFS),'" default="',              convert2str(obj.isFS),'">',              '     <section name="flowequation" />','     <help> are the Full-FS (FS) equations used ? </help>','</parameter>');
-            
-            % fe_SSA drop-down (P1, P1bubble, P1bubblecondensed, P2)
-            fprintf(fid,'%s\n%s\n%s\n%s\n',    '<parameter key ="fe_SSA" type="alternative" optional="false">','     <section name="flowequation" />','     <help> Finite Element for SSA  "P1", "P1bubble" "P1bubblecondensed" "P2" </help>');
-            fprintf(fid,'%s\n','       <option value="P1" type="string" default="true"> </option>');
-            fprintf(fid,'%s\n','       <option value="P1bubble" type="string" default="false"> </option>');
-            fprintf(fid,'%s\n','       <option value="P1bubblecondensed" type="string" default="false"> </option>');
-            fprintf(fid,'%s\n%s\n','       <option value="P2" type="string" default="false"> </option>','</parameter>');
-            
-            %fe_HO drop-down (P1, P1bubble, P1bubblecondensed, P1xP2, P2xP1, P2)
-            fprintf(fid,'%s\n%s\n%s\n%s\n',        '<parameter key ="fe_HO" type="alternative" optional="false">','     <section name="flowequation" />','     <help> Finite Element for HO   "P1" "P1bubble" "P1bubblecondensed" "P1xP2" "P2xP1" "P2" </help>');
-            fprintf(fid,'%s\n','       <option value="P1" type="string" default="true"> </option>');
-            fprintf(fid,'%s\n','       <option value="P1bubble" type="string" default="false"> </option>');
-            fprintf(fid,'%s\n','       <option value="P1bubblecondensed" type="string" default="false"> </option>');
-            fprintf(fid,'%s\n','       <option value="P1xP2" type="string" default="false"> </option>');
-            fprintf(fid,'%s\n','       <option value="P2xP1" type="string" default="false"> </option>');
-            fprintf(fid,'%s\n%s\n','       <option value="P2" type="string" default="false"> </option>','</parameter>');
-            
-            % fe_FS drop-down (P1P1, P1P1GLS, MINIcondensed, MINI, TaylowHood)
-            fprintf(fid,'%s\n%s\n%s\n%s\n',        '<parameter key ="fe_FS" type="alternative" optional="false">','     <section name="flowequation" />','     <help> Finite Element for FS   "P1P1" (debugging only) "P1P1GLS" "MINIcondensed" "MINI" "TaylorHood" </help>');
-            fprintf(fid,'%s\n','       <option value="P1P1" type="string" default="true"> </option>');
-            fprintf(fid,'%s\n','       <option value="P1P1GLS" type="string" default="false"> </option>');
-            fprintf(fid,'%s\n','       <option value="MINIcondensed" type="string" default="false"> </option>');
-            fprintf(fid,'%s\n','       <option value="MINI" type="string" default="false"> </option>');
-            fprintf(fid,'%s\n%s\n','       <option value="TaylorHood" type="string" default="false"> </option>','</parameter>');
-            
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="vertex_equation" type="',      class(obj.vertex_equation),'" default="',            convert2str(obj.vertex_equation),'">',            '     <section name="flowequation" />','     <help> flow equation for each vertex </help>','</parameter>');
-       
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="element_equation" type="',            class(obj.element_equation),'" default="',              convert2str(obj.element_equation),'">',              '     <section name="flowequation" />','     <help> flow equation for each element </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="borderSSA" type="', class(obj.borderSSA),'" default="',   convert2str(obj.borderSSA),'">',   '     <section name="flowequation" />','     <help> vertices on SSAs border (for tiling) </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="borderHO" type="',          class(obj.borderHO),'" default="',            convert2str(obj.borderHO),'">',            '     <section name="flowequation" />','     <help> vertices on HOs border (for tiling) </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n',        '<parameter key ="borderFS" type="',          class(obj.borderFS),'" default="',            convert2str(obj.borderFS),'">',            '     <section name="flowequation" />','     <help> vertices on FS border (for tiling) </help>','</parameter>');
-      
-            fprintf(fid,'%s\n%s\n','</frame>');
-        end % }}}
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="isSSA" type="',            class(obj.isSSA),'" default="',                convert2str(obj.isSSA),'">',   '     <section name="flowequation" />','     <help> is the Shelfy-Stream Approximation (SSA) used ? </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="isL1L2" type="',      class(obj.isL1L2),'" default="',          convert2str(obj.isL1L2),'">',            '     <section name="flowequation" />','     <help> is the L1L2 approximation used ? </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="isHO" type="',     class(obj.isHO),'" default="',         convert2str(obj.isHO),'">',            '     <section name="flowequation" />','     <help> is the Higher-Order (HO) approximation used ? </help>','</parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="isFS" type="',       class(obj.isFS),'" default="',              convert2str(obj.isFS),'">',              '     <section name="flowequation" />','     <help> are the Full-FS (FS) equations used ? </help>','</parameter>');
+
+			% fe_SSA drop-down (P1, P1bubble, P1bubblecondensed, P2)
+			fprintf(fid,'%s\n%s\n%s\n%s\n',    '<parameter key ="fe_SSA" type="alternative" optional="false">','     <section name="flowequation" />','     <help> Finite Element for SSA  "P1", "P1bubble" "P1bubblecondensed" "P2" </help>');
+			fprintf(fid,'%s\n','       <option value="P1" type="string" default="true"> </option>');
+			fprintf(fid,'%s\n','       <option value="P1bubble" type="string" default="false"> </option>');
+			fprintf(fid,'%s\n','       <option value="P1bubblecondensed" type="string" default="false"> </option>');
+			fprintf(fid,'%s\n%s\n','       <option value="P2" type="string" default="false"> </option>','</parameter>');
+
+			%fe_HO drop-down (P1, P1bubble, P1bubblecondensed, P1xP2, P2xP1, P2)
+			fprintf(fid,'%s\n%s\n%s\n%s\n',        '<parameter key ="fe_HO" type="alternative" optional="false">','     <section name="flowequation" />','     <help> Finite Element for HO   "P1" "P1bubble" "P1bubblecondensed" "P1xP2" "P2xP1" "P2" </help>');
+			fprintf(fid,'%s\n','       <option value="P1" type="string" default="true"> </option>');
+			fprintf(fid,'%s\n','       <option value="P1bubble" type="string" default="false"> </option>');
+			fprintf(fid,'%s\n','       <option value="P1bubblecondensed" type="string" default="false"> </option>');
+			fprintf(fid,'%s\n','       <option value="P1xP2" type="string" default="false"> </option>');
+			fprintf(fid,'%s\n','       <option value="P2xP1" type="string" default="false"> </option>');
+			fprintf(fid,'%s\n%s\n','       <option value="P2" type="string" default="false"> </option>','</parameter>');
+
+			% fe_FS drop-down (P1P1, P1P1GLS, MINIcondensed, MINI, TaylowHood)
+			fprintf(fid,'%s\n%s\n%s\n%s\n',        '<parameter key ="fe_FS" type="alternative" optional="false">','     <section name="flowequation" />','     <help> Finite Element for FS   "P1P1" (debugging only) "P1P1GLS" "MINIcondensed" "MINI" "TaylorHood" </help>');
+			fprintf(fid,'%s\n','       <option value="P1P1" type="string" default="true"> </option>');
+			fprintf(fid,'%s\n','       <option value="P1P1GLS" type="string" default="false"> </option>');
+			fprintf(fid,'%s\n','       <option value="MINIcondensed" type="string" default="false"> </option>');
+			fprintf(fid,'%s\n','       <option value="MINI" type="string" default="false"> </option>');
+			fprintf(fid,'%s\n%s\n','       <option value="TaylorHood" type="string" default="false"> </option>','</parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="vertex_equation" type="',      class(obj.vertex_equation),'" default="',            convert2str(obj.vertex_equation),'">',            '     <section name="flowequation" />','     <help> flow equation for each vertex </help>','</parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="element_equation" type="',            class(obj.element_equation),'" default="',              convert2str(obj.element_equation),'">',              '     <section name="flowequation" />','     <help> flow equation for each element </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="borderSSA" type="', class(obj.borderSSA),'" default="',   convert2str(obj.borderSSA),'">',   '     <section name="flowequation" />','     <help> vertices on SSAs border (for tiling) </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="borderHO" type="',          class(obj.borderHO),'" default="',            convert2str(obj.borderHO),'">',            '     <section name="flowequation" />','     <help> vertices on HOs border (for tiling) </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n',        '<parameter key ="borderFS" type="',          class(obj.borderFS),'" default="',            convert2str(obj.borderFS),'">',            '     <section name="flowequation" />','     <help> vertices on FS border (for tiling) </help>','</parameter>');
+
+			fprintf(fid,'%s\n%s\n','</frame>');
+		end % }}}
 		function obj = flowequation(varargin) % {{{
 			switch nargin
@@ -132,8 +135,11 @@
 				md = checkfield(md,'fieldname','flowequation.isHO','numel',[1],'values',[0 1]);
 				md = checkfield(md,'fieldname','flowequation.isFS','numel',[1],'values',[0 1]);
-				md = checkfield(md,'fieldname','flowequation.fe_SSA','values',{'P1','P1bubble','P1bubblecondensed','P2'});
-				md = checkfield(md,'fieldname','flowequation.fe_HO' ,'values',{'P1','P1bubble','P1bubblecondensed','P1xP2','P2xP1','P2','P1xP3','P2xP4'});
-				md = checkfield(md,'fieldname','flowequation.fe_FS' ,'values',{'P1P1','P1P1GLS','MINIcondensed','MINI','TaylorHood','XTaylorHood','OneLayerP4z'});
-				md = checkfield(md,'fieldname','flowequation.XTH_r','numel',[1],'>',0.);
+				md = checkfield(md,'fieldname','flowequation.fe_SSA','values',{'P1','P1bubble','P1bubblecondensed','P2','P2bubble'});
+				md = checkfield(md,'fieldname','flowequation.fe_HO' ,'values',{'P1','P1bubble','P1bubblecondensed','P1xP2','P2xP1','P2','P2bubble','P1xP3','P2xP4'});
+				md = checkfield(md,'fieldname','flowequation.fe_FS' ,'values',{'P1P1','P1P1GLS','MINIcondensed','MINI','TaylorHood','LATaylorHood','XTaylorHood','OneLayerP4z','CrouzeixRaviart'});
+				md = checkfield(md,'fieldname','flowequation.augmented_lagrangian_r','numel',[1],'>',0.);
+				md = checkfield(md,'fieldname','flowequation.augmented_lagrangian_rlambda','numel',[1],'>',0.);
+				md = checkfield(md,'fieldname','flowequation.augmented_lagrangian_rhop','numel',[1],'>',0.);
+				md = checkfield(md,'fieldname','flowequation.augmented_lagrangian_rholambda','numel',[1],'>',0.);
 				md = checkfield(md,'fieldname','flowequation.XTH_theta','numel',[1],'>=',0.,'<',0.5);
 				md = checkfield(md,'fieldname','flowequation.borderSSA','size',[md.mesh.numberofvertices 1],'values',[0 1]);
@@ -144,6 +150,6 @@
 					md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements 1],'values',[1:2]);
 				elseif strcmp(domaintype(md.mesh),'2Dvertical')
-					md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices 1],'values',[2:4]);
-					md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements 1],'values',[2:4]);
+					md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices 1],'values',[2,4,5]);
+					md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements 1],'values',[2,4,5]);
 				elseif strcmp(domaintype(md.mesh),'3D'),
 					md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices 1],'values',[0:8]);
@@ -192,5 +198,8 @@
 			WriteData(fid,'enum',FlowequationFeHOEnum() ,'data',StringToEnum(obj.fe_HO) ,'format','Integer');
 			WriteData(fid,'enum',FlowequationFeFSEnum() ,'data',StringToEnum(obj.fe_FS) ,'format','Integer');
-			WriteData(fid,'enum',AugmentedLagrangianREnum() ,'data',obj.XTH_r ,'format','Double');
+			WriteData(fid,'enum',AugmentedLagrangianREnum(),'data',obj.augmented_lagrangian_r ,'format','Double');
+			WriteData(fid,'enum',AugmentedLagrangianRhopEnum(),'data',obj.augmented_lagrangian_rhop ,'format','Double');
+			WriteData(fid,'enum',AugmentedLagrangianRlambdaEnum(),'data',obj.augmented_lagrangian_rlambda ,'format','Double');
+			WriteData(fid,'enum',AugmentedLagrangianRholambdaEnum(),'data',obj.augmented_lagrangian_rholambda ,'format','Double');
 			WriteData(fid,'enum',AugmentedLagrangianThetaEnum() ,'data',obj.XTH_theta ,'format','Double');
 			WriteData(fid,'object',obj,'fieldname','borderSSA','format','DoubleMat','mattype',1);
@@ -202,10 +211,11 @@
 			pos=find(data==1); data(pos,end)=SIAApproximationEnum();
 			pos=find(data==2); data(pos,end)=SSAApproximationEnum();
-			pos=find(data==3); data(pos,end)=HOApproximationEnum();
-			pos=find(data==4); data(pos,end)=FSApproximationEnum();
-			pos=find(data==5); data(pos,end)=SSAHOApproximationEnum();
-			pos=find(data==6); data(pos,end)=SSAFSApproximationEnum();
+			pos=find(data==3); data(pos,end)=L1L2ApproximationEnum();
+			pos=find(data==4); data(pos,end)=HOApproximationEnum();
+			pos=find(data==5); data(pos,end)=FSApproximationEnum();
+
+			pos=find(data==6); data(pos,end)=SSAHOApproximationEnum();
 			pos=find(data==7); data(pos,end)=HOFSApproximationEnum();
-			pos=find(data==8); data(pos,end)=L1L2ApproximationEnum();
+			pos=find(data==8); data(pos,end)=SSAFSApproximationEnum();
 			WriteData(fid,'data',data,'enum',FlowequationVertexEquationEnum(),'format','DoubleMat','mattype',1);
 			data=obj.element_equation;
@@ -213,10 +223,11 @@
 			pos=find(data==1); data(pos,end)=SIAApproximationEnum();
 			pos=find(data==2); data(pos,end)=SSAApproximationEnum();
-			pos=find(data==3); data(pos,end)=HOApproximationEnum();
-			pos=find(data==4); data(pos,end)=FSApproximationEnum();
-			pos=find(data==5); data(pos,end)=SSAHOApproximationEnum();
-			pos=find(data==6); data(pos,end)=SSAFSApproximationEnum();
-			pos=find(data==7); data(pos,end)=HOFSApproximationEnum();
-			pos=find(data==8); data(pos,end)=L1L2ApproximationEnum();
+			pos=find(data==3); data(pos,end)=L1L2ApproximationEnum();
+			pos=find(data==4); data(pos,end)=HOApproximationEnum();
+			pos=find(data==5); data(pos,end)=FSApproximationEnum();
+
+			pos=find(data==6); data(pos,end)=SSAHOApproximationEnum();
+			pos=find(data==7); data(pos,end)=SSAFSApproximationEnum();
+			pos=find(data==8); data(pos,end)=HOFSApproximationEnum();
 			WriteData(fid,'data',data,'enum',FlowequationElementEquationEnum(),'format','DoubleMat','mattype',2);
 		end % }}}
Index: issm/trunk/src/m/classes/flowequation.py
===================================================================
--- issm/trunk/src/m/classes/flowequation.py	(revision 18081)
+++ issm/trunk/src/m/classes/flowequation.py	(revision 18301)
@@ -17,19 +17,22 @@
 	def __init__(self): # {{{
 		
-		self.isSIA            = 0
-		self.isSSA            = 0
-		self.isL1L2           = 0
-		self.isHO             = 0
-		self.isFS             = 0
-		self.fe_SSA           = ''
-		self.fe_HO            = ''
-		self.fe_FS            = ''
-		self.XTH_r            = 1.
-		self.XTH_theta        = 0.
-		self.vertex_equation  = float('NaN')
-		self.element_equation = float('NaN')
-		self.borderSSA        = float('NaN')
-		self.borderHO         = float('NaN')
-		self.borderFS         = float('NaN')
+		self.isSIA                          = 0
+		self.isSSA                          = 0
+		self.isL1L2                         = 0
+		self.isHO                           = 0
+		self.isFS                           = 0
+		self.fe_SSA                         = ''
+		self.fe_HO                          = ''
+		self.fe_FS                          = ''
+		self.augmented_lagrangian_r         = 1.
+		self.augmented_lagrangian_rhop      = 1.
+		self.augmented_lagrangian_rlambda   = 1.
+		self.augmented_lagrangian_rholambda = 1.
+		self.XTH_theta                      = 0.
+		self.vertex_equation                = float('NaN')
+		self.element_equation               = float('NaN')
+		self.borderSSA                      = float('NaN')
+		self.borderHO                       = float('NaN')
+		self.borderFS                       = float('NaN')
 
 		#set defaults
@@ -47,5 +50,5 @@
 		string="%s\n%s"%(string,fielddisplay(self,'fe_SSA',"Finite Element for SSA: 'P1', 'P1bubble' 'P1bubblecondensed' 'P2'"))
 		string="%s\n%s"%(string,fielddisplay(self,'fe_HO' ,"Finite Element for HO:  'P1' 'P1bubble' 'P1bubblecondensed' 'P1xP2' 'P2xP1' 'P2'"))
-		string="%s\n%s"%(string,fielddisplay(self,'fe_FS' ,"Finite Element for FS:  'P1P1' (debugging only) 'P1P1GLS' 'MINIcondensed' 'MINI' 'TaylorHood' 'XTaylorHood'"))
+		string="%s\n%s"%(string,fielddisplay(self,'fe_FS' ,"Finite Element for FS:  'P1P1' (debugging only) 'P1P1GLS' 'MINIcondensed' 'MINI' 'TaylorHood' 'LATaylorHood' 'XTaylorHood'"))
 		string="%s\n%s"%(string,fielddisplay(self,'vertex_equation',"flow equation for each vertex"))
 		string="%s\n%s"%(string,fielddisplay(self,'element_equation',"flow equation for each element"))
@@ -76,11 +79,14 @@
 			md = checkfield(md,'fieldname','flowequation.isHO','numel',[1],'values',[0,1])
 			md = checkfield(md,'fieldname','flowequation.isFS','numel',[1],'values',[0,1])
-			md = checkfield(md,'fieldname','flowequation.fe_SSA','values',['P1','P1bubble','P1bubblecondensed','P2'])
-			md = checkfield(md,'fieldname','flowequation.fe_HO' ,'values',['P1','P1bubble','P1bubblecondensed','P1xP2','P2xP1','P2','P1xP3','P2xP4'])
-			md = checkfield(md,'fieldname','flowequation.fe_FS' ,'values',['P1P1','P1P1GLS','MINIcondensed','MINI','TaylorHood','XTaylorHood','OneLayerP4z'])
+			md = checkfield(md,'fieldname','flowequation.fe_SSA','values',['P1','P1bubble','P1bubblecondensed','P2','P2bubble'])
+			md = checkfield(md,'fieldname','flowequation.fe_HO' ,'values',['P1','P1bubble','P1bubblecondensed','P1xP2','P2xP1','P2','P2bubble','P1xP3','P2xP4'])
+			md = checkfield(md,'fieldname','flowequation.fe_FS' ,'values',['P1P1','P1P1GLS','MINIcondensed','MINI','TaylorHood','XTaylorHood','OneLayerP4z','CrouzeixRaviart'])
 			md = checkfield(md,'fieldname','flowequation.borderSSA','size',[md.mesh.numberofvertices],'values',[0,1])
 			md = checkfield(md,'fieldname','flowequation.borderHO','size',[md.mesh.numberofvertices],'values',[0,1])
 			md = checkfield(md,'fieldname','flowequation.borderFS','size',[md.mesh.numberofvertices],'values',[0,1])
-			md = checkfield(md,'fieldname','flowequation.XTH_r','numel',[1],'>',0.)
+			md = checkfield(md,'fieldname','flowequation.augmented_lagrangian_r','numel',[1],'>',0.)
+			md = checkfield(md,'fieldname','flowequation.augmented_lagrangian_rhop','numel',[1],'>',0.)
+			md = checkfield(md,'fieldname','flowequation.augmented_lagrangian_rlambda','numel',[1],'>',0.)
+			md = checkfield(md,'fieldname','flowequation.augmented_lagrangian_rholambda','numel',[1],'>',0.)
 			md = checkfield(md,'fieldname','flowequation.XTH_theta','numel',[1],'>=',0.,'<',.5)
 			if m.strcmp(md.mesh.domaintype(),'2Dhorizontal'):
@@ -111,5 +117,8 @@
 		WriteData(fid,'enum',FlowequationFeHOEnum() ,'data',StringToEnum(self.fe_HO)[0] ,'format','Integer')
 		WriteData(fid,'enum',FlowequationFeFSEnum() ,'data',StringToEnum(self.fe_FS)[0] ,'format','Integer')
-		WriteData(fid,'enum',AugmentedLagrangianREnum() ,'data',self.XTH_r ,'format','Double')
+		WriteData(fid,'enum',AugmentedLagrangianREnum(),'data',self.augmented_lagrangian_r ,'format','Double')
+		WriteData(fid,'enum',AugmentedLagrangianRhopEnum(),'data',self.augmented_lagrangian_rhop ,'format','Double')
+		WriteData(fid,'enum',AugmentedLagrangianRlambdaEnum(),'data',self.augmented_lagrangian_rlambda ,'format','Double')
+		WriteData(fid,'enum',AugmentedLagrangianRholambdaEnum(),'data',self.augmented_lagrangian_rholambda ,'format','Double')
 		WriteData(fid,'enum',AugmentedLagrangianThetaEnum() ,'data',self.XTH_theta ,'format','Double')
 		WriteData(fid,'object',self,'fieldname','borderSSA','format','DoubleMat','mattype',1)
@@ -121,10 +130,10 @@
 		data[numpy.nonzero(data==1)]=SIAApproximationEnum()
 		data[numpy.nonzero(data==2)]=SSAApproximationEnum()
-		data[numpy.nonzero(data==3)]=HOApproximationEnum()
-		data[numpy.nonzero(data==4)]=FSApproximationEnum()
-		data[numpy.nonzero(data==5)]=SSAHOApproximationEnum()
-		data[numpy.nonzero(data==6)]=SSAFSApproximationEnum()
+		data[numpy.nonzero(data==3)]=L1L2ApproximationEnum()
+		data[numpy.nonzero(data==4)]=HOApproximationEnum()
+		data[numpy.nonzero(data==5)]=FSApproximationEnum()
+		data[numpy.nonzero(data==6)]=SSAHOApproximationEnum()
 		data[numpy.nonzero(data==7)]=HOFSApproximationEnum()
-		data[numpy.nonzero(data==8)]=L1L2ApproximationEnum()
+		data[numpy.nonzero(data==8)]=SSAFSApproximationEnum()
 		WriteData(fid,'data',data,'enum',FlowequationVertexEquationEnum(),'format','DoubleMat','mattype',1)
 		data=copy.deepcopy(self.element_equation)
@@ -132,10 +141,10 @@
 		data[numpy.nonzero(data==1)]=SIAApproximationEnum()
 		data[numpy.nonzero(data==2)]=SSAApproximationEnum()
-		data[numpy.nonzero(data==3)]=HOApproximationEnum()
-		data[numpy.nonzero(data==4)]=FSApproximationEnum()
-		data[numpy.nonzero(data==5)]=SSAHOApproximationEnum()
-		data[numpy.nonzero(data==6)]=SSAFSApproximationEnum()
-		data[numpy.nonzero(data==7)]=HOFSApproximationEnum()
-		data[numpy.nonzero(data==8)]=L1L2ApproximationEnum()
+		data[numpy.nonzero(data==3)]=L1L2ApproximationEnum()
+		data[numpy.nonzero(data==4)]=HOApproximationEnum()
+		data[numpy.nonzero(data==5)]=FSApproximationEnum()
+		data[numpy.nonzero(data==6)]=SSAHOApproximationEnum()
+		data[numpy.nonzero(data==7)]=SSAFSApproximationEnum()
+		data[numpy.nonzero(data==8)]=HOFSApproximationEnum()
 		WriteData(fid,'data',data,'enum',FlowequationElementEquationEnum(),'format','DoubleMat','mattype',2)
 	# }}}
Index: issm/trunk/src/m/classes/groundingline.m
===================================================================
--- issm/trunk/src/m/classes/groundingline.m	(revision 18081)
+++ issm/trunk/src/m/classes/groundingline.m	(revision 18301)
@@ -7,5 +7,4 @@
 	properties (SetAccess=public) 
 		migration    = '';
-		melting_rate = NaN;
 	end
 	methods
@@ -23,5 +22,4 @@
             fprintf(fid, '%s\n%s\n','       <option value="None" type="string" default="false"></option>','</parameter>');
 
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n',    '<parameter key ="melting_rate" type="',          class(obj.melting_rate),'" default="',            convert2str(obj.melting_rate),'">',     '     <section name="groundingline" />','     <help> melting rate applied when previously grounded parts start floating [m/yr] </help>','</parameter>');
             fprintf(fid,'%s\n%s\n','</frame>');
         end % }}}
@@ -38,7 +36,4 @@
 			%Type of migration
 			obj.migration='None';
-
-			%basal melting rate correction: 
-			obj.melting_rate=0; 
 
 		end % }}}
@@ -64,10 +59,8 @@
 			disp(sprintf('   grounding line migration parameters:'));
 			fielddisplay(obj,'migration','type of grounding line migration: ''SoftMigration'',''AggressiveMigration'' or ''None''');
-			fielddisplay(obj,'melting_rate','melting rate applied when previously grounded parts start floating [m/yr]');
 
 		end % }}}
 		function marshall(obj,md,fid) % {{{
 			WriteData(fid,'data',StringToEnum(obj.migration),'enum',GroundinglineMigrationEnum(),'format','Integer');
-			WriteData(fid,'object',obj,'fieldname','melting_rate','format','Double');
 		end % }}}
 	end
Index: issm/trunk/src/m/classes/groundingline.py
===================================================================
--- issm/trunk/src/m/classes/groundingline.py	(revision 18081)
+++ issm/trunk/src/m/classes/groundingline.py	(revision 18301)
@@ -17,5 +17,4 @@
 	def __init__(self): # {{{
 		self.migration=''
-		self.melting_rate=float('NaN')
 
 		#set defaults
@@ -27,5 +26,4 @@
 
 		string="%s\n%s"%(string,fielddisplay(self,'migration','type of grounding line migration: ''SoftMigration'',''AggressiveMigration'',''SubelementMigration'',''SubelementMigration2'',''Contact'',''None'''))
-		string="%s\n%s"%(string,fielddisplay(self,'melting_rate','melting rate applied when previously grounded parts start floating [m/yr]'))
 		return string
 		#}}}	
@@ -34,7 +32,4 @@
 		#Type of migration
 		self.migration='None'
-
-		#basal melting rate correction: 
-		self.melting_rate=0;
 
 		return self
@@ -57,4 +52,3 @@
 	def marshall(self,md,fid):    # {{{
 		WriteData(fid,'data',StringToEnum(self.migration)[0],'enum',GroundinglineMigrationEnum(),'format','Integer')
-		WriteData(fid,'object',self,'fieldname','melting_rate','format','Double')
 	# }}}
Index: issm/trunk/src/m/classes/inversion.m
===================================================================
--- issm/trunk/src/m/classes/inversion.m	(revision 18081)
+++ issm/trunk/src/m/classes/inversion.m	(revision 18301)
@@ -25,53 +25,53 @@
 	end
 	methods
-         function createxml(obj,fid) % {{{
-            fprintf(fid, '<!-- inversion -->\n');            
-                    
-            % inversion parameters
-            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="inversion parameters">','<section name="inversion" />');                    
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="iscontrol" type="',class(obj.iscontrol),'" default="',convert2str(obj.iscontrol),'">','     <section name="inversion" />','     <help> is inversion activated? </help>','  </parameter>');
-            
-            % incompleteadjoing drop-down (0 or 1)
-            fprintf(fid,'%s\n%s\n%s\n%s\n','  <parameter key ="incomplete_adjoint" type="alternative" optional="false">','     <section name="inversion" />','     <help> 1: linear viscosity, 0: non-linear viscosity </help>');
-            fprintf(fid,'%s\n','       <option value="0" type="string" default="true"> </option>');
-            fprintf(fid,'%s\n%s\n','       <option value="1" type="string" default="false"> </option>','</parameter>');
-            
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="control_parameters" type="',class(obj.control_parameters),'" default="',convert2str(obj.control_parameters),'">','     <section name="inversion" />','     <help> ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''} </help>','  </parameter>');
-                
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="nsteps" type="',class(obj.nsteps),'" default="',convert2str(obj.nsteps),'">','     <section name="inversion" />','     <help> number of optimization searches </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="cost_functions" type="',class(obj.cost_functions),'" default="',convert2str(obj.cost_functions),'">','     <section name="inversion" />','     <help> indicate the type of response for each optimization step  </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="cost_functions_coefficients" type="',class(obj.cost_functions_coefficients),'" default="',convert2str(obj.cost_functions_coefficients),'">','     <section name="inversion" />','     <help> cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter </help>','  </parameter>');
-                
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="cost_function_threshold" type="',class(obj.cost_function_threshold),'" default="',convert2str(obj.cost_function_threshold),'">','     <section name="inversion" />','     <help> misfit convergence criterion. Default is 1%, NaN if not applied </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="maxiter_per_step" type="',class(obj.maxiter_per_step),'" default="',convert2str(obj.maxiter_per_step),'">','     <section name="inversion" />','     <help> maximum iterations during each optimization step  </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="gradient_scaling" type="',class(obj.gradient_scaling),'" default="',convert2str(obj.gradient_scaling),'">','     <section name="inversion" />','     <help> scaling factor on gradient direction during optimization, for each optimization step </help>','  </parameter>');
-               
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="step_threshold" type="',class(obj.step_threshold),'" default="',convert2str(obj.step_threshold),'">','     <section name="inversion" />','     <help> decrease threshold for misfit, default is 30% </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="min_parameters" type="',class(obj.min_parameters),'" default="',convert2str(obj.min_parameters),'">','     <section name="inversion" />','     <help> absolute minimum acceptable value of the inversed parameter on each vertex </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="max_parameters" type="',class(obj.max_parameters),'" default="',convert2str(obj.max_parameters),'">','     <section name="inversion" />','     <help> absolute maximum acceptable value of the inversed parameter on each vertex </help>','  </parameter>');
-               
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vx_obs" type="',class(obj.vx_obs),'" default="',convert2str(obj.vx_obs),'">','     <section name="inversion" />','     <help> observed velocity x component [m/yr] </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vy_obs" type="',class(obj.vy_obs),'" default="',convert2str(obj.vy_obs),'">','     <section name="inversion" />','     <help> observed velocity y component [m/yr]  </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vel_obs" type="',class(obj.vel_obs),'" default="',convert2str(obj.vel_obs),'">','     <section name="inversion" />','     <help> observed velocity magnitude [m/yr] </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="thickness_obs" type="',class(obj.thickness_obs),'" default="',convert2str(obj.thickness_obs),'">','     <section name="inversion" />','     <help> observed thickness [m]) </help>','  </parameter>');
-               
-            fprintf(fid,'%s\n%s\n','</frame>');    
-            
-            fprintf(fid,'%s\n%s\n%s\n','<frame key="2" label="Available cost functions">','<section name="inversion" />');                    
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="SurfaceAbsVelMisfit" type="','string','" default="','101','">','     <section name="inversion" />','     <help>  </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="SurfaceRelVelMisfit" type="','string','" default="','102','">','     <section name="inversion" />','     <help>   </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="SurfaceLogVelMisfit" type="','string','" default="','103','">','     <section name="inversion" />','     <help>  </help>','  </parameter>');
-                
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="SurfaceLogVxVyMisfit" type="','string','" default="','104','">','     <section name="inversion" />','     <help>  </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="SurfaceAverageVelMisfit" type="','string','" default="','105','">','     <section name="inversion" />','     <help>   </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="ThicknessAbsMisfit" type="','string','" default="','106','">','     <section name="inversion" />','     <help>  </help>','  </parameter>');
-               
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="DragCoefficientAbsGradient" type="','string','" default="','107','">','     <section name="inversion" />','     <help>  </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="RheologyBbarAbsGradient" type="','string','" default="','108','">','     <section name="inversion" />','     <help>  </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="ThicknessAbsGradient" type="','string','" default="','109','">','     <section name="inversion" />','     <help> </help>','  </parameter>');
-               
-            fprintf(fid,'%s\n%s\n','</frame>');    
-        
-        end % }}}       
+		function createxml(obj,fid) % {{{
+			fprintf(fid, '<!-- inversion -->\n');            
+
+			% inversion parameters
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="inversion parameters">','<section name="inversion" />');                    
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="iscontrol" type="',class(obj.iscontrol),'" default="',convert2str(obj.iscontrol),'">','     <section name="inversion" />','     <help> is inversion activated? </help>','  </parameter>');
+
+			% incompleteadjoing drop-down (0 or 1)
+			fprintf(fid,'%s\n%s\n%s\n%s\n','  <parameter key ="incomplete_adjoint" type="alternative" optional="false">','     <section name="inversion" />','     <help> 1: linear viscosity, 0: non-linear viscosity </help>');
+			fprintf(fid,'%s\n','       <option value="0" type="string" default="true"> </option>');
+			fprintf(fid,'%s\n%s\n','       <option value="1" type="string" default="false"> </option>','</parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="control_parameters" type="',class(obj.control_parameters),'" default="',convert2str(obj.control_parameters),'">','     <section name="inversion" />','     <help> ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''} </help>','  </parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="nsteps" type="',class(obj.nsteps),'" default="',convert2str(obj.nsteps),'">','     <section name="inversion" />','     <help> number of optimization searches </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="cost_functions" type="',class(obj.cost_functions),'" default="',convert2str(obj.cost_functions),'">','     <section name="inversion" />','     <help> indicate the type of response for each optimization step  </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="cost_functions_coefficients" type="',class(obj.cost_functions_coefficients),'" default="',convert2str(obj.cost_functions_coefficients),'">','     <section name="inversion" />','     <help> cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter </help>','  </parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="cost_function_threshold" type="',class(obj.cost_function_threshold),'" default="',convert2str(obj.cost_function_threshold),'">','     <section name="inversion" />','     <help> misfit convergence criterion. Default is 1%, NaN if not applied </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="maxiter_per_step" type="',class(obj.maxiter_per_step),'" default="',convert2str(obj.maxiter_per_step),'">','     <section name="inversion" />','     <help> maximum iterations during each optimization step  </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="gradient_scaling" type="',class(obj.gradient_scaling),'" default="',convert2str(obj.gradient_scaling),'">','     <section name="inversion" />','     <help> scaling factor on gradient direction during optimization, for each optimization step </help>','  </parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="step_threshold" type="',class(obj.step_threshold),'" default="',convert2str(obj.step_threshold),'">','     <section name="inversion" />','     <help> decrease threshold for misfit, default is 30% </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="min_parameters" type="',class(obj.min_parameters),'" default="',convert2str(obj.min_parameters),'">','     <section name="inversion" />','     <help> absolute minimum acceptable value of the inversed parameter on each vertex </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="max_parameters" type="',class(obj.max_parameters),'" default="',convert2str(obj.max_parameters),'">','     <section name="inversion" />','     <help> absolute maximum acceptable value of the inversed parameter on each vertex </help>','  </parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vx_obs" type="',class(obj.vx_obs),'" default="',convert2str(obj.vx_obs),'">','     <section name="inversion" />','     <help> observed velocity x component [m/yr] </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vy_obs" type="',class(obj.vy_obs),'" default="',convert2str(obj.vy_obs),'">','     <section name="inversion" />','     <help> observed velocity y component [m/yr]  </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vel_obs" type="',class(obj.vel_obs),'" default="',convert2str(obj.vel_obs),'">','     <section name="inversion" />','     <help> observed velocity magnitude [m/yr] </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="thickness_obs" type="',class(obj.thickness_obs),'" default="',convert2str(obj.thickness_obs),'">','     <section name="inversion" />','     <help> observed thickness [m]) </help>','  </parameter>');
+
+			fprintf(fid,'%s\n%s\n','</frame>');    
+
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="2" label="Available cost functions">','<section name="inversion" />');                    
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="SurfaceAbsVelMisfit" type="','string','" default="','101','">','     <section name="inversion" />','     <help>  </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="SurfaceRelVelMisfit" type="','string','" default="','102','">','     <section name="inversion" />','     <help>   </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="SurfaceLogVelMisfit" type="','string','" default="','103','">','     <section name="inversion" />','     <help>  </help>','  </parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="SurfaceLogVxVyMisfit" type="','string','" default="','104','">','     <section name="inversion" />','     <help>  </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="SurfaceAverageVelMisfit" type="','string','" default="','105','">','     <section name="inversion" />','     <help>   </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="ThicknessAbsMisfit" type="','string','" default="','106','">','     <section name="inversion" />','     <help>  </help>','  </parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="DragCoefficientAbsGradient" type="','string','" default="','107','">','     <section name="inversion" />','     <help>  </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="RheologyBbarAbsGradient" type="','string','" default="','108','">','     <section name="inversion" />','     <help>  </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="ThicknessAbsGradient" type="','string','" default="','109','">','     <section name="inversion" />','     <help> </help>','  </parameter>');
+
+			fprintf(fid,'%s\n%s\n','</frame>');    
+
+		end % }}}       
 		function obj = inversion(varargin) % {{{
 			switch nargin
@@ -132,9 +132,9 @@
 			md = checkfield(md,'fieldname','inversion.incomplete_adjoint','values',[0 1]);
 			md = checkfield(md,'fieldname','inversion.control_parameters','cell',1,'values',...
-				{'BalancethicknessThickeningRate' 'FrictionCoefficient' 'MaterialsRheologyBbar' 'DamageDbar' 'Vx' 'Vy' 'Thickness'});
+				{'BalancethicknessThickeningRate' 'FrictionCoefficient' 'MaterialsRheologyBbar' 'DamageDbar' 'Vx' 'Vy' 'Thickness' 'BalancethicknessNux' 'BalancethicknessNuy' 'BalancethicknessApparentMassbalance'});
 			md = checkfield(md,'fieldname','inversion.nsteps','numel',1,'>=',0);
 			md = checkfield(md,'fieldname','inversion.maxiter_per_step','size',[md.inversion.nsteps 1],'>=',0);
 			md = checkfield(md,'fieldname','inversion.step_threshold','size',[md.inversion.nsteps 1]);
-			md = checkfield(md,'fieldname','inversion.cost_functions','size',[1 num_costfunc],'values',[101:105 201 501:506]);
+			md = checkfield(md,'fieldname','inversion.cost_functions','size',[1 num_costfunc],'values',[101:105 201 501:507]);
 			md = checkfield(md,'fieldname','inversion.cost_functions_coefficients','size',[md.mesh.numberofvertices num_costfunc],'>=',0);
 			md = checkfield(md,'fieldname','inversion.gradient_scaling','size',[md.inversion.nsteps num_controls]);
@@ -196,5 +196,5 @@
 			if ~obj.iscontrol, return; end
 			WriteData(fid,'object',obj,'fieldname','nsteps','format','Integer');
-			WriteData(fid,'object',obj,'fieldname','maxiter_per_step','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',obj,'fieldname','maxiter_per_step','format','IntMat','mattype',3);
 			WriteData(fid,'object',obj,'fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1);
 			WriteData(fid,'object',obj,'fieldname','gradient_scaling','format','DoubleMat','mattype',3);
@@ -206,5 +206,11 @@
 			WriteData(fid,'object',obj,'fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts);
 			WriteData(fid,'object',obj,'fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts);
-			WriteData(fid,'object',obj,'fieldname','thickness_obs','format','DoubleMat','mattype',1);
+			if(numel(obj.thickness_obs)==md.mesh.numberofelements),
+				mattype=2;
+			else
+				mattype=1;
+			end
+			WriteData(fid,'object',obj,'class','inversion','fieldname','thickness_obs','format','DoubleMat','mattype',mattype);
+
 
 			%process control parameters
@@ -232,4 +238,5 @@
 			pos=find(obj.cost_functions==505); data(pos)=ThicknessAcrossGradientEnum();
 			pos=find(obj.cost_functions==506); data(pos)=BalancethicknessMisfitEnum();
+			pos=find(obj.cost_functions==507); data(pos)=Balancethickness2MisfitEnum();
 			WriteData(fid,'data',data,'enum',InversionCostFunctionsEnum(),'format','DoubleMat','mattype',3);
 			WriteData(fid,'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum(),'format','Integer');
Index: issm/trunk/src/m/classes/inversionvalidation.m
===================================================================
--- issm/trunk/src/m/classes/inversionvalidation.m	(revision 18301)
+++ issm/trunk/src/m/classes/inversionvalidation.m	(revision 18301)
@@ -0,0 +1,146 @@
+%INVERSIONVALIDATION class definition
+%
+%   Usage:
+%      inversionvalidation=inversionvalidation();
+
+classdef inversionvalidation
+	properties (SetAccess=public) 
+		iscontrol                   = 0
+		incomplete_adjoint          = 0
+		control_parameters          = NaN
+		cost_functions              = NaN
+		cost_functions_coefficients = NaN
+		min_parameters              = NaN
+		max_parameters              = NaN
+		vx_obs                      = NaN
+		vy_obs                      = NaN
+		vz_obs                      = NaN
+		vel_obs                     = NaN
+		thickness_obs               = NaN
+	end
+	methods
+		function obj = inversionvalidation(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					obj=structtoobj(inversionvalidation(),varargin{1});
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
+
+			%default is incomplete adjoint for now
+			self.incomplete_adjoint=1;
+
+			%parameter to be inferred by control methods (only
+			%drag and B are supported yet)
+			self.control_parameters={'FrictionCoefficient'};
+
+			%several responses can be used:
+			self.cost_functions=101;
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			%Early return
+			if ~obj.iscontrol, return; end
+
+			num_controls=numel(md.inversion.control_parameters);
+			num_costfunc=size(md.inversion.cost_functions,2);
+
+			md = checkfield(md,'fieldname','inversion.iscontrol','values',[0 1]);
+			md = checkfield(md,'fieldname','inversion.incomplete_adjoint','values',[0 1]);
+			md = checkfield(md,'fieldname','inversion.control_parameters','cell',1,'values',...
+				{'BalancethicknessThickeningRate' 'FrictionCoefficient' 'MaterialsRheologyBbar' 'MaterialsRheologyZbar' 'Vx' 'Vy' 'Thickness' 'BalancethicknessApparentMassbalance'});
+			md = checkfield(md,'fieldname','inversion.cost_functions','size',[1 num_costfunc],'values',[101:105 201 501:507]);
+			md = checkfield(md,'fieldname','inversion.cost_functions_coefficients','size',[md.mesh.numberofvertices num_costfunc],'>=',0);
+			md = checkfield(md,'fieldname','inversion.min_parameters','size',[md.mesh.numberofvertices num_controls]);
+			md = checkfield(md,'fieldname','inversion.max_parameters','size',[md.mesh.numberofvertices num_controls]);
+
+			if solution==BalancethicknessSolutionEnum()
+				md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+			elseif solution==BalancethicknessSoftSolutionEnum()
+				md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+			else
+				md = checkfield(md,'fieldname','inversion.vx_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+				if ~strcmp(domaintype(md.mesh),'2Dvertical'),
+					md = checkfield(md,'fieldname','inversion.vy_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+				end
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   inversionvalidation parameters:'));
+			fielddisplay(obj,'iscontrol','is inversion activated?');
+			fielddisplay(obj,'incomplete_adjoint','1: linear viscosity, 0: non-linear viscosity');
+			fielddisplay(obj,'control_parameters','ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''}');
+			fielddisplay(obj,'cost_functions','indicate the type of response for each optimization step');
+			fielddisplay(obj,'cost_functions_coefficients','cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter');
+			fielddisplay(obj,'min_parameters','absolute minimum acceptable value of the inversed parameter on each vertex');
+			fielddisplay(obj,'max_parameters','absolute maximum acceptable value of the inversed parameter on each vertex');
+			fielddisplay(obj,'vx_obs','observed velocity x component [m/yr]');
+			fielddisplay(obj,'vy_obs','observed velocity y component [m/yr]');
+			fielddisplay(obj,'vel_obs','observed velocity magnitude [m/yr]');
+			fielddisplay(obj,'thickness_obs','observed thickness [m]');
+			disp('Available cost functions:');
+			disp('   101: SurfaceAbsVelMisfit');
+			disp('   102: SurfaceRelVelMisfit');
+			disp('   103: SurfaceLogVelMisfit');
+			disp('   104: SurfaceLogVxVyMisfit');
+			disp('   105: SurfaceAverageVelMisfit');
+			disp('   201: ThicknessAbsMisfit');
+			disp('   501: DragCoefficientAbsGradient');
+			disp('   502: RheologyBbarAbsGradient');
+			disp('   503: ThicknessAbsGradient');
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+
+			yts=365.0*24.0*3600.0;
+
+			WriteData(fid,'object',obj,'class','inversion','fieldname','iscontrol','format','Boolean');
+			WriteData(fid,'enum',InversionTypeEnum(),'data',3,'format','Integer');
+			if ~obj.iscontrol, return; end
+			WriteData(fid,'object',obj,'class','inversion','fieldname','incomplete_adjoint','format','Boolean');
+			WriteData(fid,'object',obj,'class','inversion','fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','inversion','fieldname','min_parameters','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',obj,'class','inversion','fieldname','max_parameters','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',obj,'class','inversion','fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,'object',obj,'class','inversion','fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,'object',obj,'class','inversion','fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			if(numel(obj.thickness_obs)==md.mesh.numberofelements),
+				mattype=2; 
+			else
+				mattype=1;
+			end
+			WriteData(fid,'object',obj,'class','inversion','fieldname','thickness_obs','format','DoubleMat','mattype',mattype);
+
+			%process control parameters
+			num_control_parameters=numel(obj.control_parameters);
+			data=zeros(1,num_control_parameters);
+			for i=1:num_control_parameters,
+				data(i)=StringToEnum(obj.control_parameters{i});
+			end
+			WriteData(fid,'data',data,'enum',InversionControlParametersEnum(),'format','DoubleMat','mattype',3);
+			WriteData(fid,'data',num_control_parameters,'enum',InversionNumControlParametersEnum(),'format','Integer');
+
+			%process cost functions
+			num_cost_functions=size(obj.cost_functions,2);
+			data=obj.cost_functions;
+			pos=find(obj.cost_functions==101); data(pos)=SurfaceAbsVelMisfitEnum();
+			pos=find(obj.cost_functions==102); data(pos)=SurfaceRelVelMisfitEnum();
+			pos=find(obj.cost_functions==103); data(pos)=SurfaceLogVelMisfitEnum();
+			pos=find(obj.cost_functions==104); data(pos)=SurfaceLogVxVyMisfitEnum();
+			pos=find(obj.cost_functions==105); data(pos)=SurfaceAverageVelMisfitEnum();
+			pos=find(obj.cost_functions==201); data(pos)=ThicknessAbsMisfitEnum();
+			pos=find(obj.cost_functions==501); data(pos)=DragCoefficientAbsGradientEnum();
+			pos=find(obj.cost_functions==502); data(pos)=RheologyBbarAbsGradientEnum();
+			pos=find(obj.cost_functions==503); data(pos)=ThicknessAbsGradientEnum();
+			pos=find(obj.cost_functions==504); data(pos)=ThicknessAlongGradientEnum();
+			pos=find(obj.cost_functions==505); data(pos)=ThicknessAcrossGradientEnum();
+			pos=find(obj.cost_functions==506); data(pos)=BalancethicknessMisfitEnum();
+			pos=find(obj.cost_functions==507); data(pos)=Balancethickness2MisfitEnum();
+			WriteData(fid,'data',data,'enum',InversionCostFunctionsEnum(),'format','DoubleMat','mattype',3);
+			WriteData(fid,'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum(),'format','Integer');
+		end % }}}
+	end
+end
Index: issm/trunk/src/m/classes/linearbasalforcings.m
===================================================================
--- issm/trunk/src/m/classes/linearbasalforcings.m	(revision 18301)
+++ issm/trunk/src/m/classes/linearbasalforcings.m	(revision 18301)
@@ -0,0 +1,97 @@
+%LINEAR BASAL FORCINGS class definition
+%
+%   Usage:
+%      linearbasalforcings=linearbasalforcings();
+
+classdef linearbasalforcings
+	properties (SetAccess=public) 
+		groundedice_melting_rate  = NaN;
+		deepwater_melting_rate    = NaN;
+		deepwater_elevation       = NaN;
+		upperwater_elevation      = NaN;
+		geothermalflux            = NaN;
+	end
+	methods
+     function createxml(obj,fid) % {{{
+            fprintf(fid, '\n\n');
+            fprintf(fid, '%s\n', '<!-- basalforcings -->');
+			 fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="melting_rate" type="',            class(obj.melting_rate),'" default="',              num2str(obj.melting_rate),'">',              '     <section name="basalforcings" />','     <help> basal melting rate (positive if melting) [m/yr] </help>','</parameter>');
+             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n',        '<parameter key ="geothermalflux" type="',          class(obj.geothermalflux),'" default="',            num2str(obj.geothermalflux),'">',            '     <section name="basalforcings" />','     <help> geothermal heat flux [W/m^2] </help>','</parameter>');
+             
+        end % }}}
+		function obj = linearbasalforcings(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					obj=structtoobj(linearbasalforcings(),varargin{1});
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function self = initialize(self,md) % {{{
+
+			if isnan(self.groundedice_melting_rate),
+				self.groundedice_melting_rate=zeros(md.mesh.numberofvertices,1);
+				disp('      no basalforcings.groundedice_melting_rate specified: values set as zero');
+			end
+
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%default values for melting parameterization
+			obj.deepwater_melting_rate = 50;
+			obj.deepwater_elevation    = -800;
+			obj.upperwater_elevation   = -400;
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			if ismember(MasstransportAnalysisEnum(),analyses) & ~(solution==TransientSolutionEnum() & md.transient.ismasstransport==0),
+				md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'forcing',1);
+				md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0,'numel',1);
+				md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<','basalforcings.upperwater_elevation','numel',1);
+				md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<',0,'numel',1);
+			end
+			if ismember(BalancethicknessAnalysisEnum(),analyses),
+				md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0,'numel',1);
+				md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<','basalforcings.upperwater_elevation','numel',1);
+				md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<',0,'numel',1);
+			end
+			if ismember(ThermalAnalysisEnum(),analyses) & ~(solution==TransientSolutionEnum() & md.transient.isthermal==0),
+				md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'forcing',1);
+				md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0,'numel',1);
+				md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<','basalforcings.upperwater_elevation','numel',1);
+				md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<',0,'numel',1);
+				md = checkfield(md,'fieldname','basalforcings.geothermalflux','NaN',1,'forcing',1,'>=',0);
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   basal forcings parameters:'));
+
+			fielddisplay(obj,'groundedice_melting_rate','basal melting rate (positive if melting) [m/yr]');
+			fielddisplay(obj,'deepwater_melting_rate','basal melting rate (positive if melting applied for floating ice whith base < deepwater_elevation) [m/yr]');
+			fielddisplay(obj,'deepwater_elevation','elevation of ocean deepwater [m]');
+			fielddisplay(obj,'upperwater_elevation','elevation of ocean upperwater [m]');
+			fielddisplay(obj,'geothermalflux','geothermal heat flux [W/m^2]');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+
+			yts=365.0*24.0*3600.0;
+
+			floatingice_melting_rate=zeros(md.mesh.numberofvertices,1);
+			floatingice_melting_rate(find(md.geometry.base<=md.basalforcings.deepwater_elevation))=md.basalforcings.deepwater_melting_rate;
+			pos=find(md.geometry.base>md.basalforcings.deepwater_elevation & md.geometry.base<md.basalforcings.upperwater_elevation);
+			floatingice_melting_rate(pos)=md.basalforcings.deepwater_melting_rate*(md.geometry.base(pos)-md.basalforcings.upperwater_elevation)/(md.basalforcings.deepwater_elevation-md.basalforcings.upperwater_elevation);
+			WriteData(fid,'enum',BasalforcingsEnum(),'data',LinearFloatingMeltRateEnum(),'format','Integer');
+			WriteData(fid,'data',floatingice_melting_rate,'format','DoubleMat','enum',BasalforcingsFloatingiceMeltingRateEnum(),'mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+			WriteData(fid,'object',obj,'fieldname','groundedice_melting_rate','format','DoubleMat','enum',BasalforcingsGroundediceMeltingRateEnum(),'mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+			WriteData(fid,'object',obj,'fieldname','geothermalflux','enum',BasalforcingsGeothermalfluxEnum(),'format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'fieldname','deepwater_melting_rate','format','Double','enum',BasalforcingsDeepwaterMeltingRateEnum(),'scale',1./yts)
+			WriteData(fid,'object',obj,'fieldname','deepwater_elevation','format','Double','enum',BasalforcingsDeepwaterElevationEnum())
+			WriteData(fid,'object',obj,'fieldname','upperwater_elevation','format','Double','enum',BasalforcingsUpperwaterElevationEnum())
+		end % }}}
+	end
+end
Index: issm/trunk/src/m/classes/linearbasalforcings.py
===================================================================
--- issm/trunk/src/m/classes/linearbasalforcings.py	(revision 18301)
+++ issm/trunk/src/m/classes/linearbasalforcings.py	(revision 18301)
@@ -0,0 +1,108 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import checkfield
+from WriteData import WriteData
+import numpy
+
+class linearbasalforcings(object):
+	"""
+	LINEAR BASAL FORCINGS class definition
+
+	   Usage:
+	      basalforcings=linearbasalforcings();
+	"""
+
+	def __init__(self,*args): # {{{
+
+		if not len(args):
+			print 'empty init'
+			self.groundedice_melting_rate  = float('NaN')
+			self.deepwater_melting_rate    = 0.
+			self.deepwater_elevation       = 0.
+			self.upperwater_elevation      = 0.
+			self.geothermalflux            = float('NaN')
+
+			#set defaults
+			self.setdefaultparameters()
+		elif len(args)==1 and args[0].__module__=='basalforcings':
+			print 'converting basalforings to linearbasalforcings'
+			inv=args[0]
+			self.groundedice_melting_rate  = inv.groundedice_melting_rate
+			self.geothermalflux            = inv.geothermalflux
+			self.deepwater_melting_rate    = 0.
+			self.deepwater_elevation       = 0.
+			self.upperwater_elevation      = 0.
+
+			#set defaults
+			self.setdefaultparameters()
+		else:
+			raise Exception('constructor not supported')
+
+		#}}}
+	def __repr__(self): # {{{
+		string="   linear basal forcings parameters:"
+
+		string="%s\n%s"%(string,fielddisplay(self,"groundedice_melting_rate","basal melting rate (positive if melting) [m/yr]"))
+		string="%s\n%s"%(string,fielddisplay(self,"deepwater_melting_rate","basal melting rate (positive if melting applied for floating ice whith base < deepwater_elevation) [m/yr]"))
+		string="%s\n%s"%(string,fielddisplay(self,"deepwater_elevation","elevation of ocean deepwater [m]"))
+		string="%s\n%s"%(string,fielddisplay(self,"upperwater_elevation","elevation of ocean upper water [m]"))
+		string="%s\n%s"%(string,fielddisplay(self,"geothermalflux","geothermal heat flux [W/m^2]"))
+		return string
+		#}}}
+	def initialize(self,md): # {{{
+
+		if numpy.all(numpy.isnan(self.groundedice_melting_rate)):
+			self.groundedice_melting_rate=numpy.zeros((md.mesh.numberofvertices,1))
+			print "      no basalforcings.groundedice_melting_rate specified: values set as zero"
+
+		return self
+	#}}}
+	def setdefaultparameters(self): # {{{
+
+		self.deepwater_melting_rate   = 50.0
+		self.deepwater_elevation      = -800.0
+		self.upperwater_elevation     = -400.0
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		if MasstransportAnalysisEnum() in analyses and not (solution==TransientSolutionEnum() and not md.transient.ismasstransport):
+			md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'forcing',1)
+			md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0);
+			md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<',md.basalforcings.upperwater_elevation);
+			md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<',0);
+
+		if BalancethicknessAnalysisEnum() in analyses:
+			md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'size',[md.mesh.numberofvertices])
+			md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0);
+			md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<',md.basalforcings.upperwater_elevation);
+			md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<',0);
+
+		if ThermalAnalysisEnum() in analyses and not (solution==TransientSolutionEnum() and not md.transient.isthermal):
+			md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'forcing',1)
+			md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0);
+			md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<',md.basalforcings.upperwater_elevation);
+			md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<',0);
+			md = checkfield(md,'fieldname','basalforcings.geothermalflux','NaN',1,'forcing',1,'>=',0)
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+
+		yts=365.0*24.0*3600.0
+
+		floatingice_melting_rate = numpy.zeros((md.mesh.numberofvertices,1))
+		pos=numpy.nonzero(md.geometry.base<=md.basalforcings.deepwater_elevation)
+		floatingice_melting_rate[pos]=md.basalforcings.deepwater_melting_rate
+		pos=numpy.nonzero(numpy.logical_and(md.geometry.base>md.basalforcings.deepwater_elevation,md.geometry.base<md.basalforcings.upperwater_elevation))
+		floatingice_melting_rate[pos]=md.basalforcings.deepwater_melting_rate*(md.geometry.base[pos]-md.basalforcings.upperwater_elevation)/(md.basalforcings.deepwater_elevation-md.basalforcings.upperwater_elevation)
+
+		WriteData(fid,'enum',BasalforcingsEnum(),'data',LinearFloatingMeltRateEnum(),'format','Integer');
+		WriteData(fid,'object',self,'fieldname','groundedice_melting_rate','enum',BasalforcingsGroundediceMeltingRateEnum(),'format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'data',floatingice_melting_rate,'enum',BasalforcingsFloatingiceMeltingRateEnum(),'format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'fieldname','geothermalflux','enum',BasalforcingsGeothermalfluxEnum(),'format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'fieldname','deepwater_melting_rate','enum',BasalforcingsDeepwaterMeltingRateEnum(),'format','Double','scale',1./yts)
+		WriteData(fid,'object',self,'fieldname','deepwater_elevation','enum',BasalforcingsDeepwaterElevationEnum(),'format','Double')
+		WriteData(fid,'object',self,'fieldname','upperwater_elevation','enum',BasalforcingsUpperwaterElevationEnum(),'format','Double')
+	# }}}
Index: issm/trunk/src/m/classes/m1qn3inversion.m
===================================================================
--- issm/trunk/src/m/classes/m1qn3inversion.m	(revision 18081)
+++ issm/trunk/src/m/classes/m1qn3inversion.m	(revision 18301)
@@ -71,10 +71,10 @@
 			md = checkfield(md,'fieldname','inversion.incomplete_adjoint','values',[0 1]);
 			md = checkfield(md,'fieldname','inversion.control_parameters','cell',1,'values',...
-				{'BalancethicknessThickeningRate' 'FrictionCoefficient' 'MaterialsRheologyBbar' 'MaterialsRheologyZbar' 'Vx' 'Vy' 'Thickness'});
+				{'BalancethicknessThickeningRate' 'FrictionCoefficient' 'MaterialsRheologyBbar' 'MaterialsRheologyZbar' 'Vx' 'Vy' 'Thickness' 'BalancethicknessApparentMassbalance'});
 			md = checkfield(md,'fieldname','inversion.maxsteps','numel',1,'>=',0);
 			md = checkfield(md,'fieldname','inversion.maxiter','numel',1,'>=',0);
 			md = checkfield(md,'fieldname','inversion.dxmin','numel',1,'>',0);
 			md = checkfield(md,'fieldname','inversion.gttol','numel',1,'>',0);
-			md = checkfield(md,'fieldname','inversion.cost_functions','size',[1 num_costfunc],'values',[101:105 201 501:506]);
+			md = checkfield(md,'fieldname','inversion.cost_functions','size',[1 num_costfunc],'values',[101:105 201 501:507]);
 			md = checkfield(md,'fieldname','inversion.cost_functions_coefficients','size',[md.mesh.numberofvertices num_costfunc],'>=',0);
 			md = checkfield(md,'fieldname','inversion.min_parameters','size',[md.mesh.numberofvertices num_controls]);
@@ -138,5 +138,10 @@
 			WriteData(fid,'object',obj,'class','inversion','fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts);
 			WriteData(fid,'object',obj,'class','inversion','fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts);
-			WriteData(fid,'object',obj,'class','inversion','fieldname','thickness_obs','format','DoubleMat','mattype',1);
+			if(numel(obj.thickness_obs)==md.mesh.numberofelements),
+				mattype=2;
+			else
+				mattype=1;
+			end
+			WriteData(fid,'object',obj,'class','inversion','fieldname','thickness_obs','format','DoubleMat','mattype',mattype);
 
 			%process control parameters
@@ -164,4 +169,5 @@
 			pos=find(obj.cost_functions==505); data(pos)=ThicknessAcrossGradientEnum();
 			pos=find(obj.cost_functions==506); data(pos)=BalancethicknessMisfitEnum();
+			pos=find(obj.cost_functions==507); data(pos)=Balancethickness2MisfitEnum();
 			WriteData(fid,'data',data,'enum',InversionCostFunctionsEnum(),'format','DoubleMat','mattype',3);
 			WriteData(fid,'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum(),'format','Integer');
Index: issm/trunk/src/m/classes/mask.m
===================================================================
--- issm/trunk/src/m/classes/mask.m	(revision 18081)
+++ issm/trunk/src/m/classes/mask.m	(revision 18301)
@@ -43,8 +43,11 @@
 			md = checkfield(md,'fieldname','mask.groundedice_levelset','size',[md.mesh.numberofvertices 1]);
 			md = checkfield(md,'fieldname','mask.ice_levelset'        ,'size',[md.mesh.numberofvertices 1]);
-			%isice=(md.mask.ice_levelset>0);
-			%if any(sum(isice(md.mesh.elements),2)==0),
-		%		warning('elements with no ice not implemented yet, each element should have at least one vertex with md.mask.ice_levelset > 0');
-		%	end
+			isice=(md.mask.ice_levelset<=0);
+			if sum(isice)==0,
+				warning('no ice present in the domain');
+			end
+			if max(md.mask.ice_levelset)<0,
+				warning('no ice front provided');
+			end
 		end % }}}
 		function disp(obj) % {{{
Index: issm/trunk/src/m/classes/mask.py
===================================================================
--- issm/trunk/src/m/classes/mask.py	(revision 18081)
+++ issm/trunk/src/m/classes/mask.py	(revision 18301)
@@ -34,8 +34,7 @@
 
 		md = checkfield(md,'fieldname','mask.ice_levelset'        ,'size',[md.mesh.numberofvertices])
-		#isice=numpy.array(md.mask.ice_levelset<0,int)
-		#totallyicefree=(numpy.sum(isice[md.mesh.elements-1],axis=1)==0).astype(int)
-		#if any(totallyicefree):
-		#	raise TypeError("elements with no ice not implemented yet, each element should have at least one vertex with md.mask.ice_levelset > 0")
+		isice=numpy.array(md.mask.ice_levelset<=0,int)
+		if numpy.sum(isice)==0:
+			raise TypeError("no ice present in the domain")
 
 		return md
Index: issm/trunk/src/m/classes/mesh3dprisms.m
===================================================================
--- issm/trunk/src/m/classes/mesh3dprisms.m	(revision 18081)
+++ issm/trunk/src/m/classes/mesh3dprisms.m	(revision 18301)
@@ -18,6 +18,4 @@
 		hemisphere                  = NaN
 
-		elementonbase                = NaN
-		elementonsurface            = NaN
 		vertexonbase                 = NaN
 		vertexonsurface             = NaN
@@ -163,7 +161,5 @@
 			fielddisplay(obj,'numberoflayers','number of extrusion layers');
 			fielddisplay(obj,'vertexonbase','lower vertices flags list');
-			fielddisplay(obj,'elementonbase','lower elements flags list');
 			fielddisplay(obj,'vertexonsurface','upper vertices flags list');
-			fielddisplay(obj,'elementonsurface','upper elements flags list');
 			fielddisplay(obj,'uppervertex','upper vertex list (NaN for vertex on the upper surface)');
 			fielddisplay(obj,'upperelements','upper element list (NaN for element on the upper layer)');
Index: issm/trunk/src/m/classes/mesh3dprisms.py
===================================================================
--- issm/trunk/src/m/classes/mesh3dprisms.py	(revision 18081)
+++ issm/trunk/src/m/classes/mesh3dprisms.py	(revision 18301)
@@ -27,6 +27,4 @@
 		self.hemisphere                  = float('NaN');
 
-		self.elementonbase                = float('NaN');
-		self.elementonsurface            = float('NaN');
 		self.vertexonbase                 = float('NaN');
 		self.vertexonsurface             = float('NaN');
@@ -75,7 +73,5 @@
 		string="%s\n%s"%(string,fielddisplay(self,"numberoflayers","number of extrusion layers"))
 		string="%s\n%s"%(string,fielddisplay(self,"vertexonbase","lower vertices flags list"))
-		string="%s\n%s"%(string,fielddisplay(self,"elementonbase","lower elements flags list"))
 		string="%s\n%s"%(string,fielddisplay(self,"vertexonsurface","upper vertices flags list"))
-		string="%s\n%s"%(string,fielddisplay(self,"elementonsurface","upper elements flags list"))
 		string="%s\n%s"%(string,fielddisplay(self,"uppervertex","upper vertex list (-1 for vertex on the upper surface)"))
 		string="%s\n%s"%(string,fielddisplay(self,"upperelements","upper element list (-1 for element on the upper layer)"))
Index: issm/trunk/src/m/classes/model.m
===================================================================
--- issm/trunk/src/m/classes/model.m	(revision 18081)
+++ issm/trunk/src/m/classes/model.m	(revision 18301)
@@ -208,5 +208,5 @@
 			md.stressbalance.loadingforce=project2d(md,md.stressbalance.loadingforce,md.mesh.numberoflayers);
 			md.masstransport.spcthickness=project2d(md,md.masstransport.spcthickness,md.mesh.numberoflayers);
-			md.damage.spcdamage=project2d(md,md.damage.spcdamage,md.mesh.numberoflayers)
+			if ~isnan(md.damage.spcdamage), md.damage.spcdamage=project2d(md,md.damage.spcdamage,md.mesh.numberoflayers); end
 			md.thermal.spctemperature=project2d(md,md.thermal.spctemperature,md.mesh.numberoflayers);
 
@@ -221,5 +221,6 @@
 
 			%special for thermal modeling:
-			md.basalforcings.melting_rate=project2d(md,md.basalforcings.melting_rate,1); 
+			md.basalforcings.groundedice_melting_rate=project2d(md,md.basalforcings.groundedice_melting_rate,1); 
+			md.basalforcings.floatingice_melting_rate=project2d(md,md.basalforcings.floatingice_melting_rate,1); 
 			md.basalforcings.geothermalflux=project2d(md,md.basalforcings.geothermalflux,1); %bedrock only gets geothermal flux
 
@@ -236,4 +237,5 @@
 			md.geometry.base=project2d(md,md.geometry.base,1);
 			md.geometry.bed=project2d(md,md.geometry.bed,1);
+
 			md.mask.groundedice_levelset=project2d(md,md.mask.groundedice_levelset,1);
 			md.mask.ice_levelset=project2d(md,md.mask.ice_levelset,1);
@@ -250,6 +252,6 @@
 			mesh.numberofelements=md.mesh.numberofelements2d;
 			mesh.elements=md.mesh.elements2d;
-			mesh.vertexonboundary=project2d(md,md.mesh.vertexonboundary,1);
-			mesh.elementconnectivity=project2d(md,md.mesh.elementconnectivity,1);
+			if ~isnan(md.mesh.vertexonboundary), mesh.vertexonboundary=project2d(md,md.mesh.vertexonboundary,1); end
+			if ~isnan(md.mesh.elementconnectivity), mesh.elementconnectivity=project2d(md,md.mesh.elementconnectivity,1); end
 			md.mesh=mesh;
 
@@ -550,6 +552,6 @@
 			%
 			%   Example:
-			%      md=extrude(md,8,3);
-			%      md=extrude(md,8,3,2);
+			%      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]);
 			%
@@ -709,6 +711,4 @@
 
 			%bedinfo and surface info
-			md.mesh.elementonbase=project3d(md,'vector',ones(md.mesh.numberofelements2d,1),'type','element','layer',1);
-			md.mesh.elementonsurface=project3d(md,'vector',ones(md.mesh.numberofelements2d,1),'type','element','layer',md.mesh.numberoflayers-1);
 			md.mesh.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);
@@ -760,11 +760,13 @@
 
 			%connectivity
-			md.mesh.elementconnectivity=repmat(md.mesh.elementconnectivity,numlayers-1,1);
-			md.mesh.elementconnectivity(find(md.mesh.elementconnectivity==0))=NaN;
-			for i=2:numlayers-1,
-				md.mesh.elementconnectivity((i-1)*md.mesh.numberofelements2d+1:(i)*md.mesh.numberofelements2d,:)...
-					=md.mesh.elementconnectivity((i-1)*md.mesh.numberofelements2d+1:(i)*md.mesh.numberofelements2d,:)+md.mesh.numberofelements2d;
-			end
-			md.mesh.elementconnectivity(find(isnan(md.mesh.elementconnectivity)))=0;
+			if ~isnan(md.mesh.elementconnectivity)
+				md.mesh.elementconnectivity=repmat(md.mesh.elementconnectivity,numlayers-1,1);
+				md.mesh.elementconnectivity(find(md.mesh.elementconnectivity==0))=NaN;
+				for i=2:numlayers-1,
+					md.mesh.elementconnectivity((i-1)*md.mesh.numberofelements2d+1:(i)*md.mesh.numberofelements2d,:)...
+						=md.mesh.elementconnectivity((i-1)*md.mesh.numberofelements2d+1:(i)*md.mesh.numberofelements2d,:)+md.mesh.numberofelements2d;
+				end
+				md.mesh.elementconnectivity(find(isnan(md.mesh.elementconnectivity)))=0;
+			end
 
 			%materials
@@ -797,5 +799,6 @@
 
 			%special for thermal modeling:
-			md.basalforcings.melting_rate=project3d(md,'vector',md.basalforcings.melting_rate,'type','node','layer',1); 
+			md.basalforcings.groundedice_melting_rate=project3d(md,'vector',md.basalforcings.groundedice_melting_rate,'type','node','layer',1); 
+			md.basalforcings.floatingice_melting_rate=project3d(md,'vector',md.basalforcings.floatingice_melting_rate,'type','node','layer',1); 
 			if ~isnan(md.basalforcings.geothermalflux)
 				md.basalforcings.geothermalflux=project3d(md,'vector',md.basalforcings.geothermalflux,'type','node','layer',1); %bedrock only gets geothermal flux
@@ -823,5 +826,5 @@
 			if isfield(structmd,'q'), md.friction.q=structmd.p; end
 			if isfield(structmd,'melting'), md.basalforcings.melting_rate=structmd.melting; end
-			if isfield(structmd,'melting_rate'), md.basalforcings.melting_rate=structmd.melting_rate; end
+			if isfield(structmd,'melting_rate'), md.basalforcings.floatingice_melting_rate=structmd.melting_rate; end
 			if isfield(structmd,'accumulation'), md.surfaceforcings.mass_balance=structmd.accumulation; end
 			if isfield(structmd,'numberofgrids'), md.mesh.numberofvertices=structmd.numberofgrids; end
@@ -837,6 +840,5 @@
 			if isfield(structmd,'yts'), md.constants.yts=structmd.yts; end
 			if isfield(structmd,'surface_mass_balance'), md.surfaceforcings.mass_balance=structmd.surface_mass_balance; end
-			if isfield(structmd,'basal_melting_rate'), md.basalforcings.melting_rate=structmd.basal_melting_rate; end
-			if isfield(structmd,'basal_melting_rate_correction'), md.basalforcings.melting_rate_correction=structmd.basal_melting_rate_correction; end
+			if isfield(structmd,'basal_melting_rate'), md.basalforcings.floatingice_melting_rate=structmd.basal_melting_rate; end
 			if isfield(structmd,'geothermalflux'), md.basalforcings.geothermalflux=structmd.geothermalflux; end
 			if isfield(structmd,'drag'), md.friction.coefficient=structmd.drag; end
@@ -939,6 +941,4 @@
 			if isfield(structmd,'upperelements'), md.mesh.upperelements=structmd.upperelements; end
 			if isfield(structmd,'lowerelements'), md.mesh.lowerelements=structmd.lowerelements; end
-			if isfield(structmd,'elementonbase'), md.mesh.elementonbase=structmd.elementonbase; end
-			if isfield(structmd,'elementonsurface'), md.mesh.elementonsurface=structmd.elementonsurface; end
 			if isfield(structmd,'nodeonsurface'), md.mesh.vertexonsurface=structmd.nodeonsurface; end
 			if isfield(structmd,'nodeonbase'), md.mesh.vertexonbase=structmd.nodeonbase; end
@@ -1164,5 +1164,5 @@
 					elements(3*(i-1)+2,:) = [v2 v4 v5 v6];
 					elements(3*(i-1)+3,:) = [v2 v3 v4 v6];
-				elseif(min(v2,v4)>min(v1,v5) & min(v1,v6)<min(v3,v4) & min(v3,v5)>min(v2,v6)),
+				elseif(min(v2,v4)>min(v1,v5) & min(v1,v6)<min(v3,v4) & min(v3,v5)<min(v2,v6)),
 					elements(3*(i-1)+1,:) = [v1 v4 v5 v6];
 					elements(3*(i-1)+2,:) = [v1 v2 v3 v5];
@@ -1177,5 +1177,4 @@
 					elements(3*(i-1)+3,:) = [v3 v4 v5 v6];
 				elseif(min(v2,v4)>min(v1,v5) & min(v1,v6)<min(v3,v4) & min(v3,v5)<min(v2,v6)),
-					%NEW
 					elements(3*(i-1)+1,:) = [v1 v5 v6 v4];
 					elements(3*(i-1)+2,:) = [v1 v2 v3 v5];
Index: issm/trunk/src/m/classes/model.py
===================================================================
--- issm/trunk/src/m/classes/model.py	(revision 18081)
+++ issm/trunk/src/m/classes/model.py	(revision 18301)
@@ -11,4 +11,6 @@
 from SMBpdd import SMBpdd
 from SMBgradients import SMBgradients
+from SMBcomponents import SMBcomponents
+from SMBmeltcomponents import SMBmeltcomponents
 from basalforcings import basalforcings
 from matice import matice
@@ -460,7 +462,7 @@
 
 		   Example:
-		      md=extrude(md,8,3)
-		      md=extrude(md,8,3,2)
-		      md=extrude(md,[0 0.2 0.5 0.7 0.9 0.95 1])
+				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
@@ -616,6 +618,4 @@
 
 		#bedinfo and surface info
-		md.mesh.elementonbase=project3d(md,'vector',numpy.ones(md.mesh.numberofelements2d,bool),'type','element','layer',1)
-		md.mesh.elementonsurface=project3d(md,'vector',numpy.ones(md.mesh.numberofelements2d,bool),'type','element','layer',md.mesh.numberoflayers-1)
 		md.mesh.vertexonbase=project3d(md,'vector',numpy.ones(md.mesh.numberofvertices2d,bool),'type','node','layer',1)
 		md.mesh.vertexonsurface=project3d(md,'vector',numpy.ones(md.mesh.numberofvertices2d,bool),'type','node','layer',md.mesh.numberoflayers)
@@ -657,8 +657,9 @@
 		md.mesh.elementconnectivity=numpy.tile(md.mesh.elementconnectivity,(numlayers-1,1))
 		md.mesh.elementconnectivity[numpy.nonzero(md.mesh.elementconnectivity==0)]=-sys.maxint-1
-		for i in xrange(1,numlayers-1):
-			md.mesh.elementconnectivity[i*md.mesh.numberofelements2d:(i+1)*md.mesh.numberofelements2d,:] \
-				=md.mesh.elementconnectivity[i*md.mesh.numberofelements2d:(i+1)*md.mesh.numberofelements2d,:]+md.mesh.numberofelements2d
-		md.mesh.elementconnectivity[numpy.nonzero(md.mesh.elementconnectivity<0)]=0
+		if not numpy.isnan(md.mesh.elementconnectivity).all():
+			for i in xrange(1,numlayers-1):
+				md.mesh.elementconnectivity[i*md.mesh.numberofelements2d:(i+1)*md.mesh.numberofelements2d,:] \
+						=md.mesh.elementconnectivity[i*md.mesh.numberofelements2d:(i+1)*md.mesh.numberofelements2d,:]+md.mesh.numberofelements2d
+				md.mesh.elementconnectivity[numpy.nonzero(md.mesh.elementconnectivity<0)]=0
 
 		#materials
@@ -694,5 +695,6 @@
 
 		#special for thermal modeling:
-		md.basalforcings.melting_rate=project3d(md,'vector',md.basalforcings.melting_rate,'type','node','layer',1)
+		md.basalforcings.groundedice_melting_rate=project3d(md,'vector',md.basalforcings.groundedice_melting_rate,'type','node','layer',1)
+		md.basalforcings.floatingice_melting_rate=project3d(md,'vector',md.basalforcings.floatingice_melting_rate,'type','node','layer',1)
 		if not numpy.any(numpy.isnan(md.basalforcings.geothermalflux)):
 			md.basalforcings.geothermalflux=project3d(md,'vector',md.basalforcings.geothermalflux,'type','node','layer',1)    #bedrock only gets geothermal flux
@@ -764,5 +766,5 @@
 		md.stressbalance.loadingforce=project2d(md,md.stressbalance.loadingforce,md.mesh.numberoflayers)
 		md.masstransport.spcthickness=project2d(md,md.masstransport.spcthickness,md.mesh.numberoflayers)
-		md.damage.spcdamage=project2d(md,md.damage.spcdamage,md.mesh.numberoflayers-1)
+		if not numpy.isnan(md.damage.spcdamage).all(): md.damage.spcdamage=project2d(md,md.damage.spcdamage,md.mesh.numberoflayers-1)
 		md.thermal.spctemperature=project2d(md,md.thermal.spctemperature,md.mesh.numberoflayers-1)
 
@@ -776,5 +778,6 @@
 
 		#special for thermal modeling:
-		md.basalforcings.melting_rate=project2d(md,md.basalforcings.melting_rate,1) 
+		md.basalforcings.groundedice_melting_rate=project2d(md,md.basalforcings.groundedice_melting_rate,1) 
+		md.basalforcings.floatingice_melting_rate=project2d(md,md.basalforcings.floatingice_melting_rate,1) 
 		md.basalforcings.geothermalflux=project2d(md,md.basalforcings.geothermalflux,1) #bedrock only gets geothermal flux
 
@@ -805,6 +808,6 @@
 		mesh.numberofelements=md.mesh.numberofelements2d
 		mesh.elements=md.mesh.elements2d
-		mesh.vertexonboundary=project2d(md,md.mesh.vertexonboundary,1)
-		mesh.elementconnectivity=project2d(md,md.mesh.elementconnectivity,1)
+		if not numpy.isnan(md.mesh.vertexonboundary).all(): mesh.vertexonboundary=project2d(md,md.mesh.vertexonboundary,1)
+		if not numpy.isnan(md.mesh.elementconnectivity).all(): mesh.elementconnectivity=project2d(md,md.mesh.elementconnectivity,1)
 		md.mesh=mesh
 
Index: issm/trunk/src/m/classes/taoinversion.m
===================================================================
--- issm/trunk/src/m/classes/taoinversion.m	(revision 18081)
+++ issm/trunk/src/m/classes/taoinversion.m	(revision 18301)
@@ -183,4 +183,5 @@
 			pos=find(obj.cost_functions==505); data(pos)=ThicknessAcrossGradientEnum();
 			pos=find(obj.cost_functions==506); data(pos)=BalancethicknessMisfitEnum();
+			pos=find(obj.cost_functions==507); data(pos)=Balancethickness2MisfitEnum();
 			WriteData(fid,'data',data,'enum',InversionCostFunctionsEnum(),'format','DoubleMat','mattype',3);
 			WriteData(fid,'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum(),'format','Integer');
Index: issm/trunk/src/m/classes/thermal.m
===================================================================
--- issm/trunk/src/m/classes/thermal.m	(revision 18081)
+++ issm/trunk/src/m/classes/thermal.m	(revision 18301)
@@ -51,7 +51,7 @@
 
 			if self.isenthalpy,
-				list = {'Enthalpy','Temperature','Waterfraction','Watercolumn','BasalforcingsMeltingRate'};
+				list = {'Enthalpy','Temperature','Waterfraction','Watercolumn','BasalforcingsGroundediceMeltingRate'};
 			else
-				list = {'Temperature','BasalforcingsMeltingRate'};
+				list = {'Temperature','BasalforcingsGroundediceMeltingRate'};
 			end
 
Index: issm/trunk/src/m/classes/thermal.py
===================================================================
--- issm/trunk/src/m/classes/thermal.py	(revision 18081)
+++ issm/trunk/src/m/classes/thermal.py	(revision 18301)
@@ -44,7 +44,7 @@
 
 		if self.isenthalpy:
-			return ['Enthalpy','Temperature','Waterfraction','Watercolumn','BasalforcingsMeltingRate']
+			return ['Enthalpy','Temperature','Waterfraction','Watercolumn','BasalforcingsGroundediceMeltingRate']
 		else:
-			return ['Temperature','BasalforcingsMeltingRate']
+			return ['Temperature','BasalforcingsGroundediceMeltingRate']
 
 	#}}}
Index: issm/trunk/src/m/classes/timestepping.m
===================================================================
--- issm/trunk/src/m/classes/timestepping.m	(revision 18081)
+++ issm/trunk/src/m/classes/timestepping.m	(revision 18301)
@@ -11,4 +11,5 @@
 		time_adapt      = 0;
 		cfl_coefficient = 0.;
+		interp_forcings = 1;
 	end
 	methods
@@ -46,4 +47,7 @@
 			obj.time_adapt=0;
 			obj.cfl_coefficient=0.5;
+
+			%should we interpolate forcings between timesteps?
+			obj.interp_forcings=1;
 		end % }}}
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
@@ -54,4 +58,5 @@
 			md = checkfield(md,'fieldname','timestepping.time_adapt','numel',[1],'values',[0 1]);
 			md = checkfield(md,'fieldname','timestepping.cfl_coefficient','numel',[1],'>',0,'<=',1);
+			md = checkfield(md,'fieldname','timestepping.interp_forcings','numel',[1],'values',[0 1]);
 			if obj.final_time-obj.start_time<0,
 				md = checkmessage(md,'timestepping.final_time should be larger than timestepping.start_time');
@@ -66,4 +71,5 @@
 			fielddisplay(obj,'time_adapt','use cfl condition to define time step ? (0 or 1) ');
 			fielddisplay(obj,'cfl_coefficient','coefficient applied to cfl condition');
+			fielddisplay(obj,'interp_forcings','interpolate in time between requested forcing values ? (0 or 1)');
 
 		end % }}}
@@ -77,4 +83,5 @@
 			WriteData(fid,'object',obj,'fieldname','time_adapt','format','Boolean');
 			WriteData(fid,'object',obj,'fieldname','cfl_coefficient','format','Double');
+			WriteData(fid,'object',obj,'fieldname','interp_forcings','format','Boolean');
 		end % }}}
 	end
Index: issm/trunk/src/m/classes/timestepping.py
===================================================================
--- issm/trunk/src/m/classes/timestepping.py	(revision 18081)
+++ issm/trunk/src/m/classes/timestepping.py	(revision 18301)
@@ -18,4 +18,5 @@
 		self.time_adapt      = 0
 		self.cfl_coefficient = 0.
+		self.interp_forcings = 1
 		
 		#set defaults
@@ -30,4 +31,5 @@
 		string="%s\n%s"%(string,fielddisplay(self,"time_adapt","use cfl condition to define time step ? (0 or 1) "))
 		string="%s\n%s"%(string,fielddisplay(self,"cfl_coefficient","coefficient applied to cfl condition"))
+		string="%s\n%s"%(string,fielddisplay(self,"interp_forcings","interpolate in time between requested forcing values ? (0 or 1)"))
 		return string
 		#}}}
@@ -43,4 +45,7 @@
 		self.time_adapt=0
 		self.cfl_coefficient=0.5
+		
+		#should we interpolate forcings between timesteps?
+		self.interp_forcings=1
 
 		return self
@@ -55,4 +60,5 @@
 		if self.final_time-self.start_time<0:
 			md.checkmessage("timestepping.final_time should be larger than timestepping.start_time")
+		md = checkfield(md,'fieldname','timestepping.interp_forcings','numel',[1],'values',[0,1])
 
 		return md
@@ -67,3 +73,4 @@
 		WriteData(fid,'object',self,'fieldname','time_adapt','format','Boolean')
 		WriteData(fid,'object',self,'fieldname','cfl_coefficient','format','Double')
+		WriteData(fid,'object',self,'fieldname','interp_forcings','format','Boolean')
 	# }}}
Index: issm/trunk/src/m/consistency/checkfield.m
===================================================================
--- issm/trunk/src/m/consistency/checkfield.m	(revision 18081)
+++ issm/trunk/src/m/consistency/checkfield.m	(revision 18301)
@@ -23,7 +23,4 @@
 %   Usage:
 %      md = checkfield(md,fieldname,options);
-%
-%   Example:
-%      md = checkfield(md,'mesh.elementonbase','size',[md.mesh.numberofelements 1],'values',[0 1]);
 
 %get options
Index: issm/trunk/src/m/consistency/checkfield.py
===================================================================
--- issm/trunk/src/m/consistency/checkfield.py	(revision 18081)
+++ issm/trunk/src/m/consistency/checkfield.py	(revision 18301)
@@ -30,7 +30,4 @@
 	   Usage:
 	      md = checkfield(md,fieldname,options);
-
-	   Example:
-	      md = checkfield(md,'mesh.elementonbase','size',[md.mesh.numberofelements 1],'values',[0 1]);
 	"""
 
Index: issm/trunk/src/m/contrib/bamg/gmsh3d.m
===================================================================
--- issm/trunk/src/m/contrib/bamg/gmsh3d.m	(revision 18301)
+++ issm/trunk/src/m/contrib/bamg/gmsh3d.m	(revision 18301)
@@ -0,0 +1,103 @@
+function md=gmsh3d(md,domainfile,h),
+
+%Read domain
+domain=expread(domainfile);
+x   = domain.x(1:end-1);
+y   = domain.y(1:end-1);
+nbv = numel(x);
+
+%write files
+t1=clock; fprintf('%s','      writing initial mesh files...');
+fid=fopen('model.geo','w');
+fprintf(fid,['// Gmsh input file, created by ISSM on ' date '\n']);
+
+%Lower points
+for i=1:nbv,
+	fprintf(fid,'Point(%i) = {%8g, %8g, %8g};\n',i,x(i),y(i),0.);
+end
+%Upper points
+for i=1:nbv,
+	fprintf(fid,'Point(%i) = {%8g, %8g, %8g};\n',nbv+i,x(i),y(i),1.);
+end
+
+%Lower lines
+for i=1:nbv-1
+	fprintf(fid,'Line(%i) = {%i, %i};\n',i,i,i+1);
+end
+fprintf(fid,'Line(%i) = {%i, %i};\n',nbv,nbv,1);
+%Upper lines
+for i=nbv+1:2*nbv-1
+	fprintf(fid,'Line(%i) = {%i, %i};\n',i,i,i+1);
+end
+fprintf(fid,'Line(%i) = {%i, %i};\n',2*nbv,2*nbv,nbv+1);
+%Side lines
+for i=1:nbv
+	fprintf(fid,'Line(%i) = {%i, %i};\n',2*nbv+i,i,nbv+i);
+end
+
+counter = 3*nbv;
+ps = zeros(nbv+2,1);
+%Lower surface Loop and surface
+counter = counter+1;
+fprintf(fid,['Line Loop(' num2str(counter) ') = {']);
+for i=1:nbv-1
+	fprintf(fid,'%i,',i);
+end
+fprintf(fid,'%i};\n',nbv);
+fprintf(fid,['Plane Surface(' num2str(counter+1) ') = {' num2str(counter) '};\n']);
+ps(1)=counter+1;
+counter = counter+1;
+%Upper surface Loop and surface
+counter = counter+1;
+fprintf(fid,['Line Loop(' num2str(counter) ') = {']);
+for i=nbv+1:2*nbv-1
+	fprintf(fid,'%i,',i);
+end
+fprintf(fid,'%i};\n',2*nbv);
+ps(2)=counter+1;
+fprintf(fid,['Plane Surface(' num2str(counter+1) ') = {' num2str(counter) '};\n']);
+counter = counter+2;
+%Sides surfaces
+for i=1:nbv-1,
+	fprintf(fid,['Line Loop(' num2str(counter) ') = {' num2str(i) ',' num2str(2*nbv+i+1) ',-' num2str(nbv+i) ',-' num2str(2*nbv+i) '};\n']);
+	fprintf(fid,['Plane Surface(' num2str(counter+1) ') = {' num2str(counter) '};\n']);
+	ps(2+i)=counter+1;
+	counter=counter+2;
+end
+fprintf(fid,['Line Loop(' num2str(counter) ') = {' num2str(nbv) ',' num2str(2*nbv+1) ',-' num2str(2*nbv) ',-' num2str(3*nbv) '};\n']);
+fprintf(fid,['Plane Surface(' num2str(counter+1) ') = {' num2str(counter) '};\n']);
+ps(2+nbv)=counter+1;
+counter=counter+2;
+
+%Physical surfaces
+counter = counter+1;
+fprintf(fid,['Surface Loop(' num2str(counter) ') = {']);
+for i=1:numel(ps)-1
+	fprintf(fid,'%i,',ps(i));
+end
+fprintf(fid,'%i};\n',ps(end));
+fprintf(fid,['Physical Surface(1) = {' num2str(ps(2)) '};\n']);
+fprintf(fid,['Physical Surface(2) = {' num2str(ps(1)) '};\n']);
+fprintf(fid,['Physical Surface(3) = {']);
+for i=3:numel(ps)-1
+	fprintf(fid,'%i,',ps(i));
+end
+fprintf(fid,'%i};\n',ps(end));
+
+%Volume
+fprintf(fid,['Volume(1) = {' num2str(counter) '};\n']);
+fprintf(fid,['Physical Volume(2) = {1};\n']);
+
+%resolution
+fprintf(fid,'Mesh.CharacteristicLengthMax = %g;',h);
+fclose(fid);
+
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%call gmsh
+fprintf('%s\n','      call gmsh...');
+system([issmdir() '/externalpackages/gmsh/install/gmsh -3 model.geo']);
+
+%plug new mesh
+t1=clock; fprintf('\n%s','      reading final mesh files...');
+md=importgmsh('model.msh',3);
Index: issm/trunk/src/m/contrib/bamg/yams.m
===================================================================
--- issm/trunk/src/m/contrib/bamg/yams.m	(revision 18081)
+++ issm/trunk/src/m/contrib/bamg/yams.m	(revision 18301)
@@ -108,6 +108,4 @@
 md.mesh.vertexonbase=ones(md.mesh.numberofvertices,1);
 md.mesh.vertexonsurface=ones(md.mesh.numberofvertices,1);
-md.mesh.elementonbase=ones(md.mesh.numberofelements,1);
-md.mesh.elementonsurface=ones(md.mesh.numberofelements,1);
 if strcmpi(Names.interp,'node'),
 	md.inversion.vx_obs=InterpFromGridToMesh(Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vxname),md.mesh.x,md.mesh.y,0);
Index: issm/trunk/src/m/contrib/hack/tres.m
===================================================================
--- issm/trunk/src/m/contrib/hack/tres.m	(revision 18081)
+++ issm/trunk/src/m/contrib/hack/tres.m	(revision 18301)
@@ -67,5 +67,5 @@
 	md.initialization.pressure=md.results.SteadystateSolution.Pressure;
 	md.initialization.temperature=md.results.SteadystateSolution.Temperature;
-	md.basalforcings.melting_rate=md.results.SteadystateSolution.BasalforcingsMeltingRate;
+	md.basalforcings.groundedice_melting_rate=md.results.SteadystateSolution.BasalforcingsGroundediceMeltingRate;
 
 	if md.inversion.iscontrol==1,
@@ -77,5 +77,5 @@
 elseif strcmpi(string,'thermal'),
 	md.initialization.temperature=md.results.ThermalSolution.Temperature;
-	md.basalforcings.melting_rate=md.results.ThermalSolution.BasalMeltingRate;
+	md.basalforcings.groundedice_melting_rate=md.results.ThermalSolution.BasalGroundediceMeltingRate;
 elseif strcmpi(string,'hydrology'),
 	md.initialization.watercolumn=md.results.HydrologySolution.Watercolumn;
Index: issm/trunk/src/m/enum/AugmentedLagrangianRholambdaEnum.m
===================================================================
--- issm/trunk/src/m/enum/AugmentedLagrangianRholambdaEnum.m	(revision 18301)
+++ issm/trunk/src/m/enum/AugmentedLagrangianRholambdaEnum.m	(revision 18301)
@@ -0,0 +1,11 @@
+function macro=AugmentedLagrangianRholambdaEnum()
+%AUGMENTEDLAGRANGIANRHOLAMBDAENUM - Enum of AugmentedLagrangianRholambda
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AugmentedLagrangianRholambdaEnum()
+
+macro=StringToEnum('AugmentedLagrangianRholambda');
Index: issm/trunk/src/m/enum/AugmentedLagrangianRhopEnum.m
===================================================================
--- issm/trunk/src/m/enum/AugmentedLagrangianRhopEnum.m	(revision 18301)
+++ issm/trunk/src/m/enum/AugmentedLagrangianRhopEnum.m	(revision 18301)
@@ -0,0 +1,11 @@
+function macro=AugmentedLagrangianRhopEnum()
+%AUGMENTEDLAGRANGIANRHOPENUM - Enum of AugmentedLagrangianRhop
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AugmentedLagrangianRhopEnum()
+
+macro=StringToEnum('AugmentedLagrangianRhop');
Index: issm/trunk/src/m/enum/AugmentedLagrangianRlambdaEnum.m
===================================================================
--- issm/trunk/src/m/enum/AugmentedLagrangianRlambdaEnum.m	(revision 18301)
+++ issm/trunk/src/m/enum/AugmentedLagrangianRlambdaEnum.m	(revision 18301)
@@ -0,0 +1,11 @@
+function macro=AugmentedLagrangianRlambdaEnum()
+%AUGMENTEDLAGRANGIANRLAMBDAENUM - Enum of AugmentedLagrangianRlambda
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=AugmentedLagrangianRlambdaEnum()
+
+macro=StringToEnum('AugmentedLagrangianRlambda');
Index: issm/trunk/src/m/enum/BasalforcingsDeepwaterElevationEnum.m
===================================================================
--- issm/trunk/src/m/enum/BasalforcingsDeepwaterElevationEnum.m	(revision 18301)
+++ issm/trunk/src/m/enum/BasalforcingsDeepwaterElevationEnum.m	(revision 18301)
@@ -0,0 +1,11 @@
+function macro=BasalforcingsDeepwaterElevationEnum()
+%BASALFORCINGSDEEPWATERELEVATIONENUM - Enum of BasalforcingsDeepwaterElevation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BasalforcingsDeepwaterElevationEnum()
+
+macro=StringToEnum('BasalforcingsDeepwaterElevation');
Index: issm/trunk/src/m/enum/BasalforcingsDeepwaterMeltingRateEnum.m
===================================================================
--- issm/trunk/src/m/enum/BasalforcingsDeepwaterMeltingRateEnum.m	(revision 18301)
+++ issm/trunk/src/m/enum/BasalforcingsDeepwaterMeltingRateEnum.m	(revision 18301)
@@ -0,0 +1,11 @@
+function macro=BasalforcingsDeepwaterMeltingRateEnum()
+%BASALFORCINGSDEEPWATERMELTINGRATEENUM - Enum of BasalforcingsDeepwaterMeltingRate
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BasalforcingsDeepwaterMeltingRateEnum()
+
+macro=StringToEnum('BasalforcingsDeepwaterMeltingRate');
Index: issm/trunk/src/m/enum/BasalforcingsEnum.m
===================================================================
--- issm/trunk/src/m/enum/BasalforcingsEnum.m	(revision 18301)
+++ issm/trunk/src/m/enum/BasalforcingsEnum.m	(revision 18301)
@@ -0,0 +1,11 @@
+function macro=BasalforcingsEnum()
+%BASALFORCINGSENUM - Enum of Basalforcings
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BasalforcingsEnum()
+
+macro=StringToEnum('Basalforcings');
Index: issm/trunk/src/m/enum/BasalforcingsFloatingiceMeltingRateEnum.m
===================================================================
--- issm/trunk/src/m/enum/BasalforcingsFloatingiceMeltingRateEnum.m	(revision 18301)
+++ issm/trunk/src/m/enum/BasalforcingsFloatingiceMeltingRateEnum.m	(revision 18301)
@@ -0,0 +1,11 @@
+function macro=BasalforcingsFloatingiceMeltingRateEnum()
+%BASALFORCINGSFLOATINGICEMELTINGRATEENUM - Enum of BasalforcingsFloatingiceMeltingRate
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BasalforcingsFloatingiceMeltingRateEnum()
+
+macro=StringToEnum('BasalforcingsFloatingiceMeltingRate');
Index: issm/trunk/src/m/enum/BasalforcingsGroundediceMeltingRateEnum.m
===================================================================
--- issm/trunk/src/m/enum/BasalforcingsGroundediceMeltingRateEnum.m	(revision 18301)
+++ issm/trunk/src/m/enum/BasalforcingsGroundediceMeltingRateEnum.m	(revision 18301)
@@ -0,0 +1,11 @@
+function macro=BasalforcingsGroundediceMeltingRateEnum()
+%BASALFORCINGSGROUNDEDICEMELTINGRATEENUM - Enum of BasalforcingsGroundediceMeltingRate
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BasalforcingsGroundediceMeltingRateEnum()
+
+macro=StringToEnum('BasalforcingsGroundediceMeltingRate');
Index: issm/trunk/src/m/enum/BasalforcingsMeltingRateCorrectionEnum.m
===================================================================
--- issm/trunk/src/m/enum/BasalforcingsMeltingRateCorrectionEnum.m	(revision 18081)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=BasalforcingsMeltingRateCorrectionEnum()
-%BASALFORCINGSMELTINGRATECORRECTIONENUM - Enum of BasalforcingsMeltingRateCorrection
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=BasalforcingsMeltingRateCorrectionEnum()
-
-macro=StringToEnum('BasalforcingsMeltingRateCorrection');
Index: issm/trunk/src/m/enum/BasalforcingsMeltingRateEnum.m
===================================================================
--- issm/trunk/src/m/enum/BasalforcingsMeltingRateEnum.m	(revision 18081)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=BasalforcingsMeltingRateEnum()
-%BASALFORCINGSMELTINGRATEENUM - Enum of BasalforcingsMeltingRate
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=BasalforcingsMeltingRateEnum()
-
-macro=StringToEnum('BasalforcingsMeltingRate');
Index: issm/trunk/src/m/enum/BasalforcingsUpperwaterElevationEnum.m
===================================================================
--- issm/trunk/src/m/enum/BasalforcingsUpperwaterElevationEnum.m	(revision 18301)
+++ issm/trunk/src/m/enum/BasalforcingsUpperwaterElevationEnum.m	(revision 18301)
@@ -0,0 +1,11 @@
+function macro=BasalforcingsUpperwaterElevationEnum()
+%BASALFORCINGSUPPERWATERELEVATIONENUM - Enum of BasalforcingsUpperwaterElevation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BasalforcingsUpperwaterElevationEnum()
+
+macro=StringToEnum('BasalforcingsUpperwaterElevation');
Index: issm/trunk/src/m/enum/CrouzeixRaviartEnum.m
===================================================================
--- issm/trunk/src/m/enum/CrouzeixRaviartEnum.m	(revision 18301)
+++ issm/trunk/src/m/enum/CrouzeixRaviartEnum.m	(revision 18301)
@@ -0,0 +1,11 @@
+function macro=CrouzeixRaviartEnum()
+%CROUZEIXRAVIARTENUM - Enum of CrouzeixRaviart
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=CrouzeixRaviartEnum()
+
+macro=StringToEnum('CrouzeixRaviart');
Index: issm/trunk/src/m/enum/EnumDefinitions.py
===================================================================
--- issm/trunk/src/m/enum/EnumDefinitions.py	(revision 18081)
+++ issm/trunk/src/m/enum/EnumDefinitions.py	(revision 18301)
@@ -38,7 +38,13 @@
 def BalancethicknessStabilizationEnum(): return StringToEnum("BalancethicknessStabilization")[0]
 def BalancethicknessThickeningRateEnum(): return StringToEnum("BalancethicknessThickeningRate")[0]
+def BasalforcingsEnum(): return StringToEnum("Basalforcings")[0]
 def BasalforcingsGeothermalfluxEnum(): return StringToEnum("BasalforcingsGeothermalflux")[0]
-def BasalforcingsMeltingRateCorrectionEnum(): return StringToEnum("BasalforcingsMeltingRateCorrection")[0]
-def BasalforcingsMeltingRateEnum(): return StringToEnum("BasalforcingsMeltingRate")[0]
+def BasalforcingsGroundediceMeltingRateEnum(): return StringToEnum("BasalforcingsGroundediceMeltingRate")[0]
+def BasalforcingsFloatingiceMeltingRateEnum(): return StringToEnum("BasalforcingsFloatingiceMeltingRate")[0]
+def BasalforcingsDeepwaterMeltingRateEnum(): return StringToEnum("BasalforcingsDeepwaterMeltingRate")[0]
+def BasalforcingsDeepwaterElevationEnum(): return StringToEnum("BasalforcingsDeepwaterElevation")[0]
+def BasalforcingsUpperwaterElevationEnum(): return StringToEnum("BasalforcingsUpperwaterElevation")[0]
+def FloatingMeltRateEnum(): return StringToEnum("FloatingMeltRate")[0]
+def LinearFloatingMeltRateEnum(): return StringToEnum("LinearFloatingMeltRate")[0]
 def BedEnum(): return StringToEnum("Bed")[0]
 def BaseEnum(): return StringToEnum("Base")[0]
@@ -194,4 +200,5 @@
 def DamageEvolutionNumRequestedOutputsEnum(): return StringToEnum("DamageEvolutionNumRequestedOutputs")[0]
 def DamageEvolutionRequestedOutputsEnum(): return StringToEnum("DamageEvolutionRequestedOutputs")[0]
+def NewDamageEnum(): return StringToEnum("NewDamage")[0]
 def MaterialsRhoIceEnum(): return StringToEnum("MaterialsRhoIce")[0]
 def MaterialsRhoSeawaterEnum(): return StringToEnum("MaterialsRhoSeawater")[0]
@@ -322,4 +329,11 @@
 def SurfaceforcingsBNegEnum(): return StringToEnum("SurfaceforcingsBNeg")[0]
 def SMBhenningEnum(): return StringToEnum("SMBhenning")[0]
+def SMBcomponentsEnum(): return StringToEnum("SMBcomponents")[0]
+def SurfaceforcingsAccumulationEnum(): return StringToEnum("SurfaceforcingsAccumulation")[0]
+def SurfaceforcingsEvaporationEnum(): return StringToEnum("SurfaceforcingsEvaporation")[0]
+def SurfaceforcingsRunoffEnum(): return StringToEnum("SurfaceforcingsRunoff")[0]
+def SMBmeltcomponentsEnum(): return StringToEnum("SMBmeltcomponents")[0]
+def SurfaceforcingsMeltEnum(): return StringToEnum("SurfaceforcingsMelt")[0]
+def SurfaceforcingsRefreezeEnum(): return StringToEnum("SurfaceforcingsRefreeze")[0]
 def SurfaceforcingsIspddEnum(): return StringToEnum("SurfaceforcingsIspdd")[0]
 def SurfaceforcingsIssmbgradientsEnum(): return StringToEnum("SurfaceforcingsIssmbgradients")[0]
@@ -372,4 +386,5 @@
 def ThermalSolutionEnum(): return StringToEnum("ThermalSolution")[0]
 def TransientSolutionEnum(): return StringToEnum("TransientSolution")[0]
+def UzawaPressureAnalysisEnum(): return StringToEnum("UzawaPressureAnalysis")[0]
 def GiaSolutionEnum(): return StringToEnum("GiaSolution")[0]
 def GiaAnalysisEnum(): return StringToEnum("GiaAnalysis")[0]
@@ -475,5 +490,4 @@
 def FractionIncrementEnum(): return StringToEnum("FractionIncrement")[0]
 def FrictionEnum(): return StringToEnum("Friction")[0]
-def GroundinglineMeltingRateEnum(): return StringToEnum("GroundinglineMeltingRate")[0]
 def InternalEnum(): return StringToEnum("Internal")[0]
 def MassFluxEnum(): return StringToEnum("MassFlux")[0]
@@ -571,4 +585,6 @@
 def P1bubblecondensedEnum(): return StringToEnum("P1bubblecondensed")[0]
 def P2Enum(): return StringToEnum("P2")[0]
+def P2bubbleEnum(): return StringToEnum("P2bubble")[0]
+def P2bubblecondensedEnum(): return StringToEnum("P2bubblecondensed")[0]
 def P2xP1Enum(): return StringToEnum("P2xP1")[0]
 def P1xP2Enum(): return StringToEnum("P1xP2")[0]
@@ -580,6 +596,8 @@
 def MINIcondensedEnum(): return StringToEnum("MINIcondensed")[0]
 def TaylorHoodEnum(): return StringToEnum("TaylorHood")[0]
+def LATaylorHoodEnum(): return StringToEnum("LATaylorHood")[0]
 def XTaylorHoodEnum(): return StringToEnum("XTaylorHood")[0]
 def OneLayerP4zEnum(): return StringToEnum("OneLayerP4z")[0]
+def CrouzeixRaviartEnum(): return StringToEnum("CrouzeixRaviart")[0]
 def SaveResultsEnum(): return StringToEnum("SaveResults")[0]
 def BoolExternalResultEnum(): return StringToEnum("BoolExternalResult")[0]
@@ -623,4 +641,7 @@
 def IncrementalEnum(): return StringToEnum("Incremental")[0]
 def AugmentedLagrangianREnum(): return StringToEnum("AugmentedLagrangianR")[0]
+def AugmentedLagrangianRhopEnum(): return StringToEnum("AugmentedLagrangianRhop")[0]
+def AugmentedLagrangianRlambdaEnum(): return StringToEnum("AugmentedLagrangianRlambda")[0]
+def AugmentedLagrangianRholambdaEnum(): return StringToEnum("AugmentedLagrangianRholambda")[0]
 def AugmentedLagrangianThetaEnum(): return StringToEnum("AugmentedLagrangianTheta")[0]
 def NoneEnum(): return StringToEnum("None")[0]
Index: issm/trunk/src/m/enum/FloatingMeltRateEnum.m
===================================================================
--- issm/trunk/src/m/enum/FloatingMeltRateEnum.m	(revision 18301)
+++ issm/trunk/src/m/enum/FloatingMeltRateEnum.m	(revision 18301)
@@ -0,0 +1,11 @@
+function macro=FloatingMeltRateEnum()
+%FLOATINGMELTRATEENUM - Enum of FloatingMeltRate
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FloatingMeltRateEnum()
+
+macro=StringToEnum('FloatingMeltRate');
Index: issm/trunk/src/m/enum/GroundinglineMeltingRateEnum.m
===================================================================
--- issm/trunk/src/m/enum/GroundinglineMeltingRateEnum.m	(revision 18081)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=GroundinglineMeltingRateEnum()
-%GROUNDINGLINEMELTINGRATEENUM - Enum of GroundinglineMeltingRate
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=GroundinglineMeltingRateEnum()
-
-macro=StringToEnum('GroundinglineMeltingRate');
Index: issm/trunk/src/m/enum/LATaylorHoodEnum.m
===================================================================
--- issm/trunk/src/m/enum/LATaylorHoodEnum.m	(revision 18301)
+++ issm/trunk/src/m/enum/LATaylorHoodEnum.m	(revision 18301)
@@ -0,0 +1,11 @@
+function macro=LATaylorHoodEnum()
+%LATAYLORHOODENUM - Enum of LATaylorHood
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=LATaylorHoodEnum()
+
+macro=StringToEnum('LATaylorHood');
Index: issm/trunk/src/m/enum/LinearFloatingMeltRateEnum.m
===================================================================
--- issm/trunk/src/m/enum/LinearFloatingMeltRateEnum.m	(revision 18301)
+++ issm/trunk/src/m/enum/LinearFloatingMeltRateEnum.m	(revision 18301)
@@ -0,0 +1,11 @@
+function macro=LinearFloatingMeltRateEnum()
+%LINEARFLOATINGMELTRATEENUM - Enum of LinearFloatingMeltRate
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=LinearFloatingMeltRateEnum()
+
+macro=StringToEnum('LinearFloatingMeltRate');
Index: issm/trunk/src/m/enum/NewDamageEnum.m
===================================================================
--- issm/trunk/src/m/enum/NewDamageEnum.m	(revision 18301)
+++ issm/trunk/src/m/enum/NewDamageEnum.m	(revision 18301)
@@ -0,0 +1,11 @@
+function macro=NewDamageEnum()
+%NEWDAMAGEENUM - Enum of NewDamage
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=NewDamageEnum()
+
+macro=StringToEnum('NewDamage');
Index: issm/trunk/src/m/enum/P2bubbleEnum.m
===================================================================
--- issm/trunk/src/m/enum/P2bubbleEnum.m	(revision 18301)
+++ issm/trunk/src/m/enum/P2bubbleEnum.m	(revision 18301)
@@ -0,0 +1,11 @@
+function macro=P2bubbleEnum()
+%P2BUBBLEENUM - Enum of P2bubble
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=P2bubbleEnum()
+
+macro=StringToEnum('P2bubble');
Index: issm/trunk/src/m/enum/P2bubblecondensedEnum.m
===================================================================
--- issm/trunk/src/m/enum/P2bubblecondensedEnum.m	(revision 18301)
+++ issm/trunk/src/m/enum/P2bubblecondensedEnum.m	(revision 18301)
@@ -0,0 +1,11 @@
+function macro=P2bubblecondensedEnum()
+%P2BUBBLECONDENSEDENUM - Enum of P2bubblecondensed
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=P2bubblecondensedEnum()
+
+macro=StringToEnum('P2bubblecondensed');
Index: issm/trunk/src/m/enum/SMBcomponentsEnum.m
===================================================================
--- issm/trunk/src/m/enum/SMBcomponentsEnum.m	(revision 18301)
+++ issm/trunk/src/m/enum/SMBcomponentsEnum.m	(revision 18301)
@@ -0,0 +1,11 @@
+function macro=SMBcomponentsEnum()
+%SMBCOMPONENTSENUM - Enum of SMBcomponents
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SMBcomponentsEnum()
+
+macro=StringToEnum('SMBcomponents');
Index: issm/trunk/src/m/enum/SMBmeltcomponentsEnum.m
===================================================================
--- issm/trunk/src/m/enum/SMBmeltcomponentsEnum.m	(revision 18301)
+++ issm/trunk/src/m/enum/SMBmeltcomponentsEnum.m	(revision 18301)
@@ -0,0 +1,11 @@
+function macro=SMBmeltcomponentsEnum()
+%SMBMELTCOMPONENTSENUM - Enum of SMBmeltcomponents
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SMBmeltcomponentsEnum()
+
+macro=StringToEnum('SMBmeltcomponents');
Index: issm/trunk/src/m/enum/SurfaceforcingsAccumulationEnum.m
===================================================================
--- issm/trunk/src/m/enum/SurfaceforcingsAccumulationEnum.m	(revision 18301)
+++ issm/trunk/src/m/enum/SurfaceforcingsAccumulationEnum.m	(revision 18301)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsAccumulationEnum()
+%SURFACEFORCINGSACCUMULATIONENUM - Enum of SurfaceforcingsAccumulation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsAccumulationEnum()
+
+macro=StringToEnum('SurfaceforcingsAccumulation');
Index: issm/trunk/src/m/enum/SurfaceforcingsEvaporationEnum.m
===================================================================
--- issm/trunk/src/m/enum/SurfaceforcingsEvaporationEnum.m	(revision 18301)
+++ issm/trunk/src/m/enum/SurfaceforcingsEvaporationEnum.m	(revision 18301)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsEvaporationEnum()
+%SURFACEFORCINGSEVAPORATIONENUM - Enum of SurfaceforcingsEvaporation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsEvaporationEnum()
+
+macro=StringToEnum('SurfaceforcingsEvaporation');
Index: issm/trunk/src/m/enum/SurfaceforcingsMeltEnum.m
===================================================================
--- issm/trunk/src/m/enum/SurfaceforcingsMeltEnum.m	(revision 18301)
+++ issm/trunk/src/m/enum/SurfaceforcingsMeltEnum.m	(revision 18301)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsMeltEnum()
+%SURFACEFORCINGSMELTENUM - Enum of SurfaceforcingsMelt
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsMeltEnum()
+
+macro=StringToEnum('SurfaceforcingsMelt');
Index: issm/trunk/src/m/enum/SurfaceforcingsRefreezeEnum.m
===================================================================
--- issm/trunk/src/m/enum/SurfaceforcingsRefreezeEnum.m	(revision 18301)
+++ issm/trunk/src/m/enum/SurfaceforcingsRefreezeEnum.m	(revision 18301)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsRefreezeEnum()
+%SURFACEFORCINGSREFREEZEENUM - Enum of SurfaceforcingsRefreeze
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsRefreezeEnum()
+
+macro=StringToEnum('SurfaceforcingsRefreeze');
Index: issm/trunk/src/m/enum/SurfaceforcingsRunoffEnum.m
===================================================================
--- issm/trunk/src/m/enum/SurfaceforcingsRunoffEnum.m	(revision 18301)
+++ issm/trunk/src/m/enum/SurfaceforcingsRunoffEnum.m	(revision 18301)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsRunoffEnum()
+%SURFACEFORCINGSRUNOFFENUM - Enum of SurfaceforcingsRunoff
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsRunoffEnum()
+
+macro=StringToEnum('SurfaceforcingsRunoff');
Index: issm/trunk/src/m/enum/TimesteppingInterpForcingsEnum.m
===================================================================
--- issm/trunk/src/m/enum/TimesteppingInterpForcingsEnum.m	(revision 18301)
+++ issm/trunk/src/m/enum/TimesteppingInterpForcingsEnum.m	(revision 18301)
@@ -0,0 +1,11 @@
+function macro=TimesteppingInterpForcingsEnum()
+%TIMESTEPPINGINTERPFORCINGSENUM - Enum of TimesteppingInterpForcings
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TimesteppingInterpForcingsEnum()
+
+macro=StringToEnum('TimesteppingInterpForcings');
Index: issm/trunk/src/m/enum/UzawaPressureAnalysisEnum.m
===================================================================
--- issm/trunk/src/m/enum/UzawaPressureAnalysisEnum.m	(revision 18301)
+++ issm/trunk/src/m/enum/UzawaPressureAnalysisEnum.m	(revision 18301)
@@ -0,0 +1,11 @@
+function macro=UzawaPressureAnalysisEnum()
+%UZAWAPRESSUREANALYSISENUM - Enum of UzawaPressureAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=UzawaPressureAnalysisEnum()
+
+macro=StringToEnum('UzawaPressureAnalysis');
Index: issm/trunk/src/m/exp/exp2shp.m
===================================================================
--- issm/trunk/src/m/exp/exp2shp.m	(revision 18301)
+++ issm/trunk/src/m/exp/exp2shp.m	(revision 18301)
@@ -0,0 +1,37 @@
+function exp2shp(shapefilename,expfilename,geometry)
+%SHPWRITE - write a shape file from a contour structure
+%
+%   Usage:
+%      exp2shp(shapefilename,expfilename,geometry)
+%
+%   Example:
+%      exp2shp('domainoutline.shp','domainoutline.exp')
+%      exp2shp('domainoutline.shp','domainoutline.exp','Polygon')
+%      exp2shp('massfluxgate.shp','massfluxgate.exp','Line')
+%
+%   See also SHPREAD, SHPWRITE, SHP2EXP
+
+shp=expread(expfilename);
+
+%initialize number of profile
+count=0;
+
+contours=struct([]);
+for i=1:length(shp),
+	if nargin < 3
+		if length(shp(1).x) == 1
+			geometry = 'Point';
+		elseif length(shp(1).x) < 3
+			geometry = 'Line';
+		else
+			geometry = 'Polygon';
+		end
+	end
+	contours(i).Geometry=geometry;
+	contours(i).id=i;
+	contours(i).X=shp(i).x;
+	contours(i).Y=shp(i).y;
+end
+	
+shapewrite(contours,shapefilename);
+end
Index: issm/trunk/src/m/extrusion/project2d.m
===================================================================
--- issm/trunk/src/m/extrusion/project2d.m	(revision 18081)
+++ issm/trunk/src/m/extrusion/project2d.m	(revision 18301)
@@ -2,9 +2,7 @@
 %PROJECT2D - returns the value of a field for a given layer of the mesh
 %
-%   project 'value' vector taken at layer 'layer' from extruded 2d-3d mesh onto 2d mesh 
-%   used to do the extrusion. This routine is used to compare values between a 2d-3d mesh
-%   at a certain layer, and the equivalent value (if it exists), on the original 2d mesh. 
-%   This routine relies heavily on projections (contained in 3d model md) recored during 
-%   the extrude operation.
+%   returns the value of a vector for a given layer from extruded mesh onto the 2d mesh 
+%   used to do the extrusion. This function is used to compare values between different
+%   layers of a 3d mesh.
 %
 %   Usage:
@@ -12,5 +10,6 @@
 %
 %   Example:
-%      vel2=project2d(md3d,md3d.vel,2);
+%      vel2=project2d(md3d,md3d.initialization.vel,2);
+%      returns the velocity of the second layer (1 is the base)
 
 %some checks on list of arguments
Index: issm/trunk/src/m/extrusion/project2d.py
===================================================================
--- issm/trunk/src/m/extrusion/project2d.py	(revision 18081)
+++ issm/trunk/src/m/extrusion/project2d.py	(revision 18301)
@@ -5,13 +5,8 @@
 	returns the value of a field for a given layer of the mesh
 	
-	project 'value' vector taken at layer 'layer' from extruded 2d-3d
-	mesh onto 2d mesh used to do the extrusion. This routine is used to
-	compare values between a 2d-3d mesh at a certain layer, and the
-	equivalent value (if it exists), on the original 2d mesh.	
 
-	Note: for consistency with usage in ISSM, layers are indexed starting
-	from one.  This routine accounts for the fact that python indexes from
-	zero.  In other words, when using this function consider the bottom
-	layer as layer=1.  
+   returns the value of a vector for a given layer from extruded mesh onto the 2d mesh 
+   used to do the extrusion. This function is used to compare values between different
+   layers of a 3d mesh.
 
    Usage:
@@ -19,5 +14,6 @@
 
    Example:
-      vel2=project2d(md3d,md3d.vel,2)
+      vel2=project2d(md3d,md3d.initialization.vel,2);
+      returns the velocity of the second layer (1 is the base)
 	'''
 
Index: issm/trunk/src/m/interp/interp.py
===================================================================
--- issm/trunk/src/m/interp/interp.py	(revision 18081)
+++ issm/trunk/src/m/interp/interp.py	(revision 18301)
@@ -45,6 +45,8 @@
 	# create sub-vectors that just cover the limits of xi and yi
 	# TODO x,y not necessarily a grid, so need a better definition of dx,dy (e.g. average element size)
-	dx=x[1]-x[0]
-	dy=y[1]-y[0]
+	dx=500
+	dy=500
+	#dx=x[1]-x[0]
+	#dy=y[1]-y[0]
 	xlim=[min(xi)-dx,max(xi)+dx]
 	ylim=[min(yi)-dy,max(yi)+dy]
@@ -76,5 +78,5 @@
 		xyinterp=npy.dstack([xi,yi])[0]
 		xg,yg=npy.meshgrid(subx,suby)
-		xydata=npy.dstack([xg.ravel(),yg.ravel()])[0]
+		xydata=npy.dstack([subx,suby])[0]
 		tree=cKDTree(xydata)
 		nearest=tree.query(xyinterp)[1]
Index: issm/trunk/src/m/mech/backstressfrominversion.m
===================================================================
--- issm/trunk/src/m/mech/backstressfrominversion.m	(revision 18081)
+++ issm/trunk/src/m/mech/backstressfrominversion.m	(revision 18301)
@@ -23,7 +23,6 @@
 %
 %   Return values:
-%		'backstress' is the inferred backstress necessary to balance the
-%		analytical solution (keeping damage within its appropriate limits, e.g. D
-%		in [0,1]).
+%		'backstress' is the inferred backstress based on the analytical
+%		solution for ice shelf creep
 %
 %   Usage:
Index: issm/trunk/src/m/mech/backstressfrominversion.py
===================================================================
--- issm/trunk/src/m/mech/backstressfrominversion.py	(revision 18081)
+++ issm/trunk/src/m/mech/backstressfrominversion.py	(revision 18301)
@@ -8,5 +8,5 @@
 
 	This routine computes backstress based on the analytical formalism of
-	Thomas (1973) and Borstad et al. (2013, The Cryoshpere).  The model
+	Thomas (1973) and Borstad et al. (2013, The Cryosphere).  The model
 	must contain inversion results for ice rigidity.  Strain rates must
 	also be included, either from observed or modeled velocities.  Ice
@@ -29,7 +29,6 @@
 
    Return values:
-		'backstress' is the inferred backstress necessary to balance the
-		analytical solution (keeping damage within its appropriate limits, e.g. D
-		in [0,1]).
+		'backstress' is the inferred backstress based on the analytical
+		solution for ice shelf creep
 
    Usage:
Index: issm/trunk/src/m/mech/basalstress.m
===================================================================
--- issm/trunk/src/m/mech/basalstress.m	(revision 18081)
+++ issm/trunk/src/m/mech/basalstress.m	(revision 18301)
@@ -1,4 +1,6 @@
 function [bx by b]=basalstress(md)
 %BASALSTRESS - compute basal stress from basal drag and geometric information. 
+%
+%      Computes basal stress from geometric information and ice velocity in md.initialization.
 %
 %   Usage:
Index: issm/trunk/src/m/mech/calcbackstress.m
===================================================================
--- issm/trunk/src/m/mech/calcbackstress.m	(revision 18301)
+++ issm/trunk/src/m/mech/calcbackstress.m	(revision 18301)
@@ -0,0 +1,64 @@
+function backstress=calcbackstress(md,varargin)
+%BACKSTRESSFROMINVERSION - compute ice shelf backstress  
+%
+%	 This routine computes backstress based on the analytical formalism of
+%	 Thomas (1973) and Borstad et al. (2013) based on the ice rigidity,
+%	 thickness, the densities of ice and seawater, and (optionally)
+%	 damage. Strain rates must also be included, either from observed or
+%	 modeled velocities.
+
+%   Available options:
+%		- 'smoothing'	: the amount of smoothing to be applied to the strain rate data.
+%								Type 'help averaging' for more information on its
+%								usage. Defaults to 0.
+%		- 'coordsys'	: coordinate system for calculating the strain rate
+%							components. Must be one of: 
+%				'longitudinal': x axis aligned along a flowline at every point (default)
+%				'principal': x axis aligned along maximum principal strain rate
+%					at every point
+%				'xy': x and y axes same as in polar stereographic projection 
+%
+%   Return values:
+%		'backstress' is the inferred backstress based on the analytical
+%		solution for ice shelf creep
+%
+%   Usage:
+%      backstress=calcbackstress(md,options)
+%
+%   Example:
+%      backstress=backstressfrominversion(md,'smoothing',2,'coordsys','longitudinal');
+
+% check inputs
+if (nargin<1),
+	help backstressfrominversion
+	error('bad usage');
+end
+if isempty(fieldnames(md.results)),
+	error(['md.results.strainrate is not present.  Calculate using md=mechanicalproperties(md,vx,vy)']);
+end
+if dimension(md.mesh)~=2,
+	error('only 2d model supported currently');
+end
+if any(md.flowequation.element_equation~=2),
+	disp('Warning: the model has some non SSA elements. These will be treated like SSA elements');
+end
+
+% process options
+options = pairoptions(varargin{:});
+smoothing = getfieldvalue(options,'smoothing',0);
+coordsys = getfieldvalue(options,'coordsys','longitudinal');
+tempmask = getfieldvalue(options,'tempmask',false);
+
+T=0.5*md.materials.rho_ice*md.constants.g*(1-md.materials.rho_ice/md.materials.rho_water)*md.geometry.thickness;
+n=averaging(md,md.materials.rheology_n,0);
+B=md.materials.rheology_B;
+if md.damage.isdamage,
+	D=md.damage.D
+else
+	D=0.
+
+[a0,b0,theta0,ex0]=thomasparams(md,'eq','Thomas','smoothing',smoothing,'coordsys',coordsys);
+
+% analytical backstress solution
+backstress=T-(1.-D).*B.*sign(ex0).*(2+a0).*abs(ex0).^(1./n)./((1+a0+a0.^2+b0.^2).^((n-1)/2./n));
+backstress(find(backstress<0))=0;
Index: issm/trunk/src/m/mech/calcbackstress.py
===================================================================
--- issm/trunk/src/m/mech/calcbackstress.py	(revision 18301)
+++ issm/trunk/src/m/mech/calcbackstress.py	(revision 18301)
@@ -0,0 +1,66 @@
+import numpy as npy
+from averaging import averaging
+from thomasparams import thomasparams
+
+def calcbackstress(md,**kwargs):
+	'''
+	Compute ice shelf backstress.
+
+	This routine computes backstress based on the analytical formalism of
+	Thomas (1973) and Borstad et al. (2013, The Cryosphere) based on the
+	ice rigidity, thickness, the densities of ice and seawater, and
+	(optionally) damage.  Strain rates must also be included, either from
+	observed or modeled velocities. 
+	
+	Available options:
+		- 'smoothing'	: the amount of smoothing to be applied to the strain rate data.
+								Type 'help averaging' for more information on its
+								usage. Defaults to 0.
+		- 'coordsys'	: coordinate system for calculating the strain rate
+							components. Must be one of: 
+				'longitudinal': x axis aligned along a flowline at every point (default)
+				'principal': x axis aligned along maximum principal strain rate
+					at every point
+				'xy': x and y axes same as in polar stereographic projection 
+
+   Return values:
+		'backstress' is the inferred backstress based on the analytical
+		solution for ice shelf creep
+
+   Usage:
+      backstress=calcbackstress(md,options)
+
+   Example:
+      backstress=calcbackstress(md,'smoothing',2,'coordsys','longitudinal')
+	'''
+
+	# unpack kwargs
+	smoothing=kwargs.pop('smoothing',0)
+	if 'smoothing' in kwargs: del kwargs['smoothing']
+	coordsys=kwargs.pop('coordsys','longitudinal')
+	if 'coordsys' in kwargs: del kwargs['coordsys']
+	assert len(kwargs)==0, 'error, unexpected or misspelled kwargs'
+
+	# some checks
+	if not hasattr(md.results,'strainrate'):
+		raise StandardError('md.results.strainrate not present.  Calculate using md=mechanicalproperties(md,vx,vy)')
+	if not '2d' in md.mesh.__doc__:
+		raise StandardError('only 2d (planview) model supported currently')
+	if any(md.flowequation.element_equation!=2):
+		raise StandardError('Warning: the model has some non-SSA elements.  These will be treated like SSA elements')
+
+	T=0.5*md.materials.rho_ice*md.constants.g*(1-md.materials.rho_ice/md.materials.rho_water)*md.geometry.thickness
+	n=averaging(md,md.materials.rheology_n,0)
+	B=md.materials.rheology_B
+	if md.damage.isdamage:
+		D=md.damage.D
+	else:
+		D=0.
+	
+	a0,b0,theta0,ex0=thomasparams(md,eq='Thomas',smoothing=smoothing,coordsys=coordsys)
+	
+	# analytical backstress solution
+	backstress=T-(1.-D)*B*npy.sign(ex0)*(2+a0)*npy.abs(ex0)**(1./n)/((1+a0+a0**2+b0**2)**((n-1.)/2./n))
+	backstress[npy.nonzero(backstress<0)]=0
+
+	return backstress
Index: issm/trunk/src/m/mech/steadystateiceshelftemp.m
===================================================================
--- issm/trunk/src/m/mech/steadystateiceshelftemp.m	(revision 18081)
+++ issm/trunk/src/m/mech/steadystateiceshelftemp.m	(revision 18301)
@@ -12,5 +12,5 @@
 %	 The model md must also contain the fields: 
 %	 md.geometry.thickness
-%	 md.basalforcings.melting_rate (positive for melting, negative for freezing)
+%	 md.basalforcings.floatingice_melting_rate (positive for melting, negative for freezing)
 
 %   Usage:
@@ -38,5 +38,5 @@
 
 %vertical velocity of ice shelf, calculated from melting rate 
-wi=md.materials.rho_water/md.materials.rho_ice.*md.basalforcings.melting_rate; 
+wi=md.materials.rho_water/md.materials.rho_ice.*md.basalforcings.floatingice_melting_rate; 
 
 %temperature profile is linear if melting rate is zero, depth-averaged temp is simple average in this case
Index: issm/trunk/src/m/mech/steadystateiceshelftemp.py
===================================================================
--- issm/trunk/src/m/mech/steadystateiceshelftemp.py	(revision 18081)
+++ issm/trunk/src/m/mech/steadystateiceshelftemp.py	(revision 18301)
@@ -13,5 +13,5 @@
 	The model md must also contain the fields: 
 	md.geometry.thickness
-	md.basalforcings.melting_rate (positive for melting, negative for freezing)
+	md.basalforcings.floatingice_melting_rate (positive for melting, negative for freezing)
 
    Usage:
@@ -37,5 +37,5 @@
 	
 	#vertical velocity of ice shelf, calculated from melting rate 
-	wi=md.materials.rho_water/md.materials.rho_ice*md.basalforcings.melting_rate 
+	wi=md.materials.rho_water/md.materials.rho_ice*md.basalforcings.floatingice_melting_rate 
 	
 	#temperature profile is linear if melting rate is zero, depth-averaged temp is simple average in this case
Index: issm/trunk/src/m/mesh/squaremesh.py
===================================================================
--- issm/trunk/src/m/mesh/squaremesh.py	(revision 18081)
+++ issm/trunk/src/m/mesh/squaremesh.py	(revision 18301)
@@ -2,4 +2,5 @@
 from NodeConnectivity import NodeConnectivity
 from ElementConnectivity import ElementConnectivity 
+from mesh2d import mesh2d
 
 def squaremesh(md,Lx,Ly,nx,ny):
Index: issm/trunk/src/m/miscellaneous/prctile_issm.m
===================================================================
--- issm/trunk/src/m/miscellaneous/prctile_issm.m	(revision 18081)
+++ issm/trunk/src/m/miscellaneous/prctile_issm.m	(revision 18301)
@@ -26,10 +26,10 @@
 		psize=size(p);
 		if size(p,2)>1
-			p=transp(p);
+			p=transpose(p);
 		end
 
 		xsize=size(x);
 		if dim==2
-			x=transp(x);
+			x=transpose(x);
 		end
 
@@ -46,5 +46,5 @@
 %  set up percent values and interpolate
 
-				xi=transp(100.*([1:n]-0.5)/n);
+				xi=transpose(100.*([1:n]-0.5)/n);
 				y=interp1q(xi,x,p);
 
@@ -80,5 +80,5 @@
 		if (min(xsize)==1 && xsize(dim)>1 && psize(2)>1) || ...
 		   (min(xsize)> 1 && dim==2)
-			y=transp(y);
+			y=transpose(y);
 		end
 	end
Index: issm/trunk/src/m/parameterization/setflowequation.m
===================================================================
--- issm/trunk/src/m/parameterization/setflowequation.m	(revision 18081)
+++ issm/trunk/src/m/parameterization/setflowequation.m	(revision 18301)
@@ -1,4 +1,4 @@
 function md=setflowequation(md,varargin)
-%SETELEMENTSTYPE - associate a solution type to each element
+%SETFLOWEQUATION - associate a solution type to each element
 %
 %   This routine works like plotmodel: it works with an even number of inputs
@@ -70,7 +70,7 @@
 end
 
-%Check that no L1L2 or HO or FS for 2d mesh
+%Check that no HO or FS for 2d mesh
 if strcmp(domaintype(md.mesh),'2Dhorizontal')
-	if any(L1L2flag | FSflag | HOflag)
+	if any(FSflag | HOflag)
 		error('FS and HO elements not allowed in 2d mesh, extrude it first')
 	end
@@ -239,15 +239,15 @@
 end
 
-%Create MacaAyealHOApproximation where needed
+%Create element equations
 md.flowequation.element_equation=zeros(md.mesh.numberofelements,1);
 md.flowequation.element_equation(find(noneflag))=0;
 md.flowequation.element_equation(find(SIAflag))=1;
 md.flowequation.element_equation(find(SSAflag))=2;
-md.flowequation.element_equation(find(L1L2flag))=8;
-md.flowequation.element_equation(find(HOflag))=3;
-md.flowequation.element_equation(find(FSflag))=4;
-md.flowequation.element_equation(find(SSAHOflag))=5;
-md.flowequation.element_equation(find(SSAFSflag))=6;
-md.flowequation.element_equation(find(HOFSflag))=7;
+md.flowequation.element_equation(find(L1L2flag))=3;
+md.flowequation.element_equation(find(HOflag))=4;
+md.flowequation.element_equation(find(FSflag))=5;
+md.flowequation.element_equation(find(SSAHOflag))=6;
+md.flowequation.element_equation(find(SSAFSflag))=7;
+md.flowequation.element_equation(find(HOFSflag))=8;
 
 %border
@@ -258,16 +258,14 @@
 %Create vertices_type
 md.flowequation.vertex_equation=zeros(md.mesh.numberofvertices,1);
+pos=find(nodeonSIA);
+md.flowequation.vertex_equation(pos)=1;
 pos=find(nodeonSSA);
 md.flowequation.vertex_equation(pos)=2;
 pos=find(nodeonL1L2);
-md.flowequation.vertex_equation(pos)=8;
+md.flowequation.vertex_equation(pos)=3;
 pos=find(nodeonHO);
-md.flowequation.vertex_equation(pos)=3;
-pos=find(nodeonSIA);
-md.flowequation.vertex_equation(pos)=1;
-pos=find(nodeonSSAHO);
+md.flowequation.vertex_equation(pos)=4;
+pos=find(nodeonFS);
 md.flowequation.vertex_equation(pos)=5;
-pos=find(nodeonFS);
-md.flowequation.vertex_equation(pos)=4;
 if any(FSflag),
 	pos=find(~nodeonFS);
@@ -276,15 +274,17 @@
 	end
 end
+pos=find(nodeonSSAHO);
+md.flowequation.vertex_equation(pos)=6;
 pos=find(nodeonHOFS);
 md.flowequation.vertex_equation(pos)=7;
 pos=find(nodeonSSAFS);
-md.flowequation.vertex_equation(pos)=6;
+md.flowequation.vertex_equation(pos)=8;
 
 %figure out solution types
 md.flowequation.isSIA  = double(any(md.flowequation.element_equation == 1));
 md.flowequation.isSSA  = double(any(md.flowequation.element_equation == 2));
-md.flowequation.isHO   = double(any(md.flowequation.element_equation == 3));
-md.flowequation.isL1L2 = double(any(md.flowequation.element_equation == 8));
-md.flowequation.isFS   = double(any(md.flowequation.element_equation == 4));
+md.flowequation.isL1L2 = double(any(md.flowequation.element_equation == 3));
+md.flowequation.isHO   = double(any(md.flowequation.element_equation == 4));
+md.flowequation.isFS   = double(any(md.flowequation.element_equation == 5));
 
 return
Index: issm/trunk/src/m/parameterization/setflowequation.py
===================================================================
--- issm/trunk/src/m/parameterization/setflowequation.py	(revision 18081)
+++ issm/trunk/src/m/parameterization/setflowequation.py	(revision 18301)
@@ -8,5 +8,5 @@
 def setflowequation(md,*args):
 	"""
-	SETELEMENTSTYPE - associate a solution type to each element
+	SETFLOWEQUATION - associate a solution type to each element
 
 	   This routine works like plotmodel: it works with an even number of inputs
@@ -232,10 +232,10 @@
 	md.flowequation.element_equation[numpy.nonzero(SIAflag)]=1
 	md.flowequation.element_equation[numpy.nonzero(SSAflag)]=2
-	md.flowequation.element_equation[numpy.nonzero(L1L2flag)]=8
-	md.flowequation.element_equation[numpy.nonzero(HOflag)]=3
-	md.flowequation.element_equation[numpy.nonzero(FSflag)]=4
-	md.flowequation.element_equation[numpy.nonzero(SSAHOflag)]=5
-	md.flowequation.element_equation[numpy.nonzero(SSAFSflag)]=6
-	md.flowequation.element_equation[numpy.nonzero(HOFSflag)]=7
+	md.flowequation.element_equation[numpy.nonzero(L1L2flag)]=3
+	md.flowequation.element_equation[numpy.nonzero(HOflag)]=4
+	md.flowequation.element_equation[numpy.nonzero(FSflag)]=5
+	md.flowequation.element_equation[numpy.nonzero(SSAHOflag)]=6
+	md.flowequation.element_equation[numpy.nonzero(SSAFSflag)]=7
+	md.flowequation.element_equation[numpy.nonzero(HOFSflag)]=8
 
 	#border
@@ -246,31 +246,31 @@
 	#Create vertices_type
 	md.flowequation.vertex_equation=numpy.zeros(md.mesh.numberofvertices,int)
+	pos=numpy.nonzero(nodeonSIA)
+	md.flowequation.vertex_equation[pos]=1
 	pos=numpy.nonzero(nodeonSSA)
 	md.flowequation.vertex_equation[pos]=2
 	pos=numpy.nonzero(nodeonL1L2)
-	md.flowequation.vertex_equation[pos]=8
+	md.flowequation.vertex_equation[pos]=3
 	pos=numpy.nonzero(nodeonHO)
-	md.flowequation.vertex_equation[pos]=3
-	pos=numpy.nonzero(nodeonSIA)
-	md.flowequation.vertex_equation[pos]=1
-	pos=numpy.nonzero(nodeonSSAHO)
+	md.flowequation.vertex_equation[pos]=4
+	pos=numpy.nonzero(nodeonFS)
 	md.flowequation.vertex_equation[pos]=5
-	pos=numpy.nonzero(nodeonFS)
-	md.flowequation.vertex_equation[pos]=4
 	if any(FSflag):
 		pos=numpy.nonzero(numpy.logical_not(nodeonFS))
 		if not (any(HOflag) or any(SSAflag)):
 			md.flowequation.vertex_equation[pos]=0
+	pos=numpy.nonzero(nodeonSSAHO)
+	md.flowequation.vertex_equation[pos]=6
 	pos=numpy.nonzero(nodeonHOFS)
 	md.flowequation.vertex_equation[pos]=7
 	pos=numpy.nonzero(nodeonSSAFS)
-	md.flowequation.vertex_equation[pos]=6
+	md.flowequation.vertex_equation[pos]=8
 
 	#figure out solution types
 	md.flowequation.isSIA=any(md.flowequation.element_equation==1)
 	md.flowequation.isSSA=any(md.flowequation.element_equation==2)
-	md.flowequation.isL1L2=any(md.flowequation.element_equation==8)
-	md.flowequation.isHO=any(md.flowequation.element_equation==3)
-	md.flowequation.isFS=any(md.flowequation.element_equation==4)
+	md.flowequation.isL1L2=any(md.flowequation.element_equation==3)
+	md.flowequation.isHO=any(md.flowequation.element_equation==4)
+	md.flowequation.isFS=any(md.flowequation.element_equation==5)
 
 	return md
Index: issm/trunk/src/m/parameterization/sethydrostaticmask.m
===================================================================
--- issm/trunk/src/m/parameterization/sethydrostaticmask.m	(revision 18301)
+++ issm/trunk/src/m/parameterization/sethydrostaticmask.m	(revision 18301)
@@ -0,0 +1,29 @@
+function md=sethydrostaticmask(md)
+%SETHYDROSTATICMASK - establish groundedice_levelset field
+%
+%   Determines grounded and floating ice position based on 
+%   md.geometry.bed and md.geometry.thickness
+%
+%   Usage:
+%      md=sethydrostaticmask(md)
+%
+%   Examples:
+%      md=sethydrostaticmask(md);
+
+if(length(md.geometry.bed)~=md.mesh.numberofvertices | length(md.geometry.thickness)~=md.mesh.numberofvertices | length(md.geometry.base)~=md.mesh.numberofvertices),
+		error('hydrostaticmask error message: fields in md.geometry do not have the right size.');
+end
+
+%grounded ice level set
+md.mask.groundedice_levelset=md.geometry.thickness+md.geometry.bed*md.materials.rho_water/md.materials.rho_ice;
+
+%Check consistency of geometry
+pos=find(md.mask.groundedice_levelset>0);
+if(any(md.geometry.base(pos)~=md.geometry.bed(pos))),
+	disp('WARNING: md.geometry.bed and md.geometry.base not equal on grounded ice');
+end
+
+pos=find(md.mask.groundedice_levelset<=0);
+if(any(md.geometry.base(pos)<md.geometry.bed(pos))),
+	disp('WARNING: md.geometry.base < md.geometry.bed on floating ice');
+end
Index: issm/trunk/src/m/parameterization/sethydrostaticmask.py
===================================================================
--- issm/trunk/src/m/parameterization/sethydrostaticmask.py	(revision 18301)
+++ issm/trunk/src/m/parameterization/sethydrostaticmask.py	(revision 18301)
@@ -0,0 +1,35 @@
+import numpy
+import os
+from model import model
+from FlagElements import FlagElements
+import pairoptions
+from ContourToMesh import ContourToMesh
+
+def setmask(md)
+	"""
+	SETHYDROSTATICMASK - establish groundedice_levelset field
+
+   Determines grounded and floating ice position based on 
+   md.geometry.bed and md.geometry.thickness
+
+   Usage:
+      md=sethydrostaticmask(md)
+
+   Examples:
+      md=sethydrostaticmask(md);
+   """
+
+	if numpy.size(md.geometry.bed,axis=0)!=md.mesh.numberofvertices or numpy.size(md.geometry.base,axis=0)!=md.mesh.numberofvertices or numpy.size(md.geometry.thickness,axis=0)!=md.mesh.numberofvertices:
+		raise IOError("hydrostaticmask error message: fields in md.geometry do not have the right size.")
+
+   # grounded ice level set
+   md.mask.groundedice_levelset=md.geometry.thickness+md.geometry.bed*md.materials.rho_water/md.materials.rho_ice
+
+   #Check consistency of geometry
+	if any(md.geometry.base[numpy.nonzero(md.mask.groundedice_levelset>0.)]!=md.geometry.bed[numpy.nonzero(md.mask.groundedice_levelset>0.)]):
+	   print "WARNING: md.geometry.bed and md.geometry.base not equal on grounded ice"
+
+	if any(md.geometry.base[numpy.nonzero(md.mask.groundedice_levelset<=0.)]<md.geometry.bed[numpy.nonzero(md.mask.groundedice_levelset<=0.)]):
+		print "WARNING: md.geometry.base < md.geometry.bed on floating ice"
+
+	return md
Index: issm/trunk/src/m/plot/applyoptions.py
===================================================================
--- issm/trunk/src/m/plot/applyoptions.py	(revision 18081)
+++ issm/trunk/src/m/plot/applyoptions.py	(revision 18301)
@@ -219,9 +219,10 @@
 			extend='both'
 		cb = mpl.colorbar.ColorbarBase(ax.cax, cmap=cmap, norm=norm, extend=extend)
-		cb.locator=MaxNLocator(nbins=5) # default 5 ticks
 		if options.exist('alpha'):
 			cb.set_alpha(options.getfieldvalue('alpha'))
 		if options.exist('colorbarnumticks'):
 			cb.locator=MaxNLocator(nbins=options.getfieldvalue('colorbarnumticks',5))
+		else:
+			cb.locator=MaxNLocator(nbins=5) # default 5 ticks
 		if options.exist('colorbartickspacing'):
 			locs=npy.arange(lims[0],lims[1]+1,options.getfieldvalue('colorbartickspacing'))
@@ -237,4 +238,5 @@
 				cb.set_label(options.getfieldvalue('colorbartitle'),fontsize=fontsize)
 		cb.ax.tick_params(labelsize=fontsize)
+		cb.update_ticks()
 		plt.sca(ax) # return to original axes control
 	#}}}
Index: issm/trunk/src/m/plot/checkplotoptions.py
===================================================================
--- issm/trunk/src/m/plot/checkplotoptions.py	(revision 18081)
+++ issm/trunk/src/m/plot/checkplotoptions.py	(revision 18301)
@@ -18,5 +18,5 @@
 		if 'km' in options.getfieldvalue('unit','km'):
 			options.changefieldvalue('unit',10**-3)
-		if '100km' in options.getfieldvalue('unit','100km'):
+		elif '100km' in options.getfieldvalue('unit','100km'):
 			options.changefieldvalue('unit',10**-5)
 	
Index: issm/trunk/src/m/plot/plot_BC.m
===================================================================
--- issm/trunk/src/m/plot/plot_BC.m	(revision 18081)
+++ issm/trunk/src/m/plot/plot_BC.m	(revision 18301)
@@ -6,21 +6,23 @@
 hold on
 
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
 %plot dirichlets
 dirichleton=getfieldvalue(options,'dirichlet','on');
 if strcmpi(dirichleton,'on'),
 	h1=plot3(...
-		md.mesh.x(find(~isnan(md.stressbalance.spcvx(1:md.mesh.numberofvertices,1)))),...
-		md.mesh.y(find(~isnan(md.stressbalance.spcvx(1:md.mesh.numberofvertices,1)))),...
-		md.mesh.z(find(~isnan(md.stressbalance.spcvx(1:md.mesh.numberofvertices,1)))),...
+		x(find(~isnan(md.stressbalance.spcvx(1:md.mesh.numberofvertices,1)))),...
+		y(find(~isnan(md.stressbalance.spcvx(1:md.mesh.numberofvertices,1)))),...
+		z(find(~isnan(md.stressbalance.spcvx(1:md.mesh.numberofvertices,1)))),...
 		'ro','MarkerSize',14,'MarkerFaceColor','r');
 	h2=plot3(...
-		md.mesh.x(find(~isnan(md.stressbalance.spcvy(1:md.mesh.numberofvertices,1)))),...
-		md.mesh.y(find(~isnan(md.stressbalance.spcvy(1:md.mesh.numberofvertices,1)))),...
-		md.mesh.z(find(~isnan(md.stressbalance.spcvy(1:md.mesh.numberofvertices,1)))),...
+		x(find(~isnan(md.stressbalance.spcvy(1:md.mesh.numberofvertices,1)))),...
+		y(find(~isnan(md.stressbalance.spcvy(1:md.mesh.numberofvertices,1)))),...
+		z(find(~isnan(md.stressbalance.spcvy(1:md.mesh.numberofvertices,1)))),...
 		'bo','MarkerSize',10,'MarkerFaceColor','b');
 	h3=plot3(...
-		md.mesh.x(find(~isnan(md.stressbalance.spcvz(1:md.mesh.numberofvertices,1)))),...
-		md.mesh.y(find(~isnan(md.stressbalance.spcvz(1:md.mesh.numberofvertices,1)))),...
-		md.mesh.z(find(~isnan(md.stressbalance.spcvz(1:md.mesh.numberofvertices,1)))),...
+		x(find(~isnan(md.stressbalance.spcvz(1:md.mesh.numberofvertices,1)))),...
+		y(find(~isnan(md.stressbalance.spcvz(1:md.mesh.numberofvertices,1)))),...
+		z(find(~isnan(md.stressbalance.spcvz(1:md.mesh.numberofvertices,1)))),...
 		'yo','MarkerSize',6 ,'MarkerFaceColor','y');
 end
Index: issm/trunk/src/m/plot/plot_elementstype.m
===================================================================
--- issm/trunk/src/m/plot/plot_elementstype.m	(revision 18081)
+++ issm/trunk/src/m/plot/plot_elementstype.m	(revision 18301)
@@ -17,79 +17,79 @@
 subplot(width,width,i);
 
+plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options);
+return;
 if is2d
-	%SIA elements
+	posNONE=find(data==0);
+	A=elements(posNONE,1); B=elements(posNONE,2); C=elements(posNONE,3); 
+	p1=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',0,'FaceColor','flat','EdgeColor',edgecolor);
 	posH=find(data==1);
 	A=elements(posH,1); B=elements(posH,2); C=elements(posH,3); 
-	p1=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',1,'FaceColor','flat','EdgeColor',edgecolor);
-	%SSA element
+	p2=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',1,'FaceColor','flat','EdgeColor',edgecolor);
 	posM=find(data==2);
 	A=elements(posM,1); B=elements(posM,2); C=elements(posM,3); 
-	p2=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',2,'FaceColor','flat','EdgeColor',edgecolor);
-	%HO element
-	posP=find(data==3);
+	posM=find(data==3);
+	A=elements(posM,1); B=elements(posM,2); C=elements(posM,3); 
+	p4=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',2,'FaceColor','flat','EdgeColor',edgecolor);
+	posP=find(data==4);
 	A=elements(posP,1); B=elements(posP,2); C=elements(posP,3); 
-	p3=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',3,'FaceColor','flat','EdgeColor',edgecolor);
-	%SSAHO element
-	posMP=find(data==5);
-	A=elements(posMP,1); B=elements(posMP,2); C=elements(posMP,3); 
-	p5=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',5,'FaceColor','flat','EdgeColor',edgecolor);
-	%FS elements
-	posS=find(data==4);
+	p5=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',3,'FaceColor','flat','EdgeColor',edgecolor);
+	posS=find(data==5);
 	A=elements(posS,1); B=elements(posS,2); C=elements(posS,3); 
 	p6=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',4,'FaceColor','flat','EdgeColor',edgecolor);
-	%SSAFS elements
-	posMS=find(data==6);
-	A=elements(posMS,1); B=elements(posMS,2); C=elements(posMS,3); 
-	p7=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',6,'FaceColor','flat','EdgeColor',edgecolor);
-	%HOFS elements
+	posMP=find(data==6);
+	A=elements(posMP,1); B=elements(posMP,2); C=elements(posMP,3); 
+	p7=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',5,'FaceColor','flat','EdgeColor',edgecolor);
 	posPS=find(data==7);
 	A=elements(posPS,1); B=elements(posPS,2); C=elements(posPS,3); 
 	p8=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',7,'FaceColor','flat','EdgeColor',edgecolor);
-	%None elements
-	posNONE=find(data==0);
-	A=elements(posNONE,1); B=elements(posNONE,2); C=elements(posNONE,3); 
-	p9=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',0,'FaceColor','flat','EdgeColor',edgecolor);
-
-	legend([p1 p2 p3 p5 p6 p7 p8 p9],...
-		'SIA''s elements','SSA''s elements','HO''s elements',...
-		'SSAHO''s elements','FS''s elements','SSAFS''s elements','HOFS''s elements','None element');
-
+	posMS=find(data==8);
+	A=elements(posMS,1); B=elements(posMS,2); C=elements(posMS,3); 
+	p9=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',6,'FaceColor','flat','EdgeColor',edgecolor);
 else
-	%SIA elements
+	PosNONE=find(data==0);
+	A=elements(PosNONE,1); B=elements(PosNONE,2); C=elements(PosNONE,3); D=elements(PosNONE,4); E=elements(PosNONE,5); F=elements(PosNONE,6);
+	p1=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 0,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 0,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 0,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 0,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 0,'FaceColor','flat','EdgeColor',edgecolor);
 	posH=find(data==1);
 	A=elements(posH,1); B=elements(posH,2); C=elements(posH,3); D=elements(posH,4); E=elements(posH,5); F=elements(posH,6);
-	p1=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 1,'FaceColor','flat','EdgeColor',edgecolor);
+	p2=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 1,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 1,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 1,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 1,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 1,'FaceColor','flat','EdgeColor',edgecolor);
-	%SSA elements
 	posM=find(data==2);
 	A=elements(posM,1); B=elements(posM,2); C=elements(posM,3); D=elements(posM,4); E=elements(posM,5); F=elements(posM,6);
-	p2=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 2,'FaceColor','flat','EdgeColor',edgecolor);
+	p3=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 2,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 2,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 2,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 2,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 2,'FaceColor','flat','EdgeColor',edgecolor);
-	%HO elements
 	posP=find(data==3);
 	A=elements(posP,1); B=elements(posP,2); C=elements(posP,3); D=elements(posP,4); E=elements(posP,5); F=elements(posP,6);
-	p3=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
+	p4=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
-	%FS elements
+	posP=find(data==3);
+	A=elements(posP,1); B=elements(posP,2); C=elements(posP,3); D=elements(posP,4); E=elements(posP,5); F=elements(posP,6);
+	p5=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
 	posS=find(data==4);
 	A=elements(posS,1); B=elements(posS,2); C=elements(posS,3); D=elements(posS,4); E=elements(posS,5); F=elements(posS,6);
-	p4=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 4,'FaceColor','flat','EdgeColor',edgecolor);
+	p6=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 4,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 4,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 4,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 4,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 4,'FaceColor','flat','EdgeColor',edgecolor);
-	%SSAHO elements
 	posP=find(data==5);
 	A=elements(posP,1); B=elements(posP,2); C=elements(posP,3); D=elements(posP,4); E=elements(posP,5); F=elements(posP,6);
-	p5=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 5,'FaceColor','flat','EdgeColor',edgecolor);
+	p7=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 5,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 5,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 5,'FaceColor','flat','EdgeColor',edgecolor);
@@ -99,30 +99,21 @@
 	PosPS=find(data==7);
 	A=elements(PosPS,1); B=elements(PosPS,2); C=elements(PosPS,3); D=elements(PosPS,4); E=elements(PosPS,5); F=elements(PosPS,6);
-	p6=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 7,'FaceColor','flat','EdgeColor',edgecolor);
+	p8=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 7,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 7,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 7,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 7,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 7,'FaceColor','flat','EdgeColor',edgecolor);
-	%SSAFS elements
 	PosMS=find(data==6);
 	A=elements(PosMS,1); B=elements(PosMS,2); C=elements(PosMS,3); D=elements(PosMS,4); E=elements(PosMS,5); F=elements(PosMS,6);
-	p7=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 6,'FaceColor','flat','EdgeColor',edgecolor);
+	p9=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 6,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 6,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 6,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 6,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 6,'FaceColor','flat','EdgeColor',edgecolor);
-	%None elements
-	PosNONE=find(data==0);
-	A=elements(PosNONE,1); B=elements(PosNONE,2); C=elements(PosNONE,3); D=elements(PosNONE,4); E=elements(PosNONE,5); F=elements(PosNONE,6);
-	p8=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 0,'FaceColor','flat','EdgeColor',edgecolor);
-	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 0,'FaceColor','flat','EdgeColor',edgecolor);
-	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 0,'FaceColor','flat','EdgeColor',edgecolor);
-	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 0,'FaceColor','flat','EdgeColor',edgecolor);
-	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 0,'FaceColor','flat','EdgeColor',edgecolor);
 
-	legend([p1 p2 p3 p4 p5 p6 p7 p8],...
-		'SIA''s elements','SSA''s elements','HO''s elements','FS''s elements',...
-		'SSAHO''s elements','HOFS''s elements','SSAFS''s elements','None elements');
 end
+legend([p1 p2 p3 p4 p5 p6 p7 p8 p9],...
+		'None','SIA','SSA','L1L2','HO',...
+		'SSAHO','FS','SSAFS','HOFS');
 
 %apply options
Index: issm/trunk/src/m/plot/plot_scatter.m
===================================================================
--- issm/trunk/src/m/plot/plot_scatter.m	(revision 18081)
+++ issm/trunk/src/m/plot/plot_scatter.m	(revision 18301)
@@ -6,4 +6,5 @@
 %
 %   Available options:
+%      'caxis'      : default is full range
 %      'MarkerSize' : default is 3
 %      'Line'       : use line instead of circles
@@ -25,4 +26,9 @@
 Min=min(level);
 Max=max(level);
+if exist(options,'caxis');
+	range=getfieldvalue(options,'caxis');
+	Min=min(range);
+	Max=max(range);
+end
 Siz=length(level);
 nlab=10;
Index: issm/trunk/src/m/plot/plot_transient_movie.m
===================================================================
--- issm/trunk/src/m/plot/plot_transient_movie.m	(revision 18081)
+++ issm/trunk/src/m/plot/plot_transient_movie.m	(revision 18301)
@@ -13,5 +13,20 @@
 		field=getfieldvalue(options,'transient_movie_field');
 	else
-		error('specify transient_movie_field in options list');
+		disp('List of available fields:');
+		F=fields(md.results.TransientSolution(1));
+		num = [];
+		for i=1:numel(F),
+			if ~strcmp(F{i},'time') & ...
+				~strcmp(F{i},'step') & ...
+				~strcmp(F{i},'errlog') & ...
+				~strcmp(F{i},'outlog') & ...
+				~strcmp(F{i},'MaxIterationConvergenceFlag') & ...
+				~strcmp(F{i},'SolutionType'),
+				disp(['   ' num2str(i) ': ' F{i} ]);
+				num = [num i];
+			end
+		end
+		choice=input(['please enter the field number? (between ' num2str(min(num)) ' and ' num2str(max(num)) ')  ']);
+		field =  F{choice};
 	end
 
@@ -24,6 +39,19 @@
 		steps=1:length(results);
 	end
-	results=md.results.TransientSolution;
+
+	%calculate caxis
+	if ~exist(options,'caxis'),
+		range = [Inf -Inf];
+		for i=steps
+			[data datatype]=processdata(md,results(i).(field),options);
+			range(1) = min(range(1),min(data));
+			range(2) = max(range(2),max(data));
+		end
+		options=addfielddefault(options,'caxis',range);
+	end
+
+	%display movie
 	nstep=1;
+	deltat = getfieldvalue(options,'pause',.5);
 	for i=steps
 
@@ -33,4 +61,5 @@
 			[data datatype]=processdata(md,results(i).(field),options);
 
+			clf;
 			titlestring=[field ' at time ' num2str(results(i).time/md.constants.yts) ' year'];
 			plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options)
@@ -49,5 +78,5 @@
 				end
 			else
-				pause(0.1)
+				pause(deltat)
 			end
 			nstep=nstep+1;
Index: issm/trunk/src/m/plot/plot_unit.m
===================================================================
--- issm/trunk/src/m/plot/plot_unit.m	(revision 18081)
+++ issm/trunk/src/m/plot/plot_unit.m	(revision 18301)
@@ -16,7 +16,5 @@
 
 		pos=find(~isnan(data)); %needed for element on water
-		if is2d,
-			A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); patch( 'Faces', [A B C], 'Vertices', [x y z],'CData', data(pos),'FaceColor','flat','EdgeColor',edgecolor);
-		else
+		if size(elements,2)==6, %prisms
 			A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); D=elements(pos,4); E=elements(pos,5); F=elements(pos,6);
 			patch( 'Faces', [A B C],  'Vertices', [x y z],'CData', data(pos),'FaceColor','flat','EdgeColor',edgecolor);
@@ -25,4 +23,16 @@
 			patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', data(pos),'FaceColor','flat','EdgeColor',edgecolor);
 			patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+		elseif size(elements,2)==4, %tetras
+			A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4);
+			patch( 'Faces',[A B C],'Vertices', [x y z],'CData',data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces',[A B D],'Vertices', [x y z],'CData',data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces',[B C D],'Vertices', [x y z],'CData',data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces',[C A D],'Vertices', [x y z],'CData',data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+		else
+			A=elements(pos,1); B=elements(pos,2); C=elements(pos,3);
+			patch( 'Faces', [A B C], 'Vertices', [x y z],'CData', data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+		end
+
+		if is2d,
 		end
 
Index: issm/trunk/src/m/plot/plotdoc.m
===================================================================
--- issm/trunk/src/m/plot/plotdoc.m	(revision 18081)
+++ issm/trunk/src/m/plot/plotdoc.m	(revision 18301)
@@ -12,5 +12,5 @@
 disp('                Available values for ''data'' are: ');
 disp('                  - any field of the model structure. ex: plot(md,''data'',''vel''), or plot(md,''data'',md.initialization.vel)');
-disp('                  - ''basal_drag'': plot the basal drag on the bed (in kPa)');
+disp('                  - ''basal_drag'': plot the basal drag on the bed (in kPa) based on the velocity in md.initialization');
 disp('                  - ''basal_dragx'' or ''basal_dragy'' : plot a component of the basal drag on the bed (in kPa)');
 disp('                  - ''boundaries'': this will draw all the segment boundaries to the model, including rifts.');
Index: issm/trunk/src/m/plot/plotmodel.py
===================================================================
--- issm/trunk/src/m/plot/plotmodel.py	(revision 18081)
+++ issm/trunk/src/m/plot/plotmodel.py	(revision 18301)
@@ -54,6 +54,6 @@
 	if numberofplots:
 		
-		if plt.fignum_exists(figurenumber): 
-			plt.cla()
+		#if plt.fignum_exists(figurenumber): 
+		#	plt.cla()
 
 		#if figsize specified
Index: issm/trunk/src/m/plot/processdata.m
===================================================================
--- issm/trunk/src/m/plot/processdata.m	(revision 18081)
+++ issm/trunk/src/m/plot/processdata.m	(revision 18301)
@@ -15,4 +15,15 @@
 if (iscell(data) | isempty(data) | length(data)==0 | (length(data)==1 & ~isstruct(data) & isnan(data))),
 	error('plotmodel error message: data provided is empty');
+end
+
+%specials for struct
+if isstruct(data),
+	disp('data provided is a struct with the following fields:');
+	F=fields(data);
+	for i=1:numel(F),
+		disp(['   ' num2str(i) ': ' F{i} ]);
+	end
+	choice=input(['please enter the field number? (between 1 and ' num2str(numel(F)) ')  ']);
+	[data datatype]=processdata(md,data.(F{choice}),options);
 end
 
Index: issm/trunk/src/m/solve/parseresultsfromdisk.m
===================================================================
--- issm/trunk/src/m/solve/parseresultsfromdisk.m	(revision 18081)
+++ issm/trunk/src/m/solve/parseresultsfromdisk.m	(revision 18301)
@@ -178,5 +178,5 @@
 	elseif strcmp(fieldname,'Vel'),
 		field = field*yts;
-	elseif strcmp(fieldname,'BasalforcingsMeltingRate'),
+	elseif strcmp(fieldname,'BasalforcingsGroundediceMeltingRate'),
 		field = field*yts;
 	elseif strcmp(fieldname,'TotalSmb'),
Index: issm/trunk/src/m/solve/parseresultsfromdisk.py
===================================================================
--- issm/trunk/src/m/solve/parseresultsfromdisk.py	(revision 18081)
+++ issm/trunk/src/m/solve/parseresultsfromdisk.py	(revision 18301)
@@ -178,5 +178,5 @@
 		elif m.strcmp(fieldname,'Vel'):
 			field = field*yts
-		elif m.strcmp(fieldname,'BasalforcingsMeltingRate'):
+		elif m.strcmp(fieldname,'BasalforcingsGroundediceMeltingRate'):
 			field = field*yts
 		elif m.strcmp(fieldname,'TotalSmb'):
Index: issm/trunk/src/m/solve/solve.m
===================================================================
--- issm/trunk/src/m/solve/solve.m	(revision 18081)
+++ issm/trunk/src/m/solve/solve.m	(revision 18301)
@@ -21,4 +21,5 @@
 %      - loadonly    : does not solve. only load results
 %      - runtimename : true or false (default is true), makes name unique
+%      - checkconsistency : 'yes' or 'no' (default is 'yes'), ensures checks on consistency of model
 %
 %   Examples:
@@ -36,16 +37,18 @@
 
 %check model consistency
-if md.verbose.solution,
-	disp('checking model consistency');
-end
-if (solutionenum == FlaimSolutionEnum())
-	md.private.isconsistent=true;
-	md=checkconsistency(md.mesh,md,solutionenum);
-	md=checkconsistency(md.flaim,md,solutionenum);
-	if md.private.isconsistent==false,
-		error('Model not consistent, see messages above');
+if strcmpi(getfieldvalue(options,'checkconsistency','yes'),'yes'),
+	if md.verbose.solution,
+		disp('checking model consistency');
 	end
-else
-	ismodelselfconsistent(md),
+	if (solutionenum == FlaimSolutionEnum())
+		md.private.isconsistent=true;
+		md=checkconsistency(md.mesh,md,solutionenum);
+		md=checkconsistency(md.flaim,md,solutionenum);
+		if md.private.isconsistent==false,
+			error('Model not consistent, see messages above');
+		end
+	else
+		ismodelselfconsistent(md),
+	end
 end
 
Index: issm/trunk/src/m/solve/solve.py
===================================================================
--- issm/trunk/src/m/solve/solve.py	(revision 18081)
+++ issm/trunk/src/m/solve/solve.py	(revision 18301)
@@ -33,4 +33,5 @@
 	   extra options:
 	      - loadonly : does not solve. only load results
+		  - checkconsistency : 'yes' or 'no' (default is 'yes'), ensures checks on consistency of model
  
 	   Examples:
@@ -48,13 +49,14 @@
 
 	#check model consistency
-	print "checking model consistency"
-	if solutionenum == FlaimSolutionEnum():
-		md.private.isconsistent=True
-		md.mesh.checkconsistency(md,solutionenum)
-		md.flaim.checkconsistency(md,solutionenum)
-		if not md.private.isconsistent:
-			raise RuntimeError("Model not consistent, see messages above.")
-	else:
-		ismodelselfconsistent(md)
+	if m.strcmpi(options.getfieldvalue('checkconsistency','yes'),'yes'):
+		print "checking model consistency"
+		if solutionenum == FlaimSolutionEnum():
+			md.private.isconsistent=True
+			md.mesh.checkconsistency(md,solutionenum)
+			md.flaim.checkconsistency(md,solutionenum)
+			if not md.private.isconsistent:
+				raise RuntimeError("Model not consistent, see messages above.")
+		else:
+			ismodelselfconsistent(md)
 
 	#First, build a runtime name that is unique
Index: issm/trunk/src/wrappers/InterpFromGridToMesh/InterpFromGridToMesh.cpp
===================================================================
--- issm/trunk/src/wrappers/InterpFromGridToMesh/InterpFromGridToMesh.cpp	(revision 18081)
+++ issm/trunk/src/wrappers/InterpFromGridToMesh/InterpFromGridToMesh.cpp	(revision 18301)
@@ -9,5 +9,5 @@
 	_printf0_("\n");
 	_printf0_("   This function is a multi-threaded mex file that interpolates a field\n");
-	_printf0_("   defined on a grid onto a list of points\n");
+	_printf0_("   defined on a grid onto a list of points based on a bilinear interpolation\n");
 	_printf0_("\n");
 	_printf0_("   Usage:\n");
Index: issm/trunk/src/wrappers/Makefile.am
===================================================================
--- issm/trunk/src/wrappers/Makefile.am	(revision 18081)
+++ issm/trunk/src/wrappers/Makefile.am	(revision 18301)
@@ -1,3 +1,5 @@
 SUBDIRS = 
+
+if WRAPPERS
 if MATLAB
 SUBDIRS += matlab
@@ -7,2 +9,3 @@
 SUBDIRS += python
 endif
+endif 
Index: issm/trunk/src/wrappers/matlab/Makefile.am
===================================================================
--- issm/trunk/src/wrappers/matlab/Makefile.am	(revision 18081)
+++ issm/trunk/src/wrappers/matlab/Makefile.am	(revision 18301)
@@ -1,4 +1,4 @@
 AM_CPPFLAGS = @DAKOTAINCL@ @MATLABINCL@ @PETSCINCL@ @MPIINCL@ @SPOOLESINCL@ @METISINCL@ @TRIANGLEINCL@ @CHACOINCL@ @SCOTCHINCL@ @SHAPELIBINCL@ @AMPIINCL@
-#AUTOMAKE_OPTIONS = subdir-objects
+AUTOMAKE_OPTIONS = subdir-objects
 
 EXEEXT=$(MATLABWRAPPEREXT)
@@ -46,17 +46,12 @@
 #}}}
 #Wrappers {{{
-if WRAPPERS
-lib_LTLIBRARIES +=  AverageFilter.la\
-						 BamgMesher.la\
+lib_LTLIBRARIES += BamgMesher.la\
 						 BamgConvertMesh.la\
 						 BamgTriangulate.la\
 						 ContourToMesh.la\
 						 ContourToNodes.la\
-						 EdgeDetection.la\
 						 ElementConnectivity.la\
 						 EnumToString.la\
 						 ExpSimplify.la\
-						 HoleFiller.la\
-						 InternalFront.la\
 						 InterpFromGridToMesh.la\
 						 InterpFromMeshToMesh2d.la\
@@ -91,5 +86,4 @@
 				   Shp2Kml.la
 endif
-endif 
 #}}}
 
@@ -133,8 +127,4 @@
 libISSMApi_la_LDFLAGS = -module -export-dynamic
 
-AverageFilter_la_SOURCES = ../AverageFilter/AverageFilter.cpp\
-									../AverageFilter/AverageFilter.h
-AverageFilter_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
-
 BamgMesher_la_SOURCES = ../BamgMesher/BamgMesher.cpp\
 								../BamgMesher/BamgMesher.h
@@ -173,12 +163,4 @@
 StringToEnum_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
-HoleFiller_la_SOURCES = ../HoleFiller/HoleFiller.cpp\
-								../HoleFiller/HoleFiller.h
-HoleFiller_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)  $(GSLLIB)
-
-InternalFront_la_SOURCES = ../InternalFront/InternalFront.cpp\
-									../InternalFront/InternalFront.h
-InternalFront_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
-
 InterpFromGridToMesh_la_SOURCES = ../InterpFromGridToMesh/InterpFromGridToMesh.cpp\
 											 ../InterpFromGridToMesh/InterpFromGridToMesh.h
@@ -225,8 +207,4 @@
 Ll2xy_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
-EdgeDetection_la_SOURCES = ../EdgeDetection/EdgeDetection.cpp\
-							../EdgeDetection/EdgeDetection.h
-EdgeDetection_la_LIBADD= ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
-
 ExpSimplify_la_SOURCES = ../ExpSimplify/ExpSimplify.cpp\
 							../ExpSimplify/ExpSimplify.h
Index: issm/trunk/src/wrappers/python/Makefile.am
===================================================================
--- issm/trunk/src/wrappers/python/Makefile.am	(revision 18081)
+++ issm/trunk/src/wrappers/python/Makefile.am	(revision 18301)
@@ -45,22 +45,20 @@
 #}}}
 #Wrappers {{{
-if WRAPPERS
-lib_LTLIBRARIES = BamgConvertMesh.la\
-						BamgMesher.la\
-						ContourToMesh.la\
-						ContourToNodes.la\
-						ElementConnectivity.la\
-						EnumToString.la\
-						InterpFromMeshToMesh2d.la\
-						InterpFromMeshToMesh3d.la\
-						InterpFromGridToMesh.la\
-						InterpFromMeshToGrid.la\
-						IssmConfig.la\
-						MeshProfileIntersection.la\
-						NodeConnectivity.la\
-						StringToEnum.la\
-						TriMesh.la\
-						TriMeshProcessRifts.la
-endif 
+lib_LTLIBRARIES += BamgConvertMesh.la\
+						 BamgMesher.la\
+						 ContourToMesh.la\
+						 ContourToNodes.la\
+						 ElementConnectivity.la\
+						 EnumToString.la\
+						 InterpFromMeshToMesh2d.la\
+						 InterpFromMeshToMesh3d.la\
+						 InterpFromGridToMesh.la\
+						 InterpFromMeshToGrid.la\
+						 IssmConfig.la\
+						 MeshProfileIntersection.la\
+						 NodeConnectivity.la\
+						 StringToEnum.la\
+						 TriMesh.la\
+						 TriMeshProcessRifts.la
 #}}}
 #Flags and libraries {{{
Index: issm/trunk/test/Exp/SquareFront.exp
===================================================================
--- issm/trunk/test/Exp/SquareFront.exp	(revision 18081)
+++ issm/trunk/test/Exp/SquareFront.exp	(revision 18301)
@@ -4,7 +4,7 @@
 5 1.
 # X pos Y pos
--1000 900000
+-1000 999999
 -1000 1100000
 1100000 1100000
-1100000 900000
--1000 900000
+1100000 999999
+-1000 999999
Index: issm/trunk/test/NightlyRun/IdToName.m
===================================================================
--- issm/trunk/test/NightlyRun/IdToName.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/IdToName.m	(revision 18301)
@@ -67,4 +67,6 @@
 	case 236, name='SquareShelfTranIspddIsdeltaSSA2d';
 	case 237, name='SquareShelfTranIspddIsdeltaSSA3d';
+	case 238, name='SquareShelfTranForceNoInterp2d';
+	case 239, name='SquareShelfTranForceNoInterp3d';
 	case 270, name='SquareShelfStressSSA2dDamage';
 	case 271, name='SquareShelfStressSSA2dDamageTran';
@@ -76,4 +78,6 @@
 	case 285, name='SquareShelfStressHOHigherOrder';
 	case 290, name='SquareShelfStressFSP2P1';
+	case 291, name='SquareShelfStressFSP4z';
+	case 292, name='SquareShelfTranSSA2dFloatingMeltParam';
 	case 301, name='SquareSheetConstrainedStressSSA2d';
 	case 302, name='SquareSheetConstrainedStressSIA2d';
@@ -109,4 +113,8 @@
 	case 334, name='SquareSheetConstrainedExtrudedHydrologyDC';
 	case 335, name='SquareSheetExtrudedHydrologyDCTwoLayers';
+	case 336, name='SquareSheetConstrainedSmbComponents2d';
+	case 337, name='SquareSheetConstrainedSmbComponents3d';
+	case 338, name='SquareSheetConstrainedSmbMeltComponents2d';
+	case 339, name='SquareSheetConstrainedSmbMeltComponents3d';
 	case 401, name='SquareSheetShelfStressSSA2d';
 	case 402, name='SquareSheetShelfStressSSA3d';
Index: issm/trunk/test/NightlyRun/IdToName.py
===================================================================
--- issm/trunk/test/NightlyRun/IdToName.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/IdToName.py	(revision 18301)
@@ -77,4 +77,6 @@
 	285  : 'SquareShelfStressHOHigherOrder',
 	290  : 'SquareShelfStressFSP2P1',
+	291  : 'SquareShelfStressFSP4z',
+	292  : 'SquareShelfTranSSA2dFloatingMeltParam',
 	301  : 'SquareSheetConstrainedStressSSA2d',
 	302  : 'SquareSheetConstrainedStressSIA2d',
Index: issm/trunk/test/NightlyRun/runme.m
===================================================================
--- issm/trunk/test/NightlyRun/runme.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/runme.m	(revision 18301)
@@ -20,4 +20,5 @@
 %                      'adolc'   : validation of adolc tests
 %                      'gia'   : validation of gia tests
+%                      'qmu'   : validation of dakota tests
 %                      ...
 %      'procedure'     'check' :   run the test (default)
@@ -51,5 +52,5 @@
 %GET benchmark {{{
 benchmark=getfieldvalue(options,'benchmark','nightly');
-if ~ismember(benchmark,{'all','nightly','ismip','eismint','thermal','mesh','validation','tranforcing','adolc','gia'})
+if ~ismember(benchmark,{'all','nightly','ismip','eismint','thermal','mesh','validation','tranforcing','adolc','gia','qmu'})
 	disp('runme warning: benchmark not supported, defaulting to test ''nightly''')
 	benchmark='nightly';
@@ -123,4 +124,6 @@
 elseif strcmpi(benchmark,'adolc'),
 	test_ids=intersect(test_ids,[3001:3200]);
+elseif strcmpi(benchmark,'qmu'),
+	test_ids=intersect(test_ids,[218 234 235 412:414 417 418 420]);
 end
 % }}}
Index: issm/trunk/test/NightlyRun/temp291.m
===================================================================
--- issm/trunk/test/NightlyRun/temp291.m	(revision 18081)
+++ 	(revision )
@@ -1,8 +1,0 @@
-md=triangle(model(),'../Exp/Square.exp',150000.);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,2,1.);
-md=setflowequation(md,'FS','all');
-md.flowequation.fe_FS='OneLayerP4z';
-md.cluster=generic('name',oshostname(),'np',1);
-md=solve(md,StressbalanceSolutionEnum());
Index: issm/trunk/test/NightlyRun/temp291.py
===================================================================
--- issm/trunk/test/NightlyRun/temp291.py	(revision 18081)
+++ 	(revision )
@@ -1,18 +1,0 @@
-from model import *
-from triangle import *
-from setmask import *
-from parameterize import *
-from setflowequation import *
-from EnumDefinitions import *
-from solve import *
-from MatlabFuncs import *
-from ContourToMesh import *
-
-md=triangle(model(),'../Exp/Square.exp',150000.)
-md=setmask(md,'all','')
-md=parameterize(md,'../Par/SquareShelf.py')
-md.extrude(2,1.)
-md=setflowequation(md,'FS','all')
-md.flowequation.fe_FS='OneLayerP4z'
-md.cluster=generic('name',oshostname(),'np',1)
-md=solve(md,StressbalanceSolutionEnum())
Index: issm/trunk/test/NightlyRun/test108.m
===================================================================
--- issm/trunk/test/NightlyRun/test108.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test108.m	(revision 18301)
@@ -9,8 +9,8 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_names     ={'Temperature','BasalforcingsGroundediceMeltingRate'};
 field_tolerances={1e-13,1e-5};
 field_values={...
 	(md.results.ThermalSolution.Temperature),...
-	(md.results.ThermalSolution.BasalforcingsMeltingRate),...
+	(md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test108.py
===================================================================
--- issm/trunk/test/NightlyRun/test108.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test108.py	(revision 18301)
@@ -18,8 +18,8 @@
 
 #Fields and tolerances to track changes
-field_names     =['Temperature','BasalforcingsMeltingRate']
+field_names     =['Temperature','BasalforcingsGroundediceMeltingRate']
 field_tolerances=[1e-13,1e-5]
 field_values=[\
 	md.results.ThermalSolution.Temperature,\
-	md.results.ThermalSolution.BasalforcingsMeltingRate,\
+	md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test109.m
===================================================================
--- issm/trunk/test/NightlyRun/test109.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test109.m	(revision 18301)
@@ -12,8 +12,8 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_names     ={'Temperature','BasalforcingsGroundediceMeltingRate'};
 field_tolerances={1e-13,1e-13};
 field_values={...
 	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test109.py
===================================================================
--- issm/trunk/test/NightlyRun/test109.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test109.py	(revision 18301)
@@ -21,8 +21,8 @@
 
 #Fields and tolerances to track changes
-field_names     =['Temperature','BasalforcingsMeltingRate']
+field_names     =['Temperature','BasalforcingsGroundediceMeltingRate']
 field_tolerances=[1e-13,1e-13]
 field_values=[\
 	md.results.TransientSolution[0].Temperature,\
-	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test111.m
===================================================================
--- issm/trunk/test/NightlyRun/test111.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test111.m	(revision 18301)
@@ -10,7 +10,7 @@
 %Fields and tolerances to track changes
 field_names={...
-	'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface2','Thickness1','Temperature1','BasalforcingsMeltingRate1','Volume1', ...
-	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2','Volume2', ...
-	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3','Volume3'};
+	'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface2','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1','Volume1', ...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2','Volume2', ...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3','Volume3'};
 field_tolerances={...
 	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,1e-13,...
@@ -27,5 +27,5 @@
 	(md.results.TransientSolution(1).Thickness),...
 	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(1).IceVolume),...
 	(md.results.TransientSolution(2).Vx),...
@@ -38,5 +38,5 @@
 	(md.results.TransientSolution(2).Thickness),...
 	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(2).IceVolume),...
 	(md.results.TransientSolution(3).Vx),...
@@ -49,5 +49,5 @@
 	(md.results.TransientSolution(3).Thickness),...
 	(md.results.TransientSolution(3).Temperature),...
-	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(3).IceVolume),...
 	};
Index: issm/trunk/test/NightlyRun/test111.py
===================================================================
--- issm/trunk/test/NightlyRun/test111.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test111.py	(revision 18301)
@@ -19,7 +19,7 @@
 #Fields and tolerances to track changes
 field_names=[\
-	'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface2','Thickness1','Temperature1','BasalforcingsMeltingRate1','Volume1', \
-	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2','Volume2', \
-	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3','Volume3']
+	'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface2','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1','Volume1', \
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2','Volume2', \
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3','Volume3']
 field_tolerances=[\
 	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,1e-13,\
@@ -36,5 +36,5 @@
 	md.results.TransientSolution[0].Thickness,\
 	md.results.TransientSolution[0].Temperature,\
-	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[0].IceVolume,\
 	md.results.TransientSolution[1].Vx,\
@@ -47,5 +47,5 @@
 	md.results.TransientSolution[1].Thickness,\
 	md.results.TransientSolution[1].Temperature,\
-	md.results.TransientSolution[1].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[1].IceVolume,\
 	md.results.TransientSolution[2].Vx,\
@@ -58,5 +58,5 @@
 	md.results.TransientSolution[2].Thickness,\
 	md.results.TransientSolution[2].Temperature,\
-	md.results.TransientSolution[2].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[2].IceVolume,\
 	]
Index: issm/trunk/test/NightlyRun/test1208.m
===================================================================
--- issm/trunk/test/NightlyRun/test1208.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test1208.m	(revision 18301)
@@ -30,5 +30,5 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure','Thickness','Base','Surface','Temperature','BasalforcingsMeltingRate'};
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Thickness','Base','Surface','Temperature','BasalforcingsGroundediceMeltingRate'};
 field_tolerances={1e-08,1e-08,1e-07,1e-08,1e-08,1e-08,1e-08,1e-08,1e-07,3e-07};
 field_values={...
@@ -42,4 +42,4 @@
 	(md.results.TransientSolution(end).Surface),...
 	(md.results.TransientSolution(end).Temperature),...
-	(md.results.TransientSolution(end).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(end).BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test1208.py
===================================================================
--- issm/trunk/test/NightlyRun/test1208.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test1208.py	(revision 18301)
@@ -43,5 +43,5 @@
 
 #Fields and tolerances to track changes
-field_names     =['Vx','Vy','Vz','Vel','Pressure','Thickness','Base','Surface','Temperature','BasalforcingsMeltingRate']
+field_names     =['Vx','Vy','Vz','Vel','Pressure','Thickness','Base','Surface','Temperature','BasalforcingsGroundediceMeltingRate']
 field_tolerances=[1e-08,1e-08,1e-07,1e-08,1e-08,1e-08,1e-08,1e-08,1e-07,1e-07]
 field_values=[\
@@ -55,4 +55,4 @@
 	md.results.TransientSolution[-1].Surface,\
 	md.results.TransientSolution[-1].Temperature,\
-	md.results.TransientSolution[-1].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[-1].BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test1301.m
===================================================================
--- issm/trunk/test/NightlyRun/test1301.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test1301.m	(revision 18301)
@@ -29,5 +29,5 @@
 
 %plot results
-comp_melting=md.results.ThermalSolution.BasalforcingsMeltingRate;
+comp_melting=md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate;
 relative=abs((comp_melting-melting)./melting)*100.;
 relative(find(comp_melting==melting))=0.;
Index: issm/trunk/test/NightlyRun/test1301.py
===================================================================
--- issm/trunk/test/NightlyRun/test1301.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test1301.py	(revision 18301)
@@ -43,5 +43,5 @@
 
 #plot results
-comp_melting=md.results.ThermalSolution.BasalforcingsMeltingRate
+comp_melting=md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate
 relative=numpy.abs((comp_melting-melting)/melting)*100.
 relative[numpy.nonzero(comp_melting==melting)[0]]=0.
Index: issm/trunk/test/NightlyRun/test206.m
===================================================================
--- issm/trunk/test/NightlyRun/test206.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test206.m	(revision 18301)
@@ -9,8 +9,8 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_names     ={'Temperature','BasalforcingsGroundediceMeltingRate'};
 field_tolerances={1e-13,5e-6};
 field_values={...
 	(md.results.ThermalSolution.Temperature),...
-	(md.results.ThermalSolution.BasalforcingsMeltingRate),...
+	(md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test206.py
===================================================================
--- issm/trunk/test/NightlyRun/test206.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test206.py	(revision 18301)
@@ -22,8 +22,8 @@
 # Fields and tolerances to track changes
 
-field_names     =['Temperature','BasalforcingsMeltingRate']
+field_names     =['Temperature','BasalforcingsGroundediceMeltingRate']
 field_tolerances=[1e-13,5e-6]
 field_values=[\
 	md.results.ThermalSolution.Temperature,\
-	md.results.ThermalSolution.BasalforcingsMeltingRate,\
+	md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test207.m
===================================================================
--- issm/trunk/test/NightlyRun/test207.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test207.m	(revision 18301)
@@ -12,12 +12,12 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Temperature1','BasalforcingsMeltingRate1','Temperature2','BasalforcingsMeltingRate2','Temperature3','BasalforcingsMeltingRate3'};
+field_names     ={'Temperature1','BasalforcingsGroundediceMeltingRate1','Temperature2','BasalforcingsGroundediceMeltingRate2','Temperature3','BasalforcingsGroundediceMeltingRate3'};
 field_tolerances={1e-13,1e-6,1e-13,1e-6,1e-13,1e-6};
 field_values={...
 	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(3).Temperature),...
-	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test207.py
===================================================================
--- issm/trunk/test/NightlyRun/test207.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test207.py	(revision 18301)
@@ -23,12 +23,12 @@
 
 # Fields and tolerances to track changes
-field_names     =['Temperature1','BasalforcingsMeltingRate1','Temperature2','BasalforcingsMeltingRate2','Temperature3','BasalforcingsMeltingRate3']
+field_names     =['Temperature1','BasalforcingsGroundediceMeltingRate1','Temperature2','BasalforcingsGroundediceMeltingRate2','Temperature3','BasalforcingsGroundediceMeltingRate3']
 field_tolerances=[1e-13,1e-6,1e-13,1e-6,1e-13,1e-6]
 field_values=[\
 	md.results.TransientSolution[0].Temperature,\
-	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[1].Temperature,\
-	md.results.TransientSolution[1].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[2].Temperature,\
-	md.results.TransientSolution[2].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test209.m
===================================================================
--- issm/trunk/test/NightlyRun/test209.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test209.m	(revision 18301)
@@ -8,7 +8,7 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
-	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
-	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', ...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', ...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'};
 field_tolerances={...
 	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-8,...
@@ -25,5 +25,5 @@
 	(md.results.TransientSolution(1).Thickness),...
 	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(2).Vx),...
 	(md.results.TransientSolution(2).Vy),...
@@ -35,5 +35,5 @@
 	(md.results.TransientSolution(2).Thickness),...
 	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(3).Vx),...
 	(md.results.TransientSolution(3).Vy),...
@@ -45,4 +45,4 @@
 	(md.results.TransientSolution(3).Thickness),...
 	(md.results.TransientSolution(3).Temperature),...
-	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test209.py
===================================================================
--- issm/trunk/test/NightlyRun/test209.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test209.py	(revision 18301)
@@ -21,7 +21,7 @@
 # Fields and tolerances to track changes
 
-field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', \
-	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', \
-	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3']
+field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', \
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', \
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3']
 field_tolerances=[\
 	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-8,\
@@ -39,5 +39,5 @@
 	md.results.TransientSolution[0].Thickness,\
 	md.results.TransientSolution[0].Temperature,\
-	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[1].Vx,\
 	md.results.TransientSolution[1].Vy,\
@@ -49,5 +49,5 @@
 	md.results.TransientSolution[1].Thickness,\
 	md.results.TransientSolution[1].Temperature,\
-	md.results.TransientSolution[1].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[2].Vx,\
 	md.results.TransientSolution[2].Vy,\
@@ -59,4 +59,4 @@
 	md.results.TransientSolution[2].Thickness,\
 	md.results.TransientSolution[2].Temperature,\
-	md.results.TransientSolution[2].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test210.m
===================================================================
--- issm/trunk/test/NightlyRun/test210.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test210.m	(revision 18301)
@@ -8,7 +8,7 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
-				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
-					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', ...
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'};
 field_tolerances={...
 	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,...
@@ -25,5 +25,5 @@
 	(md.results.TransientSolution(1).Thickness),...
 	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(2).Vx),...
 	(md.results.TransientSolution(2).Vy),...
@@ -35,5 +35,5 @@
 	(md.results.TransientSolution(2).Thickness),...
 	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(3).Vx),...
 	(md.results.TransientSolution(3).Vy),...
@@ -45,4 +45,4 @@
 	(md.results.TransientSolution(3).Thickness),...
 	(md.results.TransientSolution(3).Temperature),...
-	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test210.py
===================================================================
--- issm/trunk/test/NightlyRun/test210.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test210.py	(revision 18301)
@@ -21,7 +21,7 @@
 # Fields and tolerances to track changes
 
-field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', \
-				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', \
-					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3']
+field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', \
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', \
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3']
 field_tolerances=[\
 	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,\
@@ -38,5 +38,5 @@
 	md.results.TransientSolution[0].Thickness,\
 	md.results.TransientSolution[0].Temperature,\
-	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[1].Vx,\
 	md.results.TransientSolution[1].Vy,\
@@ -48,5 +48,5 @@
 	md.results.TransientSolution[1].Thickness,\
 	md.results.TransientSolution[1].Temperature,\
-	md.results.TransientSolution[1].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[2].Vx,\
 	md.results.TransientSolution[2].Vy,\
@@ -58,4 +58,4 @@
 	md.results.TransientSolution[2].Thickness,\
 	md.results.TransientSolution[2].Temperature,\
-	md.results.TransientSolution[2].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test211.m
===================================================================
--- issm/trunk/test/NightlyRun/test211.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test211.m	(revision 18301)
@@ -10,7 +10,7 @@
 %Fields and tolerances to track changes
 field_names={...
-	'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
-	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
-	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+	'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', ...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', ...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'};
 field_tolerances={...
 	2e-08,2e-08,1e-06,2e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,...
@@ -27,5 +27,5 @@
 	(md.results.TransientSolution(1).Thickness),...
 	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(2).Vx),...
 	(md.results.TransientSolution(2).Vy),...
@@ -37,5 +37,5 @@
 	(md.results.TransientSolution(2).Thickness),...
 	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(3).Vx),...
 	(md.results.TransientSolution(3).Vy),...
@@ -47,4 +47,4 @@
 	(md.results.TransientSolution(3).Thickness),...
 	(md.results.TransientSolution(3).Temperature),...
-	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test211.py
===================================================================
--- issm/trunk/test/NightlyRun/test211.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test211.py	(revision 18301)
@@ -23,7 +23,7 @@
 
 field_names=[\
-	'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', \
-	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', \
-	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3']
+	'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', \
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', \
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3']
 field_tolerances=[\
 	2e-08,2e-08,1e-06,2e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,\
@@ -40,5 +40,5 @@
 	md.results.TransientSolution[0].Thickness,\
 	md.results.TransientSolution[0].Temperature,\
-	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[1].Vx,\
 	md.results.TransientSolution[1].Vy,\
@@ -50,5 +50,5 @@
 	md.results.TransientSolution[1].Thickness,\
 	md.results.TransientSolution[1].Temperature,\
-	md.results.TransientSolution[1].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[2].Vx,\
 	md.results.TransientSolution[2].Vy,\
@@ -60,4 +60,4 @@
 	md.results.TransientSolution[2].Thickness,\
 	md.results.TransientSolution[2].Temperature,\
-	md.results.TransientSolution[2].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test224.m
===================================================================
--- issm/trunk/test/NightlyRun/test224.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test224.m	(revision 18301)
@@ -9,7 +9,7 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
-	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
-	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', ...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', ...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'};
 field_tolerances={...
 	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,...
@@ -26,5 +26,5 @@
 	(md.results.TransientSolution(1).Thickness),...
 	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(2).Vx),...
 	(md.results.TransientSolution(2).Vy),...
@@ -36,5 +36,5 @@
 	(md.results.TransientSolution(2).Thickness),...
 	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(3).Vx),...
 	(md.results.TransientSolution(3).Vy),...
@@ -46,4 +46,4 @@
 	(md.results.TransientSolution(3).Thickness),...
 	(md.results.TransientSolution(3).Temperature),...
-	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test224.py
===================================================================
--- issm/trunk/test/NightlyRun/test224.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test224.py	(revision 18301)
@@ -18,7 +18,7 @@
 
 #Fields and tolerances to track changes
-field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', \
-	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', \
-	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3']
+field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', \
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', \
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3']
 field_tolerances=[\
 	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,\
@@ -35,5 +35,5 @@
 	md.results.TransientSolution[0].Thickness,\
 	md.results.TransientSolution[0].Temperature,\
-	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[1].Vx,\
 	md.results.TransientSolution[1].Vy,\
@@ -45,5 +45,5 @@
 	md.results.TransientSolution[1].Thickness,\
 	md.results.TransientSolution[1].Temperature,\
-	md.results.TransientSolution[1].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[2].Vx,\
 	md.results.TransientSolution[2].Vy,\
@@ -55,4 +55,4 @@
 	md.results.TransientSolution[2].Thickness,\
 	md.results.TransientSolution[2].Temperature,\
-	md.results.TransientSolution[2].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test225.m
===================================================================
--- issm/trunk/test/NightlyRun/test225.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test225.m	(revision 18301)
@@ -10,7 +10,7 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
-	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
-	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', ...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', ...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'};
 field_tolerances={...
 	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,...
@@ -27,5 +27,5 @@
 	(md.results.TransientSolution(1).Thickness),...
 	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(2).Vx),...
 	(md.results.TransientSolution(2).Vy),...
@@ -37,5 +37,5 @@
 	(md.results.TransientSolution(2).Thickness),...
 	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(3).Vx),...
 	(md.results.TransientSolution(3).Vy),...
@@ -47,4 +47,4 @@
 	(md.results.TransientSolution(3).Thickness),...
 	(md.results.TransientSolution(3).Temperature),...
-	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test225.py
===================================================================
--- issm/trunk/test/NightlyRun/test225.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test225.py	(revision 18301)
@@ -20,7 +20,7 @@
 
 #Fields and tolerances to track changes
-field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', \
-	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', \
-	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3']
+field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', \
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', \
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3']
 field_tolerances=[\
 	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,\
@@ -37,5 +37,5 @@
 	md.results.TransientSolution[0].Thickness,\
 	md.results.TransientSolution[0].Temperature,\
-	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[1].Vx,\
 	md.results.TransientSolution[1].Vy,\
@@ -47,5 +47,5 @@
 	md.results.TransientSolution[1].Thickness,\
 	md.results.TransientSolution[1].Temperature,\
-	md.results.TransientSolution[1].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[2].Vx,\
 	md.results.TransientSolution[2].Vy,\
@@ -57,4 +57,4 @@
 	md.results.TransientSolution[2].Thickness,\
 	md.results.TransientSolution[2].Temperature,\
-	md.results.TransientSolution[2].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test227.m
===================================================================
--- issm/trunk/test/NightlyRun/test227.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test227.m	(revision 18301)
@@ -10,7 +10,7 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
-	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
-	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', ...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', ...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'};
 field_tolerances={...
 	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,...
@@ -27,5 +27,5 @@
 	(md.results.TransientSolution(1).Thickness),...
 	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(2).Vx),...
 	(md.results.TransientSolution(2).Vy),...
@@ -37,5 +37,5 @@
 	(md.results.TransientSolution(2).Thickness),...
 	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(3).Vx),...
 	(md.results.TransientSolution(3).Vy),...
@@ -47,4 +47,4 @@
 	(md.results.TransientSolution(3).Thickness),...
 	(md.results.TransientSolution(3).Temperature),...
-	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test227.py
===================================================================
--- issm/trunk/test/NightlyRun/test227.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test227.py	(revision 18301)
@@ -19,7 +19,7 @@
 
 #Fields and tolerances to track changes
-field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', \
-	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', \
-	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3']
+field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', \
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', \
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3']
 field_tolerances=[\
 	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,\
@@ -36,5 +36,5 @@
 	md.results.TransientSolution[0].Thickness,\
 	md.results.TransientSolution[0].Temperature,\
-	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[1].Vx,\
 	md.results.TransientSolution[1].Vy,\
@@ -46,5 +46,5 @@
 	md.results.TransientSolution[1].Thickness,\
 	md.results.TransientSolution[1].Temperature,\
-	md.results.TransientSolution[1].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[2].Vx,\
 	md.results.TransientSolution[2].Vy,\
@@ -56,4 +56,4 @@
 	md.results.TransientSolution[2].Thickness,\
 	md.results.TransientSolution[2].Temperature,\
-	md.results.TransientSolution[2].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test230.m
===================================================================
--- issm/trunk/test/NightlyRun/test230.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test230.m	(revision 18301)
@@ -24,5 +24,5 @@
 	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
 	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', ...
-	'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceMassbalance4'};
+	'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassbalance4'};
 field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
 	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
Index: issm/trunk/test/NightlyRun/test230.py
===================================================================
--- issm/trunk/test/NightlyRun/test230.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test230.py	(revision 18301)
@@ -33,5 +33,5 @@
 	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', \
 	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', \
-	'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceMassbalance4']
+	'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassbalance4']
 field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,\
 	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,\
Index: issm/trunk/test/NightlyRun/test231.m
===================================================================
--- issm/trunk/test/NightlyRun/test231.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test231.m	(revision 18301)
@@ -24,5 +24,5 @@
 	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
 	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', ...
-	'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceMassbalance4'};
+	'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassbalance4'};
 field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
 	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
Index: issm/trunk/test/NightlyRun/test231.py
===================================================================
--- issm/trunk/test/NightlyRun/test231.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test231.py	(revision 18301)
@@ -33,5 +33,5 @@
 	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', \
 	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', \
-	'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceMassbalance4']
+	'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassbalance4']
 field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,\
 	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,\
Index: issm/trunk/test/NightlyRun/test232.m
===================================================================
--- issm/trunk/test/NightlyRun/test232.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test232.m	(revision 18301)
@@ -15,14 +15,14 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Temperature1','BasalforcingsMeltingRate1','Temperature2','BasalforcingsMeltingRate2','Temperature3','BasalforcingsMeltingRate3','Temperature4','BasalforcingsMeltingRate4'};
+field_names     ={'Temperature1','BasalforcingsGroundediceMeltingRate1','Temperature2','BasalforcingsGroundediceMeltingRate2','Temperature3','BasalforcingsGroundediceMeltingRate3','Temperature4','BasalforcingsGroundediceMeltingRate4'};
 field_tolerances={1e-13,1e-6,1e-13,1e-6,1e-13,1e-6,1e-13,1e-6};
 field_values={...
 	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(3).Temperature),...
-	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(4).Temperature),...
-	(md.results.TransientSolution(4).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(4).BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test232.py
===================================================================
--- issm/trunk/test/NightlyRun/test232.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test232.py	(revision 18301)
@@ -25,14 +25,14 @@
 
 #Fields and tolerances to track changes
-field_names     =['Temperature1','BasalforcingsMeltingRate1','Temperature2','BasalforcingsMeltingRate2','Temperature3','BasalforcingsMeltingRate3','Temperature4','BasalforcingsMeltingRate4']
+field_names     =['Temperature1','BasalforcingsGroundediceMeltingRate1','Temperature2','BasalforcingsGroundediceMeltingRate2','Temperature3','BasalforcingsGroundediceMeltingRate3','Temperature4','BasalforcingsGroundediceMeltingRate4']
 field_tolerances=[1e-13,1e-6,1e-13,1e-6,1e-13,1e-6,1e-13,1e-6]
 field_values=[\
 	md.results.TransientSolution[0].Temperature,\
-	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[1].Temperature,\
-	md.results.TransientSolution[1].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[2].Temperature,\
-	md.results.TransientSolution[2].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[3].Temperature,\
-	md.results.TransientSolution[3].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[3].BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test233.m
===================================================================
--- issm/trunk/test/NightlyRun/test233.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test233.m	(revision 18301)
@@ -11,8 +11,8 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
-	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
-	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3', ...
-	'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','Temperature4','BasalforcingsMeltingRate4'};
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', ...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', ...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3', ...
+	'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','Temperature4','BasalforcingsGroundediceMeltingRate4'};
 field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09, ...
 	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06, ...
@@ -29,5 +29,5 @@
 	(md.results.TransientSolution(1).Thickness),...
 	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(2).Vx),...
 	(md.results.TransientSolution(2).Vy),...
@@ -39,5 +39,5 @@
 	(md.results.TransientSolution(2).Thickness),...
 	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(3).Vx),...
 	(md.results.TransientSolution(3).Vy),...
@@ -49,5 +49,5 @@
 	(md.results.TransientSolution(3).Thickness),...
 	(md.results.TransientSolution(3).Temperature),...
-	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(4).Vx),...
 	(md.results.TransientSolution(4).Vy),...
@@ -59,4 +59,4 @@
 	(md.results.TransientSolution(4).Thickness),...
 	(md.results.TransientSolution(4).Temperature),...
-	(md.results.TransientSolution(4).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(4).BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test233.py
===================================================================
--- issm/trunk/test/NightlyRun/test233.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test233.py	(revision 18301)
@@ -21,8 +21,8 @@
 
 #Fields and tolerances to track changes
-field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', \
-	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', \
-	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3', \
-	'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','Temperature4','BasalforcingsMeltingRate4']
+field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', \
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', \
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3', \
+	'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','Temperature4','BasalforcingsGroundediceMeltingRate4']
 field_tolerances=[1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09, \
 	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06, \
@@ -39,5 +39,5 @@
 	md.results.TransientSolution[0].Thickness,\
 	md.results.TransientSolution[0].Temperature,\
-	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[1].Vx,\
 	md.results.TransientSolution[1].Vy,\
@@ -49,5 +49,5 @@
 	md.results.TransientSolution[1].Thickness,\
 	md.results.TransientSolution[1].Temperature,\
-	md.results.TransientSolution[1].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[2].Vx,\
 	md.results.TransientSolution[2].Vy,\
@@ -59,5 +59,5 @@
 	md.results.TransientSolution[2].Thickness,\
 	md.results.TransientSolution[2].Temperature,\
-	md.results.TransientSolution[2].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[3].Vx,\
 	md.results.TransientSolution[3].Vy,\
@@ -69,4 +69,4 @@
 	md.results.TransientSolution[3].Thickness,\
 	md.results.TransientSolution[3].Temperature,\
-	md.results.TransientSolution[3].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[3].BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test237.m
===================================================================
--- issm/trunk/test/NightlyRun/test237.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test237.m	(revision 18301)
@@ -54,7 +54,7 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
-						'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
-						'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', ...
+						'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', ...
+						'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'};
 field_tolerances={...
 	1e-13,1e-13,1e-13,1e-13,1e-13,1e-8,1e-8,1e-8,1e-13,1e-8,...
@@ -71,5 +71,5 @@
 	(md.results.TransientSolution(1).Thickness),...
 	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(1).SurfaceforcingsMonthlytemperatures),...
 	(md.results.TransientSolution(1).SurfaceforcingsMassBalance),...
@@ -83,5 +83,5 @@
 	(md.results.TransientSolution(2).Thickness),...
 	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(2).SurfaceforcingsMonthlytemperatures),...
 	(md.results.TransientSolution(2).SurfaceforcingsMassBalance),...
@@ -95,5 +95,5 @@
 	(md.results.TransientSolution(3).Thickness),...
 	(md.results.TransientSolution(3).Temperature),...
-	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(3).SurfaceforcingsMonthlytemperatures),...
 	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
Index: issm/trunk/test/NightlyRun/test237.py
===================================================================
--- issm/trunk/test/NightlyRun/test237.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test237.py	(revision 18301)
@@ -66,7 +66,7 @@
 
 #Fields and tolerances to track changes
-field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', \
-						'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', \
-						'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3']
+field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', \
+						'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', \
+						'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3']
 field_tolerances=[\
 	1e-13,1e-13,1e-13,1e-13,1e-13,1e-8,1e-8,1e-13,1e-13,1e-8,\
@@ -83,5 +83,5 @@
 	md.results.TransientSolution[0].Thickness,\
 	md.results.TransientSolution[0].Temperature,\
-	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[0].SurfaceforcingsMonthlytemperatures,\
 	md.results.TransientSolution[0].SurfaceforcingsMassBalance,\
@@ -95,5 +95,5 @@
 	md.results.TransientSolution[1].Thickness,\
 	md.results.TransientSolution[1].Temperature,\
-	md.results.TransientSolution[1].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[1].SurfaceforcingsMonthlytemperatures,\
 	md.results.TransientSolution[1].SurfaceforcingsMassBalance,\
@@ -107,5 +107,5 @@
 	md.results.TransientSolution[2].Thickness,\
 	md.results.TransientSolution[2].Temperature,\
-	md.results.TransientSolution[2].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[2].SurfaceforcingsMonthlytemperatures,\
 	md.results.TransientSolution[2].SurfaceforcingsMassBalance,\
Index: issm/trunk/test/NightlyRun/test238.m
===================================================================
--- issm/trunk/test/NightlyRun/test238.m	(revision 18301)
+++ issm/trunk/test/NightlyRun/test238.m	(revision 18301)
@@ -0,0 +1,64 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+md.timestepping.time_step=1.;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4.;
+md.timestepping.interp_forcings=0;
+
+%Set up transient
+smb=ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*-1. ];
+
+md.surfaceforcings.mass_balance=smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3.];
+md.transient.isthermal=0;
+
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
+	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
+	'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', ...
+	'Vx4','Vy4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassBalance4'};
+field_tolerances={1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Base),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
+	};
Index: issm/trunk/test/NightlyRun/test238.py
===================================================================
--- issm/trunk/test/NightlyRun/test238.py	(revision 18301)
+++ issm/trunk/test/NightlyRun/test238.py	(revision 18301)
@@ -0,0 +1,73 @@
+import numpy
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+
+md.timestepping.time_step=1.
+md.settings.output_frequency=1
+md.timestepping.final_time=4.
+md.timestepping.interp_forcings=False
+
+#Set up transient
+smb=numpy.ones((md.mesh.numberofvertices,1))*3.6
+smb=numpy.hstack((smb,smb*-1.))
+
+md.surfaceforcings.mass_balance=numpy.vstack((smb,[1.5,3.]))
+md.transient.isthermal=False
+
+md=solve(md,TransientSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names=['Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', \
+	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', \
+	'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', \
+	'Vx4','Vy4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassBalance4']
+field_tolerances=[1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,\
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,\
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,\
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10]
+field_values=[\
+	md.results.TransientSolution[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Base,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].SurfaceforcingsMassBalance,\
+	md.results.TransientSolution[1].Vx,\
+	md.results.TransientSolution[1].Vy,\
+	md.results.TransientSolution[1].Vel,\
+	md.results.TransientSolution[1].Pressure,\
+	md.results.TransientSolution[1].Base,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].SurfaceforcingsMassBalance,\
+	md.results.TransientSolution[2].Vx,\
+	md.results.TransientSolution[2].Vy,\
+	md.results.TransientSolution[2].Vel,\
+	md.results.TransientSolution[2].Pressure,\
+	md.results.TransientSolution[2].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].SurfaceforcingsMassBalance,\
+	md.results.TransientSolution[3].Vx,\
+	md.results.TransientSolution[3].Vy,\
+	md.results.TransientSolution[3].Vel,\
+	md.results.TransientSolution[3].Pressure,\
+	md.results.TransientSolution[3].Base,\
+	md.results.TransientSolution[3].Surface,\
+	md.results.TransientSolution[3].Thickness,\
+	md.results.TransientSolution[3].SurfaceforcingsMassBalance,\
+	]
Index: issm/trunk/test/NightlyRun/test239.m
===================================================================
--- issm/trunk/test/NightlyRun/test239.m	(revision 18301)
+++ issm/trunk/test/NightlyRun/test239.m	(revision 18301)
@@ -0,0 +1,70 @@
+md=triangle(model(),'../Exp/Square.exp',350000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+md.timestepping.time_step=1;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4;
+md.timestepping.interp_forcings=0;
+
+%Set up transient
+smb=ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*-1. ];
+
+md.surfaceforcings.mass_balance=smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3.];
+md.transient.isthermal=0;
+
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', ...
+	'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassbalance4'};
+field_tolerances={...
+	1e-09,1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-13,...
+	1e-09,1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-13,...
+	1e-09,1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-13,...
+	1e-09,1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vz),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Base),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
+	};
Index: issm/trunk/test/NightlyRun/test239.py
===================================================================
--- issm/trunk/test/NightlyRun/test239.py	(revision 18301)
+++ issm/trunk/test/NightlyRun/test239.py	(revision 18301)
@@ -0,0 +1,79 @@
+import numpy
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',350000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(3,1.)
+md=setflowequation(md,'HO','all')
+md.cluster=generic('name',oshostname(),'np',3)
+
+md.timestepping.time_step=1.
+md.settings.output_frequency=1
+md.timestepping.final_time=4.
+md.timestepping.interp_forcings=False
+
+#Set up transient
+smb=numpy.ones((md.mesh.numberofvertices,1))*3.6
+smb=numpy.hstack((smb,smb*-1.))
+
+md.surfaceforcings.mass_balance=numpy.vstack((smb,[1.5,3.]))
+md.transient.isthermal=False
+
+md=solve(md,TransientSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', \
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', \
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', \
+	'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassbalance4']
+field_tolerances=[\
+		1e-09,1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-13,\
+		1e-09,1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-13,\
+		1e-09,1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-13,\
+		1e-09,1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-13]
+field_values=[\
+	md.results.TransientSolution[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vz,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Base,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].SurfaceforcingsMassBalance,\
+	md.results.TransientSolution[1].Vx,\
+	md.results.TransientSolution[1].Vy,\
+	md.results.TransientSolution[1].Vz,\
+	md.results.TransientSolution[1].Vel,\
+	md.results.TransientSolution[1].Pressure,\
+	md.results.TransientSolution[1].Base,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].SurfaceforcingsMassBalance,\
+	md.results.TransientSolution[2].Vx,\
+	md.results.TransientSolution[2].Vy,\
+	md.results.TransientSolution[2].Vz,\
+	md.results.TransientSolution[2].Vel,\
+	md.results.TransientSolution[2].Pressure,\
+	md.results.TransientSolution[2].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].SurfaceforcingsMassBalance,\
+	md.results.TransientSolution[3].Vx,\
+	md.results.TransientSolution[3].Vy,\
+	md.results.TransientSolution[3].Vz,\
+	md.results.TransientSolution[3].Vel,\
+	md.results.TransientSolution[3].Pressure,\
+	md.results.TransientSolution[3].Base,\
+	md.results.TransientSolution[3].Surface,\
+	md.results.TransientSolution[3].Thickness,\
+	md.results.TransientSolution[3].SurfaceforcingsMassBalance,\
+	]
Index: issm/trunk/test/NightlyRun/test271.m
===================================================================
--- issm/trunk/test/NightlyRun/test271.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test271.m	(revision 18301)
@@ -6,5 +6,5 @@
 md.damage.D=zeros(md.mesh.numberofvertices,1);
 md.damage.spcdamage=NaN*ones(md.mesh.numberofvertices,1);
-md.damage.law='pralong';
+md.damage.law=1;
 
 %boundary conditions for damage, to be put in SquareShelf.par
Index: issm/trunk/test/NightlyRun/test271.py
===================================================================
--- issm/trunk/test/NightlyRun/test271.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test271.py	(revision 18301)
@@ -19,5 +19,5 @@
 md.damage.D=numpy.zeros(md.mesh.numberofvertices)
 md.damage.spcdamage=numpy.nan*numpy.ones(md.mesh.numberofvertices)
-md.damage.law='pralong'
+md.damage.law=1
 md.damage.stabilization=1;
 
Index: issm/trunk/test/NightlyRun/test275.m
===================================================================
--- issm/trunk/test/NightlyRun/test275.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test275.m	(revision 18301)
@@ -6,5 +6,5 @@
 md.damage.D=0.1*ones(md.mesh.numberofvertices,1);
 md.damage.spcdamage=NaN*ones(md.mesh.numberofvertices,1);
-md.damage.law='pralong';
+md.damage.law=1;
 
 md.damage.c1=1.e-11;
Index: issm/trunk/test/NightlyRun/test275.py
===================================================================
--- issm/trunk/test/NightlyRun/test275.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test275.py	(revision 18301)
@@ -19,5 +19,5 @@
 md.damage.D=0.1*numpy.ones(md.mesh.numberofvertices)
 md.damage.spcdamage=numpy.nan*numpy.ones(md.mesh.numberofvertices)
-md.damage.law='pralong'
+md.damage.law=1
 
 md.damage.c1=1.e-11
Index: issm/trunk/test/NightlyRun/test291.m
===================================================================
--- issm/trunk/test/NightlyRun/test291.m	(revision 18301)
+++ issm/trunk/test/NightlyRun/test291.m	(revision 18301)
@@ -0,0 +1,19 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,2,1.);
+md=setflowequation(md,'FS','all');
+md.flowequation.fe_FS='OneLayerP4z';
+md.cluster=generic('name',oshostname(),'np',1);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={5e-5,5e-5,8e-5,5e-5,1e-7};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: issm/trunk/test/NightlyRun/test291.py
===================================================================
--- issm/trunk/test/NightlyRun/test291.py	(revision 18301)
+++ issm/trunk/test/NightlyRun/test291.py	(revision 18301)
@@ -0,0 +1,29 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+from ContourToMesh import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(2,1.)
+md=setflowequation(md,'FS','all')
+md.flowequation.fe_FS='OneLayerP4z'
+md.cluster=generic('name',oshostname(),'np',1)
+md=solve(md,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx', 'Vy', 'Vz', 'Vel','Pressure'];
+field_tolerances=[5e-5,5e-5,8e-5,5e-5,1e-7]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	];
Index: issm/trunk/test/NightlyRun/test292.m
===================================================================
--- issm/trunk/test/NightlyRun/test292.m	(revision 18301)
+++ issm/trunk/test/NightlyRun/test292.m	(revision 18301)
@@ -0,0 +1,34 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.basalforcings=linearbasalforcings(md.basalforcings);
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: issm/trunk/test/NightlyRun/test292.py
===================================================================
--- issm/trunk/test/NightlyRun/test292.py	(revision 18301)
+++ issm/trunk/test/NightlyRun/test292.py	(revision 18301)
@@ -0,0 +1,47 @@
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+from numpy import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+from generic import generic
+from linearbasalforcings import linearbasalforcings
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.basalforcings=linearbasalforcings(md.basalforcings)
+md=solve(md,TransientSolutionEnum())
+
+# Fields and tolerances to track changes
+
+field_names     =['Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3']
+field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13]
+field_values=[\
+	md.results.TransientSolution[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Base,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[1].Vx,\
+	md.results.TransientSolution[1].Vy,\
+	md.results.TransientSolution[1].Vel,\
+	md.results.TransientSolution[1].Pressure,\
+	md.results.TransientSolution[1].Base,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[2].Vx,\
+	md.results.TransientSolution[2].Vy,\
+	md.results.TransientSolution[2].Vel,\
+	md.results.TransientSolution[2].Pressure,\
+	md.results.TransientSolution[2].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	]
Index: issm/trunk/test/NightlyRun/test3008.m
===================================================================
--- issm/trunk/test/NightlyRun/test3008.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test3008.m	(revision 18301)
@@ -12,8 +12,8 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_names     ={'Temperature','BasalforcingsGroundediceMeltingRate'};
 field_tolerances={1e-13,1e-13};
 field_values={...
 	(md.results.ThermalSolution.Temperature),...
-	(md.results.ThermalSolution.BasalforcingsMeltingRate),...
+	(md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test3008.py
===================================================================
--- issm/trunk/test/NightlyRun/test3008.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test3008.py	(revision 18301)
@@ -20,8 +20,8 @@
 
 #Fields and tolerances to track changes
-field_names     =['Temperature','BasalforcingsMeltingRate']
+field_names     =['Temperature','BasalforcingsGroundediceMeltingRate']
 field_tolerances=[1e-13,1e-13]
 field_values=[\
 	md.results.ThermalSolution.Temperature,\
-	md.results.ThermalSolution.BasalforcingsMeltingRate,\
+	md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test3009.m
===================================================================
--- issm/trunk/test/NightlyRun/test3009.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test3009.m	(revision 18301)
@@ -15,8 +15,8 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_names     ={'Temperature','BasalforcingsGroundediceMeltingRate'};
 field_tolerances={1e-13,1e-13};
 field_values={...
 	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test3009.py
===================================================================
--- issm/trunk/test/NightlyRun/test3009.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test3009.py	(revision 18301)
@@ -23,8 +23,8 @@
 
 #Fields and tolerances to track changes
-field_names     =['Temperature','BasalforcingsMeltingRate']
+field_names     =['Temperature','BasalforcingsGroundediceMeltingRate']
 field_tolerances=[1e-13,1e-13]
 field_values=[\
 	md.results.TransientSolution[0].Temperature,\
-	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test3108.m
===================================================================
--- issm/trunk/test/NightlyRun/test3108.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test3108.m	(revision 18301)
@@ -12,8 +12,8 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_names     ={'Temperature','BasalforcingsGroundediceMeltingRate'};
 field_tolerances={1e-13,1e-13};
 field_values={...
 	(md.results.ThermalSolution.Temperature),...
-	(md.results.ThermalSolution.BasalforcingsMeltingRate),...
+	(md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test3108.py
===================================================================
--- issm/trunk/test/NightlyRun/test3108.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test3108.py	(revision 18301)
@@ -20,8 +20,8 @@
 
 #Fields and tolerances to track changes
-field_names     =['Temperature','BasalforcingsMeltingRate']
+field_names     =['Temperature','BasalforcingsGroundediceMeltingRate']
 field_tolerances=[1e-13,1e-13]
 field_values=[\
 	md.results.ThermalSolution.Temperature,\
-	md.results.ThermalSolution.BasalforcingsMeltingRate,\
+	md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test3109.m
===================================================================
--- issm/trunk/test/NightlyRun/test3109.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test3109.m	(revision 18301)
@@ -15,8 +15,8 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_names     ={'Temperature','BasalforcingsGroundediceMeltingRate'};
 field_tolerances={1e-13,1e-13};
 field_values={...
 	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test3109.py
===================================================================
--- issm/trunk/test/NightlyRun/test3109.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test3109.py	(revision 18301)
@@ -23,8 +23,8 @@
 
 #Fields and tolerances to track changes
-field_names     =['Temperature','BasalforcingsMeltingRate']
+field_names     =['Temperature','BasalforcingsGroundediceMeltingRate']
 field_tolerances=[1e-13,1e-13]
 field_values=[\
 	md.results.TransientSolution[0].Temperature,\
-	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test312.m
===================================================================
--- issm/trunk/test/NightlyRun/test312.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test312.m	(revision 18301)
@@ -9,8 +9,8 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_names     ={'Temperature','BasalforcingsGroundediceMeltingRate'};
 field_tolerances={1e-13,1e-8};
 field_values={...
 	(md.results.ThermalSolution.Temperature),...
-	(md.results.ThermalSolution.BasalforcingsMeltingRate),...
+	(md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test312.py
===================================================================
--- issm/trunk/test/NightlyRun/test312.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test312.py	(revision 18301)
@@ -18,8 +18,8 @@
 
 #Fields and tolerances to track changes
-field_names     =['Temperature','BasalforcingsMeltingRate']
+field_names     =['Temperature','BasalforcingsGroundediceMeltingRate']
 field_tolerances=[1e-13,1e-8]
 field_values=[\
 	md.results.ThermalSolution.Temperature,\
-	md.results.ThermalSolution.BasalforcingsMeltingRate,\
+	md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test313.m
===================================================================
--- issm/trunk/test/NightlyRun/test313.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test313.m	(revision 18301)
@@ -13,8 +13,8 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_names     ={'Temperature','BasalforcingsGroundediceMeltingRate'};
 field_tolerances={1e-13,1e-13};
 field_values={...
 	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test313.py
===================================================================
--- issm/trunk/test/NightlyRun/test313.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test313.py	(revision 18301)
@@ -22,8 +22,8 @@
 
 #Fields and tolerances to track changes
-field_names     =['Temperature','BasalforcingsMeltingRate']
+field_names     =['Temperature','BasalforcingsGroundediceMeltingRate']
 field_tolerances=[1e-13,1e-13]
 field_values=[\
 	md.results.TransientSolution[0].Temperature,\
-	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test315.m
===================================================================
--- issm/trunk/test/NightlyRun/test315.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test315.m	(revision 18301)
@@ -8,7 +8,7 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1',...
-	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2',...
-	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1',...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2',...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'};
 field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...,
 	1e-10,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
@@ -24,5 +24,5 @@
 	(md.results.TransientSolution(1).Thickness),...
 	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(2).Vx),...
 	(md.results.TransientSolution(2).Vy),...
@@ -34,5 +34,5 @@
 	(md.results.TransientSolution(2).Thickness),...
 	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(3).Vx),...
 	(md.results.TransientSolution(3).Vy),...
@@ -44,4 +44,4 @@
 	(md.results.TransientSolution(3).Thickness),...
 	(md.results.TransientSolution(3).Temperature),...
-	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test315.py
===================================================================
--- issm/trunk/test/NightlyRun/test315.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test315.py	(revision 18301)
@@ -17,7 +17,7 @@
 
 #Fields and tolerances to track changes
-field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1',\
-	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2',\
-	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3']
+field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1',\
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2',\
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3']
 field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,\
 	1e-10,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,\
@@ -33,5 +33,5 @@
 	md.results.TransientSolution[0].Thickness,\
 	md.results.TransientSolution[0].Temperature,\
-	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[1].Vx,\
 	md.results.TransientSolution[1].Vy,\
@@ -43,5 +43,5 @@
 	md.results.TransientSolution[1].Thickness,\
 	md.results.TransientSolution[1].Temperature,\
-	md.results.TransientSolution[1].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[2].Vx,\
 	md.results.TransientSolution[2].Vy,\
@@ -53,4 +53,4 @@
 	md.results.TransientSolution[2].Thickness,\
 	md.results.TransientSolution[2].Temperature,\
-	md.results.TransientSolution[2].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test317.m
===================================================================
--- issm/trunk/test/NightlyRun/test317.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test317.m	(revision 18301)
@@ -8,7 +8,7 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1',...
-	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2',...
-	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1',...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2',...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'};
 field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
 	1e-09,1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
@@ -24,5 +24,5 @@
 	(md.results.TransientSolution(1).Thickness),...
 	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(2).Vx),...
 	(md.results.TransientSolution(2).Vy),...
@@ -34,5 +34,5 @@
 	(md.results.TransientSolution(2).Thickness),...
 	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(3).Vx),...
 	(md.results.TransientSolution(3).Vy),...
@@ -44,4 +44,4 @@
 	(md.results.TransientSolution(3).Thickness),...
 	(md.results.TransientSolution(3).Temperature),...
-	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test317.py
===================================================================
--- issm/trunk/test/NightlyRun/test317.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test317.py	(revision 18301)
@@ -17,7 +17,7 @@
 
 #Fields and tolerances to track changes
-field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1',\
-	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2',\
-	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3']
+field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1',\
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2',\
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3']
 field_tolerances=[1e-09,1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,\
 		1e-09,1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,\
@@ -33,5 +33,5 @@
 	md.results.TransientSolution[0].Thickness,\
 	md.results.TransientSolution[0].Temperature,\
-	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[1].Vx,\
 	md.results.TransientSolution[1].Vy,\
@@ -43,5 +43,5 @@
 	md.results.TransientSolution[1].Thickness,\
 	md.results.TransientSolution[1].Temperature,\
-	md.results.TransientSolution[1].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[2].Vx,\
 	md.results.TransientSolution[2].Vy,\
@@ -53,4 +53,4 @@
 	md.results.TransientSolution[2].Thickness,\
 	md.results.TransientSolution[2].Temperature,\
-	md.results.TransientSolution[2].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test318.m
===================================================================
--- issm/trunk/test/NightlyRun/test318.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test318.m	(revision 18301)
@@ -9,5 +9,5 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsGroundediceMeltingRate'};
 field_tolerances={1e-13,1e-13,4e-10,1e-10,1e-13,1e-11,1e-6};
 field_values={...
@@ -18,4 +18,4 @@
 	(md.results.SteadystateSolution.Pressure),...
 	(md.results.SteadystateSolution.Temperature),...
-	(md.results.SteadystateSolution.BasalforcingsMeltingRate),...
+	(md.results.SteadystateSolution.BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test318.py
===================================================================
--- issm/trunk/test/NightlyRun/test318.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test318.py	(revision 18301)
@@ -18,5 +18,5 @@
 
 #Fields and tolerances to track changes
-field_names     =['Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate']
+field_names     =['Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsGroundediceMeltingRate']
 field_tolerances=[1e-13,1e-13,1.5e-10,1e-10,1e-13,1e-11,1e-6]
 field_values=[\
@@ -27,4 +27,4 @@
 	md.results.SteadystateSolution.Pressure,\
 	md.results.SteadystateSolution.Temperature,\
-	md.results.SteadystateSolution.BasalforcingsMeltingRate,\
+	md.results.SteadystateSolution.BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test322.m
===================================================================
--- issm/trunk/test/NightlyRun/test322.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test322.m	(revision 18301)
@@ -23,5 +23,5 @@
 %Fields and tolerances to track changes
 field_names     ={'Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy'};
-field_tolerances={5e-05,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,5e-08,5e-08,5e-08};
+field_tolerances={5e-05,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,5e-08,5e-08,5e-08};
 field_values={...
 	(md.results.StressbalanceSolution.Gradient1),...
Index: issm/trunk/test/NightlyRun/test322.py
===================================================================
--- issm/trunk/test/NightlyRun/test322.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test322.py	(revision 18301)
@@ -35,5 +35,5 @@
 #Fields and tolerances to track changes
 field_names     =['Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy']
-field_tolerances=[5e-05,1e-08,1e-09,1e-09,5e-08,5e-08,5e-08]
+field_tolerances=[5e-05,1e-08,1e-08,1e-09,5e-08,5e-08,5e-08]
 field_values=[\
 	md.results.StressbalanceSolution.Gradient1,\
Index: issm/trunk/test/NightlyRun/test324.m
===================================================================
--- issm/trunk/test/NightlyRun/test324.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test324.m	(revision 18301)
@@ -10,7 +10,7 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1',...
-	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2'};
-	%'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1',...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2'};
+	%'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'};
 field_tolerances={1e-13,  1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...,
 	5*1e-11,1e-13,1.5e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
@@ -26,5 +26,5 @@
 	(md.results.TransientSolution(1).Thickness),...
 	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(2).Vx),...
 	(md.results.TransientSolution(2).Vy),...
@@ -36,5 +36,5 @@
 	(md.results.TransientSolution(2).Thickness),...
 	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
 %	(md.results.TransientSolution(3).Vx),...
 %	(md.results.TransientSolution(3).Vy),...
@@ -46,4 +46,4 @@
 %	(md.results.TransientSolution(3).Thickness),...
 %	(md.results.TransientSolution(3).Temperature),...
-%	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+%	(md.results.TransientSolution(3).BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test324.py
===================================================================
--- issm/trunk/test/NightlyRun/test324.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test324.py	(revision 18301)
@@ -20,7 +20,7 @@
 
 #Fields and tolerances to track changes
-field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1',\
-	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2']
-	#'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3']
+field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1',\
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2']
+	#'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3']
 field_tolerances=[1e-13,  1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,\
 	5*1e-11,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,\
@@ -36,5 +36,5 @@
 	md.results.TransientSolution[0].Thickness,\
 	md.results.TransientSolution[0].Temperature,\
-	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[1].Vx,\
 	md.results.TransientSolution[1].Vy,\
@@ -46,5 +46,5 @@
 	md.results.TransientSolution[1].Thickness,\
 	md.results.TransientSolution[1].Temperature,\
-	md.results.TransientSolution[1].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
 #	md.results.TransientSolution[2].Vx,\
 #	md.results.TransientSolution[2].Vy,\
@@ -56,4 +56,4 @@
 #	md.results.TransientSolution[2].Thickness,\
 #	md.results.TransientSolution[2].Temperature,\
-#	md.results.TransientSolution[2].BasalforcingsMeltingRate,\
+#	md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test332.m
===================================================================
--- issm/trunk/test/NightlyRun/test332.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test332.m	(revision 18301)
@@ -15,5 +15,6 @@
 pos=find(md.mesh.y==0);
 md.hydrology.spcsediment_head(pos)=0.0;
-md.basalforcings.melting_rate = 2.0*ones(md.mesh.numberofvertices,1);
+md.basalforcings.groundedice_melting_rate = 2.0*ones(md.mesh.numberofvertices,1);
+md.basalforcings.floatingice_melting_rate = 0.0*ones(md.mesh.numberofvertices,1);
 md.hydrology.sediment_transmitivity=3*ones(md.mesh.numberofvertices,1);
 md.timestepping.time_step=0;
Index: issm/trunk/test/NightlyRun/test333.m
===================================================================
--- issm/trunk/test/NightlyRun/test333.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test333.m	(revision 18301)
@@ -13,5 +13,6 @@
 md.initialization.sediment_head=0.0*ones(md.mesh.numberofvertices,1);
 md.hydrology.spcsediment_head=NaN*ones(md.mesh.numberofvertices,1);
-md.basalforcings.melting_rate = 2.0*ones(md.mesh.numberofvertices,1);
+md.basalforcings.groundedice_melting_rate = 2.0*ones(md.mesh.numberofvertices,1);
+md.basalforcings.floatingice_melting_rate = 0.0*ones(md.mesh.numberofvertices,1);
 md.hydrology.sediment_transmitivity=3*ones(md.mesh.numberofvertices,1);
 
@@ -20,5 +21,4 @@
 md.hydrology.spcepl_head=NaN*ones(md.mesh.numberofvertices,1);
 md.hydrology.mask_eplactive_node=0*ones(md.mesh.numberofvertices,1);
-md.basalforcings.melting_rate = 2.0*ones(md.mesh.numberofvertices,1);
 md.hydrology.epl_conductivity=30;
 md.hydrology.epl_initial_thickness=1;
Index: issm/trunk/test/NightlyRun/test334.m
===================================================================
--- issm/trunk/test/NightlyRun/test334.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test334.m	(revision 18301)
@@ -15,5 +15,6 @@
 pos=find(md.mesh.y==0);
 md.hydrology.spcsediment_head(pos)=0.0;
-md.basalforcings.melting_rate = 2.0*ones(md.mesh.numberofvertices,1);
+md.basalforcings.groundedice_melting_rate = 2.0*ones(md.mesh.numberofvertices,1);
+md.basalforcings.floatingice_melting_rate = 0.0*ones(md.mesh.numberofvertices,1);
 md.hydrology.sediment_transmitivity= 3.0*ones(md.mesh.numberofvertices,1);
 md.timestepping.time_step=0;
Index: issm/trunk/test/NightlyRun/test335.m
===================================================================
--- issm/trunk/test/NightlyRun/test335.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test335.m	(revision 18301)
@@ -13,5 +13,6 @@
 md.initialization.sediment_head=0.0*ones(md.mesh.numberofvertices,1);
 md.hydrology.spcsediment_head=NaN*ones(md.mesh.numberofvertices,1);
-md.basalforcings.melting_rate = 2.0*ones(md.mesh.numberofvertices,1);
+md.basalforcings.groundedice_melting_rate = 2.0*ones(md.mesh.numberofvertices,1);
+md.basalforcings.floatingice_melting_rate = 0.0*ones(md.mesh.numberofvertices,1);
 md.hydrology.sediment_transmitivity=3*ones(md.mesh.numberofvertices,1);
 
@@ -20,5 +21,4 @@
 md.hydrology.spcepl_head=NaN*ones(md.mesh.numberofvertices,1);
 md.hydrology.mask_eplactive_node=0*ones(md.mesh.numberofvertices,1);
-md.basalforcings.melting_rate = 2.0*ones(md.mesh.numberofvertices,1);
 md.hydrology.epl_conductivity=30;
 md.hydrology.epl_initial_thickness=1;
Index: issm/trunk/test/NightlyRun/test336.m
===================================================================
--- issm/trunk/test/NightlyRun/test336.m	(revision 18301)
+++ issm/trunk/test/NightlyRun/test336.m	(revision 18301)
@@ -0,0 +1,65 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+md.timestepping.time_step=1.;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4.;
+
+%Set up transient
+smb=ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*-1. ];
+
+md.surfaceforcings=SMBcomponents();
+md.surfaceforcings.accumulation=[smb*2; [1.5 3.]];
+md.surfaceforcings.runoff=[smb/2; [1.5 3.]];
+md.surfaceforcings.evaporation=[smb/2; [1.5 3.]];
+md.transient.isthermal=0;
+
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
+	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
+	'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', ...
+	'Vx4','Vy4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassBalance4'};
+field_tolerances={1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Base),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
+	};
Index: issm/trunk/test/NightlyRun/test336.py
===================================================================
--- issm/trunk/test/NightlyRun/test336.py	(revision 18301)
+++ issm/trunk/test/NightlyRun/test336.py	(revision 18301)
@@ -0,0 +1,75 @@
+import numpy
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+
+md.timestepping.time_step=1.
+md.settings.output_frequency=1
+md.timestepping.final_time=4.
+
+#Set up transient
+smb=numpy.ones((md.mesh.numberofvertices,1))*3.6
+smb=numpy.hstack((smb,smb*-1.))
+
+md.surfaceforcings=SMBcomponents();
+md.surfaceforcings.accumulation=numpy.vstack((smb*2, [1.5,3.]));
+md.surfaceforcings.runoff=numpy.vstack((smb/2, [1.5,3.]));
+md.surfaceforcings.evaporation=numpy.vstack((smb/2, [1.5,3.]));
+md.transient.isthermal=False
+
+md=solve(md,TransientSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names=['Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', \
+	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', \
+	'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', \
+	'Vx4','Vy4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassBalance4']
+field_tolerances=[1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,\
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,\
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,\
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10]
+field_values=[\
+	md.results.TransientSolution[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Base,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].SurfaceforcingsMassBalance,\
+	md.results.TransientSolution[1].Vx,\
+	md.results.TransientSolution[1].Vy,\
+	md.results.TransientSolution[1].Vel,\
+	md.results.TransientSolution[1].Pressure,\
+	md.results.TransientSolution[1].Base,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].SurfaceforcingsMassBalance,\
+	md.results.TransientSolution[2].Vx,\
+	md.results.TransientSolution[2].Vy,\
+	md.results.TransientSolution[2].Vel,\
+	md.results.TransientSolution[2].Pressure,\
+	md.results.TransientSolution[2].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].SurfaceforcingsMassBalance,\
+	md.results.TransientSolution[3].Vx,\
+	md.results.TransientSolution[3].Vy,\
+	md.results.TransientSolution[3].Vel,\
+	md.results.TransientSolution[3].Pressure,\
+	md.results.TransientSolution[3].Base,\
+	md.results.TransientSolution[3].Surface,\
+	md.results.TransientSolution[3].Thickness,\
+	md.results.TransientSolution[3].SurfaceforcingsMassBalance,\
+	]
Index: issm/trunk/test/NightlyRun/test337.m
===================================================================
--- issm/trunk/test/NightlyRun/test337.m	(revision 18301)
+++ issm/trunk/test/NightlyRun/test337.m	(revision 18301)
@@ -0,0 +1,67 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+md.timestepping.time_step=1.;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4.;
+
+%Set up transient
+smb=ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*-1. ];
+
+md.surfaceforcings=SMBcomponents();
+md.surfaceforcings.accumulation=[smb*2; [1.5 3.]];
+md.surfaceforcings.runoff=[smb/2; [1.5 3.]];
+md.surfaceforcings.evaporation=[smb/2; [1.5 3.]];
+md.transient.isthermal=0;
+
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
+	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
+	'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', ...
+	'Vx4','Vy4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassBalance4'};
+field_tolerances={...
+	5e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	5e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	5e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	5e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Base),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
+	};
Index: issm/trunk/test/NightlyRun/test337.py
===================================================================
--- issm/trunk/test/NightlyRun/test337.py	(revision 18301)
+++ issm/trunk/test/NightlyRun/test337.py	(revision 18301)
@@ -0,0 +1,77 @@
+import numpy
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(3,1.)
+md=setflowequation(md,'HO','all')
+md.cluster=generic('name',oshostname(),'np',3)
+
+md.timestepping.time_step=1.
+md.settings.output_frequency=1
+md.timestepping.final_time=4.
+
+#Set up transient
+smb=numpy.ones((md.mesh.numberofvertices,1))*3.6
+smb=numpy.hstack((smb,smb*-1.))
+
+md.surfaceforcings=SMBcomponents();
+md.surfaceforcings.accumulation=numpy.vstack((smb*2, [1.5,3.]));
+md.surfaceforcings.runoff=numpy.vstack((smb/2, [1.5,3.]));
+md.surfaceforcings.evaporation=numpy.vstack((smb/2, [1.5,3.]));
+md.transient.isthermal=False
+
+md=solve(md,TransientSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names=['Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', \
+	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', \
+	'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', \
+	'Vx4','Vy4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassBalance4']
+field_tolerances=[\
+		5e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,\
+		5e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,\
+		5e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,\
+		5e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10]
+field_values=[\
+	md.results.TransientSolution[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Base,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].SurfaceforcingsMassBalance,\
+	md.results.TransientSolution[1].Vx,\
+	md.results.TransientSolution[1].Vy,\
+	md.results.TransientSolution[1].Vel,\
+	md.results.TransientSolution[1].Pressure,\
+	md.results.TransientSolution[1].Base,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].SurfaceforcingsMassBalance,\
+	md.results.TransientSolution[2].Vx,\
+	md.results.TransientSolution[2].Vy,\
+	md.results.TransientSolution[2].Vel,\
+	md.results.TransientSolution[2].Pressure,\
+	md.results.TransientSolution[2].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].SurfaceforcingsMassBalance,\
+	md.results.TransientSolution[3].Vx,\
+	md.results.TransientSolution[3].Vy,\
+	md.results.TransientSolution[3].Vel,\
+	md.results.TransientSolution[3].Pressure,\
+	md.results.TransientSolution[3].Base,\
+	md.results.TransientSolution[3].Surface,\
+	md.results.TransientSolution[3].Thickness,\
+	md.results.TransientSolution[3].SurfaceforcingsMassBalance,\
+	]
Index: issm/trunk/test/NightlyRun/test338.m
===================================================================
--- issm/trunk/test/NightlyRun/test338.m	(revision 18301)
+++ issm/trunk/test/NightlyRun/test338.m	(revision 18301)
@@ -0,0 +1,66 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+md.timestepping.time_step=1.;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4.;
+
+%Set up transient
+smb=ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*-1. ];
+
+md.surfaceforcings=SMBmeltcomponents();
+md.surfaceforcings.accumulation=[smb; [1.5 3.]];
+md.surfaceforcings.melt=[smb/2; [1.5 3.]];
+md.surfaceforcings.refreeze=[smb; [1.5 3.]];
+md.surfaceforcings.evaporation=[smb/2; [1.5 3.]];
+md.transient.isthermal=0;
+
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
+	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
+	'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', ...
+	'Vx4','Vy4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassBalance4'};
+field_tolerances={1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Base),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
+	};
Index: issm/trunk/test/NightlyRun/test338.py
===================================================================
--- issm/trunk/test/NightlyRun/test338.py	(revision 18301)
+++ issm/trunk/test/NightlyRun/test338.py	(revision 18301)
@@ -0,0 +1,76 @@
+import numpy
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+
+md.timestepping.time_step=1.
+md.settings.output_frequency=1
+md.timestepping.final_time=4.
+
+#Set up transient
+smb=numpy.ones((md.mesh.numberofvertices,1))*3.6
+smb=numpy.hstack((smb,smb*-1.))
+
+md.surfaceforcings=SMBmeltcomponents();
+md.surfaceforcings.accumulation=numpy.vstack((smb, [1.5,3.]));
+md.surfaceforcings.evaporation=numpy.vstack((smb/2, [1.5,3.]));
+md.surfaceforcings.melt=numpy.vstack((smb/2, [1.5,3.]));
+md.surfaceforcings.refreeze=numpy.vstack((smb, [1.5,3.]));
+md.transient.isthermal=False
+
+md=solve(md,TransientSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names=['Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', \
+	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', \
+	'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', \
+	'Vx4','Vy4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassBalance4']
+field_tolerances=[1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,\
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,\
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,\
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10]
+field_values=[\
+	md.results.TransientSolution[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Base,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].SurfaceforcingsMassBalance,\
+	md.results.TransientSolution[1].Vx,\
+	md.results.TransientSolution[1].Vy,\
+	md.results.TransientSolution[1].Vel,\
+	md.results.TransientSolution[1].Pressure,\
+	md.results.TransientSolution[1].Base,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].SurfaceforcingsMassBalance,\
+	md.results.TransientSolution[2].Vx,\
+	md.results.TransientSolution[2].Vy,\
+	md.results.TransientSolution[2].Vel,\
+	md.results.TransientSolution[2].Pressure,\
+	md.results.TransientSolution[2].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].SurfaceforcingsMassBalance,\
+	md.results.TransientSolution[3].Vx,\
+	md.results.TransientSolution[3].Vy,\
+	md.results.TransientSolution[3].Vel,\
+	md.results.TransientSolution[3].Pressure,\
+	md.results.TransientSolution[3].Base,\
+	md.results.TransientSolution[3].Surface,\
+	md.results.TransientSolution[3].Thickness,\
+	md.results.TransientSolution[3].SurfaceforcingsMassBalance,\
+	]
Index: issm/trunk/test/NightlyRun/test339.m
===================================================================
--- issm/trunk/test/NightlyRun/test339.m	(revision 18301)
+++ issm/trunk/test/NightlyRun/test339.m	(revision 18301)
@@ -0,0 +1,68 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+md.timestepping.time_step=1.;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4.;
+
+%Set up transient
+smb=ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*-1. ];
+
+md.surfaceforcings=SMBmeltcomponents();
+md.surfaceforcings.accumulation=[smb; [1.5 3.]];
+md.surfaceforcings.melt=[smb/2; [1.5 3.]];
+md.surfaceforcings.refreeze=[smb; [1.5 3.]];
+md.surfaceforcings.evaporation=[smb/2; [1.5 3.]];
+md.transient.isthermal=0;
+
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
+	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
+	'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', ...
+	'Vx4','Vy4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassBalance4'};
+field_tolerances={...
+	1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Base),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
+	};
Index: issm/trunk/test/NightlyRun/test339.py
===================================================================
--- issm/trunk/test/NightlyRun/test339.py	(revision 18301)
+++ issm/trunk/test/NightlyRun/test339.py	(revision 18301)
@@ -0,0 +1,78 @@
+import numpy
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(3,1.)
+md=setflowequation(md,'HO','all')
+md.cluster=generic('name',oshostname(),'np',3)
+
+md.timestepping.time_step=1.
+md.settings.output_frequency=1
+md.timestepping.final_time=4.
+
+#Set up transient
+smb=numpy.ones((md.mesh.numberofvertices,1))*3.6
+smb=numpy.hstack((smb,smb*-1.))
+
+md.surfaceforcings=SMBmeltcomponents();
+md.surfaceforcings.accumulation=numpy.vstack((smb, [1.5,3.]));
+md.surfaceforcings.evaporation=numpy.vstack((smb/2, [1.5,3.]));
+md.surfaceforcings.melt=numpy.vstack((smb/2, [1.5,3.]));
+md.surfaceforcings.refreeze=numpy.vstack((smb, [1.5,3.]));
+md.transient.isthermal=False
+
+md=solve(md,TransientSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names=['Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', \
+	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', \
+	'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', \
+	'Vx4','Vy4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassBalance4']
+field_tolerances=[\
+		1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,\
+		1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,\
+		1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,\
+		1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10]
+field_values=[\
+	md.results.TransientSolution[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Base,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].SurfaceforcingsMassBalance,\
+	md.results.TransientSolution[1].Vx,\
+	md.results.TransientSolution[1].Vy,\
+	md.results.TransientSolution[1].Vel,\
+	md.results.TransientSolution[1].Pressure,\
+	md.results.TransientSolution[1].Base,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].SurfaceforcingsMassBalance,\
+	md.results.TransientSolution[2].Vx,\
+	md.results.TransientSolution[2].Vy,\
+	md.results.TransientSolution[2].Vel,\
+	md.results.TransientSolution[2].Pressure,\
+	md.results.TransientSolution[2].Base,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].SurfaceforcingsMassBalance,\
+	md.results.TransientSolution[3].Vx,\
+	md.results.TransientSolution[3].Vy,\
+	md.results.TransientSolution[3].Vel,\
+	md.results.TransientSolution[3].Pressure,\
+	md.results.TransientSolution[3].Base,\
+	md.results.TransientSolution[3].Surface,\
+	md.results.TransientSolution[3].Thickness,\
+	md.results.TransientSolution[3].SurfaceforcingsMassBalance,\
+	]
Index: issm/trunk/test/NightlyRun/test406.m
===================================================================
--- issm/trunk/test/NightlyRun/test406.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test406.m	(revision 18301)
@@ -9,8 +9,8 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_names     ={'Temperature','BasalforcingsGroundediceMeltingRate'};
 field_tolerances={1e-13,1e-5};
 field_values={...
 	(md.results.ThermalSolution.Temperature),...
-	(md.results.ThermalSolution.BasalforcingsMeltingRate),...
+	(md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test406.py
===================================================================
--- issm/trunk/test/NightlyRun/test406.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test406.py	(revision 18301)
@@ -19,8 +19,8 @@
 
 #Fields and tolerances to track changes
-field_names     =['Temperature','BasalforcingsMeltingRate']
+field_names     =['Temperature','BasalforcingsGroundediceMeltingRate']
 field_tolerances=[1e-13,1e-5]
 field_values=[\
 	md.results.ThermalSolution.Temperature,\
-	md.results.ThermalSolution.BasalforcingsMeltingRate,\
+	md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test407.m
===================================================================
--- issm/trunk/test/NightlyRun/test407.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test407.m	(revision 18301)
@@ -12,8 +12,8 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_names     ={'Temperature','BasalforcingsGroundediceMeltingRate'};
 field_tolerances={1e-13,1e-13};
 field_values={...
 	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test407.py
===================================================================
--- issm/trunk/test/NightlyRun/test407.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test407.py	(revision 18301)
@@ -22,8 +22,8 @@
 
 #Fields and tolerances to track changes
-field_names     =['Temperature','BasalforcingsMeltingRate']
+field_names     =['Temperature','BasalforcingsGroundediceMeltingRate']
 field_tolerances=[1e-13,1e-13]
 field_values=[\
 	md.results.TransientSolution[0].Temperature,\
-	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test409.m
===================================================================
--- issm/trunk/test/NightlyRun/test409.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test409.m	(revision 18301)
@@ -8,7 +8,7 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
-				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
-					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', ...
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'};
 field_tolerances={...
 	1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,...
@@ -25,5 +25,5 @@
 	(md.results.TransientSolution(1).Thickness),...
 	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(2).Vx),...
 	(md.results.TransientSolution(2).Vy),...
@@ -35,5 +35,5 @@
 	(md.results.TransientSolution(2).Thickness),...
 	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(3).Vx),...
 	(md.results.TransientSolution(3).Vy),...
@@ -45,4 +45,4 @@
 	(md.results.TransientSolution(3).Thickness),...
 	(md.results.TransientSolution(3).Temperature),...
-	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test409.py
===================================================================
--- issm/trunk/test/NightlyRun/test409.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test409.py	(revision 18301)
@@ -18,7 +18,7 @@
 
 #Fields and tolerances to track changes
-field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', \
-				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', \
-					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3']
+field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', \
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', \
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3']
 field_tolerances=[\
 	1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,\
@@ -35,5 +35,5 @@
 	md.results.TransientSolution[0].Thickness,\
 	md.results.TransientSolution[0].Temperature,\
-	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[1].Vx,\
 	md.results.TransientSolution[1].Vy,\
@@ -45,5 +45,5 @@
 	md.results.TransientSolution[1].Thickness,\
 	md.results.TransientSolution[1].Temperature,\
-	md.results.TransientSolution[1].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[2].Vx,\
 	md.results.TransientSolution[2].Vy,\
@@ -55,4 +55,4 @@
 	md.results.TransientSolution[2].Thickness,\
 	md.results.TransientSolution[2].Temperature,\
-	md.results.TransientSolution[2].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[2].BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test410.m
===================================================================
--- issm/trunk/test/NightlyRun/test410.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test410.m	(revision 18301)
@@ -9,5 +9,5 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsGroundediceMeltingRate'};
 field_tolerances={1e-09,1e-09,1e-08,3e-10,1e-13,3e-10,1e-06};
 field_values={...
@@ -18,4 +18,4 @@
 	(md.results.SteadystateSolution.Pressure),...
 	(md.results.SteadystateSolution.Temperature),...
-	(md.results.SteadystateSolution.BasalforcingsMeltingRate),...
+	(md.results.SteadystateSolution.BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test410.py
===================================================================
--- issm/trunk/test/NightlyRun/test410.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test410.py	(revision 18301)
@@ -19,5 +19,5 @@
 
 #Fields and tolerances to track changes
-field_names     =['Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate']
+field_names     =['Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsGroundediceMeltingRate']
 field_tolerances=[1e-09,1e-09,1e-08,1e-09,1e-13,3e-10,1e-06]
 field_values=[\
@@ -28,4 +28,4 @@
 	md.results.SteadystateSolution.Pressure,\
 	md.results.SteadystateSolution.Temperature,\
-	md.results.SteadystateSolution.BasalforcingsMeltingRate,\
+	md.results.SteadystateSolution.BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test411.m
===================================================================
--- issm/trunk/test/NightlyRun/test411.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test411.m	(revision 18301)
@@ -9,5 +9,5 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsGroundediceMeltingRate'};
 field_tolerances={2e-09,1e-09,1e-08,1e-09,1e-09,1e-08,1e-05
 };
@@ -19,4 +19,4 @@
 	(md.results.SteadystateSolution.Pressure),...
 	(md.results.SteadystateSolution.Temperature),...
-	(md.results.SteadystateSolution.BasalforcingsMeltingRate),...
+	(md.results.SteadystateSolution.BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test411.py
===================================================================
--- issm/trunk/test/NightlyRun/test411.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test411.py	(revision 18301)
@@ -19,5 +19,5 @@
 
 #Fields and tolerances to track changes
-field_names     =['Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate']
+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
 ]
@@ -29,4 +29,4 @@
 	md.results.SteadystateSolution.Pressure,\
 	md.results.SteadystateSolution.Temperature,\
-	md.results.SteadystateSolution.BasalforcingsMeltingRate,\
+	md.results.SteadystateSolution.BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test415.m
===================================================================
--- issm/trunk/test/NightlyRun/test415.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test415.m	(revision 18301)
@@ -23,6 +23,6 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy','Vz','Temperature','BasalforcingsMeltingRate'};
-field_tolerances={9e-10,1e-9,1e-10,1e-13,1e-09,1e-09,1e-09,1e-8,1e-09,1e-6};
+field_names     ={'Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy','Vz','Temperature','BasalforcingsGroundediceMeltingRate'};
+field_tolerances={1e-09,1e-9,2e-10,1e-13,1e-09,1e-09,1e-09,1e-8,1e-09,1e-6};
 field_values={...
 	(md.results.SteadystateSolution.Gradient1),...
@@ -35,4 +35,4 @@
 	(md.results.SteadystateSolution.Vz),...
 	(md.results.SteadystateSolution.Temperature),...
-	(md.results.SteadystateSolution.BasalforcingsMeltingRate)
+	(md.results.SteadystateSolution.BasalforcingsGroundediceMeltingRate)
 };
Index: issm/trunk/test/NightlyRun/test415.py
===================================================================
--- issm/trunk/test/NightlyRun/test415.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test415.py	(revision 18301)
@@ -35,6 +35,6 @@
 
 #Fields and tolerances to track changes
-field_names     =['Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy','Vz','Temperature','BasalforcingsMeltingRate']
-field_tolerances=[5e-10,1e-9,1e-10,1e-13,1e-09,1e-09,1e-09,1e-8,1e-09,1e-6]
+field_names     =['Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy','Vz','Temperature','BasalforcingsGroundediceMeltingRate']
+field_tolerances=[1e-9,1e-9,2e-10,1e-13,1e-09,1e-09,1e-09,1e-8,1e-09,1e-6]
 field_values=[\
 	md.results.SteadystateSolution.Gradient1,\
@@ -47,4 +47,4 @@
 	md.results.SteadystateSolution.Vz,\
 	md.results.SteadystateSolution.Temperature,\
-	md.results.SteadystateSolution.BasalforcingsMeltingRate
+	md.results.SteadystateSolution.BasalforcingsGroundediceMeltingRate
 ]
Index: issm/trunk/test/NightlyRun/test416.m
===================================================================
--- issm/trunk/test/NightlyRun/test416.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test416.m	(revision 18301)
@@ -23,5 +23,5 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy','Vz','Temperature','BasalforcingsMeltingRate'};
+field_names     ={'Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy','Vz','Temperature','BasalforcingsGroundediceMeltingRate'};
 field_tolerances={1e-08,1e-07,1e-08,1e-08,1e-08,1e-08,1e-08,1e-07,1e-08,1e-05};
 field_values={...
@@ -35,4 +35,4 @@
 	(md.results.SteadystateSolution.Vz),...
 	(md.results.SteadystateSolution.Temperature),...
-	(md.results.SteadystateSolution.BasalforcingsMeltingRate)
+	(md.results.SteadystateSolution.BasalforcingsGroundediceMeltingRate)
 };
Index: issm/trunk/test/NightlyRun/test416.py
===================================================================
--- issm/trunk/test/NightlyRun/test416.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test416.py	(revision 18301)
@@ -35,5 +35,5 @@
 
 #Fields and tolerances to track changes
-field_names     =['Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy','Vz','Temperature','BasalforcingsMeltingRate']
+field_names     =['Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy','Vz','Temperature','BasalforcingsGroundediceMeltingRate']
 field_tolerances=[1e-08,1e-07,1e-08,1e-08,1e-08,1e-08,1e-08,1e-07,1e-08,1e-05]
 field_values=[\
@@ -47,4 +47,4 @@
 	md.results.SteadystateSolution.Vz,\
 	md.results.SteadystateSolution.Temperature,\
-	md.results.SteadystateSolution.BasalforcingsMeltingRate
+	md.results.SteadystateSolution.BasalforcingsGroundediceMeltingRate
 ]
Index: issm/trunk/test/NightlyRun/test417.m
===================================================================
--- issm/trunk/test/NightlyRun/test417.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test417.m	(revision 18301)
@@ -38,7 +38,9 @@
 
 %%  a variety of parameters
-md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.direct=true;
 md.qmu.params.analysis_driver='';
 md.qmu.params.analysis_components='';
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.tabular_graphics_data=true;
 
 %partitioning
Index: issm/trunk/test/NightlyRun/test435.m
===================================================================
--- issm/trunk/test/NightlyRun/test435.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test435.m	(revision 18301)
@@ -31,5 +31,6 @@
 md.friction.p=3*ones(md.mesh.numberofelements,1);
 md.surfaceforcings.mass_balance(:)=1;
-md.basalforcings.melting_rate(:)=0;
+md.basalforcings.groundedice_melting_rate(:)=0;
+md.basalforcings.floatingice_melting_rate(:)=0;
 md.transient.isthermal=0;
 md.transient.isstressbalance=1;
@@ -47,5 +48,5 @@
 	'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,4e-10,1e-08,6e-10,1e-13,...
+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};
Index: issm/trunk/test/NightlyRun/test505.m
===================================================================
--- issm/trunk/test/NightlyRun/test505.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test505.m	(revision 18301)
@@ -8,6 +8,6 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
-				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2'};
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2'};
 field_tolerances={1e-12,1e-12,3e-10,1e-12,1e-13,1e-11,5e-12,9e-12,1e-13,5e-9,...
 						5e-11,5e-11,1e-10,2e-11,7e-12,1e-11,1e-11,5e-12,1e-11,2e-8};
@@ -22,5 +22,5 @@
 	(md.results.TransientSolution(1).Thickness),...
 	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(2).Vx),...
 	(md.results.TransientSolution(2).Vy),...
@@ -32,4 +32,4 @@
 	(md.results.TransientSolution(2).Thickness),...
 	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test505.py
===================================================================
--- issm/trunk/test/NightlyRun/test505.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test505.py	(revision 18301)
@@ -17,6 +17,6 @@
 
 # Fields and tolerances to track changes
-field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', \
-				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2']
+field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', \
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2']
 field_tolerances=[1e-12,1e-12,1e-10,1e-12,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13, \
 						1e-13,1e-12,1e-10,1e-12,1e-13,1e-11,1e-11,2e-12,1e-11,1e-8]
@@ -31,5 +31,5 @@
 	md.results.TransientSolution[0].Thickness,\
 	md.results.TransientSolution[0].Temperature,\
-	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[1].Vx,\
 	md.results.TransientSolution[1].Vy,\
@@ -41,4 +41,4 @@
 	md.results.TransientSolution[1].Thickness,\
 	md.results.TransientSolution[1].Temperature,\
-	md.results.TransientSolution[1].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test506.m
===================================================================
--- issm/trunk/test/NightlyRun/test506.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test506.m	(revision 18301)
@@ -8,6 +8,6 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
-				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2'};
+field_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};
@@ -22,5 +22,5 @@
 	(md.results.TransientSolution(1).Thickness),...
 	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(2).Vx),...
 	(md.results.TransientSolution(2).Vy),...
@@ -32,4 +32,4 @@
 	(md.results.TransientSolution(2).Thickness),...
 	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test506.py
===================================================================
--- issm/trunk/test/NightlyRun/test506.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test506.py	(revision 18301)
@@ -17,6 +17,6 @@
 
 # Fields and tolerances to track changes
-field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', \
-				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2']
+field_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]
@@ -31,5 +31,5 @@
 	md.results.TransientSolution[0].Thickness,\
 	md.results.TransientSolution[0].Temperature,\
-	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[1].Vx,\
 	md.results.TransientSolution[1].Vy,\
@@ -41,4 +41,4 @@
 	md.results.TransientSolution[1].Thickness,\
 	md.results.TransientSolution[1].Temperature,\
-	md.results.TransientSolution[1].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test507.m
===================================================================
--- issm/trunk/test/NightlyRun/test507.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test507.m	(revision 18301)
@@ -8,6 +8,6 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
-				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2'};
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2'};
 field_tolerances={1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-06,1e-06,1e-06,1e-06,1e-06,1e-06,1e-06,1e-06,3e-06,1e-06};
 field_values={...
@@ -21,5 +21,5 @@
 	(md.results.TransientSolution(1).Thickness),...
 	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(2).Vx),...
 	(md.results.TransientSolution(2).Vy),...
@@ -31,4 +31,4 @@
 	(md.results.TransientSolution(2).Thickness),...
 	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test507.py
===================================================================
--- issm/trunk/test/NightlyRun/test507.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test507.py	(revision 18301)
@@ -17,6 +17,6 @@
 
 # Fields and tolerances to track changes
-field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', \
-				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2']
+field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', \
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2']
 field_tolerances=[1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-06,1e-06,1e-06,1e-06,1e-06,1e-06,1e-06,1e-06,1e-06,1e-06]
 field_values=[\
@@ -30,5 +30,5 @@
 	md.results.TransientSolution[0].Thickness,\
 	md.results.TransientSolution[0].Temperature,\
-	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[1].Vx,\
 	md.results.TransientSolution[1].Vy,\
@@ -40,4 +40,4 @@
 	md.results.TransientSolution[1].Thickness,\
 	md.results.TransientSolution[1].Temperature,\
-	md.results.TransientSolution[1].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test508.m
===================================================================
--- issm/trunk/test/NightlyRun/test508.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test508.m	(revision 18301)
@@ -1,6 +1,6 @@
-md=triangle(model(),'../Exp/Pig.exp',30000.);
+md=triangle(model(),'../Exp/Pig.exp',35000.);
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
 md=parameterize(md,'../Par/Pig.par');
-md=extrude(md,4,1.1);
+md=extrude(md,3,1.1);
 md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
@@ -9,5 +9,5 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsGroundediceMeltingRate'};
 field_tolerances={5e-08,3e-08,5e-08,3e-08,1e-09,2e-07,8e-07};
 field_values={...
@@ -18,4 +18,4 @@
 	(md.results.SteadystateSolution.Pressure),...
 	(md.results.SteadystateSolution.Temperature),...
-	(md.results.SteadystateSolution.BasalforcingsMeltingRate),...
+	(md.results.SteadystateSolution.BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test508.py
===================================================================
--- issm/trunk/test/NightlyRun/test508.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test508.py	(revision 18301)
@@ -8,8 +8,8 @@
 from MatlabFuncs import *
 
-md=triangle(model(),'../Exp/Pig.exp',30000.)
+md=triangle(model(),'../Exp/Pig.exp',35000.)
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp')
 md=parameterize(md,'../Par/Pig.py')
-md.extrude(4,1.1)
+md.extrude(3,1.1)
 md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
@@ -18,5 +18,5 @@
 
 # Fields and tolerances to track changes
-field_names     =['Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate']
+field_names     =['Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsGroundediceMeltingRate']
 field_tolerances=[5e-08,1.6e-08,5e-08,1.6e-08,1e-09,6e-08,5e-07]
 field_values=[\
@@ -27,4 +27,4 @@
 	md.results.SteadystateSolution.Pressure,\
 	md.results.SteadystateSolution.Temperature,\
-	md.results.SteadystateSolution.BasalforcingsMeltingRate,\
+	md.results.SteadystateSolution.BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test509.m
===================================================================
--- issm/trunk/test/NightlyRun/test509.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test509.m	(revision 18301)
@@ -10,5 +10,5 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsGroundediceMeltingRate'};
 field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06
 };
@@ -20,4 +20,4 @@
 	(md.results.SteadystateSolution.Pressure),...
 	(md.results.SteadystateSolution.Temperature),...
-	(md.results.SteadystateSolution.BasalforcingsMeltingRate),...
+	(md.results.SteadystateSolution.BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test509.py
===================================================================
--- issm/trunk/test/NightlyRun/test509.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test509.py	(revision 18301)
@@ -19,5 +19,5 @@
 
 # Fields and tolerances to track changes
-field_names     =['Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate']
+field_names     =['Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsGroundediceMeltingRate']
 field_tolerances=[1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06]
 field_values=[\
@@ -28,4 +28,4 @@
 	md.results.SteadystateSolution.Pressure,\
 	md.results.SteadystateSolution.Temperature,\
-	md.results.SteadystateSolution.BasalforcingsMeltingRate,\
+	md.results.SteadystateSolution.BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test510.m
===================================================================
--- issm/trunk/test/NightlyRun/test510.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test510.m	(revision 18301)
@@ -9,5 +9,5 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsGroundediceMeltingRate'};
 field_tolerances={1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-06};
 field_values={...
@@ -18,4 +18,4 @@
 	(md.results.SteadystateSolution.Pressure),...
 	(md.results.SteadystateSolution.Temperature),...
-	(md.results.SteadystateSolution.BasalforcingsMeltingRate),...
+	(md.results.SteadystateSolution.BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test510.py
===================================================================
--- issm/trunk/test/NightlyRun/test510.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test510.py	(revision 18301)
@@ -18,5 +18,5 @@
 
 # Fields and tolerances to track changes
-field_names     =['Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate']
+field_names     =['Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsGroundediceMeltingRate']
 field_tolerances=[1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-06]
 field_values=[\
@@ -27,4 +27,4 @@
 	md.results.SteadystateSolution.Pressure,\
 	md.results.SteadystateSolution.Temperature,\
-	md.results.SteadystateSolution.BasalforcingsMeltingRate,\
+	md.results.SteadystateSolution.BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test513.m
===================================================================
--- issm/trunk/test/NightlyRun/test513.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test513.m	(revision 18301)
@@ -24,6 +24,6 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy','Vz','Temperature','BasalforcingsMeltingRate'};
-field_tolerances={2e-10,2e-10,1e-10,1e-10,3e-6,3e-6,3e-6,3e-6,2e-6,2e-06};
+field_names     ={'Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy','Vz','Temperature','BasalforcingsGroundediceMeltingRate'};
+field_tolerances={1e-09,2e-10,1e-10,1e-10,3e-6,3e-6,3e-6,3e-6,2e-6,2e-06};
 field_values={...
 	(md.results.SteadystateSolution.Gradient1),...
@@ -36,4 +36,4 @@
 	(md.results.SteadystateSolution.Vz),...
 	(md.results.SteadystateSolution.Temperature),...
-	(md.results.SteadystateSolution.BasalforcingsMeltingRate)
+	(md.results.SteadystateSolution.BasalforcingsGroundediceMeltingRate)
 };
Index: issm/trunk/test/NightlyRun/test513.py
===================================================================
--- issm/trunk/test/NightlyRun/test513.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test513.py	(revision 18301)
@@ -35,6 +35,6 @@
 
 # Fields and tolerances to track changes
-field_names     =['Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy','Vz','Temperature','BasalforcingsMeltingRate']
-field_tolerances=[2e-10,2e-10,1e-10,1e-10,3e-6,3e-6,3e-6,3e-6,2e-6,2e-06]
+field_names     =['Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy','Vz','Temperature','BasalforcingsGroundediceMeltingRate']
+field_tolerances=[1e-09,2e-10,1e-10,1e-10,3e-6,3e-6,3e-6,3e-6,2e-6,2e-06]
 field_values=[\
 	md.results.SteadystateSolution.Gradient1,\
@@ -47,4 +47,4 @@
 	md.results.SteadystateSolution.Vz,\
 	md.results.SteadystateSolution.Temperature,\
-	md.results.SteadystateSolution.BasalforcingsMeltingRate
+	md.results.SteadystateSolution.BasalforcingsGroundediceMeltingRate
 ]
Index: issm/trunk/test/NightlyRun/test515.m
===================================================================
--- issm/trunk/test/NightlyRun/test515.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test515.m	(revision 18301)
@@ -13,11 +13,11 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Temperature1','BasalforcingsMeltingRate1', ...
-				      'Temperature2','BasalforcingsMeltingRate2'};
+field_names     ={'Temperature1','BasalforcingsGroundediceMeltingRate1', ...
+				      'Temperature2','BasalforcingsGroundediceMeltingRate2'};
 field_tolerances={1e-13,1e-8,1e-13,3e-8};
 field_values={...
 	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(1).BasalforcingsGroundediceMeltingRate),...
 	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test515.py
===================================================================
--- issm/trunk/test/NightlyRun/test515.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test515.py	(revision 18301)
@@ -22,11 +22,11 @@
 
 # Fields and tolerances to track changes
-field_names     =['Temperature1','BasalforcingsMeltingRate1', \
-				      'Temperature2','BasalforcingsMeltingRate2']
+field_names     =['Temperature1','BasalforcingsGroundediceMeltingRate1', \
+				      'Temperature2','BasalforcingsGroundediceMeltingRate2']
 field_tolerances=[1e-13,1e-8,1e-13,2e-8]
 field_values=[\
 	md.results.TransientSolution[0].Temperature,\
-	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[0].BasalforcingsGroundediceMeltingRate,\
 	md.results.TransientSolution[1].Temperature,\
-	md.results.TransientSolution[1].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[1].BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test516.m
===================================================================
--- issm/trunk/test/NightlyRun/test516.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test516.m	(revision 18301)
@@ -11,8 +11,8 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_names     ={'Temperature','BasalforcingsGroundediceMeltingRate'};
 field_tolerances={1e-11,1e-11};
 field_values={...
 	(md.results.ThermalSolution.Temperature),...
-	(md.results.ThermalSolution.BasalforcingsMeltingRate),...
+	(md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate),...
 	};
Index: issm/trunk/test/NightlyRun/test516.py
===================================================================
--- issm/trunk/test/NightlyRun/test516.py	(revision 18081)
+++ issm/trunk/test/NightlyRun/test516.py	(revision 18301)
@@ -21,8 +21,8 @@
 
 #Fields and tolerances to track changes
-field_names     =['Temperature','BasalforcingsMeltingRate']
+field_names     =['Temperature','BasalforcingsGroundediceMeltingRate']
 field_tolerances=[1e-11,1e-11]
 field_values=[\
 	md.results.ThermalSolution.Temperature,\
-	md.results.ThermalSolution.BasalforcingsMeltingRate,\
+	md.results.ThermalSolution.BasalforcingsGroundediceMeltingRate,\
 	]
Index: issm/trunk/test/NightlyRun/test701.m
===================================================================
--- issm/trunk/test/NightlyRun/test701.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test701.m	(revision 18301)
@@ -34,23 +34,30 @@
 md.stressbalance.spcvx(find(vertexflags(md.mesh,4)))=0;
 md.stressbalance.spcvy(find(vertexflags(md.mesh,4)))=0;
-%md.stressbalance.spcvx(find(vertexflags(md.mesh,4) | vertexflags(md.mesh,2)))=0;
-%md.stressbalance.spcvy(find(vertexflags(md.mesh,4) | vertexflags(md.mesh,2)))=0;
 
 %Misc
 md=setflowequation(md,'FS','all');
-md.flowequation.fe_FS='TaylorHood';
 md.stressbalance.abstol=NaN;
+md.stressbalance.FSreconditioning=1;
+md.stressbalance.maxiter=20;
+md.flowequation.augmented_lagrangian_r=10000;
 md.miscellaneous.name = 'flowline';
+md.cluster=generic('np',2);
 
 %Go solve
-md.cluster=generic('np',2);
-md=solve(md,StressbalanceSolutionEnum());
-
-%Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vel','Pressure'};
-field_tolerances={5e-10,2e-9,2e-9,1e-10};
-field_values={...
-	(md.results.StressbalanceSolution.Vx),...
-	(md.results.StressbalanceSolution.Vy),...
-	(md.results.StressbalanceSolution.Vel),...
-	(md.results.StressbalanceSolution.Pressure)};
+field_names={};
+field_tolerances={};
+field_values={};
+for i={'MINI','MINIcondensed','TaylorHood','XTaylorHood','LATaylorHood','CrouzeixRaviart'}
+	disp(' ');
+	disp(['====== Testing ' i{1} ' Full-Stokes Finite element =====']);
+	md.flowequation.fe_FS=i{1};
+	md=solve(md,StressbalanceSolutionEnum());
+	field_names     ={field_names{:},['Vx' i{1}],['Vy' i{1}],['Vel' i{1}],['Pressure' i{1}]};
+	field_tolerances={field_tolerances{:},8e-5,8e-5,8e-5,1e-10};
+	field_values={field_values{:},...
+		(md.results.StressbalanceSolution.Vx),...
+		(md.results.StressbalanceSolution.Vy),...
+		(md.results.StressbalanceSolution.Vel),...
+		(md.results.StressbalanceSolution.Pressure),...
+		};
+end
Index: issm/trunk/test/NightlyRun/test703.m
===================================================================
--- issm/trunk/test/NightlyRun/test703.m	(revision 18081)
+++ issm/trunk/test/NightlyRun/test703.m	(revision 18301)
@@ -43,8 +43,10 @@
 md.stressbalance.shelf_dampening=1;
 md.surfaceforcings.mass_balance=zeros(md.mesh.numberofvertices,1);
-md.basalforcings.melting_rate=zeros(md.mesh.numberofvertices,1);
+md.basalforcings.groundedice_melting_rate=zeros(md.mesh.numberofvertices,1);
+md.basalforcings.floatingice_melting_rate=zeros(md.mesh.numberofvertices,1);
 md.basalforcings.geothermalflux=zeros(md.mesh.numberofvertices,1);
 posb=find((md.mesh.x>0) & md.mesh.vertexonbase);
-md.basalforcings.melting_rate(posb)=18;
+md.basalforcings.groundedice_melting_rate(posb)=18;
+md.basalforcings.floatingice_melting_rate(posb)=18;
 md.initialization.vx=zeros(md.mesh.numberofvertices,1);
 md.initialization.vy=zeros(md.mesh.numberofvertices,1);
Index: issm/trunk/test/Par/79North.par
===================================================================
--- issm/trunk/test/Par/79North.par	(revision 18081)
+++ issm/trunk/test/Par/79North.par	(revision 18301)
@@ -28,6 +28,7 @@
 
 %Ice shelf melting and surface mass balance 
-md.basalforcings.melting_rate=zeros(md.mesh.numberofvertices,1);
-md.basalforcings.melting_rate(find(md.mask.groundedice_levelset<0.))=0.;
+md.basalforcings.floatingice_melting_rate=zeros(md.mesh.numberofvertices,1);
+md.basalforcings.floatingice_melting_rate(find(md.mask.groundedice_levelset<0.))=0.;
+md.basalforcings.groundedice_melting_rate=zeros(md.mesh.numberofvertices,1);
 md.surfaceforcings.mass_balance=15.*ones(md.mesh.numberofvertices,1);
 
Index: issm/trunk/test/Par/79North.py
===================================================================
--- issm/trunk/test/Par/79North.py	(revision 18081)
+++ issm/trunk/test/Par/79North.py	(revision 18301)
@@ -40,6 +40,7 @@
 
 #Ice shelf melting and surface mass balance 
-md.basalforcings.melting_rate=numpy.zeros((md.mesh.numberofvertices,1))
-md.basalforcings.melting_rate[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
+md.basalforcings.floatingice_melting_rate=numpy.zeros((md.mesh.numberofvertices,1))
+md.basalforcings.floatingice_melting_rate[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
+md.basalforcings.groundedice_melting_rate=numpy.zeros((md.mesh.numberofvertices,1))
 md.surfaceforcings.mass_balance=15*numpy.ones((md.mesh.numberofvertices,1))
 
Index: issm/trunk/test/Par/RoundSheetShelf.par
===================================================================
--- issm/trunk/test/Par/RoundSheetShelf.par	(revision 18081)
+++ issm/trunk/test/Par/RoundSheetShelf.par	(revision 18301)
@@ -63,6 +63,7 @@
 %Surface mass balance and basal melting
 md.surfaceforcings.mass_balance=-10.*ones(md.mesh.numberofvertices,1);
-md.basalforcings.melting_rate=zeros(md.mesh.numberofvertices,1);
-pos=find(md.mask.groundedice_levelset>0.);md.basalforcings.melting_rate(pos)=10.;
+md.basalforcings.groundedice_melting_rate=zeros(md.mesh.numberofvertices,1);
+pos=find(md.mask.groundedice_levelset>0.);md.basalforcings.groundedice_melting_rate(pos)=10.;
+md.basalforcings.floatingice_melting_rate=zeros(md.mesh.numberofvertices,1);
 md.basalforcings.geothermalflux=ones(md.mesh.numberofvertices,1);
 
@@ -94,5 +95,5 @@
 
 %bathymetry and grounding line migration:
-md.groundingline.migration='AgressiveMigration';
+md.groundingline.migration='AggressiveMigration';
 md.geometry.bed=md.geometry.base;
 pos=find(md.mask.groundedice_levelset<0.); md.geometry.bed(pos)=md.geometry.base(pos)-900.;
Index: issm/trunk/test/Par/RoundSheetShelf.py
===================================================================
--- issm/trunk/test/Par/RoundSheetShelf.py	(revision 18081)
+++ issm/trunk/test/Par/RoundSheetShelf.py	(revision 18301)
@@ -70,7 +70,8 @@
 #Surface mass balance and basal melting
 md.surfaceforcings.mass_balance=-10.*numpy.ones((md.mesh.numberofvertices,1))
-md.basalforcings.melting_rate=numpy.zeros((md.mesh.numberofvertices,1))
+md.basalforcings.groundedice_melting_rate=numpy.zeros((md.mesh.numberofvertices,1))
 pos=numpy.nonzero(md.mask.groundedice_levelset>0.)[0]
-md.basalforcings.melting_rate[pos]=10.
+md.basalforcings.groundedice_melting_rate[pos]=10.
+md.basalforcings.floatingice_melting_rate=numpy.zeros((md.mesh.numberofvertices,1))
 md.basalforcings.geothermalflux=numpy.ones((md.mesh.numberofvertices,1))
 
Index: issm/trunk/test/Par/SquareEISMINT.par
===================================================================
--- issm/trunk/test/Par/SquareEISMINT.par	(revision 18081)
+++ issm/trunk/test/Par/SquareEISMINT.par	(revision 18301)
@@ -28,5 +28,6 @@
 disp('      creating surface mass balance');
 md.surfaceforcings.mass_balance=0.2*ones(md.mesh.numberofvertices,1); %0m/a
-md.basalforcings.melting_rate=0.*ones(md.mesh.numberofvertices,1); %0m/a
+md.basalforcings.floatingice_melting_rate=0.*ones(md.mesh.numberofvertices,1); %0m/a
+md.basalforcings.groundedice_melting_rate=0.*ones(md.mesh.numberofvertices,1); %0m/a
 
 disp('      boundary conditions');
Index: issm/trunk/test/Par/SquareEISMINT.py
===================================================================
--- issm/trunk/test/Par/SquareEISMINT.py	(revision 18081)
+++ issm/trunk/test/Par/SquareEISMINT.py	(revision 18301)
@@ -31,5 +31,6 @@
 print "      creating surface mass balance"
 md.surfaceforcings.mass_balance=0.2*numpy.ones((md.mesh.numberofvertices,1))    #0m/a
-md.basalforcings.melting_rate=0.*numpy.ones((md.mesh.numberofvertices,1))    #0m/a
+md.basalforcings.floatingice_melting_rate=0.*numpy.ones((md.mesh.numberofvertices,1))    #0m/a
+md.basalforcings.groundedice_melting_rate=0.*numpy.ones((md.mesh.numberofvertices,1))    #0m/a
 
 print "      boundary conditions"
Index: issm/trunk/test/Par/SquareSheetShelf.par
===================================================================
--- issm/trunk/test/Par/SquareSheetShelf.par	(revision 18081)
+++ issm/trunk/test/Par/SquareSheetShelf.par	(revision 18301)
@@ -34,5 +34,6 @@
 %Accumulation and melting
 md.surfaceforcings.mass_balance=10.*ones(md.mesh.numberofvertices,1);
-md.basalforcings.melting_rate=5.*ones(md.mesh.numberofvertices,1);
+md.basalforcings.groundedice_melting_rate=5.*ones(md.mesh.numberofvertices,1);
+md.basalforcings.floatingice_melting_rate=5.*ones(md.mesh.numberofvertices,1);
 
 %Friction
Index: issm/trunk/test/Par/SquareSheetShelf.py
===================================================================
--- issm/trunk/test/Par/SquareSheetShelf.py	(revision 18081)
+++ issm/trunk/test/Par/SquareSheetShelf.py	(revision 18301)
@@ -45,5 +45,6 @@
 #Accumulation and melting
 md.surfaceforcings.mass_balance=10.*numpy.ones((md.mesh.numberofvertices,1))
-md.basalforcings.melting_rate=5.*numpy.ones((md.mesh.numberofvertices,1))
+md.basalforcings.groundedice_melting_rate=5.*numpy.ones((md.mesh.numberofvertices,1))
+md.basalforcings.floatingice_melting_rate=5.*numpy.ones((md.mesh.numberofvertices,1))
 
 #Friction
Index: issm/trunk/test/Par/SquareShelfConstrained.par
===================================================================
--- issm/trunk/test/Par/SquareShelfConstrained.par	(revision 18081)
+++ issm/trunk/test/Par/SquareShelfConstrained.par	(revision 18301)
@@ -31,5 +31,6 @@
 %Surface mass balance and basal melting
 md.surfaceforcings.mass_balance=10*ones(md.mesh.numberofvertices,1);
-md.basalforcings.melting_rate=5*ones(md.mesh.numberofvertices,1);
+md.basalforcings.floatingice_melting_rate=5*ones(md.mesh.numberofvertices,1);
+md.basalforcings.groundedice_melting_rate=5*ones(md.mesh.numberofvertices,1);
 
 %Friction
Index: issm/trunk/test/Par/SquareShelfConstrained.py
===================================================================
--- issm/trunk/test/Par/SquareShelfConstrained.py	(revision 18081)
+++ issm/trunk/test/Par/SquareShelfConstrained.py	(revision 18301)
@@ -42,5 +42,6 @@
 #Surface mass balance and basal melting
 md.surfaceforcings.mass_balance=10.*numpy.ones((md.mesh.numberofvertices,1))
-md.basalforcings.melting_rate=5.*numpy.ones((md.mesh.numberofvertices,1))
+md.basalforcings.groundedice_melting_rate=5.*numpy.ones((md.mesh.numberofvertices,1))
+md.basalforcings.floatingice_melting_rate=5.*numpy.ones((md.mesh.numberofvertices,1))
 
 #Friction
Index: issm/trunk/test/Par/SquareThermal.par
===================================================================
--- issm/trunk/test/Par/SquareThermal.par	(revision 18081)
+++ issm/trunk/test/Par/SquareThermal.par	(revision 18301)
@@ -29,5 +29,6 @@
 disp('      creating surface mass balance');
 md.surfaceforcings.mass_balance=ones(md.mesh.numberofvertices,1)/md.constants.yts; %1m/a
-md.basalforcings.melting_rate=0.*ones(md.mesh.numberofvertices,1)/md.constants.yts; %1m/a
+md.basalforcings.groundedice_melting_rate=0.*ones(md.mesh.numberofvertices,1)/md.constants.yts; %1m/a
+md.basalforcings.floatingice_melting_rate=0.*ones(md.mesh.numberofvertices,1)/md.constants.yts; %1m/a
 
 %Deal with boundary conditions:
Index: issm/trunk/test/Par/ValleyGlacierShelf.par
===================================================================
--- issm/trunk/test/Par/ValleyGlacierShelf.par	(revision 18081)
+++ issm/trunk/test/Par/ValleyGlacierShelf.par	(revision 18301)
@@ -50,5 +50,6 @@
 %Surface mass balance and basal melting
 md.surfaceforcings.mass_balance = 0.3*ones(md.mesh.numberofvertices,1);
-md.basalforcings.melting_rate = md.surfaceforcings.mass_balance;
+md.basalforcings.floatingice_melting_rate = md.surfaceforcings.mass_balance;
+md.basalforcings.groundedice_melting_rate = md.surfaceforcings.mass_balance;
 
 %Friction
Index: issm/trunk/test/Par/ValleyGlacierShelf.py
===================================================================
--- issm/trunk/test/Par/ValleyGlacierShelf.py	(revision 18081)
+++ issm/trunk/test/Par/ValleyGlacierShelf.py	(revision 18301)
@@ -57,5 +57,6 @@
 #Surface mass balance and basal melting
 md.surfaceforcings.mass_balance=0.3*numpy.ones((md.mesh.numberofvertices,1))
-md.basalforcings.melting_rate=md.surfaceforcings.mass_balance
+md.basalforcings.groundedice_melting_rate=md.surfaceforcings.mass_balance
+md.basalforcings.floatingice_melting_rate=md.surfaceforcings.mass_balance
 
 #Friction
