function stress=Stress(triaelem,grids,materials,inputs)
%STRESS - compute the stress on each element
%
%   Usage:
%      stress=Stress(triaelem,grids,materials,inputs)
%
%   See also GETSTRAINRATE, GETVISCOSITY2D

	%initialize
	stress=zeros(3,1);
	volume=0;

	%some variables
	NDOF1=1;
	numgrids=3;

	%recover material parameters
	matice=materials(triaelem.matid).material;
	B=matice.B;

	%Get all element grid data:
	xyz_list=getgriddata(triaelem,grids);

	%recover extra inputs
	[velocity_param velocity_is_present]=recover_input(inputs,'velocity');
	[flow_law_param flow_law_is_present]=recover_input(inputs,'B');

	%we need velocities to compute thermal profiles (even if it is a zero 
	%vector). 
	if ~velocity_is_present,
		error('Stress error message: input velocity not present!');
	end

	%initialize vxvyvz_list
	vxvy_list=zeros(numgrids,2);
	pressure=zeros(numgrids,1);

	%Build row indices for elementary vector.
	for i=1:numgrids,
		doflist=grids(triaelem.g(i)).grid.doflist;
		for j=1:2,
			dof=doflist(j);
			vxvy_list(i,j)=velocity_param(dof);
		end
		pressure(i)=velocity_param(doflist(4));	
		dof=doflist(1);
		if(flow_law_is_present), B_list(i) = flow_law_param(dof);end;
	end
	
	%Update material parameter that deals with ice rigidity: 
	if flow_law_is_present,
		B_param=GetParameterValue(triaelem,B_list,gauss_coord);
		matice.B=B_param; clear B_param.
	end
	
	% Get gaussian points and weights 
	[num_area_gauss,first_area_gauss_coord,second_area_gauss_coord,third_area_gauss_coord,area_gauss_weights]=GaussTria(2);

	%Start  looping on the number of gaussian points:
	for igarea=1:num_area_gauss,

		%Pick up the gaussian point and its weight:
		gauss_weight=area_gauss_weights(igarea);
		gauss_coord=[first_area_gauss_coord(igarea) second_area_gauss_coord(igarea) third_area_gauss_coord(igarea)];
	    
		%Build Stress
		stress_g=zeros(3,1);
		epsilon=GetStrainRate(triaelem,vxvy_list,xyz_list,gauss_coord);
		viscosity=GetViscosity2d(matice,epsilon);
		pressure_g=GetParameterValue(triaelem,pressure,gauss_coord);
		deviatoricstress=viscosity*epsilon;
		stress_g=deviatoricstress;
		stress_g([1;2],1)=stress_g(1:2,1)-pressure_g;         %stress=deviatoricstress-pressure

		%Get Jacobian determinant:
		Jdet=GetJacobianDeterminant(triaelem,xyz_list,gauss_coord);

		stress=stress+stress_g*Jdet*gauss_weight;

		volume=volume+Jdet*gauss_weight;

	end %for ig=1:num_area_gauss,

%Divide stress, integrated over volume, by volume.
stress=stress/volume;
