/*!\file Tria.cpp
 * \brief: implementation of the Tria object
 */
/*Headers:*/
/*{{{*/
#ifdef HAVE_CONFIG_H
	#include <config.h>
#else
#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
#endif

#include <stdio.h>
#include <string.h>
#include "../classes.h"
#include "../../shared/shared.h"
#ifdef _HAVE_GIA_
#include "../../modules/GiaDeflectionCorex/GiaDeflectionCorex.h"
#endif
/*}}}*/

/*Element macros*/
#define NUMVERTICES   3
#define NUMVERTICES1D 2

/*Constructors/destructor/copy*/
/*FUNCTION Tria::Tria(int id, int sid,int index, IoModel* iomodel,int nummodels){{{*/
Tria::Tria(int tria_id, int tria_sid, int index, IoModel* iomodel,int nummodels)
	:TriaRef(nummodels),ElementHook(nummodels,index+1,NUMVERTICES,iomodel){

		/*id: */
		this->id  = tria_id;
		this->sid = tria_sid;

		//this->parameters: we still can't point to it, it may not even exist. Configure will handle this.
		this->parameters = NULL;

		/*intialize inputs: */
		this->inputs  = new Inputs();

		/*initialize pointers:*/
		this->nodes    = NULL;
		this->vertices = NULL;
		this->material = NULL;
		this->matpar   = NULL;
}
/*}}}*/
/*FUNCTION Tria::~Tria(){{{*/
Tria::~Tria(){
	this->parameters=NULL;
}
/*}}}*/
/*FUNCTION Tria::copy {{{*/
Object* Tria::copy() {

	int i;
	Tria* tria=NULL;

	tria=new Tria();

	//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];

	//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();
	tria->hvertices = (Hook*)this->hvertices->copy();
	tria->hmaterial = (Hook*)this->hmaterial->copy();
	tria->hmatpar   = (Hook*)this->hmatpar->copy();

	/*deal with Tria fields: */
	tria->id  = this->id;
	tria->sid = this->sid;
	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();

	return tria;
}
/*}}}*/

/*Other*/
/*FUNCTION Tria::AddBasalInput{{{*/
void  Tria::AddBasalInput(int input_enum,IssmDouble* values, int interpolation_enum){

	/*Call inputs method*/
	_assert_(this->inputs);
	
	int meshtype;
	parameters->FindParam(&meshtype,MeshTypeEnum);
	switch(meshtype){
		case Mesh2DhorizontalEnum:
			this->inputs->AddInput(new TriaInput(input_enum,values,interpolation_enum));
			break;
		case Mesh2DverticalEnum:{
			if(interpolation_enum==P1Enum){
				IssmDouble values2[NUMVERTICES]={0.};
				int        numindices;
				int       *indices = NULL;
				int        index = this->EdgeOnBedIndex();
				NodeOnEdgeIndices(&numindices,&indices,index,this->FiniteElement());
				for(int i=0;i<numindices;i++){
					values2[indices[i]] = values[i];
				}
				this->inputs->AddInput(new TriaInput(input_enum,values2,interpolation_enum));
				xDelete<int>(indices);
			}
			else _error_("not implemented yet");
			}
			break;
		default: _error_("mesh "<<EnumToStringx(meshtype)<<" not supported yet");
	}

}
/*}}}*/
/*FUNCTION Tria::AddInput{{{*/
void  Tria::AddInput(int input_enum,IssmDouble* values, int interpolation_enum){

	/*Call inputs method*/
	_assert_(this->inputs);
	this->inputs->AddInput(new TriaInput(input_enum,values,interpolation_enum));
}
/*}}}*/
/*FUNCTION Tria::CharacteristicLength{{{*/
IssmDouble Tria::CharacteristicLength(void){

	return sqrt(2*this->GetArea());
}
/*}}}*/
/*FUNCTION Tria::ComputeBasalStress {{{*/
void  Tria::ComputeBasalStress(Vector<IssmDouble>* eps){
	_error_("Not Implemented yet");
}
/*}}}*/
/*FUNCTION Tria::ComputeStrainRate {{{*/
void  Tria::ComputeStrainRate(Vector<IssmDouble>* eps){
	_error_("Not Implemented yet");
}
/*}}}*/
/*FUNCTION Tria::ComputeStressTensor {{{*/
void  Tria::ComputeStressTensor(){

	IssmDouble  xyz_list[NUMVERTICES][3];
	IssmDouble  pressure,viscosity;
	IssmDouble  epsilon[3]; /* epsilon=[exx,eyy,exy];*/
	IssmDouble  sigma_xx[NUMVERTICES];
	IssmDouble	sigma_yy[NUMVERTICES];
	IssmDouble	sigma_zz[NUMVERTICES]={0,0,0};
	IssmDouble  sigma_xy[NUMVERTICES];
	IssmDouble	sigma_xz[NUMVERTICES]={0,0,0};
	IssmDouble	sigma_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* pressure_input=inputs->GetInput(PressureEnum); _assert_(pressure_input);
	Input* vx_input=inputs->GetInput(VxEnum);             _assert_(vx_input);
	Input* vy_input=inputs->GetInput(VyEnum);             _assert_(vy_input);

	/* Start looping on the number of vertices: */
	gauss=new GaussTria();
	for (int iv=0;iv<NUMVERTICES;iv++){
		gauss->GaussVertex(iv);

		/*Compute strain rate viscosity and pressure: */
		this->StrainRateSSA(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
		this->ViscositySSA(&viscosity,2,&xyz_list[0][0],gauss,vx_input,vy_input);
		pressure_input->GetInputValue(&pressure,gauss);

		/*Compute Stress*/
		sigma_xx[iv]=2*viscosity*epsilon[0]-pressure; // sigma = nu eps - pressure
		sigma_yy[iv]=2*viscosity*epsilon[1]-pressure;
		sigma_xy[iv]=2*viscosity*epsilon[2];
	}

	/*Add Stress tensor components into inputs*/
	this->inputs->AddInput(new TriaInput(StressTensorxxEnum,&sigma_xx[0],P1Enum));
	this->inputs->AddInput(new TriaInput(StressTensorxyEnum,&sigma_xy[0],P1Enum));
	this->inputs->AddInput(new TriaInput(StressTensorxzEnum,&sigma_xz[0],P1Enum));
	this->inputs->AddInput(new TriaInput(StressTensoryyEnum,&sigma_yy[0],P1Enum));
	this->inputs->AddInput(new TriaInput(StressTensoryzEnum,&sigma_yz[0],P1Enum));
	this->inputs->AddInput(new TriaInput(StressTensorzzEnum,&sigma_zz[0],P1Enum));

	/*Clean up and return*/
	delete gauss;
}
/*}}}*/
/*FUNCTION Tria::Configure {{{*/
void  Tria::Configure(Elements* elementsin, Loads* loadsin,Nodes* nodesin,Vertices *verticesin,Materials* materialsin, Parameters* parametersin){

	/*go into parameters and get the analysis_counter: */
	int analysis_counter;
	parametersin->FindParam(&analysis_counter,AnalysisCounterEnum);

	/*Get Element type*/
	this->element_type=this->element_type_list[analysis_counter];

	/*Take care of hooking up all objects for this element, ie links the objects in the hooks to their respective 
	 * datasets, using internal ids and offsets hidden in hooks: */
	if(this->hnodes[analysis_counter]) this->hnodes[analysis_counter]->configure(nodesin);
	this->hvertices->configure(verticesin);
	this->hmaterial->configure(materialsin);
	this->hmatpar->configure(materialsin);

	/*Now, go pick up the objects inside the hooks: */
	if(this->hnodes[analysis_counter]) this->nodes=(Node**)this->hnodes[analysis_counter]->deliverp();
	else this->nodes=NULL;
	this->vertices = (Vertex**)this->hvertices->deliverp();
	this->material = (Material*)this->hmaterial->delivers();
	this->matpar   = (Matpar*)this->hmatpar->delivers();

	/*point parameters to real dataset: */
	this->parameters=parametersin;

	/*get inputs configured too: */
	this->inputs->Configure(parameters);

}
/*}}}*/
/*FUNCTION Tria::Delta18oParameterization{{{*/
void  Tria::Delta18oParameterization(void){

	int        i;
	IssmDouble monthlytemperatures[NUMVERTICES][12],monthlyprec[NUMVERTICES][12];
	IssmDouble TemperaturesPresentday[NUMVERTICES][12],TemperaturesLgm[NUMVERTICES][12];
	IssmDouble PrecipitationsPresentday[NUMVERTICES][12];
	IssmDouble tmp[NUMVERTICES];
	IssmDouble Delta18oPresent,Delta18oLgm,Delta18oTime;
	IssmDouble Delta18oSurfacePresent,Delta18oSurfaceLgm,Delta18oSurfaceTime;
	IssmDouble time,yts,finaltime;

	/*Recover parameters*/
	this->parameters->FindParam(&time,TimeEnum);
	this->parameters->FindParam(&yts,ConstantsYtsEnum);
	this->parameters->FindParam(&finaltime,TimesteppingFinalTimeEnum);

	/*Recover present day temperature and precipitation*/
	Input* input=inputs->GetInput(SurfaceforcingsTemperaturesPresentdayEnum);    _assert_(input);
	Input* input2=inputs->GetInput(SurfaceforcingsTemperaturesLgmEnum);          _assert_(input2);
	Input* input3=inputs->GetInput(SurfaceforcingsPrecipitationsPresentdayEnum); _assert_(input3);
	GaussTria* gauss=new GaussTria();
	for(int month=0;month<12;month++){
		for(int iv=0;iv<NUMVERTICES;iv++){
			gauss->GaussVertex(iv);
			input->GetInputValue(&TemperaturesPresentday[iv][month],gauss,month/12.*yts);
			input2->GetInputValue(&TemperaturesLgm[iv][month],gauss,month/12.*yts);
			input3->GetInputValue(&PrecipitationsPresentday[iv][month],gauss,month/12.*yts);
			PrecipitationsPresentday[iv][month]=PrecipitationsPresentday[iv][month]/yts; // converion in m/sec
		}
	}

	/*Recover delta18o and Delta18oSurface at present day, lgm and at time t*/
	this->parameters->FindParam(&Delta18oPresent,SurfaceforcingsDelta18oEnum,finaltime);
	this->parameters->FindParam(&Delta18oLgm,SurfaceforcingsDelta18oEnum,(finaltime-(21000*yts)));
	this->parameters->FindParam(&Delta18oTime,SurfaceforcingsDelta18oEnum,time);
	this->parameters->FindParam(&Delta18oSurfacePresent,SurfaceforcingsDelta18oSurfaceEnum,finaltime);
	this->parameters->FindParam(&Delta18oSurfaceLgm,SurfaceforcingsDelta18oSurfaceEnum,(finaltime-(21000*yts)));
	this->parameters->FindParam(&Delta18oSurfaceTime,SurfaceforcingsDelta18oSurfaceEnum,time);

	/*Compute the temperature and precipitation*/
	for(int iv=0;iv<NUMVERTICES;iv++){
		ComputeDelta18oTemperaturePrecipitation(Delta18oSurfacePresent, Delta18oSurfaceLgm, Delta18oSurfaceTime, 
					Delta18oPresent, Delta18oLgm, Delta18oTime,
					&PrecipitationsPresentday[iv][0], 
					&TemperaturesLgm[iv][0], &TemperaturesPresentday[iv][0], 
					&monthlytemperatures[iv][0], &monthlyprec[iv][0]);
	}

	/*Update inputs*/ 
	TransientInput* NewTemperatureInput = new TransientInput(SurfaceforcingsMonthlytemperaturesEnum);
	TransientInput* NewPrecipitationInput = new TransientInput(SurfaceforcingsPrecipitationEnum);
	for (int imonth=0;imonth<12;imonth++) {
		for(i=0;i<NUMVERTICES;i++) tmp[i]=monthlytemperatures[i][imonth];
		TriaInput* newmonthinput1 = new TriaInput(SurfaceforcingsMonthlytemperaturesEnum,&tmp[0],P1Enum);
		NewTemperatureInput->AddTimeInput(newmonthinput1,time+imonth/12.*yts);

		for(i=0;i<NUMVERTICES;i++) tmp[i]=monthlyprec[i][imonth];
		TriaInput* newmonthinput2 = new TriaInput(SurfaceforcingsPrecipitationEnum,&tmp[0],P1Enum);
		NewPrecipitationInput->AddTimeInput(newmonthinput2,time+imonth/12.*yts);
	}
	NewTemperatureInput->Configure(this->parameters);
	NewPrecipitationInput->Configure(this->parameters);

	this->inputs->AddInput(NewTemperatureInput);
	this->inputs->AddInput(NewPrecipitationInput);

	/*clean-up*/
	delete gauss;
}
/*}}}*/
/*FUNCTION Tria::ElementSizes{{{*/
void Tria::ElementSizes(IssmDouble* hx,IssmDouble* hy,IssmDouble* hz){

	IssmDouble xyz_list[NUMVERTICES][3];
	IssmDouble xmin,ymin;
	IssmDouble xmax,ymax;

	/*Get xyz list: */
	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
	xmin=xyz_list[0][0]; xmax=xyz_list[0][0];
	ymin=xyz_list[0][1]; ymax=xyz_list[0][1];

	for(int i=1;i<NUMVERTICES;i++){
		if(xyz_list[i][0]<xmin) xmin=xyz_list[i][0];
		if(xyz_list[i][0]>xmax) xmax=xyz_list[i][0];
		if(xyz_list[i][1]<ymin) ymin=xyz_list[i][1];
		if(xyz_list[i][1]>ymax) ymax=xyz_list[i][1];
	}

	*hx=xmax-xmin;
	*hy=ymax-ymin;
	*hz=0.;
}
/*}}}*/
/*FUNCTION Tria::FiniteElement{{{*/
int Tria::FiniteElement(void){
	return this->element_type;
}
/*}}}*/
/*FUNCTION Tria::ObjectEnum{{{*/
int Tria::ObjectEnum(void){

	return TriaEnum;

}
/*}}}*/
/*FUNCTION Tria::GetArea {{{*/
IssmDouble Tria::GetArea(void){

	IssmDouble xyz_list[NUMVERTICES][3];
	IssmDouble x1,y1,x2,y2,x3,y3;

	/*Get xyz list: */
	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
	x1=xyz_list[0][0]; y1=xyz_list[0][1];
	x2=xyz_list[1][0]; y2=xyz_list[1][1];
	x3=xyz_list[2][0]; y3=xyz_list[2][1];

	_assert_(x2*y3 - y2*x3 + x1*y2 - y1*x2 + x3*y1 - y3*x1>0);
	return (x2*y3 - y2*x3 + x1*y2 - y1*x2 + x3*y1 - y3*x1)/2;
}
/*}}}*/
/*FUNCTION Tria::GetAreaCoordinates{{{*/
void Tria::GetAreaCoordinates(IssmDouble* area_coordinates,IssmDouble* xyz_zero,IssmDouble* xyz_list,int numpoints){
	/*Computeportion of the element that is grounded*/ 

	int         i,j,k;
	IssmDouble  area_init,area_portion;
	IssmDouble  xyz_bis[NUMVERTICES][3];

	area_init=GetArea();

	/*Initialize xyz_list with original xyz_list of triangle coordinates*/
	for(j=0;j<3;j++){ 
		for(k=0;k<3;k++){
			xyz_bis[j][k]=xyz_list[j*3+k];
		}
	}
	for(i=0;i<numpoints;i++){
		for(j=0;j<3;j++){ 
			for(k=0;k<3;k++){
				/*Change appropriate line*/
				xyz_bis[j][k]=xyz_zero[i*3+k];
			}

			/*Compute area fraction*/
			area_portion=fabs(xyz_bis[1][0]*xyz_bis[2][1] - xyz_bis[1][1]*xyz_bis[2][0] + xyz_bis[0][0]*xyz_bis[1][1] - xyz_bis[0][1]*xyz_bis[1][0] + xyz_bis[2][0]*xyz_bis[0][1] - xyz_bis[2][1]*xyz_bis[0][0])/2.;
			*(area_coordinates+3*i+j)=area_portion/area_init;

			/*Reinitialize xyz_list*/
			for(k=0;k<3;k++){
				/*Reinitialize xyz_list with original coordinates*/
				xyz_bis[j][k]=xyz_list[j*3+k];
			}
		}
	}
}
/*}}}*/
/*FUNCTION Tria::GetElementType {{{*/
int Tria::GetElementType(){

	/*return TriaRef field*/
	return this->element_type;

}
/*}}}*/
/*FUNCTION Tria::GetGroundedPart{{{*/
void Tria::GetGroundedPart(int* point1,IssmDouble* fraction1,IssmDouble* fraction2, bool* mainlyfloating){
	/*Computeportion of the element that is grounded*/ 

	bool               floating=true;
	int                point;
	const IssmPDouble  epsilon= 1.e-15;
	IssmDouble         gl[NUMVERTICES];
	IssmDouble         f1,f2;

	/*Recover parameters and values*/
	GetInputListOnVertices(&gl[0],MaskGroundediceLevelsetEnum);

	/*Be sure that values are not zero*/
	if(gl[0]==0.) gl[0]=gl[0]+epsilon;
	if(gl[1]==0.) gl[1]=gl[1]+epsilon;
	if(gl[2]==0.) gl[2]=gl[2]+epsilon;

	/*Check that not all nodes are grounded or floating*/
	if(gl[0]>0 && gl[1]>0 && gl[2]>0){ // All grounded
		point=0;
		f1=1.;
		f2=1.;
	}
	else if(gl[0]<0 && gl[1]<0 && gl[2]<0){ //All floating
		point=0;
		f1=0.;
		f2=0.;
	}
	else{
		if(gl[0]*gl[1]*gl[2]<0) floating=false;

		if(gl[0]*gl[1]>0){ //Nodes 0 and 1 are similar, so points must be found on segment 0-2 and 1-2
			point=2;
			f1=gl[2]/(gl[2]-gl[0]);
			f2=gl[2]/(gl[2]-gl[1]);
		}
		else if(gl[1]*gl[2]>0){ //Nodes 1 and 2 are similar, so points must be found on segment 0-1 and 0-2
			point=0;
			f1=gl[0]/(gl[0]-gl[1]);
			f2=gl[0]/(gl[0]-gl[2]);
		}
		else if(gl[0]*gl[2]>0){ //Nodes 0 and 2 are similar, so points must be found on segment 1-0 and 1-2
			point=1;
			f1=gl[1]/(gl[1]-gl[2]);
			f2=gl[1]/(gl[1]-gl[0]);
		}
	}
	*point1=point;
	*fraction1=f1;
	*fraction2=f2;
	*mainlyfloating=floating;
}
/*}}}*/
/*FUNCTION Tria::GetGroundedPortion{{{*/
IssmDouble Tria::GetGroundedPortion(IssmDouble* xyz_list){
	/*Computeportion of the element that is grounded*/ 

	bool              mainlyfloating = true;
	int               meshtype,index1,index2;
	const IssmPDouble epsilon        = 1.e-15;
	IssmDouble        phi,s1,s2,area_init,area_grounded;
	IssmDouble        gl[NUMVERTICES];
	IssmDouble        xyz_bis[3][3];

	/*Recover parameters and values*/
	parameters->FindParam(&meshtype,MeshTypeEnum);
	GetInputListOnVertices(&gl[0],MaskGroundediceLevelsetEnum);

	/*Be sure that values are not zero*/
	if(gl[0]==0.) gl[0]=gl[0]+epsilon;
	if(gl[1]==0.) gl[1]=gl[1]+epsilon;
	if(gl[2]==0.) gl[2]=gl[2]+epsilon;

	if(meshtype==Mesh2DverticalEnum){
		this->EdgeOnBedIndices(&index1,&index2);
		if(gl[index1]>0 && gl[index2]>0) phi=1; // All grounded
		else if(gl[index1]<0 && gl[index2]<0) phi=0; // All floating
		else if(gl[index1]<0 && gl[index2]>0){ //index2 grounded
			phi=1./(1.-gl[index1]/gl[index2]);
		}
		else if(gl[index2]<0 && gl[index1]>0){ //index1 grounded
			phi=1./(1.-gl[index2]/gl[index1]);
		}

	}
	else if(meshtype==Mesh2DhorizontalEnum || meshtype==Mesh3DEnum){
		/*Check that not all nodes are grounded or floating*/
		if(gl[0]>0 && gl[1]>0 && gl[2]>0){ // All grounded
			phi=1;
		}
		else if(gl[0]<0 && gl[1]<0 && gl[2]<0){ //All floating
			phi=0;
		}
		else{
			/*Figure out if two nodes are floating or grounded*/
			if(gl[0]*gl[1]*gl[2]>0) mainlyfloating=false;

			if(gl[0]*gl[1]>0){ //Nodes 0 and 1 are similar, so points must be found on segment 0-2 and 1-2
				/*Coordinates of point 2: same as initial point 2*/
				xyz_bis[2][0]=*(xyz_list+3*2+0);
				xyz_bis[2][1]=*(xyz_list+3*2+1);
				xyz_bis[2][2]=*(xyz_list+3*2+2);

				/*Portion of the segments*/
				s1=gl[2]/(gl[2]-gl[1]);
				s2=gl[2]/(gl[2]-gl[0]);

				/*New point 1*/
				xyz_bis[1][0]=*(xyz_list+3*2+0)+s1*(*(xyz_list+3*1+0)-*(xyz_list+3*2+0));
				xyz_bis[1][1]=*(xyz_list+3*2+1)+s1*(*(xyz_list+3*1+1)-*(xyz_list+3*2+1));
				xyz_bis[1][2]=*(xyz_list+3*2+2)+s1*(*(xyz_list+3*1+2)-*(xyz_list+3*2+2));

				/*New point 0*/
				xyz_bis[0][0]=*(xyz_list+3*2+0)+s2*(*(xyz_list+3*0+0)-*(xyz_list+3*2+0));
				xyz_bis[0][1]=*(xyz_list+3*2+1)+s2*(*(xyz_list+3*0+1)-*(xyz_list+3*2+1));
				xyz_bis[0][2]=*(xyz_list+3*2+2)+s2*(*(xyz_list+3*0+2)-*(xyz_list+3*2+2));
			}
			else if(gl[1]*gl[2]>0){ //Nodes 1 and 2 are similar, so points must be found on segment 0-1 and 0-2
				/*Coordinates of point 0: same as initial point 2*/
				xyz_bis[0][0]=*(xyz_list+3*0+0);
				xyz_bis[0][1]=*(xyz_list+3*0+1);
				xyz_bis[0][2]=*(xyz_list+3*0+2);

				/*Portion of the segments*/
				s1=gl[0]/(gl[0]-gl[1]);
				s2=gl[0]/(gl[0]-gl[2]);

				/*New point 1*/
				xyz_bis[1][0]=*(xyz_list+3*0+0)+s1*(*(xyz_list+3*1+0)-*(xyz_list+3*0+0));
				xyz_bis[1][1]=*(xyz_list+3*0+1)+s1*(*(xyz_list+3*1+1)-*(xyz_list+3*0+1));
				xyz_bis[1][2]=*(xyz_list+3*0+2)+s1*(*(xyz_list+3*1+2)-*(xyz_list+3*0+2));

				/*New point 2*/
				xyz_bis[2][0]=*(xyz_list+3*0+0)+s2*(*(xyz_list+3*2+0)-*(xyz_list+3*0+0));
				xyz_bis[2][1]=*(xyz_list+3*0+1)+s2*(*(xyz_list+3*2+1)-*(xyz_list+3*0+1));
				xyz_bis[2][2]=*(xyz_list+3*0+2)+s2*(*(xyz_list+3*2+2)-*(xyz_list+3*0+2));
			}
			else if(gl[0]*gl[2]>0){ //Nodes 0 and 2 are similar, so points must be found on segment 1-0 and 1-2
				/*Coordinates of point 1: same as initial point 2*/
				xyz_bis[1][0]=*(xyz_list+3*1+0);
				xyz_bis[1][1]=*(xyz_list+3*1+1);
				xyz_bis[1][2]=*(xyz_list+3*1+2);

				/*Portion of the segments*/
				s1=gl[1]/(gl[1]-gl[0]);
				s2=gl[1]/(gl[1]-gl[2]);

				/*New point 0*/
				xyz_bis[0][0]=*(xyz_list+3*1+0)+s1*(*(xyz_list+3*0+0)-*(xyz_list+3*1+0));
				xyz_bis[0][1]=*(xyz_list+3*1+1)+s1*(*(xyz_list+3*0+1)-*(xyz_list+3*1+1));
				xyz_bis[0][2]=*(xyz_list+3*1+2)+s1*(*(xyz_list+3*0+2)-*(xyz_list+3*1+2));

				/*New point 2*/
				xyz_bis[2][0]=*(xyz_list+3*1+0)+s2*(*(xyz_list+3*2+0)-*(xyz_list+3*1+0));
				xyz_bis[2][1]=*(xyz_list+3*1+1)+s2*(*(xyz_list+3*2+1)-*(xyz_list+3*1+1));
				xyz_bis[2][2]=*(xyz_list+3*1+2)+s2*(*(xyz_list+3*2+2)-*(xyz_list+3*1+2));
			}

			/*Compute fraction of grounded element*/
			GetJacobianDeterminant(&area_init, xyz_list,NULL);
			GetJacobianDeterminant(&area_grounded, &xyz_bis[0][0],NULL);
			if(mainlyfloating==true) area_grounded=area_init-area_grounded;
			phi=area_grounded/area_init;
		}
	}
	else _error_("mesh type "<<EnumToStringx(meshtype)<<"not supported yet ");

	if(phi>1 || phi<0) _error_("Error. Problem with portion of grounded element: value should be between 0 and 1");

	return phi;
}
/*}}}*/
/*FUNCTION Tria::GetVerticesCoordinatesBase(IssmDouble** pxyz_list){{{*/
void Tria::GetVerticesCoordinatesBase(IssmDouble** pxyz_list){

	int        indices[2];
	IssmDouble xyz_list[NUMVERTICES][3];

	/*Element XYZ list*/
	::GetVerticesCoordinates(&xyz_list[0][0],this->vertices,NUMVERTICES);

	/*Allocate Output*/
	IssmDouble* xyz_list_edge = xNew<IssmDouble>(2*3);
	this->EdgeOnBedIndices(&indices[0],&indices[1]);
	for(int i=0;i<2;i++) for(int j=0;j<2;j++) xyz_list_edge[i*3+j]=xyz_list[indices[i]][j];

	/*Assign output pointer*/
	*pxyz_list = xyz_list_edge;

}/*}}}*/
/*FUNCTION Tria::GetVerticesCoordinatesTop(IssmDouble** pxyz_list){{{*/
void Tria::GetVerticesCoordinatesTop(IssmDouble** pxyz_list){

	int        indices[2];
	IssmDouble xyz_list[NUMVERTICES][3];

	/*Element XYZ list*/
	::GetVerticesCoordinates(&xyz_list[0][0],this->vertices,NUMVERTICES);

	/*Allocate Output*/
	IssmDouble* xyz_list_edge = xNew<IssmDouble>(2*3);
	this->EdgeOnSurfaceIndices(&indices[0],&indices[1]);
	for(int i=0;i<2;i++) for(int j=0;j<2;j++) xyz_list_edge[i*3+j]=xyz_list[indices[i]][j];

	/*Assign output pointer*/
	*pxyz_list = xyz_list_edge;

}/*}}}*/
/*FUNCTION Tria::NormalSection{{{*/
void Tria::NormalSection(IssmDouble* normal,IssmDouble* xyz_list){

	/*Build unit outward pointing vector*/
	IssmDouble vector[2];
	IssmDouble norm;

	vector[0]=xyz_list[1*3+0] - xyz_list[0*3+0];
	vector[1]=xyz_list[1*3+1] - xyz_list[0*3+1];

	norm=sqrt(vector[0]*vector[0] + vector[1]*vector[1]);

	normal[0]= + vector[1]/norm;
	normal[1]= - vector[0]/norm;
}
/*}}}*/
/*FUNCTION Tria::ZeroLevelsetCoordinates{{{*/
void Tria::ZeroLevelsetCoordinates(IssmDouble** pxyz_zero,IssmDouble* xyz_list,int levelsetenum){

	int         normal_orientation=0;
	IssmDouble  s1,s2;
	IssmDouble  levelset[NUMVERTICES];

	/*Recover parameters and values*/
	IssmDouble* xyz_zero = xNew<IssmDouble>(2*3);
	GetInputListOnVertices(&levelset[0],levelsetenum);

	if(levelset[0]*levelset[1]>0.){ //Nodes 0 and 1 are similar, so points must be found on segment 0-2 and 1-2
		/*Portion of the segments*/
		s1=levelset[2]/(levelset[2]-levelset[1]);
		s2=levelset[2]/(levelset[2]-levelset[0]);

		if(levelset[2]<0.) normal_orientation=1; //orientation of quadrangle depending on distribution of levelsetfunction
		/*New point 1*/
		xyz_zero[3*normal_orientation+0]=xyz_list[2*3+0]+s1*(xyz_list[1*3+0]-xyz_list[2*3+0]);
		xyz_zero[3*normal_orientation+1]=xyz_list[2*3+1]+s1*(xyz_list[1*3+1]-xyz_list[2*3+1]);
		xyz_zero[3*normal_orientation+2]=xyz_list[2*3+2]+s1*(xyz_list[1*3+2]-xyz_list[2*3+2]);

		/*New point 0*/
		xyz_zero[3*(1-normal_orientation)+0]=xyz_list[2*3+0]+s2*(xyz_list[0*3+0]-xyz_list[2*3+0]);
		xyz_zero[3*(1-normal_orientation)+1]=xyz_list[2*3+1]+s2*(xyz_list[0*3+1]-xyz_list[2*3+1]);
		xyz_zero[3*(1-normal_orientation)+2]=xyz_list[2*3+2]+s2*(xyz_list[0*3+2]-xyz_list[2*3+2]);
	}
	else if(levelset[1]*levelset[2]>0.){ //Nodes 1 and 2 are similar, so points must be found on segment 0-1 and 0-2
		/*Portion of the segments*/
		s1=levelset[0]/(levelset[0]-levelset[2]);
		s2=levelset[0]/(levelset[0]-levelset[1]);

		if(levelset[0]<0.) normal_orientation=1;
		/*New point 1*/
		xyz_zero[3*normal_orientation+0]=xyz_list[0*3+0]+s1*(xyz_list[2*3+0]-xyz_list[0*3+0]);
		xyz_zero[3*normal_orientation+1]=xyz_list[0*3+1]+s1*(xyz_list[2*3+1]-xyz_list[0*3+1]);
		xyz_zero[3*normal_orientation+2]=xyz_list[0*3+2]+s1*(xyz_list[2*3+2]-xyz_list[0*3+2]);

		/*New point 2*/
		xyz_zero[3*(1-normal_orientation)+0]=xyz_list[0*3+0]+s2*(xyz_list[1*3+0]-xyz_list[0*3+0]);
		xyz_zero[3*(1-normal_orientation)+1]=xyz_list[0*3+1]+s2*(xyz_list[1*3+1]-xyz_list[0*3+1]);
		xyz_zero[3*(1-normal_orientation)+2]=xyz_list[0*3+2]+s2*(xyz_list[1*3+2]-xyz_list[0*3+2]);
	}
	else if(levelset[0]*levelset[2]>0.){ //Nodes 0 and 2 are similar, so points must be found on segment 1-0 and 1-2
		/*Portion of the segments*/
		s1=levelset[1]/(levelset[1]-levelset[0]);
		s2=levelset[1]/(levelset[1]-levelset[2]);

		if(levelset[1]<0.) normal_orientation=1;
		/*New point 0*/
		xyz_zero[3*normal_orientation+0]=xyz_list[1*3+0]+s1*(xyz_list[0*3+0]-xyz_list[1*3+0]);
		xyz_zero[3*normal_orientation+1]=xyz_list[1*3+1]+s1*(xyz_list[0*3+1]-xyz_list[1*3+1]);
		xyz_zero[3*normal_orientation+2]=xyz_list[1*3+2]+s1*(xyz_list[0*3+2]-xyz_list[1*3+2]);

		/*New point 2*/
		xyz_zero[3*(1-normal_orientation)+0]=xyz_list[1*3+0]+s2*(xyz_list[2*3+0]-xyz_list[1*3+0]);
		xyz_zero[3*(1-normal_orientation)+1]=xyz_list[1*3+1]+s2*(xyz_list[2*3+1]-xyz_list[1*3+1]);
		xyz_zero[3*(1-normal_orientation)+2]=xyz_list[1*3+2]+s2*(xyz_list[2*3+2]-xyz_list[1*3+2]);
	}
	else if(levelset[0]==0. && levelset[1]==0.){ //front is on point 0 and 1
		xyz_zero[3*0+0]=xyz_list[0*3+0];
		xyz_zero[3*0+1]=xyz_list[0*3+1];
		xyz_zero[3*0+2]=xyz_list[0*3+2];

		/*New point 2*/
		xyz_zero[3*1+0]=xyz_list[1*3+0];
		xyz_zero[3*1+1]=xyz_list[1*3+1];
		xyz_zero[3*1+2]=xyz_list[1*3+2];
	}
	else if(levelset[0]==0. && levelset[2]==0.){ //front is on point 0 and 1
		xyz_zero[3*0+0]=xyz_list[2*3+0];
		xyz_zero[3*0+1]=xyz_list[2*3+1];
		xyz_zero[3*0+2]=xyz_list[2*3+2];

		/*New point 2*/
		xyz_zero[3*1+0]=xyz_list[0*3+0];
		xyz_zero[3*1+1]=xyz_list[0*3+1];
		xyz_zero[3*1+2]=xyz_list[0*3+2];
	}
	else if(levelset[1]==0. && levelset[2]==0.){ //front is on point 0 and 1
		xyz_zero[3*0+0]=xyz_list[1*3+0];
		xyz_zero[3*0+1]=xyz_list[1*3+1];
		xyz_zero[3*0+2]=xyz_list[1*3+2];

		/*New point 2*/
		xyz_zero[3*1+0]=xyz_list[2*3+0];
		xyz_zero[3*1+1]=xyz_list[2*3+1];
		xyz_zero[3*1+2]=xyz_list[2*3+2];
	}
	else _error_("Case not covered");

	/*Assign output pointer*/
	*pxyz_zero= xyz_zero;
}
/*}}}*/
void  Tria::GetIcefrontCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum){/*{{{*/
	
	/* 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]>=0.){
			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);
}/*}}}*/
void  Tria::GetNormalFromLSF(IssmDouble *pnormal){/*{{{*/

	/* Intermediaries */
	int         i;
	const int   dim=2;
	IssmDouble* xyz_list = NULL;
	IssmDouble  dlevelset[dim], norm_dlevelset;
	IssmDouble  normal[dim]={0.};

	/*Retrieve all inputs and parameters*/
	Input* levelset_input=this->GetInput(MaskIceLevelsetEnum); _assert_(levelset_input);
	this->GetVerticesCoordinates(&xyz_list);
	
	IssmDouble counter=0.;
	Gauss* gauss = this->NewGauss(2);
	for(int ig=gauss->begin();ig<gauss->end();ig++){
		/* Get normal on node */
		levelset_input->GetInputDerivativeValue(&dlevelset[0],xyz_list,gauss);
		norm_dlevelset=0.;
		for(i=0;i<dim;i++) norm_dlevelset+=dlevelset[i]*dlevelset[i]; 
		norm_dlevelset=sqrt(norm_dlevelset)+1.e-14;
		for(i=0;i<dim;i++) normal[i]+=dlevelset[i]/norm_dlevelset;
		counter++;
	}
	_assert_(counter>0.);
	for(i=0;i<dim;i++) normal[i] = normal[i]/counter;
	
	pnormal=&normal[0];

	delete gauss;
	xDelete<IssmDouble>(xyz_list);
}/*}}}*/
/*FUNCTION Tria::GetNodeIndex {{{*/
int Tria::GetNodeIndex(Node* node){

	_assert_(nodes);
	for(int i=0;i<NUMVERTICES;i++){
		if(node==nodes[i])
		 return i;
	}
	_error_("Node provided not found among element nodes");
}
/*}}}*/
/*FUNCTION Tria::GetNumberOfNodes;{{{*/
int Tria::GetNumberOfNodes(void){
	return this->NumberofNodes();
}
/*}}}*/
/*FUNCTION Tria::GetNumberOfVertices;{{{*/
int Tria::GetNumberOfVertices(void){
	return NUMVERTICES;
}
/*}}}*/
/*FUNCTION Tria::GetInputValue(IssmDouble* pvalue,Node* node,int enumtype) {{{*/
void Tria::GetInputValue(IssmDouble* pvalue,Node* node,int enumtype){

	Input* input=inputs->GetInput(enumtype);
	if(!input) _error_("No input of type " << EnumToStringx(enumtype) << " found in tria");

	GaussTria* gauss=new GaussTria();
	gauss->GaussVertex(this->GetNodeIndex(node));

	input->GetInputValue(pvalue,gauss);
	delete gauss;
}
/*}}}*/
Node* Tria::GetNode(int node_number){/*{{{*/
	_assert_(node_number>=0); 
	_assert_(node_number<this->NumberofNodes()); 
	return this->nodes[node_number];

}/*}}}*/
/*FUNCTION Tria::GetVertexPidList {{{*/
void  Tria::GetVertexPidList(int* doflist){

	for(int i=0;i<3;i++) doflist[i]=vertices[i]->Pid();

}
/*}}}*/
/*FUNCTION Tria::GetVectorFromInputs{{{*/
void  Tria::GetVectorFromInputs(Vector<IssmDouble>* vector,int input_enum){

	int vertexpidlist[NUMVERTICES];

	/*Get out if this is not an element input*/
	if(!IsInput(input_enum)) return;

	/*Prepare index list*/
	this->GetVertexPidList(&vertexpidlist[0]);

	/*Get input (either in element or material)*/
	Input* input=inputs->GetInput(input_enum);
	if(!input) _error_("Input " << EnumToStringx(input_enum) << " not found in element");

	/*We found the enum.  Use its values to fill into the vector, using the vertices ids: */
	input->GetVectorFromInputs(vector,&vertexpidlist[0]);
}
/*}}}*/
/*FUNCTION Tria::GetXcoord {{{*/
IssmDouble Tria::GetXcoord(Gauss* gauss){

	IssmDouble x;
	IssmDouble xyz_list[NUMVERTICES][3];
	IssmDouble x_list[NUMVERTICES];

	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
	for(int i=0;i<NUMVERTICES;i++) x_list[i]=xyz_list[i][0];
	TriaRef::GetInputValue(&x,x_list,gauss,P1Enum);

	return x;
}
/*}}}*/
/*FUNCTION Tria::GetYcoord {{{*/
IssmDouble Tria::GetYcoord(Gauss* gauss){

	IssmDouble y;
	IssmDouble xyz_list[NUMVERTICES][3];
	IssmDouble y_list[NUMVERTICES];

	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
	for(int i=0;i<NUMVERTICES;i++) y_list[i]=xyz_list[i][1];
	TriaRef::GetInputValue(&y,y_list,gauss,P1Enum);

	return y;
}
/*}}}*/
/*FUNCTION Tria::InputDepthAverageAtBase {{{*/
void  Tria::InputDepthAverageAtBase(int enum_type,int average_enum_type){

	/*New input*/
	Input* oldinput=NULL;
	Input* newinput=NULL;

	/*copy input of enum_type*/
	oldinput=(Input*)this->inputs->GetInput(enum_type);
	if(!oldinput)_error_("could not find old input with enum: " << EnumToStringx(enum_type));
	newinput=(Input*)oldinput->copy();

	/*Assign new name (average)*/
	newinput->ChangeEnum(average_enum_type);

	/*Add new input to current element*/
	this->inputs->AddInput((Input*)newinput);
}
/*}}}*/
/*FUNCTION Tria::InputDuplicate{{{*/
void  Tria::InputDuplicate(int original_enum,int new_enum){

	/*Call inputs method*/
	if (IsInput(original_enum)) {
		inputs->DuplicateInput(original_enum,new_enum);
	}
}
/*}}}*/
/*FUNCTION Tria::InputScale{{{*/
void  Tria::InputScale(int enum_type,IssmDouble scale_factor){

	Input* input=NULL;

	/*Make a copy of the original input: */
	input=(Input*)this->inputs->GetInput(enum_type);
	if(!input)_error_("could not find old input with enum: " << EnumToStringx(enum_type));

	/*Scale: */
	input->Scale(scale_factor);
}
/*}}}*/
/*FUNCTION Tria::InputUpdateFromIoModel{{{*/
void Tria::InputUpdateFromIoModel(int index, IoModel* iomodel){ //i is the element index

	/*Intermediaries*/
	int        i,j;
	int        tria_vertex_ids[3];
	IssmDouble nodeinputs[3];
	IssmDouble cmmininputs[3];
	IssmDouble cmmaxinputs[3];
	bool       control_analysis   = false;
	int        num_control_type,num_responses;
	IssmDouble yts;

	/*Get parameters: */
	iomodel->Constant(&yts,ConstantsYtsEnum); 
	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
	if(control_analysis) iomodel->Constant(&num_control_type,InversionNumControlParametersEnum);
	if(control_analysis) iomodel->Constant(&num_responses,InversionNumCostFunctionsEnum);

	/*Recover vertices ids needed to initialize inputs*/
	for(i=0;i<3;i++){ 
		tria_vertex_ids[i]=reCast<int>(iomodel->elements[3*index+i]); //ids for vertices are in the elements array from Matlab
	}

	/*Need to know the type of approximation for this element*/
	if(iomodel->Data(FlowequationElementEquationEnum)){
		this->inputs->AddInput(new IntInput(ApproximationEnum,reCast<int>(iomodel->Data(FlowequationElementEquationEnum)[index])));
	}


	/*Control Inputs*/
	if (control_analysis && iomodel->Data(InversionControlParametersEnum)){
		for(i=0;i<num_control_type;i++){
			switch(reCast<int>(iomodel->Data(InversionControlParametersEnum)[i])){
				case BalancethicknessThickeningRateEnum:
					if (iomodel->Data(BalancethicknessThickeningRateEnum)){
						for(j=0;j<3;j++)nodeinputs[j]=iomodel->Data(BalancethicknessThickeningRateEnum)[tria_vertex_ids[j]-1];
						for(j=0;j<3;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i]/yts;
						for(j=0;j<3;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i]/yts;
						this->inputs->AddInput(new ControlInput(BalancethicknessThickeningRateEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
					}
					break;
				case VxEnum:
					if (iomodel->Data(VxEnum)){
						for(j=0;j<3;j++)nodeinputs[j]=iomodel->Data(VxEnum)[tria_vertex_ids[j]-1];
						for(j=0;j<3;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i]/yts;
						for(j=0;j<3;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i]/yts;
						this->inputs->AddInput(new ControlInput(VxEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
					}
					break;
				case VyEnum:
					if (iomodel->Data(VyEnum)){
						for(j=0;j<3;j++)nodeinputs[j]=iomodel->Data(VyEnum)[tria_vertex_ids[j]-1];
						for(j=0;j<3;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i]/yts;
						for(j=0;j<3;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i]/yts;
						this->inputs->AddInput(new ControlInput(VyEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
					}
					break;
				case ThicknessEnum:
					if (iomodel->Data(ThicknessEnum)){
						for(j=0;j<3;j++)nodeinputs[j]=iomodel->Data(ThicknessEnum)[tria_vertex_ids[j]-1];
						for(j=0;j<3;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i];
						for(j=0;j<3;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i];
						this->inputs->AddInput(new ControlInput(ThicknessEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
					}
					break;
				case FrictionCoefficientEnum:
					if (iomodel->Data(FrictionCoefficientEnum)){
						for(j=0;j<3;j++)nodeinputs[j]=iomodel->Data(FrictionCoefficientEnum)[tria_vertex_ids[j]-1];
						for(j=0;j<3;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i];
						for(j=0;j<3;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i];
						this->inputs->AddInput(new ControlInput(FrictionCoefficientEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
					}
					break;
				case MaterialsRheologyBbarEnum:
					if(iomodel->Data(MaterialsRheologyBEnum)){
						for(j=0;j<3;j++) nodeinputs[j]=iomodel->Data(MaterialsRheologyBEnum)[tria_vertex_ids[j]-1];
						for(j=0;j<3;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i];
						for(j=0;j<3;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i];
						this->inputs->AddInput(new ControlInput(MaterialsRheologyBbarEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
					}
					break;
				case DamageDbarEnum:
					if(iomodel->Data(DamageDEnum)){
						for(j=0;j<3;j++) nodeinputs[j]=iomodel->Data(DamageDEnum)[tria_vertex_ids[j]-1];
						for(j=0;j<3;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i];
						for(j=0;j<3;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i];
						this->inputs->AddInput(new ControlInput(DamageDbarEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
					}
					break;
				default:
					_error_("Control " << EnumToStringx(reCast<int,IssmDouble>(iomodel->Data(InversionControlParametersEnum)[i])) << " not implemented yet");
			}
		}
	}

	/*DatasetInputs*/
	if (control_analysis && iomodel->Data(InversionCostFunctionsCoefficientsEnum)){

		/*Create inputs and add to DataSetInput*/
		DatasetInput* datasetinput=new DatasetInput(InversionCostFunctionsCoefficientsEnum);
		for(i=0;i<num_responses;i++){
			for(j=0;j<3;j++)nodeinputs[j]=iomodel->Data(InversionCostFunctionsCoefficientsEnum)[(tria_vertex_ids[j]-1)*num_responses+i];
			datasetinput->AddInput(new TriaInput(InversionCostFunctionsCoefficientsEnum,nodeinputs,P1Enum),reCast<int>(iomodel->Data(InversionCostFunctionsEnum)[i]));
		}

		/*Add datasetinput to element inputs*/
		this->inputs->AddInput(datasetinput);
	}
}
/*}}}*/
/*FUNCTION Tria::InputUpdateFromSolutionOneDof{{{*/
void  Tria::InputUpdateFromSolutionOneDof(IssmDouble* solution,int enum_type){

	/*Intermediary*/
	int* doflist = NULL;

	/*Fetch number of nodes for this finite element*/
	int numnodes = this->NumberofNodes();

	/*Fetch dof list and allocate solution vector*/
	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
	IssmDouble* values    = xNew<IssmDouble>(numnodes);

	/*Use the dof list to index into the solution vector: */
	for(int i=0;i<numnodes;i++){
		values[i]=solution[doflist[i]];
		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
	}

	/*Add input to the element: */
	this->inputs->AddInput(new TriaInput(enum_type,values,P1Enum));

	/*Free ressources:*/
	xDelete<IssmDouble>(values);
	xDelete<int>(doflist);
}
/*}}}*/
/*FUNCTION Tria::InputUpdateFromVector(IssmDouble* vector, int name, int type);{{{*/
void  Tria::InputUpdateFromVector(IssmDouble* vector, int name, int type){

	/*Check that name is an element input*/
	if (!IsInput(name)) return;

	int         numnodes;
	int        *doflist = NULL;
	IssmDouble *values  = NULL;

	switch(type){
	case VertexPIdEnum: 
		values = xNew<IssmDouble>(NUMVERTICES);
		for(int i=0;i<NUMVERTICES;i++){
			values[i]=vector[this->vertices[i]->Pid()];
		}
		/*update input*/
		this->inputs->AddInput(new TriaInput(name,values,P1Enum));
		break;

	case VertexSIdEnum: 
		values = xNew<IssmDouble>(NUMVERTICES);
		for(int i=0;i<NUMVERTICES;i++){
			values[i]=vector[this->vertices[i]->Sid()];
		}
		/*update input*/
		this->inputs->AddInput(new TriaInput(name,values,P1Enum));
		break;

	case NodesEnum:

		/*Get number of nodes and dof list: */
		numnodes = this->NumberofNodes();
		values   = xNew<IssmDouble>(numnodes);
		GetDofList(&doflist,NoneApproximationEnum,GsetEnum);

		for(int i=0;i<numnodes;i++){
			values[i]=vector[doflist[i]];
			if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in vector");
		}
		this->inputs->AddInput(new TriaInput(name,values,this->element_type));
		break;

	case NodeSIdEnum:

		/*Get number of nodes and dof list: */
		numnodes = this->NumberofNodes();
		values   = xNew<IssmDouble>(numnodes);

		for(int i=0;i<numnodes;i++){
			values[i]=vector[nodes[i]->Sid()];
			if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in vector");
		}
		this->inputs->AddInput(new TriaInput(name,values,this->element_type));
		break;

	default:
		_error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
	}

	/*Clean-up*/
	xDelete<int>(doflist);
	xDelete<IssmDouble>(values);

}
/*}}}*/
/*FUNCTION Tria::IsOnBed {{{*/
bool Tria::IsOnBed(){

	int meshtype;
	this->parameters->FindParam(&meshtype,MeshTypeEnum);
	switch(meshtype){
		case Mesh2DverticalEnum:
			return HasEdgeOnBed();
		case Mesh2DhorizontalEnum:
			return true;
		default: _error_("mesh "<<EnumToStringx(meshtype)<<" not supported yet");
	}
}
/*}}}*/
/*FUNCTION Tria::IsOnSurface {{{*/
bool Tria::IsOnSurface(){

	int meshtype;
	this->parameters->FindParam(&meshtype,MeshTypeEnum);
	switch(meshtype){
		case Mesh2DverticalEnum:
			return HasEdgeOnSurface();
		case Mesh2DhorizontalEnum:
			return true;
		default: _error_("mesh "<<EnumToStringx(meshtype)<<" not supported yet");
	}
}
/*}}}*/
/*FUNCTION Tria::JacobianDeterminant{{{*/
void Tria::JacobianDeterminant(IssmDouble* pJdet,IssmDouble* xyz_list,Gauss* gauss){

	_assert_(gauss->Enum()==GaussTriaEnum);
	this->GetJacobianDeterminant(pJdet,xyz_list,(GaussTria*)gauss);

}
/*}}}*/
/*FUNCTION Tria::JacobianDeterminantBase{{{*/
void Tria::JacobianDeterminantBase(IssmDouble* pJdet,IssmDouble* xyz_list_base,Gauss* gauss){

	_assert_(gauss->Enum()==GaussTriaEnum);
	this->GetSegmentJacobianDeterminant(pJdet,xyz_list_base,(GaussTria*)gauss);

}
/*}}}*/
/*FUNCTION Tria::JacobianDeterminantSurface{{{*/
void Tria::JacobianDeterminantSurface(IssmDouble* pJdet,IssmDouble* xyz_list,Gauss* gauss){

	_assert_(gauss->Enum()==GaussTriaEnum);
	this->GetSegmentJacobianDeterminant(pJdet,xyz_list,(GaussTria*)gauss);

}
/*}}}*/
/*FUNCTION Tria::JacobianDeterminantTop{{{*/
void Tria::JacobianDeterminantTop(IssmDouble* pJdet,IssmDouble* xyz_list_top,Gauss* gauss){

	_assert_(gauss->Enum()==GaussTriaEnum);
	this->GetSegmentJacobianDeterminant(pJdet,xyz_list_top,(GaussTria*)gauss);

}
/*}}}*/
/*FUNCTION Tria::HasEdgeOnBed {{{*/
bool Tria::HasEdgeOnBed(){

	IssmDouble values[NUMVERTICES];
	IssmDouble sum;

	/*Retrieve all inputs and parameters*/
	GetInputListOnVertices(&values[0],MeshVertexonbedEnum);
	sum = values[0]+values[1]+values[2];

	_assert_(sum==0. || sum==1. || sum==2.);

	if(sum==3.)  _error_("Two edges on bed not supported yet...");

	if(sum>1.){
		return true;
	}
	else{
		return false;
	}
}
/*}}}*/
/*FUNCTION Tria::HasEdgeOnSurface {{{*/
bool Tria::HasEdgeOnSurface(){

	IssmDouble values[NUMVERTICES];
	IssmDouble sum;

	/*Retrieve all inputs and parameters*/
	GetInputListOnVertices(&values[0],MeshVertexonsurfaceEnum);
	sum = values[0]+values[1]+values[2];

	_assert_(sum==0. || sum==1. || sum==2.);

	if(sum==3.)  _error_("Two edges on surface not supported yet...");

	if(sum>1.){
		return true;
	}
	else{
		return false;
	}
}
/*}}}*/
/*FUNCTION Tria::EdgeOnBedIndices{{{*/
void Tria::EdgeOnBedIndices(int* pindex1,int* pindex2){

	IssmDouble values[NUMVERTICES];
	int        indices[3][2] = {{1,2},{2,0},{0,1}};

	/*Retrieve all inputs and parameters*/
	GetInputListOnVertices(&values[0],MeshVertexonbedEnum);

	for(int i=0;i<3;i++){
		if(values[indices[i][0]] == 1. && values[indices[i][1]] == 1.){
			*pindex1 = indices[i][0];
			*pindex2 = indices[i][1];
			return;
		}
	}

	_printf_("list of vertices on bed: "<<values[0]<<" "<<values[1]<<" "<<values[2]);
	_error_("Could not find 2 vertices on bed");
}
/*}}}*/
/*FUNCTION Tria::EdgeOnSurfaceIndices{{{*/
void Tria::EdgeOnSurfaceIndices(int* pindex1,int* pindex2){

	IssmDouble values[NUMVERTICES];
	int        indices[3][2] = {{1,2},{2,0},{0,1}};

	/*Retrieve all inputs and parameters*/
	GetInputListOnVertices(&values[0],MeshVertexonsurfaceEnum);

	for(int i=0;i<3;i++){
		if(values[indices[i][0]] == 1. && values[indices[i][1]] == 1.){
			*pindex1 = indices[i][0];
			*pindex2 = indices[i][1];
			return;
		}
	}

	_printf_("list of vertices on surface: "<<values[0]<<" "<<values[1]<<" "<<values[2]);
	_error_("Could not find 2 vertices on surface");
}
/*}}}*/
/*FUNCTION Tria::EdgeOnBedIndex{{{*/
int Tria::EdgeOnBedIndex(void){

	IssmDouble values[NUMVERTICES];
	int        indices[3][2] = {{1,2},{2,0},{0,1}};

	/*Retrieve all inputs and parameters*/
	GetInputListOnVertices(&values[0],MeshVertexonbedEnum);

	for(int i=0;i<3;i++){
		if(values[indices[i][0]] == 1. && values[indices[i][1]] == 1.){
			return i;
		}
	}

	_printf_("list of vertices on bed: "<<values[0]<<" "<<values[1]<<" "<<values[2]);
	_error_("Could not find 2 vertices on bed");
}
/*}}}*/
/*FUNCTION Tria::EdgeOnSurfaceIndex{{{*/
int Tria::EdgeOnSurfaceIndex(void){

	IssmDouble values[NUMVERTICES];
	int        indices[3][2] = {{1,2},{2,0},{0,1}};

	/*Retrieve all inputs and parameters*/
	GetInputListOnVertices(&values[0],MeshVertexonsurfaceEnum);

	for(int i=0;i<3;i++){
		if(values[indices[i][0]] == 1. && values[indices[i][1]] == 1.){
			return i;
		}
	}

	_printf_("list of vertices on surface: "<<values[0]<<" "<<values[1]<<" "<<values[2]);
	_error_("Could not find 2 vertices on surface");
}
/*}}}*/
/*FUNCTION Tria::IsNodeOnShelfFromFlags {{{*/
bool   Tria::IsNodeOnShelfFromFlags(IssmDouble* flags){

	int  i;
	bool shelf=false;

	for(i=0;i<NUMVERTICES;i++){
		if (flags[vertices[i]->Pid()]<0.){
			shelf=true;
			break;
		}
	}
	return shelf;
}
/*}}}*/
/*FUNCTION Tria::NewGauss(){{{*/
Gauss* Tria::NewGauss(void){
	return new GaussTria();
}
/*}}}*/
/*FUNCTION Tria::NewGauss(int order){{{*/
Gauss* Tria::NewGauss(int order){
	return new GaussTria(order);
}
/*}}}*/
/*FUNCTION Tria::NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order){{{*/
Gauss* Tria::NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order){

	IssmDouble  area_coordinates[2][3];
	GetAreaCoordinates(&area_coordinates[0][0],xyz_list_front,xyz_list,2);
	return new GaussTria(area_coordinates,order);
}
/*}}}*/
/*FUNCTION Tria::NewGauss(int point1,IssmDouble fraction1,IssmDouble fraction2,bool mainlyfloating){{{*/
Gauss* Tria::NewGauss(int point1,IssmDouble fraction1,IssmDouble fraction2,bool mainlyfloating,int order){

	return new GaussTria(point1,fraction1,fraction2,mainlyfloating,order);
}
/*}}}*/
/*FUNCTION Tria::NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order_horiz,int order_vert){{{*/
Gauss* Tria::NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order_horiz,int order_vert){

	IssmDouble  area_coordinates[2][3];
	GetAreaCoordinates(&area_coordinates[0][0],xyz_list_front,xyz_list,2);
	return new GaussTria(area_coordinates,order_vert);
}
/*}}}*/
/*FUNCTION Tria::NewGaussBase(int order){{{*/
Gauss* Tria::NewGaussBase(int order){

	int indices[2];
	this->EdgeOnBedIndices(&indices[0],&indices[1]);
	return new GaussTria(indices[0],indices[1],order);
}
/*}}}*/
/*FUNCTION Tria::NewGaussTop(int order){{{*/
Gauss* Tria::NewGaussTop(int order){

	int indices[2];
	this->EdgeOnSurfaceIndices(&indices[0],&indices[1]);
	return new GaussTria(indices[0],indices[1],order);
}
/*}}}*/
/*FUNCTION Tria::NodalFunctions{{{*/
void Tria::NodalFunctions(IssmDouble* basis, Gauss* gauss){

	_assert_(gauss->Enum()==GaussTriaEnum);
	this->GetNodalFunctions(basis,(GaussTria*)gauss);

}
/*}}}*/
/*FUNCTION Tria::NodalFunctionsDerivatives{{{*/
void Tria::NodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){

	_assert_(gauss->Enum()==GaussTriaEnum);
	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussTria*)gauss);

}
/*}}}*/
/*FUNCTION Tria::NodalFunctionsDerivativesVelocity{{{*/
void Tria::NodalFunctionsDerivativesVelocity(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){

	_assert_(gauss->Enum()==GaussTriaEnum);
	this->GetNodalFunctionsDerivativesVelocity(dbasis,xyz_list,(GaussTria*)gauss);

}
/*}}}*/
/*FUNCTION Tria::NodalFunctionsVelocity{{{*/
void Tria::NodalFunctionsVelocity(IssmDouble* basis, Gauss* gauss){

	_assert_(gauss->Enum()==GaussTriaEnum);
	this->GetNodalFunctionsVelocity(basis,(GaussTria*)gauss);

}
/*}}}*/
/*FUNCTION Tria::NodalFunctionsPressure{{{*/
void Tria::NodalFunctionsPressure(IssmDouble* basis, Gauss* gauss){

	_assert_(gauss->Enum()==GaussTriaEnum);
	this->GetNodalFunctionsPressure(basis,(GaussTria*)gauss);

}
/*}}}*/
/*FUNCTION Tria::NodalFunctionsTensor{{{*/
void Tria::NodalFunctionsTensor(IssmDouble* basis, Gauss* gauss){

	_assert_(gauss->Enum()==GaussTriaEnum);
	this->GetNodalFunctionsTensor(basis,(GaussTria*)gauss);

}
/*}}}*/
/*FUNCTION Tria::NodalValue {{{*/
int    Tria::NodalValue(IssmDouble* pvalue, int index, int natureofdataenum){

	int         found = 0;
	IssmDouble  value;
	Input      *data  = NULL;
	GaussTria  *gauss = NULL;

	/*First, serarch the input: */
	data=inputs->GetInput(natureofdataenum); 

	/*figure out if we have the vertex id: */
	found=0;
	for(int i=0;i<NUMVERTICES;i++){
		if(index==vertices[i]->Id()){
			/*Do we have natureofdataenum in our inputs? :*/
			if(data){
				/*ok, we are good. retrieve value of input at vertex :*/
				gauss=new GaussTria(); gauss->GaussVertex(i);
				data->GetInputValue(&value,gauss);
				found=1;
				break;
			}
		}
	}

	/*clean-up*/
	delete gauss;

	if(found)*pvalue=value;
	return found;
}
/*}}}*/
/*FUNCTION Tria::NormalBase {{{*/
void Tria::NormalBase(IssmDouble* bed_normal,IssmDouble* xyz_list){

	/*Build unit outward pointing vector*/
	IssmDouble vector[2];
	IssmDouble norm;

	vector[0]=xyz_list[1*3+0] - xyz_list[0*3+0];
	vector[1]=xyz_list[1*3+1] - xyz_list[0*3+1];

	norm=sqrt(vector[0]*vector[0] + vector[1]*vector[1]);

	bed_normal[0]= + vector[1]/norm;
	bed_normal[1]= - vector[0]/norm;
}
/*}}}*/
/*FUNCTION Tria::NormalTop {{{*/
void Tria::NormalTop(IssmDouble* bed_normal,IssmDouble* xyz_list){

	/*Build unit outward pointing vector*/
	IssmDouble vector[2];
	IssmDouble norm;

	vector[0]=xyz_list[1*3+0] - xyz_list[0*3+0];
	vector[1]=xyz_list[1*3+1] - xyz_list[0*3+1];

	norm=sqrt(vector[0]*vector[0] + vector[1]*vector[1]);

	bed_normal[0]= + vector[1]/norm;
	bed_normal[1]= - vector[0]/norm;
}
/*}}}*/
/*FUNCTION Tria::VelocityInterpolation{{{*/
int Tria::VelocityInterpolation(void){
	return TriaRef::VelocityInterpolation();
}
/*}}}*/
/*FUNCTION Tria::PressureInterpolation{{{*/
int Tria::PressureInterpolation(void){
	return TriaRef::PressureInterpolation();
}
/*}}}*/
/*FUNCTION Tria::NumberofNodesPressure{{{*/
int Tria::NumberofNodesPressure(void){
	return TriaRef::NumberofNodesPressure();
}
/*}}}*/
/*FUNCTION Tria::NumberofNodesVelocity{{{*/
int Tria::NumberofNodesVelocity(void){
	return TriaRef::NumberofNodesVelocity();
}
/*}}}*/
/*FUNCTION Tria::PositiveDegreeDay{{{*/
void  Tria::PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm){

   IssmDouble agd[NUMVERTICES];             // surface mass balance
   IssmDouble monthlytemperatures[NUMVERTICES][12],monthlyprec[NUMVERTICES][12];
   IssmDouble h[NUMVERTICES],s[NUMVERTICES];
   IssmDouble rho_water,rho_ice,desfac,s0p;

   /*Recover monthly temperatures and precipitation*/
   Input*     input=inputs->GetInput(SurfaceforcingsMonthlytemperaturesEnum); _assert_(input);
   Input*     input2=inputs->GetInput(SurfaceforcingsPrecipitationEnum); _assert_(input2);
   GaussTria* gauss=new GaussTria();
   IssmDouble time,yts;
   this->parameters->FindParam(&time,TimeEnum);
   this->parameters->FindParam(&yts,ConstantsYtsEnum);
   for(int month=0;month<12;month++) {
     for(int iv=0;iv<NUMVERTICES;iv++) {
       gauss->GaussVertex(iv);
       input->GetInputValue(&monthlytemperatures[iv][month],gauss,time+month/12.*yts);
       monthlytemperatures[iv][month]=monthlytemperatures[iv][month]-273.15; // conversion from Kelvin to celcius
       input2->GetInputValue(&monthlyprec[iv][month],gauss,time+month/12.*yts);
       monthlyprec[iv][month]=monthlyprec[iv][month]*yts; // convertion in m/y
     }
   }

  /*Recover info at the vertices: */
  GetInputListOnVertices(&h[0],ThicknessEnum);
  GetInputListOnVertices(&s[0],SurfaceEnum);

  /*Get material parameters :*/
  rho_ice=matpar->GetRhoIce();
  rho_water=matpar->GetRhoFreshwater();

  /*Get desertification effect parameters*/
  desfac=matpar->GetDesFac();
  s0p=matpar->GetS0p();

   /*measure the surface mass balance*/
   for (int iv = 0; iv<NUMVERTICES; iv++){
     agd[iv]=PddSurfaceMassBlance(&monthlytemperatures[iv][0], &monthlyprec[iv][0], pdds, pds, signorm, yts, h[iv], s[iv], rho_ice, rho_water, desfac, s0p);
   }

   /*Update inputs*/    
   this->inputs->AddInput(new TriaInput(SurfaceforcingsMassBalanceEnum,&agd[0],P1Enum));
   // this->inputs->AddInput(new TriaVertexInput(ThermalSpcTemperatureEnum,&Tsurf[0]));

	/*clean-up*/
	delete gauss;
}
/*}}}*/
/*FUNCTION Tria::ReduceMatrices {{{*/
void Tria::ReduceMatrices(ElementMatrix* Ke,ElementVector* pe){

	/*Static condensation if requested*/
	if(pe){
		if(this->element_type==MINIcondensedEnum){
			int indices[2]={6,7};
			pe->StaticCondensation(Ke,2,&indices[0]);
		}
		else if(this->element_type==P1bubblecondensedEnum){
			int size   = nodes[3]->GetNumberOfDofs(NoneApproximationEnum,GsetEnum);
			int offset = 0;
			for(int i=0;i<3;i++) offset+=nodes[i]->GetNumberOfDofs(NoneApproximationEnum,GsetEnum);
			int* indices=xNew<int>(size);
			for(int i=0;i<size;i++) indices[i] = offset+i;
			pe->StaticCondensation(Ke,size,indices);
			xDelete<int>(indices);
		}
	}

	if(Ke){
		if(this->element_type==MINIcondensedEnum){
			int indices[2]={6,7};
			Ke->StaticCondensation(2,&indices[0]);
		}
		else if(this->element_type==P1bubblecondensedEnum){
			int size   = nodes[3]->GetNumberOfDofs(NoneApproximationEnum,GsetEnum);
			int offset = 0;
			for(int i=0;i<3;i++) offset+=nodes[i]->GetNumberOfDofs(NoneApproximationEnum,GsetEnum);
			int* indices=xNew<int>(size);
			for(int i=0;i<size;i++) indices[i] = offset+i;
			Ke->StaticCondensation(size,indices);
			xDelete<int>(indices);
		}
	}


}
/*}}}*/
/*FUNCTION Tria::ResetFSBasalBoundaryCondition{{{*/
void  Tria::ResetFSBasalBoundaryCondition(void){

	int numnodes = this->NumberofNodesVelocity();

	int          approximation;
	IssmDouble*  vertexonbed= NULL;
	IssmDouble   slope,groundedice;
	IssmDouble   xz_plane[6];

	/*For FS only: we want the CS to be tangential to the bedrock*/
	inputs->GetInputValue(&approximation,ApproximationEnum);
	if(!HasNodeOnBed() ||  approximation!=FSApproximationEnum) return;

	//printf("element number %i \n",this->id);
	/*Get inputs*/
	Input* slope_input=inputs->GetInput(BedSlopeXEnum);                             _assert_(slope_input);
	Input* groundedicelevelset_input=inputs->GetInput(MaskGroundediceLevelsetEnum); _assert_(groundedicelevelset_input);
	vertexonbed = xNew<IssmDouble>(numnodes);
	this->GetInputListOnNodesVelocity(&vertexonbed[0],MeshVertexonbedEnum);

	/*Loop over basal nodes and update their CS*/
	GaussTria* gauss = new GaussTria();
	for(int i=0;i<this->NumberofNodesVelocity();i++){

		if(vertexonbed[i]==1){
			gauss->GaussNode(this->VelocityInterpolation(),i);
			slope_input->GetInputValue(&slope,gauss);
			groundedicelevelset_input->GetInputValue(&groundedice,gauss);
			IssmDouble theta = atan(slope);

			/*New X axis                  New Z axis*/
			xz_plane[0]=cos(theta);       xz_plane[3]=0.;  
			xz_plane[1]=sin(theta);       xz_plane[4]=0.;  
			xz_plane[2]=0.;               xz_plane[5]=1.;          
			if(groundedice>0){
				this->nodes[i]->DofInSSet(1); //vy
			}
			else{
				this->nodes[i]->DofInFSet(1); //vy
			}

			XZvectorsToCoordinateSystem(&this->nodes[i]->coord_system[0][0],&xz_plane[0]);
		}
	}

	/*cleanup*/
	xDelete<IssmDouble>(vertexonbed);
	delete gauss;
}
/*}}}*/
/*FUNCTION Tria::SetClone {{{*/
void  Tria::SetClone(int* minranks){

	_error_("not implemented yet");
}
/*}}}*/
/*FUNCTION Tria::SmbGradients{{{*/
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));
}
/*}}}*/
/*FUNCTION Tria::SpawnSeg {{{*/
Seg*  Tria::SpawnSeg(int index1,int index2){

	int analysis_counter;

	/*go into parameters and get the analysis_counter: */
	this->parameters->FindParam(&analysis_counter,AnalysisCounterEnum);

	/*Create Seg*/
	Seg* seg=new Seg();
	seg->id=this->id;
	seg->inputs=(Inputs*)this->inputs->SpawnSegInputs(index1,index2);
	seg->parameters=this->parameters;
	seg->element_type=P1Enum; //Only P1 CG for now (TO BE CHANGED)
	this->SpawnSegHook(dynamic_cast<ElementHook*>(seg),index1,index2);

	/*Spawn material*/
	seg->material=(Material*)this->material->copy2(seg);

	/*recover nodes, material and matpar: */
	seg->nodes    = (Node**)seg->hnodes[analysis_counter]->deliverp();
	seg->vertices = (Vertex**)seg->hvertices->deliverp();
	seg->matpar   = (Matpar*)seg->hmatpar->delivers();

	/*Return new Seg*/
	return seg;
}
/*}}}*/
/*FUNCTION Tria::SpawnBasalElement{{{*/
Element*  Tria::SpawnBasalElement(void){

	int index1,index2;
	int meshtype;

	this->parameters->FindParam(&meshtype,MeshTypeEnum);
	switch(meshtype){
		case Mesh2DhorizontalEnum:
			return this;
		case Mesh2DverticalEnum:
			_assert_(HasEdgeOnBed());
			this->EdgeOnBedIndices(&index1,&index2);
			return SpawnSeg(index1,index2);
		default:
			_error_("not implemented yet");
	}
}
/*}}}*/
/*FUNCTION Tria::SpawnTopElement{{{*/
Element*  Tria::SpawnTopElement(void){

	int index1,index2;
	int meshtype;

	this->parameters->FindParam(&meshtype,MeshTypeEnum);
	switch(meshtype){
		case Mesh2DhorizontalEnum:
			return this;
		case Mesh2DverticalEnum:
			_assert_(HasEdgeOnSurface());
			this->EdgeOnSurfaceIndices(&index1,&index2);
			return SpawnSeg(index2,index1); //reverse order
		default:
			_error_("not implemented yet");
	}
}
/*}}}*/
/*FUNCTION Tria::SetCurrentConfiguration {{{*/
void  Tria::SetCurrentConfiguration(Elements* elementsin, Loads* loadsin, Nodes* nodesin, Materials* materialsin, Parameters* parametersin){

	/*go into parameters and get the analysis_counter: */
	int analysis_counter;
	parametersin->FindParam(&analysis_counter,AnalysisCounterEnum);

	/*Get Element type*/
	this->element_type=this->element_type_list[analysis_counter];

	/*Pick up nodes*/
	if(this->hnodes[analysis_counter]) this->nodes=(Node**)this->hnodes[analysis_counter]->deliverp();
	else this->nodes=NULL;

}
/*}}}*/
/*FUNCTION Tria::SurfaceArea {{{*/
IssmDouble Tria::SurfaceArea(void){

	IssmDouble S;
	IssmDouble normal[3];
	IssmDouble v13[3],v23[3];
	IssmDouble xyz_list[NUMVERTICES][3];

	/*If on water, return 0: */
	if(!IsIceInElement()) return 0.;

	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);

	for(int i=0;i<3;i++){
		v13[i]=xyz_list[0][i]-xyz_list[2][i];
		v23[i]=xyz_list[1][i]-xyz_list[2][i];
	}

	normal[0]=v13[1]*v23[2]-v13[2]*v23[1];
	normal[1]=v13[2]*v23[0]-v13[0]*v23[2];
	normal[2]=v13[0]*v23[1]-v13[1]*v23[0];

	S = 0.5 * sqrt(normal[0]*normal[0] + normal[1]*normal[1] + normal[2]*normal[2]);

	/*Return: */
	return S;
}
/*}}}*/
/*FUNCTION Tria::TimeAdapt{{{*/
IssmDouble  Tria::TimeAdapt(void){

	/*intermediary: */
	int    i;
	IssmDouble C,dt;
	IssmDouble dx,dy;
	IssmDouble maxx,minx;
	IssmDouble maxy,miny;
	IssmDouble maxabsvx,maxabsvy;
	IssmDouble xyz_list[NUMVERTICES][3];

	/*get CFL coefficient:*/
	this->parameters->FindParam(&C,TimesteppingCflCoefficientEnum);

	/*Get for Vx and Vy, the max of abs value: */
	this->MaxAbsVx(&maxabsvx);
	this->MaxAbsVy(&maxabsvy);

	/* Get node coordinates and dof list: */
	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);

	minx=xyz_list[0][0];
	maxx=xyz_list[0][0];
	miny=xyz_list[0][1];
	maxy=xyz_list[0][1];

	for(i=1;i<NUMVERTICES;i++){
		if (xyz_list[i][0]<minx)minx=xyz_list[i][0];
		if (xyz_list[i][0]>maxx)maxx=xyz_list[i][0];
		if (xyz_list[i][1]<miny)miny=xyz_list[i][1];
		if (xyz_list[i][1]>maxy)maxy=xyz_list[i][1];
	}
	dx=maxx-minx;
	dy=maxy-miny;

	/*CFL criterion: */
	dt=C/(maxabsvy/dx+maxabsvy/dy);

	return dt;
}
/*}}}*/
/*FUNCTION Tria::Update{{{*/
void Tria::Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finiteelement_type){

	/*Intermediaries*/
	int  numnodes;
	int* tria_node_ids = NULL;

	/*Checks if debuging*/
	_assert_(iomodel->elements);

	/*Recover element type*/
	this->SetElementType(finiteelement_type,analysis_counter);

	/*Recover nodes ids needed to initialize the node hook.*/
	switch(finiteelement_type){
		case P1Enum:
			numnodes        = 3;
			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];
			break;
		case P1DGEnum:
			numnodes        = 3;
			tria_node_ids   = xNew<int>(numnodes);
			tria_node_ids[0]=iomodel->nodecounter+3*index+1;
			tria_node_ids[1]=iomodel->nodecounter+3*index+2;
			tria_node_ids[2]=iomodel->nodecounter+3*index+3;
			break;
		case P1bubbleEnum: case P1bubblecondensedEnum:
			numnodes        = 4;
			tria_node_ids   = xNew<int>(numnodes);
			tria_node_ids[0]=iomodel->nodecounter+iomodel->elements[3*index+0];
			tria_node_ids[1]=iomodel->nodecounter+iomodel->elements[3*index+1];
			tria_node_ids[2]=iomodel->nodecounter+iomodel->elements[3*index+2];
			tria_node_ids[3]=iomodel->nodecounter+iomodel->numberofvertices+index+1;
			break;
		case P2Enum:
			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 P1P1Enum: case P1P1GLSEnum:
			numnodes        = 6;
			tria_node_ids   = xNew<int>(numnodes);
			tria_node_ids[0]=iomodel->nodecounter+iomodel->elements[3*index+0];
			tria_node_ids[1]=iomodel->nodecounter+iomodel->elements[3*index+1];
			tria_node_ids[2]=iomodel->nodecounter+iomodel->elements[3*index+2];

			tria_node_ids[3]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elements[3*index+0];
			tria_node_ids[4]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elements[3*index+1];
			tria_node_ids[5]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elements[3*index+2];
			break;
		case MINIEnum: case MINIcondensedEnum:
			numnodes       = 7;
			tria_node_ids  = xNew<int>(numnodes);
			tria_node_ids[0]=iomodel->nodecounter+iomodel->elements[3*index+0];
			tria_node_ids[1]=iomodel->nodecounter+iomodel->elements[3*index+1];
			tria_node_ids[2]=iomodel->nodecounter+iomodel->elements[3*index+2];
			tria_node_ids[3]=iomodel->nodecounter+iomodel->numberofvertices+index+1;

			tria_node_ids[4]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+iomodel->elements[3*index+0];
			tria_node_ids[5]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+iomodel->elements[3*index+1];
			tria_node_ids[6]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+iomodel->elements[3*index+2];
			break;
		case TaylorHoodEnum:
		case XTaylorHoodEnum:
			numnodes        = 9;
			tria_node_ids   = xNew<int>(numnodes);
			tria_node_ids[0]=iomodel->nodecounter+iomodel->elements[3*index+0];
			tria_node_ids[1]=iomodel->nodecounter+iomodel->elements[3*index+1];
			tria_node_ids[2]=iomodel->nodecounter+iomodel->elements[3*index+2];
			tria_node_ids[3]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+0]+1;
			tria_node_ids[4]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+1]+1;
			tria_node_ids[5]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+2]+1;

			tria_node_ids[6]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elements[3*index+0];
			tria_node_ids[7]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elements[3*index+1];
			tria_node_ids[8]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elements[3*index+2];
			break;
		default:
			_error_("Finite element "<<EnumToStringx(finiteelement_type)<<" not supported yet");
	}

	/*hooks: */
	this->SetHookNodes(tria_node_ids,numnodes,analysis_counter); this->nodes=NULL;
	xDelete<int>(tria_node_ids);

	/*Fill with IoModel*/
	this->InputUpdateFromIoModel(index,iomodel);
}
/*}}}*/
/*FUNCTION Tria::UpdateConstraintsExtrudeFromBase{{{*/
void  Tria::UpdateConstraintsExtrudeFromBase(void){

	if(!HasEdgeOnBed()) return;

	int        extrusioninput;
	IssmDouble value,isonbed;

	this->parameters->FindParam(&extrusioninput,InputToExtrudeEnum);
	Input* input = inputs->GetInput(extrusioninput);      _assert_(input);
	Input* onbed = inputs->GetInput(MeshVertexonbedEnum); _assert_(onbed);

	GaussTria* gauss=new GaussTria();
	for(int iv=0;iv<this->NumberofNodes();iv++){
		gauss->GaussNode(this->element_type,iv);
		onbed->GetInputValue(&isonbed,gauss);
		if(isonbed==1.){
			input->GetInputValue(&value,gauss);
			this->nodes[iv]->ApplyConstraint(1,value);
		}
	}
	delete gauss;

}
/*}}}*/
/*FUNCTION Tria::UpdateConstraintsExtrudeFromTop{{{*/
void  Tria::UpdateConstraintsExtrudeFromTop(void){

	if(!HasEdgeOnSurface()) return;

	int extrusioninput;
	int indices[2];
	IssmDouble value;

	this->parameters->FindParam(&extrusioninput,InputToExtrudeEnum);
	Input* input = inputs->GetInput(extrusioninput); _assert_(input);
	this->EdgeOnSurfaceIndices(&indices[0],&indices[1]);

	GaussTria* gauss=new GaussTria();
	for(int i=0;i<2;i++){
		gauss->GaussNode(P1Enum,indices[i]);
		input->GetInputValue(&value,gauss);
		this->nodes[indices[i]]->ApplyConstraint(1,value);
	}
	delete gauss;

}
/*}}}*/
/*FUNCTION Tria::ValueP1OnGauss{{{*/
void Tria::ValueP1OnGauss(IssmDouble* pvalue,IssmDouble* values,Gauss* gauss){
	TriaRef::GetInputValue(pvalue,values,gauss,P1Enum);
}
/*}}}*/
/*FUNCTION Tria::ValueP1DerivativesOnGauss{{{*/
void Tria::ValueP1DerivativesOnGauss(IssmDouble* dvalue,IssmDouble* values,IssmDouble* xyz_list,Gauss* gauss){
	TriaRef::GetInputDerivativeValue(dvalue,values,xyz_list,gauss);
}
/*}}}*/
/*FUNCTION Tria::VertexConnectivity{{{*/
int Tria::VertexConnectivity(int vertexindex){
	_assert_(this->vertices);
	return this->vertices[vertexindex]->Connectivity();
}
/*}}}*/
/*FUNCTION Tria::IsZeroLevelset{{{*/
bool Tria::IsZeroLevelset(int levelset_enum){

	bool iszerols;
	IssmDouble ls[NUMVERTICES];

	/*Retrieve all inputs and parameters*/
	GetInputListOnVertices(&ls[0],levelset_enum);

	/*If the level set is awlays <0, there is no ice front here*/
	iszerols= false;
	if(IsIceInElement()){
		if(ls[0]*ls[1]<0. || ls[0]*ls[2]<0. || (ls[0]*ls[1]*ls[2]==0. && ls[0]*ls[1]+ls[0]*ls[2]+ls[1]*ls[2]<=0.)){
			iszerols = true;
		}
	}

	return iszerols;
}
/*}}}*/
bool Tria::IsIcefront(void){/*{{{*/

	bool isicefront;
	int i,nrice;
   IssmDouble ls[NUMVERTICES];

	/*Retrieve all inputs and parameters*/
	GetInputListOnVertices(&ls[0],MaskIceLevelsetEnum);

	/* If only one vertex has ice, there is an ice front here */
	isicefront=false;
	if(IsIceInElement()){
		nrice=0;       
		for(i=0;i<NUMVERTICES;i++)
			if(ls[i]<0.) nrice++;
		if(nrice==1) isicefront= true;
	}
	return isicefront;
}/*}}}*/
/*FUNCTION Tria::AverageOntoPartition {{{*/
void  Tria::AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part){

	bool       already = false;
	int        i,j;
	int        partition[NUMVERTICES];
	int        offsetsid[NUMVERTICES];
	int        offsetdof[NUMVERTICES];
	IssmDouble area;
	IssmDouble mean;

	/*First, get the area: */
	area=this->GetArea();

	/*Figure out the average for this element: */
	this->GetVerticesSidList(&offsetsid[0]);
	this->GetVertexPidList(&offsetdof[0]);
	mean=0;
	for(i=0;i<NUMVERTICES;i++){
		partition[i]=reCast<int>(qmu_part[offsetsid[i]]);
		mean=mean+1.0/NUMVERTICES*vertex_response[offsetdof[i]];
	}

	/*Add contribution: */
	for(i=0;i<NUMVERTICES;i++){
		already=false;
		for(j=0;j<i;j++){
			if (partition[i]==partition[j]){
				already=true;
				break;
			}
		}
		if(!already){
			partition_contributions->SetValue(partition[i],mean*area,ADD_VAL);
			partition_areas->SetValue(partition[i],area,ADD_VAL);
		};
	}
}
/*}}}*/
/*FUNCTION Tria::IceVolume {{{*/
IssmDouble Tria::IceVolume(void){

	/*The volume of a troncated prism is base * 1/3 sum(length of edges)*/
	IssmDouble base,surface,bed;
	IssmDouble xyz_list[NUMVERTICES][3];

	if(!IsIceInElement())return 0;

	/*First get back the area of the base*/
	base=this->GetArea();

	/*Now get the average height*/
	Input* surface_input = inputs->GetInput(SurfaceEnum); _assert_(surface_input);
	Input* base_input     = inputs->GetInput(BaseEnum);     _assert_(base_input);
	surface_input->GetInputAverage(&surface);
	base_input->GetInputAverage(&bed);

	/*Return: */
	int meshtype;
	parameters->FindParam(&meshtype,MeshTypeEnum);
	if(meshtype==Mesh2DverticalEnum){
	  return base;
	}
	else{
	  return base*(surface-bed);
	}
}
/*}}}*/
/*FUNCTION Tria::IceVolumeAboveFloatation {{{*/
IssmDouble Tria::IceVolumeAboveFloatation(void){

	/*The volume above floatation: H + rho_water/rho_ice * bathymetry */
	IssmDouble rho_ice,rho_water;
	IssmDouble base,surface,bed,bathymetry;
	IssmDouble xyz_list[NUMVERTICES][3];

	if(!IsIceInElement() || IsFloating())return 0;

	rho_ice=matpar->GetRhoIce();
	rho_water=matpar->GetRhoWater();
	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);

	/*First calculate the area of the base (cross section triangle)
	 * http://en.wikipedia.org/wiki/Triangle
	 * base = 1/2 abs((xA-xC)(yB-yA)-(xA-xB)(yC-yA))*/
	base = 1./2. * fabs((xyz_list[0][0]-xyz_list[2][0])*(xyz_list[1][1]-xyz_list[0][1]) - (xyz_list[0][0]-xyz_list[1][0])*(xyz_list[2][1]-xyz_list[0][1]));

	/*Now get the average height and bathymetry*/
	Input* surface_input    = inputs->GetInput(SurfaceEnum);    _assert_(surface_input);
	Input* base_input        = inputs->GetInput(BaseEnum);        _assert_(base_input);
	Input* bed_input = inputs->GetInput(BedEnum); _assert_(bed_input);
	surface_input->GetInputAverage(&surface);
	base_input->GetInputAverage(&bed);
	bed_input->GetInputAverage(&bathymetry);
	
	/*Return: */
	return base*(surface-bed+min(rho_water/rho_ice*bathymetry,0.));
}
/*}}}*/
/*FUNCTION Tria::MassFlux {{{*/
IssmDouble Tria::MassFlux( IssmDouble x1, IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id){

	int        meshtype;
	IssmDouble mass_flux=0.;
	IssmDouble xyz_list[NUMVERTICES][3];
	IssmDouble normal[2];
	IssmDouble length,rho_ice;
	IssmDouble h1,h2;
	IssmDouble vx1,vx2,vy1,vy2;
	GaussTria* gauss_1=NULL;
	GaussTria* gauss_2=NULL;

	/*Get material parameters :*/
	rho_ice=matpar->GetRhoIce();

	/*First off, check that this segment belongs to this element: */
	if (segment_id!=this->id)_error_("error message: segment with id " << segment_id << " does not belong to element with id:" << this->id);

	/*Get xyz list: */
	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);

	/*get area coordinates of 0 and 1 locations: */
	gauss_1=new GaussTria();
	gauss_1->GaussFromCoords(x1,y1,&xyz_list[0][0]);
	gauss_2=new GaussTria();
	gauss_2->GaussFromCoords(x2,y2,&xyz_list[0][0]);

	normal[0]=cos(atan2(x1-x2,y2-y1));
	normal[1]=sin(atan2(x1-x2,y2-y1));

	length=sqrt(pow(x2-x1,2)+pow(y2-y1,2));

	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
	this->parameters->FindParam(&meshtype,MeshTypeEnum);
	Input* vx_input=NULL;
	Input* vy_input=NULL;
	if(meshtype==Mesh2DhorizontalEnum){
		vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
		vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
	}
	else{
		vx_input=inputs->GetInput(VxAverageEnum); _assert_(vx_input);
		vy_input=inputs->GetInput(VyAverageEnum); _assert_(vy_input);
	}

	thickness_input->GetInputValue(&h1, gauss_1);
	thickness_input->GetInputValue(&h2, gauss_2);
	vx_input->GetInputValue(&vx1,gauss_1);
	vx_input->GetInputValue(&vx2,gauss_2);
	vy_input->GetInputValue(&vy1,gauss_1);
	vy_input->GetInputValue(&vy2,gauss_2);

	mass_flux= rho_ice*length*(  
				(ONETHIRD*(h1-h2)*(vx1-vx2)+0.5*h2*(vx1-vx2)+0.5*(h1-h2)*vx2+h2*vx2)*normal[0]+
				(ONETHIRD*(h1-h2)*(vy1-vy2)+0.5*h2*(vy1-vy2)+0.5*(h1-h2)*vy2+h2*vy2)*normal[1]
				);

	/*clean up and return:*/
	delete gauss_1;
	delete gauss_2;
	return mass_flux;
}
/*}}}*/
/*FUNCTION Tria::MassFlux {{{*/
IssmDouble Tria::MassFlux( IssmDouble* segment){

	int        meshtype;
	IssmDouble mass_flux=0.;
	IssmDouble xyz_list[NUMVERTICES][3];
	IssmDouble normal[2];
	IssmDouble length,rho_ice;
	IssmDouble x1,y1,x2,y2,h1,h2;
	IssmDouble vx1,vx2,vy1,vy2;
	GaussTria* gauss_1=NULL;
	GaussTria* gauss_2=NULL;

	/*Get material parameters :*/
	rho_ice=matpar->GetRhoIce();

	/*First off, check that this segment belongs to this element: */
	if (reCast<int>(*(segment+4))!=this->id)_error_("error message: segment with id " << reCast<int>(*(segment+4)) << " does not belong to element with id:" << this->id);

	/*Recover segment node locations: */
	x1=*(segment+0); y1=*(segment+1); x2=*(segment+2); y2=*(segment+3);

	/*Get xyz list: */
	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);

	/*get area coordinates of 0 and 1 locations: */
	gauss_1=new GaussTria();
	gauss_1->GaussFromCoords(x1,y1,&xyz_list[0][0]);
	gauss_2=new GaussTria();
	gauss_2->GaussFromCoords(x2,y2,&xyz_list[0][0]);

	normal[0]=cos(atan2(x1-x2,y2-y1));
	normal[1]=sin(atan2(x1-x2,y2-y1));

	length=sqrt(pow(x2-x1,2)+pow(y2-y1,2));

	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
	this->parameters->FindParam(&meshtype,MeshTypeEnum);
	Input* vx_input=NULL;
	Input* vy_input=NULL;
	if(meshtype==Mesh2DhorizontalEnum){
		vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
		vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
	}
	else{
		vx_input=inputs->GetInput(VxAverageEnum); _assert_(vx_input);
		vy_input=inputs->GetInput(VyAverageEnum); _assert_(vy_input);
	}

	thickness_input->GetInputValue(&h1, gauss_1);
	thickness_input->GetInputValue(&h2, gauss_2);
	vx_input->GetInputValue(&vx1,gauss_1);
	vx_input->GetInputValue(&vx2,gauss_2);
	vy_input->GetInputValue(&vy1,gauss_1);
	vy_input->GetInputValue(&vy2,gauss_2);

	mass_flux= rho_ice*length*(  
				(ONETHIRD*(h1-h2)*(vx1-vx2)+0.5*h2*(vx1-vx2)+0.5*(h1-h2)*vx2+h2*vx2)*normal[0]+
				(ONETHIRD*(h1-h2)*(vy1-vy2)+0.5*h2*(vy1-vy2)+0.5*(h1-h2)*vy2+h2*vy2)*normal[1]
				);

	/*clean up and return:*/
	delete gauss_1;
	delete gauss_2;
	return mass_flux;
}
/*}}}*/
/*FUNCTION Tria::MaxAbsVx{{{*/
void  Tria::MaxAbsVx(IssmDouble* pmaxabsvx){

	/*Get maximum:*/
	IssmDouble maxabsvx=this->inputs->MaxAbs(VxEnum);

	/*Assign output pointers:*/
	*pmaxabsvx=maxabsvx;
}
/*}}}*/
/*FUNCTION Tria::MaxAbsVy{{{*/
void  Tria::MaxAbsVy(IssmDouble* pmaxabsvy){

	/*Get maximum:*/
	IssmDouble maxabsvy=this->inputs->MaxAbs(VyEnum);

	/*Assign output pointers:*/
	*pmaxabsvy=maxabsvy;
}
/*}}}*/
/*FUNCTION Tria::MaxAbsVz{{{*/
void  Tria::MaxAbsVz(IssmDouble* pmaxabsvz){

	/*Get maximum:*/
	IssmDouble maxabsvz=this->inputs->MaxAbs(VzEnum);

	/*Assign output pointers:*/
	*pmaxabsvz=maxabsvz;
}
/*}}}*/
/*FUNCTION Tria::MaxVel{{{*/
void  Tria::MaxVel(IssmDouble* pmaxvel){

	/*Get maximum:*/
	IssmDouble maxvel=this->inputs->Max(VelEnum);

	/*Assign output pointers:*/
	*pmaxvel=maxvel;
}
/*}}}*/
/*FUNCTION Tria::MaxVx{{{*/
void  Tria::MaxVx(IssmDouble* pmaxvx){

	/*Get maximum:*/
	IssmDouble maxvx=this->inputs->Max(VxEnum);

	/*Assign output pointers:*/
	*pmaxvx=maxvx;
}
/*}}}*/
/*FUNCTION Tria::MaxVy{{{*/
void  Tria::MaxVy(IssmDouble* pmaxvy){

	/*Get maximum:*/
	IssmDouble maxvy=this->inputs->Max(VyEnum);

	/*Assign output pointers:*/
	*pmaxvy=maxvy;

}
/*}}}*/
/*FUNCTION Tria::MaxVz{{{*/
void  Tria::MaxVz(IssmDouble* pmaxvz){

	/*Get maximum:*/
	IssmDouble maxvz=this->inputs->Max(VzEnum);

	/*Assign output pointers:*/
	*pmaxvz=maxvz;
}
/*}}}*/
/*FUNCTION Tria::MinVel{{{*/
void  Tria::MinVel(IssmDouble* pminvel){

	/*Get minimum:*/
	IssmDouble minvel=this->inputs->Min(VelEnum);

	/*Assign output pointers:*/
	*pminvel=minvel;
}
/*}}}*/
/*FUNCTION Tria::MinVx{{{*/
void  Tria::MinVx(IssmDouble* pminvx){

	/*Get minimum:*/
	IssmDouble minvx=this->inputs->Min(VxEnum);

	/*Assign output pointers:*/
	*pminvx=minvx;
}
/*}}}*/
/*FUNCTION Tria::MinVy{{{*/
void  Tria::MinVy(IssmDouble* pminvy){

	/*Get minimum:*/
	IssmDouble minvy=this->inputs->Min(VyEnum);

	/*Assign output pointers:*/
	*pminvy=minvy;
}
/*}}}*/
/*FUNCTION Tria::MinVz{{{*/
void  Tria::MinVz(IssmDouble* pminvz){

	/*Get minimum:*/
	IssmDouble minvz=this->inputs->Min(VzEnum);

	/*Assign output pointers:*/
	*pminvz=minvz;
}
/*}}}*/
/*FUNCTION Tria::ElementResponse{{{*/
void Tria::ElementResponse(IssmDouble* presponse,int response_enum){

	switch(response_enum){
		case MaterialsRheologyBbarEnum:
			*presponse=this->material->GetBbar();
			break;

		case VelEnum:{

			/*Get input:*/
			IssmDouble vel;
			Input* vel_input;

			vel_input=this->inputs->GetInput(VelEnum); _assert_(vel_input);
			vel_input->GetInputAverage(&vel);

			/*Assign output pointers:*/
			*presponse=vel;}
			break;
		default:  
			_error_("Response type " << EnumToStringx(response_enum) << " not supported yet!");
	}

}
/*}}}*/
/*FUNCTION Tria::TotalSmb {{{*/
IssmDouble Tria::TotalSmb(void){

	/*The smb[kg yr-1] of one element is area[m2] * smb [kg m^-2 yr^-1]*/
	IssmDouble base,smb,rho_ice;
	IssmDouble Total_Smb=0;
	IssmDouble xyz_list[NUMVERTICES][3];

	/*Get material parameters :*/
	rho_ice=matpar->GetRhoIce();

   if(!IsIceInElement())return 0;

	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);

	/*First calculate the area of the base (cross section triangle)
	 * http://en.wikipedia.org/wiki/Triangle
	 * base = 1/2 abs((xA-xC)(yB-yA)-(xA-xB)(yC-yA))*/
	base = 1./2. * fabs((xyz_list[0][0]-xyz_list[2][0])*(xyz_list[1][1]-xyz_list[0][1]) - (xyz_list[0][0]-xyz_list[1][0])*(xyz_list[2][1]-xyz_list[0][1]));	// area of element in m2

	/*Now get the average SMB over the element*/
	Input* smb_input = inputs->GetInput(SurfaceforcingsMassBalanceEnum); _assert_(smb_input);
	smb_input->GetInputAverage(&smb);																								// average smb on element in m ice s-1
   Total_Smb=rho_ice*base*smb;																											// smb on element in kg s-1

	/*Return: */
	return Total_Smb;
}
/*}}}*/
/*FUNCTION Tria::MisfitArea{{{*/
IssmDouble Tria::MisfitArea(int weightsenum){

	/*Intermediaries*/
	IssmDouble weight;
	IssmDouble Jdet;
	IssmDouble Jelem = 0;
	IssmDouble xyz_list[NUMVERTICES][3];
	GaussTria *gauss = NULL;

	/*If on water, return 0: */
	if(!IsIceInElement())return 0;

	/*Retrieve all inputs we will be needing: */
	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
	Input* weights_input     =inputs->GetInput(weightsenum);     _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);

		/* Get Jacobian determinant: */
		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);

		/*Get parameters at gauss point*/
		weights_input->GetInputValue(&weight,gauss);

		/*compute misfit between model and observation */
		Jelem+=Jdet*weight*gauss->weight;
	}

	/* clean up and Return: */
	delete gauss;
	return Jelem;
}
/*}}}*/
/*FUNCTION Tria::Misfit{{{*/
IssmDouble Tria::Misfit(int modelenum,int observationenum,int weightsenum){

	/*Intermediaries*/
	IssmDouble model,observation,weight;
	IssmDouble Jdet;
	IssmDouble Jelem = 0;
	IssmDouble xyz_list[NUMVERTICES][3];
	GaussTria *gauss = NULL;

	/*If on water, return 0: */
	if(!IsIceInElement())return 0;

	/*Retrieve all inputs we will be needing: */
	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
	Input* model_input=inputs->GetInput(modelenum);   _assert_(model_input);
	Input* observation_input=inputs->GetInput(observationenum);_assert_(observation_input);
	Input* weights_input     =inputs->GetInput(weightsenum);     _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);

		/* Get Jacobian determinant: */
		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);

		/*Get parameters at gauss point*/
		model_input->GetInputValue(&model,gauss);
		observation_input->GetInputValue(&observation,gauss);
		weights_input->GetInputValue(&weight,gauss);

		/*compute misfit between model and observation */
		Jelem+=0.5*(model-observation)*(model-observation)*Jdet*weight*gauss->weight;
	}

	/* clean up and Return: */
	delete gauss;
	return Jelem;
}
/*}}}*/

#ifdef _HAVE_GIA_
/*FUNCTION Tria::GiaDeflection {{{*/
void Tria::GiaDeflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt,IssmDouble* x, IssmDouble* y){

	int i;
	int gsize;
	IssmDouble xi,yi,ri,re,area;
	IssmDouble x0,y0;
	IssmDouble xyz_list[NUMVERTICES][3];

	/*thickness averages: */
	IssmDouble* hes=NULL;
	IssmDouble* times=NULL;
	IssmDouble  currenttime;
	int         numtimes;
	Input* thickness_input=NULL;

	/*gia solution parameters:*/
	int cross_section_shape=0;

	/*gia material parameters: */
	IssmDouble lithosphere_shear_modulus;
	IssmDouble lithosphere_density;
	IssmDouble mantle_shear_modulus;
	IssmDouble mantle_density;
	Input* mantle_viscosity_input=NULL;
	IssmDouble mantle_viscosity;
	Input* lithosphere_thickness_input=NULL;
	IssmDouble lithosphere_thickness;

	/*ice properties: */
	IssmDouble rho_ice;

	/*constants: */
	IssmDouble yts;

	/*output: */
	IssmDouble  wi;
	IssmDouble  dwidt;

	/*arguments to GiaDeflectionCorex: */
	GiaDeflectionCoreArgs arguments;

	/*how many dofs are we working with here? */
	this->parameters->FindParam(&gsize,MeshNumberofverticesEnum);
	this->parameters->FindParam(&yts,ConstantsYtsEnum);

	/*recover gia solution parameters: */
	this->parameters->FindParam(&cross_section_shape,GiaCrossSectionShapeEnum);

	/*what time is it? :*/
	this->parameters->FindParam(&currenttime,TimeEnum);

	/*recover material parameters: */
	lithosphere_shear_modulus=matpar->GetLithosphereShearModulus();
	lithosphere_density=matpar->GetLithosphereDensity();
	mantle_shear_modulus=matpar->GetMantleShearModulus();
	mantle_density=matpar->GetMantleDensity();
	rho_ice=matpar->GetRhoIce();

	/*pull thickness averages: */
	thickness_input=inputs->GetInput(ThicknessEnum); 
	if (!thickness_input)_error_("thickness input needed to compute gia deflection!");
	thickness_input->GetInputUpToCurrentTimeAverages(&hes,&times,&numtimes,currenttime);

	/*recover mantle viscosity: */
	mantle_viscosity_input=inputs->GetInput(GiaMantleViscosityEnum);
	if (!mantle_viscosity_input)_error_("mantle viscosity input needed to compute gia deflection!");
	mantle_viscosity_input->GetInputAverage(&mantle_viscosity);

	/*recover lithosphere thickness: */
	lithosphere_thickness_input=inputs->GetInput(GiaLithosphereThicknessEnum);
	if (!lithosphere_thickness_input)_error_("lithosphere thickness input needed to compute gia deflection!");
	lithosphere_thickness_input->GetInputAverage(&lithosphere_thickness);

	/*pull area of this Tria: */
	area=this->GetArea();

	/*element radius: */
	re=sqrt(area/PI);

	/*figure out gravity center of our element: */
	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
	x0=(xyz_list[0][0]+xyz_list[1][0]+xyz_list[2][0])/3.0;
	y0=(xyz_list[0][1]+xyz_list[1][1]+xyz_list[2][1])/3.0;

	/*start loading GiaDeflectionCore arguments: */
	arguments.re=re;
	arguments.hes=hes;
	arguments.times=times;
	arguments.numtimes=numtimes;
	arguments.currenttime=currenttime;
	arguments.lithosphere_shear_modulus=lithosphere_shear_modulus;
	arguments.lithosphere_density=lithosphere_density;
	arguments.mantle_shear_modulus=mantle_shear_modulus;
	arguments.mantle_viscosity=mantle_viscosity;
	arguments.mantle_density=mantle_density;
	arguments.lithosphere_thickness=lithosphere_thickness;
	arguments.rho_ice=rho_ice;
	arguments.idisk=this->id;
	arguments.iedge=cross_section_shape;
	arguments.yts=yts;

	for(i=0;i<gsize;i++){
		/*compute distance from the center of the tria to the vertex i: */
		xi=x[i]; yi=y[i];
		ri=sqrt(pow(xi-x0,2)+pow(yi-y0,2));

		/*load ri onto arguments for this vertex i: */
		arguments.ri=ri;

		/*for this Tria, compute contribution to rebound at vertex i: */
		GiaDeflectionCorex(&wi,&dwidt,&arguments);

		/*plug value into solution vector: */
		wg->SetValue(i,wi,ADD_VAL);
		dwgdt->SetValue(i,dwidt,ADD_VAL);

	}

	/*Free ressources: */
	xDelete<IssmDouble>(hes);
	xDelete<IssmDouble>(times);

	return;
}
/*}}}*/
#endif

/*FUNCTION Tria::BalancethicknessMisfit{{{*/
IssmDouble Tria::BalancethicknessMisfit(void){

	/* Intermediaries */
	IssmDouble Jelem = 0;
	IssmDouble weight;
	IssmDouble Jdet,temp;
	IssmDouble xyz_list[NUMVERTICES][3];
	IssmDouble dH[2];
	IssmDouble vx,vy,H;
	IssmDouble dvx[2],dvy[2];
	IssmDouble dhdt,basal_melting,surface_mass_balance;
	GaussTria *gauss = NULL;

	/*If on water, return 0: */
	if(!IsIceInElement()) return 0;

	/*Retrieve all inputs we will be needing: */
	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
	Input* weights_input              = inputs->GetInput(InversionCostFunctionsCoefficientsEnum);   _assert_(weights_input);
	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* 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);

		/* Get Jacobian determinant: */
		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);

		/*Get all parameters at gaussian point*/
		weights_input->GetInputValue(&weight,gauss,BalancethicknessMisfitEnum);
		thickness_input->GetInputValue(&H, gauss);
		thickness_input->GetInputDerivativeValue(&dH[0],&xyz_list[0][0],gauss);
		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);

		/*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);
		Jelem+=weight*1/2*temp*temp*Jdet*gauss->weight;
	}

	/*Clean up and return*/
	delete gauss;
	return Jelem;
}
/*}}}*/
/*FUNCTION Tria::InputControlUpdate{{{*/
void  Tria::InputControlUpdate(IssmDouble scalar,bool save_parameter){

	/*Intermediary*/
	int    num_controls;
	int*   control_type=NULL;
	Input* input=NULL;

	/*retrieve some parameters: */
	this->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
	this->parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);

	for(int i=0;i<num_controls;i++){
		input=(Input*)this->inputs->GetInput(control_type[i]);   _assert_(input);
		if (input->ObjectEnum()!=ControlInputEnum){
			_error_("input " << EnumToStringx(control_type[i]) << " is not a ControlInput");
		}

		((ControlInput*)input)->UpdateValue(scalar);
		((ControlInput*)input)->Constrain();
		if (save_parameter) ((ControlInput*)input)->SaveValue();

	}

	/*Clean up and return*/
	xDelete<int>(control_type);
}
/*}}}*/
/*FUNCTION Tria::ControlInputGetGradient{{{*/
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]);

}/*}}}*/
/*FUNCTION Tria::ControlInputScaleGradient{{{*/
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);
}/*}}}*/
/*FUNCTION Tria::ControlInputSetGradient{{{*/
void Tria::ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index){

	int    vertexpidlist[NUMVERTICES];
	IssmDouble grad_list[NUMVERTICES];
	Input* grad_input=NULL;

	Input* input=inputs->GetInput(enum_type);
	if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found");
	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");

	GradientIndexing(&vertexpidlist[0],control_index);
	for(int i=0;i<NUMVERTICES;i++) grad_list[i]=gradient[vertexpidlist[i]];
	grad_input=new TriaInput(GradientEnum,grad_list,P1Enum);

	((ControlInput*)input)->SetGradient(grad_input);

}/*}}}*/
/*FUNCTION Tria::ControlToVectors{{{*/
void Tria::ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum){

	Input* input=inputs->GetInput(control_enum);
	if (!input) _error_("Input " << EnumToStringx(control_enum) << " not found");
	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(control_enum) << " is not a ControlInput");

	int         sidlist[NUMVERTICES];
	int         connectivity[NUMVERTICES];
	IssmPDouble values[NUMVERTICES];
	IssmPDouble gradients[NUMVERTICES]; 
	IssmDouble  value,gradient;

	this->GetVerticesConnectivityList(&connectivity[0]);
	this->GetVerticesSidList(&sidlist[0]);

	GaussTria* gauss=new GaussTria();
	for (int iv=0;iv<NUMVERTICES;iv++){
		gauss->GaussVertex(iv);

		((ControlInput*)input)->GetInputValue(&value,gauss);
		((ControlInput*)input)->GetGradientValue(&gradient,gauss);

		values[iv]    = reCast<IssmPDouble>(value)/reCast<IssmPDouble>(connectivity[iv]);
		gradients[iv] = reCast<IssmPDouble>(gradient)/reCast<IssmPDouble>(connectivity[iv]);
	}
	delete gauss;

	vector_control->SetValues(NUMVERTICES,&sidlist[0],&values[0],ADD_VAL);
	vector_gradient->SetValues(NUMVERTICES,&sidlist[0],&gradients[0],ADD_VAL);

}/*}}}*/
/*FUNCTION Tria::Gradj {{{*/
void  Tria::Gradj(Vector<IssmDouble>* gradient,int control_type,int control_index){
	/*dJ/dalpha = ∂L/∂alpha = ∂J/∂alpha + ∂/∂alpha(KU-F)*/

	/*If on water, grad = 0: */
	if(!IsIceInElement()) return;

	/*First deal with ∂/∂alpha(KU-F)*/
	switch(control_type){
		case FrictionCoefficientEnum:
			GradjDragSSA(gradient,control_index);
			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:
			GradjDragGradient(gradient,control_index);
			break;
		case RheologyBbarAbsGradientEnum:
			GradjBGradient(gradient,control_index);
			break;
		default:
			_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
	}

	xDelete<int>(responses);
}
/*}}}*/
/*FUNCTION Tria::GradjBGradient{{{*/
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;
}
/*}}}*/
/*FUNCTION Tria::GradjBSSA{{{*/
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;
}
/*}}}*/
/*FUNCTION Tria::GradjDSSA{{{*/
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);
	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;
}
/*}}}*/
/*FUNCTION Tria::GradjDragSSA {{{*/
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,vx_input,vy_input,NULL);

		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,vx_input,vy_input,vz_input);
	//	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;
}
/*}}}*/
/*FUNCTION Tria::GradjDragGradient{{{*/
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;
}
/*}}}*/
/*FUNCTION Tria::GradjDhDtBalancedthickness{{{*/
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);
}
/*}}}*/
/*FUNCTION Tria::GradjVxBalancedthickness{{{*/
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;
}
/*}}}*/
/*FUNCTION Tria::GradjVyBalancedthickness{{{*/
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;
}
/*}}}*/
/*FUNCTION Tria::GradjThicknessBalancethicknessSoft{{{*/
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);
}
/*}}}*/
/*FUNCTION Tria::GradientIndexing{{{*/
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;
	}

}
/*}}}*/
/*FUNCTION Tria::RheologyBbarAbsGradient{{{*/
IssmDouble Tria::RheologyBbarAbsGradient(void){

	/* Intermediaries */
	IssmDouble Jelem = 0;
	IssmDouble weight;
	IssmDouble Jdet;
	IssmDouble xyz_list[NUMVERTICES][3];
	IssmDouble dp[NDOF2];
	GaussTria *gauss = NULL;

	/*retrieve parameters and inputs*/

	/*If on water, return 0: */
	if(!IsIceInElement()) return 0;

	/*Retrieve all inputs we will be needing: */
	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
	Input* weights_input  =inputs->GetInput(InversionCostFunctionsCoefficientsEnum);              _assert_(weights_input);
	Input* rheologyb_input=inputs->GetInput(MaterialsRheologyBbarEnum); _assert_(rheologyb_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);

		/* Get Jacobian determinant: */
		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);

		/*Get all parameters at gaussian point*/
		weights_input->GetInputValue(&weight,gauss,RheologyBbarAbsGradientEnum);
		rheologyb_input->GetInputDerivativeValue(&dp[0],&xyz_list[0][0],gauss);

		/*Tikhonov regularization: J = 1/2 ((dp/dx)^2 + (dp/dy)^2) */ 
		Jelem+=weight*1/2*(dp[0]*dp[0] + dp[1]*dp[1])*Jdet*gauss->weight;
	}

	/*Clean up and return*/
	delete gauss;
	return Jelem;
}
/*}}}*/
/*FUNCTION Tria::SurfaceAverageVelMisfit {{{*/
IssmDouble Tria::SurfaceAverageVelMisfit(void){

	IssmDouble Jelem=0,S,Jdet;
	IssmDouble misfit;
	IssmDouble vx,vy,vxobs,vyobs,weight;
	IssmDouble xyz_list[NUMVERTICES][3];
	GaussTria *gauss=NULL;

	/*If on water, return 0: */
	if(!IsIceInElement())return 0;

	/* Get node coordinates and dof list: */
	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);

	/*Retrieve all inputs we will be needing: */
	inputs->GetInputValue(&S,SurfaceAreaEnum);
	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);   _assert_(weights_input);
	Input* vx_input     =inputs->GetInput(VxEnum);        _assert_(vx_input);
	Input* vy_input     =inputs->GetInput(VyEnum);        _assert_(vy_input);
	Input* vxobs_input  =inputs->GetInput(InversionVxObsEnum);     _assert_(vxobs_input);
	Input* vyobs_input  =inputs->GetInput(InversionVyObsEnum);     _assert_(vyobs_input);

	/* Start  looping on the number of gaussian points: */
	gauss=new GaussTria(3);
	for(int ig=gauss->begin();ig<gauss->end();ig++){

		gauss->GaussPoint(ig);

		/* Get Jacobian determinant: */
		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);

		/*Get all parameters at gaussian point*/
		weights_input->GetInputValue(&weight,gauss,SurfaceAverageVelMisfitEnum);
		vx_input->GetInputValue(&vx,gauss);
		vy_input->GetInputValue(&vy,gauss);
		vxobs_input->GetInputValue(&vxobs,gauss);
		vyobs_input->GetInputValue(&vyobs,gauss);

		/*Compute SurfaceAverageVelMisfitEnum:
		 *
		 *      1                    2              2
		 * J = ---  sqrt(  (u - u   )  +  (v - v   )  )
		 *      S                obs            obs
		 */
		misfit=1/S*sqrt( pow(vx-vxobs,2) + pow(vy-vyobs,2));

		/*Add to cost function*/
		Jelem+=misfit*weight*Jdet*gauss->weight;
	}

	/*clean-up and Return: */
	delete gauss;
	return Jelem;
}
/*}}}*/
/*FUNCTION Tria::SurfaceLogVelMisfit {{{*/
IssmDouble Tria::SurfaceLogVelMisfit(void){

	IssmDouble Jelem=0.;
	IssmDouble misfit,Jdet;
	IssmDouble epsvel=2.220446049250313e-16;
	IssmDouble meanvel=3.170979198376458e-05; /*1000 m/yr*/
	IssmDouble velocity_mag,obs_velocity_mag;
	IssmDouble xyz_list[NUMVERTICES][3];
	IssmDouble vx,vy,vxobs,vyobs,weight;
	GaussTria *gauss=NULL;

	/*If on water, return 0: */
	if(!IsIceInElement())return 0;

	/* Get node coordinates and dof list: */
	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);

	/*Retrieve all inputs we will be needing: */
	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);   _assert_(weights_input);
	Input* vx_input     =inputs->GetInput(VxEnum);        _assert_(vx_input);
	Input* vy_input     =inputs->GetInput(VyEnum);        _assert_(vy_input);
	Input* vxobs_input  =inputs->GetInput(InversionVxObsEnum);     _assert_(vxobs_input);
	Input* vyobs_input  =inputs->GetInput(InversionVyObsEnum);     _assert_(vyobs_input);

	/* Start  looping on the number of gaussian points: */
	gauss=new GaussTria(4);
	for(int ig=gauss->begin();ig<gauss->end();ig++){

		gauss->GaussPoint(ig);

		/* Get Jacobian determinant: */
		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);

		/*Get all parameters at gaussian point*/
		weights_input->GetInputValue(&weight,gauss,SurfaceLogVelMisfitEnum);
		vx_input->GetInputValue(&vx,gauss);
		vy_input->GetInputValue(&vy,gauss);
		vxobs_input->GetInputValue(&vxobs,gauss);
		vyobs_input->GetInputValue(&vyobs,gauss);

		/*Compute SurfaceLogVelMisfit:
		 *        4         [        vel + eps     ] 2
		 * J = 4 \bar{v}^2 | log ( -----------  ) |  
		 *                 [       vel   + eps    ]
		 *                            obs
		 */
		velocity_mag    =sqrt(pow(vx,   2)+pow(vy,   2))+epsvel;
		obs_velocity_mag=sqrt(pow(vxobs,2)+pow(vyobs,2))+epsvel;
		misfit=4*pow(meanvel,2)*pow(log(velocity_mag/obs_velocity_mag),2);

		/*Add to cost function*/
		Jelem+=misfit*weight*Jdet*gauss->weight;
	}

	/*clean-up and Return: */
	delete gauss;
	return Jelem;
}
/*}}}*/
/*FUNCTION Tria::SurfaceLogVxVyMisfit {{{*/
IssmDouble Tria::SurfaceLogVxVyMisfit(void){

	IssmDouble Jelem=0, S=0;
	IssmDouble epsvel=2.220446049250313e-16;
	IssmDouble meanvel=3.170979198376458e-05; /*1000 m/yr*/
	IssmDouble misfit, Jdet;
	IssmDouble vx,vy,vxobs,vyobs,weight;
	IssmDouble xyz_list[NUMVERTICES][3];
	GaussTria *gauss=NULL;

	/*If on water, return 0: */
	if(!IsIceInElement())return 0;

	/* Get node coordinates and dof list: */
	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);

	/*Retrieve all inputs we will be needing: */
	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);   _assert_(weights_input);
	Input* vx_input     =inputs->GetInput(VxEnum);        _assert_(vx_input);
	Input* vy_input     =inputs->GetInput(VyEnum);        _assert_(vy_input);
	Input* vxobs_input  =inputs->GetInput(InversionVxObsEnum);     _assert_(vxobs_input);
	Input* vyobs_input  =inputs->GetInput(InversionVyObsEnum);     _assert_(vyobs_input);

	/* Start  looping on the number of gaussian points: */
	gauss=new GaussTria(4);
	for(int ig=gauss->begin();ig<gauss->end();ig++){

		gauss->GaussPoint(ig);

		/* Get Jacobian determinant: */
		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);

		/*Get all parameters at gaussian point*/
		weights_input->GetInputValue(&weight,gauss,SurfaceLogVxVyMisfitEnum);
		vx_input->GetInputValue(&vx,gauss);
		vy_input->GetInputValue(&vy,gauss);
		vxobs_input->GetInputValue(&vxobs,gauss);
		vyobs_input->GetInputValue(&vyobs,gauss);

		/*Compute SurfaceRelVelMisfit:
		 *
		 *      1            [        |u| + eps     2          |v| + eps     2  ]
		 * J = --- \bar{v}^2 | log ( -----------  )   +  log ( -----------  )   |  
		 *      2            [       |u    |+ eps              |v    |+ eps     ]
		 *                              obs                       obs
		 */
		misfit=0.5*pow(meanvel,2)*(
					pow(log((fabs(vx)+epsvel)/(fabs(vxobs)+epsvel)),2) +
					pow(log((fabs(vy)+epsvel)/(fabs(vyobs)+epsvel)),2) );

		/*Add to cost function*/
		Jelem+=misfit*weight*Jdet*gauss->weight;
	}

	/*clean-up and Return: */
	delete gauss;
	return Jelem;
}
/*}}}*/
/*FUNCTION Tria::SurfaceAbsVelMisfit {{{*/
IssmDouble Tria::SurfaceAbsVelMisfit(void){

	IssmDouble Jelem=0;
	IssmDouble misfit,Jdet;
	IssmDouble vx,vy,vxobs,vyobs,weight;
	IssmDouble xyz_list[NUMVERTICES][3];
	GaussTria *gauss=NULL;

	/*If on water, return 0: */
	if(!IsIceInElement())return 0;

	/* Get node coordinates and dof list: */
	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);

	/*Retrieve all inputs we will be needing: */
	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);   _assert_(weights_input);
	Input* vx_input     =inputs->GetInput(VxEnum);        _assert_(vx_input);
	Input* vy_input     =inputs->GetInput(VyEnum);        _assert_(vy_input);
	Input* vxobs_input  =inputs->GetInput(InversionVxObsEnum);     _assert_(vxobs_input);
	Input* vyobs_input  =inputs->GetInput(InversionVyObsEnum);     _assert_(vyobs_input);

	/* Start  looping on the number of gaussian points: */
	gauss=new GaussTria(2);
	for(int ig=gauss->begin();ig<gauss->end();ig++){

		gauss->GaussPoint(ig);

		/* Get Jacobian determinant: */
		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);

		/*Get all parameters at gaussian point*/
		weights_input->GetInputValue(&weight,gauss,SurfaceAbsVelMisfitEnum);
		vx_input->GetInputValue(&vx,gauss);
		vy_input->GetInputValue(&vy,gauss);
		vxobs_input->GetInputValue(&vxobs,gauss);
		vyobs_input->GetInputValue(&vyobs,gauss);

		/*Compute SurfaceAbsVelMisfitEnum:
		 *
		 *      1  [           2              2 ]
		 * J = --- | (u - u   )  +  (v - v   )  |
		 *      2  [       obs            obs   ]
		 *
		 */
		misfit=0.5*( pow(vx-vxobs,2) + pow(vy-vyobs,2) );

		/*Add to cost function*/
		Jelem+=misfit*weight*Jdet*gauss->weight;
	}

	/*clean up and Return: */
	delete gauss;
	return Jelem;
}
/*}}}*/
/*FUNCTION Tria::SurfaceRelVelMisfit {{{*/
IssmDouble Tria::SurfaceRelVelMisfit(void){

	IssmDouble  Jelem=0;
	IssmDouble  scalex=1,scaley=1;
	IssmDouble  misfit,Jdet;
	IssmDouble  epsvel=2.220446049250313e-16;
	IssmDouble  meanvel=3.170979198376458e-05; /*1000 m/yr*/
	IssmDouble  vx,vy,vxobs,vyobs,weight;
	IssmDouble  xyz_list[NUMVERTICES][3];
	GaussTria *gauss=NULL;

	/*If on water, return 0: */
	if(!IsIceInElement())return 0;

	/* Get node coordinates and dof list: */
	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);

	/*Retrieve all inputs we will be needing: */
	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);   _assert_(weights_input);
	Input* vx_input     =inputs->GetInput(VxEnum);        _assert_(vx_input);
	Input* vy_input     =inputs->GetInput(VyEnum);        _assert_(vy_input);
	Input* vxobs_input  =inputs->GetInput(InversionVxObsEnum);     _assert_(vxobs_input);
	Input* vyobs_input  =inputs->GetInput(InversionVyObsEnum);     _assert_(vyobs_input);

	/* Start  looping on the number of gaussian points: */
	gauss=new GaussTria(4);
	for(int ig=gauss->begin();ig<gauss->end();ig++){

		gauss->GaussPoint(ig);

		/* Get Jacobian determinant: */
		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);

		/*Get all parameters at gaussian point*/
		weights_input->GetInputValue(&weight,gauss,SurfaceRelVelMisfitEnum);
		vx_input->GetInputValue(&vx,gauss);
		vy_input->GetInputValue(&vy,gauss);
		vxobs_input->GetInputValue(&vxobs,gauss);
		vyobs_input->GetInputValue(&vyobs,gauss);

		/*Compute SurfaceRelVelMisfit:
		 *                        
		 *      1  [     \bar{v}^2             2   \bar{v}^2              2 ]
		 * J = --- | -------------  (u - u   ) + -------------  (v - v   )  |
		 *      2  [  (u   + eps)^2       obs    (v   + eps)^2       obs    ]
		 *              obs                        obs                      
		 */
		scalex=pow(meanvel/(vxobs+epsvel),2); if(vxobs==0)scalex=0;
		scaley=pow(meanvel/(vyobs+epsvel),2); if(vyobs==0)scaley=0;
		misfit=0.5*(scalex*pow((vx-vxobs),2)+scaley*pow((vy-vyobs),2));

		/*Add to cost function*/
		Jelem+=misfit*weight*Jdet*gauss->weight;
	}

	/*clean up and Return: */
	delete gauss;
	return Jelem;
}
/*}}}*/
/*FUNCTION Tria::ThicknessAbsGradient{{{*/
IssmDouble Tria::ThicknessAbsGradient(void){

	/* Intermediaries */
	IssmDouble Jelem = 0;
	IssmDouble weight;
	IssmDouble Jdet;
	IssmDouble xyz_list[NUMVERTICES][3];
	IssmDouble dp[NDOF2];
	GaussTria *gauss = NULL;

	/*retrieve parameters and inputs*/

	/*If on water, return 0: */
	if(!IsIceInElement()) return 0;

	/*Retrieve all inputs we will be needing: */
	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
	Input* weights_input  =inputs->GetInput(InversionCostFunctionsCoefficientsEnum);   _assert_(weights_input);
	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);

	/* Start looping on the number of gaussian points: */
	gauss=new GaussTria(2);
	for(int ig=gauss->begin();ig<gauss->end();ig++){

		gauss->GaussPoint(ig);

		/* Get Jacobian determinant: */
		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);

		/*Get all parameters at gaussian point*/
		weights_input->GetInputValue(&weight,gauss,ThicknessAbsGradientEnum);
		thickness_input->GetInputDerivativeValue(&dp[0],&xyz_list[0][0],gauss);

		/*Tikhonov regularization: J = 1/2 ((dp/dx)^2 + (dp/dy)^2) */ 
		Jelem+=weight*1/2*(dp[0]*dp[0]+dp[1]*dp[1])*Jdet*gauss->weight;
	}

	/*Clean up and return*/
	delete gauss;
	return Jelem;
}
/*}}}*/
/*FUNCTION Tria::ThicknessAlongGradient{{{*/
IssmDouble Tria::ThicknessAlongGradient(void){

	/* Intermediaries */
	IssmDouble  Jelem = 0;
	IssmDouble  weight;
	IssmDouble  Jdet;
	IssmDouble  xyz_list[NUMVERTICES][3];
	IssmDouble  dp[NDOF2];
	IssmDouble  vx,vy,vel;
	GaussTria  *gauss                    = NULL;

	/*retrieve parameters and inputs*/

	/*If on water, return 0: */
	if(!IsIceInElement()) return 0;

	/*Retrieve all inputs we will be needing: */
	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
	Input* weights_input  = inputs->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
	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);

	/* Start looping on the number of gaussian points: */
	gauss=new GaussTria(2);
	for(int ig=gauss->begin();ig<gauss->end();ig++){

		gauss->GaussPoint(ig);

		/* Get Jacobian determinant: */
		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);

		/*Get all parameters at gaussian point*/
		weights_input->GetInputValue(&weight,gauss,ThicknessAlongGradientEnum);
		thickness_input->GetInputDerivativeValue(&dp[0],&xyz_list[0][0],gauss);
		vx_input->GetInputValue(&vx,gauss);
		vy_input->GetInputValue(&vy,gauss);
		vel = sqrt(vx*vx+vy*vy);
		vx  = vx/(vel+1.e-9);
		vy  = vy/(vel+1.e-9);

		/*J = 1/2 ( vx*dH/dx + vy*dH/dy )^2 */
		Jelem+=weight*1/2*(vx*dp[0] + vy*dp[1])*(vx*dp[0] + vy*dp[1])*Jdet*gauss->weight;
	}

	/*Clean up and return*/
	delete gauss;
	return Jelem;
}
/*}}}*/
/*FUNCTION Tria::ThicknessAcrossGradient{{{*/
IssmDouble Tria::ThicknessAcrossGradient(void){

	/* Intermediaries */
	IssmDouble  Jelem = 0;
	IssmDouble  weight;
	IssmDouble  Jdet;
	IssmDouble  xyz_list[NUMVERTICES][3];
	IssmDouble  dp[NDOF2];
	IssmDouble  vx,vy,vel;
	GaussTria  *gauss                    = NULL;

	/*retrieve parameters and inputs*/

	/*If on water, return 0: */
	if(!IsIceInElement()) return 0;

	/*Retrieve all inputs we will be needing: */
	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
	Input* weights_input  = inputs->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
	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);

	/* Start looping on the number of gaussian points: */
	gauss=new GaussTria(2);
	for(int ig=gauss->begin();ig<gauss->end();ig++){

		gauss->GaussPoint(ig);

		/* Get Jacobian determinant: */
		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);

		/*Get all parameters at gaussian point*/
		weights_input->GetInputValue(&weight,gauss,ThicknessAcrossGradientEnum);
		thickness_input->GetInputDerivativeValue(&dp[0],&xyz_list[0][0],gauss);
		vx_input->GetInputValue(&vx,gauss);
		vy_input->GetInputValue(&vy,gauss);
		vel = sqrt(vx*vx+vy*vy);
		vx  = vx/(vel+1.e-9);
		vy  = vy/(vel+1.e-9);

		/*J = 1/2 ( -vy*dH/dx + vx*dH/dy )^2 */
		Jelem+=weight*1/2*(-vy*dp[0] + vx*dp[1])*(-vy*dp[0] + vx*dp[1])*Jdet*gauss->weight;
	}

	/*Clean up and return*/
	delete gauss;
	return Jelem;
}
/*}}}*/
/*FUNCTION Tria::ThicknessAbsMisfit {{{*/
IssmDouble Tria::ThicknessAbsMisfit(void){

	/*Intermediaries*/
	IssmDouble thickness,thicknessobs,weight;
	IssmDouble Jdet;
	IssmDouble Jelem = 0;
	IssmDouble xyz_list[NUMVERTICES][3];
	GaussTria *gauss = NULL;
	IssmDouble dH[2];

	/*If on water, return 0: */
	if(!IsIceInElement())return 0;

	/*Retrieve all inputs we will be needing: */
	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
	Input* thickness_input   =inputs->GetInput(ThicknessEnum);   _assert_(thickness_input);
	Input* thicknessobs_input=inputs->GetInput(InversionThicknessObsEnum);_assert_(thicknessobs_input);
	Input* weights_input     =inputs->GetInput(InversionCostFunctionsCoefficientsEnum);     _assert_(weights_input);

	/* Start  looping on the number of gaussian points: */
	gauss=new GaussTria(2);
	for(int ig=gauss->begin();ig<gauss->end();ig++){

		gauss->GaussPoint(ig);

		/* Get Jacobian determinant: */
		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);

		/*Get parameters at gauss point*/
		thickness_input->GetInputValue(&thickness,gauss);
		thickness_input->GetInputDerivativeValue(&dH[0],&xyz_list[0][0],gauss);
		thicknessobs_input->GetInputValue(&thicknessobs,gauss);
		weights_input->GetInputValue(&weight,gauss,ThicknessAbsMisfitEnum);

		/*compute ThicknessAbsMisfit*/
		Jelem+=0.5*(thickness-thicknessobs)*(thickness-thicknessobs)*weight*Jdet*gauss->weight;
	}

	/* clean up and Return: */
	delete gauss;
	return Jelem;
}
/*}}}*/
/*FUNCTION Tria::DragCoefficientAbsGradient{{{*/
IssmDouble Tria::DragCoefficientAbsGradient(void){

	/* Intermediaries */
	IssmDouble Jelem = 0;
	IssmDouble weight;
	IssmDouble Jdet;
	IssmDouble xyz_list[NUMVERTICES][3];
	IssmDouble dp[NDOF2];
	GaussTria *gauss = NULL;

	/*retrieve parameters and inputs*/

	/*If on water, return 0: */
	if(!IsIceInElement()) return 0;

	/*Retrieve all inputs we will be needing: */
	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);         _assert_(weights_input);
	Input* drag_input   =inputs->GetInput(FrictionCoefficientEnum); _assert_(drag_input);

	/* Start looping on the number of gaussian points: */
	gauss=new GaussTria(2);
	for(int ig=gauss->begin();ig<gauss->end();ig++){

		gauss->GaussPoint(ig);

		/* Get Jacobian determinant: */
		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);

		/*Get all parameters at gaussian point*/
		weights_input->GetInputValue(&weight,gauss,DragCoefficientAbsGradientEnum);
		drag_input->GetInputDerivativeValue(&dp[0],&xyz_list[0][0],gauss);

		/*Tikhonov regularization: J = 1/2 ((dp/dx)^2 + (dp/dy)^2) */ 
		Jelem+=weight*1/2*(dp[0]*dp[0]+dp[1]*dp[1])*Jdet*gauss->weight;
	}

	/*Clean up and return*/
	delete gauss;
	return Jelem;
}
/*}}}*/
/*FUNCTION Tria::GetVectorFromControlInputs{{{*/
void  Tria::GetVectorFromControlInputs(Vector<IssmDouble>* vector,int control_enum,int control_index,const char* data){

	int vertexpidlist[NUMVERTICES];
	Input *input=NULL;

	/*Get out if this is not an element input*/
	if(!IsInput(control_enum)) return;

	/*Prepare index list*/
	GradientIndexing(&vertexpidlist[0],control_index);

	/*Get input (either in element or material)*/
	input=(Input*)this->inputs->GetInput(control_enum);   _assert_(input);

	/*Check that it is a ControlInput*/
	if (input->ObjectEnum()!=ControlInputEnum){
		_error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
	}

	((ControlInput*)input)->GetVectorFromInputs(vector,&vertexpidlist[0],data);
}
/*}}}*/
/*FUNCTION Tria::SetControlInputsFromVector{{{*/
void  Tria::SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index){

	IssmDouble  values[NUMVERTICES];
	int     vertexpidlist[NUMVERTICES];
	Input  *input     = NULL;
	Input  *new_input = NULL;

	/*Get out if this is not an element input*/
	if(!IsInput(control_enum)) return;

	/*Prepare index list*/
	GradientIndexing(&vertexpidlist[0],control_index);

	/*Get values on vertices*/
	for (int i=0;i<NUMVERTICES;i++){
		values[i]=vector[vertexpidlist[i]];
	}
	new_input = new TriaInput(control_enum,values,P1Enum);

	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);
}
/*}}}*/
/*FUNCTION Tria::CreateHydrologyWaterVelocityInput {{{*/
void Tria::CreateHydrologyWaterVelocityInput(void){

	/*material parameters: */
	IssmDouble mu_water;
	IssmDouble VelocityFactor;  // This factor represents the number 12 in laminar flow velocity which can vary by differnt hydrology.CR
	IssmDouble n_man,CR;
	IssmDouble w;
	IssmDouble rho_ice, rho_water, g;
	IssmDouble dsdx,dsdy,dbdx,dbdy;
	IssmDouble vx[NUMVERTICES];
	IssmDouble vy[NUMVERTICES];
	GaussTria *gauss = NULL;

	/*Retrieve all inputs and parameters*/
	rho_ice=matpar->GetRhoIce();
	rho_water=matpar->GetRhoWater();
	g=matpar->GetG();
	CR=matpar->GetHydrologyCR(); // To have Lebrocq equavalent equation: CR=0.01,n_man=0.02
	n_man=matpar->GetHydrologyN(); 
	mu_water=matpar->GetMuWater();
	Input* surfaceslopex_input=inputs->GetInput(SurfaceSlopeXEnum); _assert_(surfaceslopex_input);
	Input* surfaceslopey_input=inputs->GetInput(SurfaceSlopeYEnum); _assert_(surfaceslopey_input);
	Input* bedslopex_input=inputs->GetInput(BedSlopeXEnum);         _assert_(bedslopex_input);
	Input* bedslopey_input=inputs->GetInput(BedSlopeYEnum);         _assert_(bedslopey_input);
	Input* watercolumn_input=inputs->GetInput(WatercolumnEnum);     _assert_(watercolumn_input);

	/* compute VelocityFactor */
	VelocityFactor= n_man*CR*CR*rho_water*g/mu_water;

	gauss=new GaussTria();
	for(int iv=0;iv<NUMVERTICES;iv++){
		gauss->GaussVertex(iv);
		surfaceslopex_input->GetInputValue(&dsdx,gauss);
		surfaceslopey_input->GetInputValue(&dsdy,gauss);
		bedslopex_input->GetInputValue(&dbdx,gauss);
		bedslopey_input->GetInputValue(&dbdy,gauss);
		watercolumn_input->GetInputValue(&w,gauss);

		/* Water velocity x and y components */
	//	vx[iv]= - w*w/(12 * mu_water)*(rho_ice*g*dsdx+(rho_water-rho_ice)*g*dbdx);
	//	vy[iv]= - w*w/(12 * mu_water)*(rho_ice*g*dsdy+(rho_water-rho_ice)*g*dbdy);
		vx[iv]= - w*w/(VelocityFactor* mu_water)*(rho_ice*g*dsdx+(rho_water-rho_ice)*g*dbdx);
		vy[iv]= - w*w/(VelocityFactor* mu_water)*(rho_ice*g*dsdy+(rho_water-rho_ice)*g*dbdy);
	}

	/*clean-up*/
	delete gauss;

	/*Add to inputs*/
	this->inputs->AddInput(new TriaInput(HydrologyWaterVxEnum,vx,P1Enum));
	this->inputs->AddInput(new TriaInput(HydrologyWaterVyEnum,vy,P1Enum));
}
/*}}}*/
/*FUNCTION Tria::GetSolutionFromInputsOneDof{{{*/
void  Tria::GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution, int enum_type){

	int        *doflist = NULL;
	IssmDouble  value;

	/*Fetch number of nodes for this finite element*/
	int numnodes = this->NumberofNodes();

	/*Fetch dof list and allocate solution vector*/
	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
	IssmDouble* values = xNew<IssmDouble>(numnodes);

	/*Get inputs*/
	Input* enum_input=inputs->GetInput(enum_type); _assert_(enum_input);

	/*Ok, we have the values, fill in the array: */
	GaussTria* gauss=new GaussTria();
	for(int i=0;i<numnodes;i++){
		gauss->GaussNode(this->element_type,i);

		enum_input->GetInputValue(&value,gauss);
		values[i]=value;
	}

	solution->SetValues(numnodes,doflist,values,INS_VAL);

	/*Free ressources:*/
	xDelete<int>(doflist);
	xDelete<IssmDouble>(values);
	delete gauss;
}
/*}}}*/

#ifdef _HAVE_DAKOTA_
/*FUNCTION Tria::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type);{{{*/
void  Tria::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){

	int i,j;

	/*Check that name is an element input*/
	if (!IsInput(name)) return;

	switch(type){

		case VertexEnum:

			/*New TriaInput*/
			IssmDouble values[3];

			/*Get values on the 3 vertices*/
			for (i=0;i<3;i++){
				values[i]=vector[this->vertices[i]->Sid()]; //careful, vector of values here is not parallel distributed, but serial distributed (from a serial Dakota core!)
			}

			/*Branch on the specified type of update: */
			switch(name){
				case ThicknessEnum:
					IssmDouble  thickness[3];
					IssmDouble  thickness_init[3];
					IssmDouble  hydrostatic_ratio[3];
					IssmDouble  surface[3];
					IssmDouble  bed[3];

					/*retrieve inputs: */
					GetInputListOnVertices(&thickness_init[0],ThicknessEnum);
					GetInputListOnVertices(&hydrostatic_ratio[0],GeometryHydrostaticRatioEnum);
					GetInputListOnVertices(&bed[0],BaseEnum);
					GetInputListOnVertices(&surface[0],SurfaceEnum);

					/*build new bed and surface: */
					if (this->IsFloating()){
						/*hydrostatic equilibrium: */
						IssmDouble rho_ice,rho_water,di;
						rho_ice   = this->matpar->GetRhoIce();
						rho_water = this->matpar->GetRhoWater();
						di        = rho_ice/rho_water;

						/*build new thickness: */
						for (j=0; j<3; j++) {
							/*  for observed/interpolated/hydrostatic thickness, remove scaling from any hydrostatic thickness  */
							if (hydrostatic_ratio[j] >= 0.)
								thickness[j]=values[j]-(values[j]/thickness_init[j]-1.)*hydrostatic_ratio[j]*surface[j]/(1.-di);
							/*  for minimum thickness, don't scale  */
							else
								thickness[j]=thickness_init[j];

							/*  check the computed thickness and update bed*/
							if (thickness[j] < 0.) thickness[j]=1./(1.-di);
							bed[j]=surface[j]-thickness[j];
						}
					}
					else{
						/*build new thickness: */
						for (j=0; j<3; j++) {
							/*  for observed thickness, use scaled value  */
							if (hydrostatic_ratio[j] >= 0.)
								thickness[j]=values[j];
							/*  for minimum thickness, don't scale  */
							else
								thickness[j]=thickness_init[j];
						}

						/*update bed on grounded ice: */
						for(j=0;j<3;j++)bed[j]=surface[j]-thickness[j];
					}

					/*Add new inputs: */
					this->inputs->AddInput(new TriaInput(ThicknessEnum,thickness,P1Enum));
					this->inputs->AddInput(new TriaInput(BaseEnum,bed,P1Enum));
					this->inputs->AddInput(new TriaInput(SurfaceEnum,surface,P1Enum));

					break;
				case MaterialsRheologyBEnum:
					this->inputs->AddInput(new TriaInput(MaterialsRheologyBbarEnum,values,P1Enum));
					break;
				default:
					this->inputs->AddInput(new TriaInput(name,values,P1Enum));
			}
			break;

		default:
			_error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
	}

}
/*}}}*/
/*FUNCTION Tria::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type);{{{*/
void  Tria::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type){

	int             i,t,row;
	IssmDouble      time;
	TransientInput *transientinput = NULL;
	IssmDouble      values[3];

	/*Check that name is an element input*/
	if (!IsInput(name)) return;

	switch(type){

		case VertexEnum:
			/*Create transient input: */
			for(t=0;t<ncols;t++){ //ncols is the number of times

				/*create input values: */
				for(i=0;i<3;i++){
					row=this->vertices[i]->Sid();
					values[i]=matrix[ncols*row+t];
				}

				/*time:*/
				time=matrix[(nrows-1)*ncols+t];

				if(t==0) transientinput=new TransientInput(name);
				transientinput->AddTimeInput(new TriaInput(name,values,P1Enum),time);
				transientinput->Configure(parameters);
			}
			this->inputs->AddInput(transientinput);
			break;

		default:
			_error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
	}

}
/*}}}*/
#endif

/*FUNCTION Tria::MigrateGroundingLine{{{*/
void  Tria::MigrateGroundingLine(IssmDouble* phi_ungrounding){

	int        i,migration_style;
	bool       oldfloating;
	bool       floatingelement = false;
	bool       groundedelement = false;
	IssmDouble bed_hydro,yts,gl_melting_rate;
	IssmDouble rho_water,rho_ice,density;
	IssmDouble melting[NUMVERTICES],phi[NUMVERTICES];;
	IssmDouble h[NUMVERTICES],s[NUMVERTICES],b[NUMVERTICES],r[NUMVERTICES];

	/*Recover info at the vertices: */
	parameters->FindParam(&migration_style,GroundinglineMigrationEnum);
	parameters->FindParam(&gl_melting_rate,GroundinglineMeltingRateEnum);
	parameters->FindParam(&yts,ConstantsYtsEnum);
	GetInputListOnVertices(&h[0],ThicknessEnum);
	GetInputListOnVertices(&s[0],SurfaceEnum);
	GetInputListOnVertices(&b[0],BaseEnum);
	GetInputListOnVertices(&r[0],BedEnum);
	GetInputListOnVertices(&phi[0],MaskGroundediceLevelsetEnum);
	rho_water   = matpar->GetRhoWater();
	rho_ice     = matpar->GetRhoIce();
	density     = rho_ice/rho_water;
	oldfloating = this->IsFloating(); //figure out if element is floating before we start to change everything

	/*go through vertices, and update inputs, considering them to be TriaVertex type: */
	for(i=0;i<NUMVERTICES;i++){
		/*Ice shelf: if bed below bathymetry, impose it at the bathymetry and update surface, elso do nothing */
		if(phi[i]<=0.){
			if(b[i]<=r[i]){ 
				b[i]        = r[i];
				s[i]        = b[i]+h[i];
			}
		}
		/*Ice sheet: if hydrostatic bed above bathymetry, ice sheet starts to unground, elso do nothing */
		/*Change only if AgressiveMigration or if the ice sheet is in contact with the ocean*/
		else{ // phi>0
			bed_hydro=-density*h[i];
			if (bed_hydro>r[i]){
				/*Unground only if the element is connected to the ice shelf*/
				if(migration_style==AgressiveMigrationEnum || migration_style==SubelementMigrationEnum || migration_style==SubelementMigration2Enum){
					s[i]        = (1-density)*h[i];
					b[i]        = -density*h[i];
				}
				else if(migration_style==SoftMigrationEnum && phi_ungrounding[vertices[i]->Pid()]<0.){
					s[i]        = (1-density)*h[i];
					b[i]        = -density*h[i];
				}
				else{
					if(migration_style!=SoftMigrationEnum) _error_("Error: migration should be Aggressive, Soft or Subelement");
				}
			}
		}
	}

	/*Recalculate phi*/
	for(i=0;i<NUMVERTICES;i++){
		if(migration_style==SoftMigrationEnum){
			bed_hydro=-density*h[i];
			if(phi[i]<0. || bed_hydro<=r[i] || phi_ungrounding[vertices[i]->Pid()]<0.){
				phi[i]=h[i]+r[i]/density;
			}
		}
		else phi[i]=h[i]+r[i]/density;
	}
	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));
	this->inputs->AddInput(new TriaInput(BaseEnum,&b[0],P1Enum));

}
/*}}}*/
/*FUNCTION Tria::PotentialUngrounding{{{*/
void  Tria::PotentialUngrounding(Vector<IssmDouble>* potential_ungrounding){

	IssmDouble  h[NUMVERTICES],r[NUMVERTICES],gl[NUMVERTICES];
	IssmDouble  bed_hydro;
	IssmDouble  rho_water,rho_ice,density;

	/*material parameters: */
	rho_water=matpar->GetRhoWater();
	rho_ice=matpar->GetRhoIce();
	density=rho_ice/rho_water;
	GetInputListOnVertices(&h[0],ThicknessEnum);
	GetInputListOnVertices(&r[0],BedEnum);
	GetInputListOnVertices(&gl[0],MaskGroundediceLevelsetEnum);

	/*go through vertices, and figure out which ones are grounded and want to unground: */
	for(int i=0;i<NUMVERTICES;i++){
		/*Find if grounded vertices want to start floating*/
		if (gl[i]>0.){
			bed_hydro=-density*h[i];
			if(bed_hydro>r[i]){
				/*Vertex that could potentially unground, flag it*/
				potential_ungrounding->SetValue(vertices[i]->Pid(),1,INS_VAL);
			}
		}
	}
}
/*}}}*/
/*FUNCTION Tria::UpdatePotentialUngrounding{{{*/
int Tria::UpdatePotentialUngrounding(IssmDouble* vertices_potentially_ungrounding,Vector<IssmDouble>* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf){

	int i;
	int nflipped=0;

	/*Go through nodes, and whoever is on the potential_ungrounding, ends up in nodes_on_iceshelf: */
	for(i=0;i<3;i++){
		if (reCast<bool>(vertices_potentially_ungrounding[vertices[i]->Pid()])){
			vec_nodes_on_iceshelf->SetValue(vertices[i]->Pid(),-1.,INS_VAL);

			/*If node was not on ice shelf, we flipped*/
			if(nodes_on_iceshelf[vertices[i]->Pid()]>=0.){
				nflipped++;
			}
		}
	}
	return nflipped;
}
/*}}}*/
