function md=meshconvert(md,varargin)
%CONVERTMESH - convert mesh to bamg mesh
%
%   Usage:
%      md=meshconvert(md);
%      md=meshconvert(md,index,x,y);

if nargin~=1 & nargin~=4,
	help meshconvert
	error('meshconvert error message: bad usage');
end

if nargin==1,
	x=md.x;
	y=md.y;
	index=md.elements;
else
	x=varargin{1};
	y=varargin{2};
	index=varargin{3};
end

%call Bamg
[bamgmesh_out bamggeom_out]=BamgConvertMesh(index,x,y);

% plug results onto model
md.private.bamg=struct();
md.private.bamg.mesh=bamgmesh(bamgmesh_out);
md.private.bamg.geometry=bamggeom(bamggeom_out);
md.x=bamgmesh_out.Vertices(:,1);
md.y=bamgmesh_out.Vertices(:,2);
md.elements=bamgmesh_out.Triangles(:,1:3);
md.edges=bamgmesh_out.IssmEdges;
md.mesh.segments=bamgmesh_out.IssmSegments(:,1:3);
md.mesh.segmentmarkers=bamgmesh_out.IssmSegments(:,4);

%Fill in rest of fields:
md.mesh.dimension=2;
md.mesh.numberofelements=size(md.elements,1);
md.mesh.numberofvertices=length(md.x);
md.z=zeros(md.mesh.numberofvertices,1);
md.nodeonbed=ones(md.mesh.numberofvertices,1);
md.mask.vertexonwater=zeros(md.mesh.numberofvertices,1);
md.nodeonsurface=ones(md.mesh.numberofvertices,1);
md.elementonbed=ones(md.mesh.numberofelements,1);
md.elementonsurface=ones(md.mesh.numberofelements,1);
md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
