import numpy
from collections import OrderedDict
from BamgConvertMesh import *
from bamgmesh import *
from bamggeom import *

def meshconvert(md,*args):
	"""
	CONVERTMESH - convert mesh to bamg mesh

	   Usage:
	      md=meshconvert(md);
	      md=meshconvert(md,index,x,y);
	"""

	if not len(args)==0 and not len(args)==3:
		raise TypeError("meshconvert error message: bad usage")

	if not len(args):
		x=md.mesh.x
		y=md.mesh.y
		index=md.mesh.elements
	else:
		x=args[0]
		y=args[1]
		index=args[2]

	#call Bamg
	bamgmesh_out,bamggeom_out=BamgConvertMesh(index,x,y)

	# plug results onto model
	md.private.bamg=OrderedDict()
	md.private.bamg['mesh']=bamgmesh(bamgmesh_out)
	md.private.bamg['geometry']=bamggeom(bamggeom_out)
	md.mesh.x=bamgmesh_out['Vertices'][:,0].copy()
	md.mesh.y=bamgmesh_out['Vertices'][:,1].copy()
	md.mesh.elements=bamgmesh_out['Triangles'][:,0:3].copy()
	md.mesh.edges=bamgmesh_out['IssmEdges'].copy()
	md.mesh.segments=bamgmesh_out['IssmSegments'][:,0:3].copy()
	md.mesh.segmentmarkers=bamgmesh_out['IssmSegments'][:,3].copy()

	#Fill in rest of fields:
	md.mesh.dimension=2
	md.mesh.numberofelements=numpy.size(md.mesh.elements,axis=0)
	md.mesh.numberofvertices=numpy.size(md.mesh.x)
	md.mesh.numberofedges=numpy.size(md.mesh.edges,axis=0)
	md.mesh.z=numpy.zeros(md.mesh.numberofvertices)
	md.mesh.vertexonbed=numpy.ones(md.mesh.numberofvertices)
	md.mask.vertexonwater=numpy.zeros(md.mesh.numberofvertices)
	md.mesh.vertexonsurface=numpy.ones(md.mesh.numberofvertices)
	md.mesh.elementonbed=numpy.ones(md.mesh.numberofelements)
	md.mesh.elementonsurface=numpy.ones(md.mesh.numberofelements)
	md.mesh.vertexonboundary=numpy.zeros(md.mesh.numberofvertices)
	md.mesh.vertexonboundary[md.mesh.segments[:,0:2].astype(int)-1]=1

	return md

