from math import isnan
import numpy as  np

def processmesh(md,data,options):
	"""
	PROCESSMESH - process the mesh for plotting

	Usage:
		x,y,z,elements,is2d=processmech(md,data,options)

	See also: PLOTMODEL, PROCESSDATA
	"""

	# {{{ check mesh size parameters
	if md.mesh.numberofvertices==0:
		raise ValueError('processmesh error: mesh is empty')
	if md.mesh.numberofvertices==md.mesh.numberofelements:
		raise ValueError('processmesh error: the number of elements is the same as the number of nodes')
	# }}}
	# {{{ treating non data plots mesh
	if len(data)==0 or not isinstance(data,dict):
		if 'latlon' not in options.getfieldvalue('coord','xy').lower(): #convert to lower case for comparison
			try:
				x=md.mesh.x2d
			except AttributeError:
				x=md.mesh.x
			try:
				y=md.mesh.x2d
			except AttributeError:				
				y=md.mesh.y
		else:
			x=md.mesh.long
			y=md.mesh.lat
		try:
			z=md.mesh.z
		except AttributeError:
			z=np.zeros_like(md.mesh.x)
		
		try:
			elements2d=md.mesh.elements2d-1
		except AttributeError:
			elements=md.mesh.elements-1

		#is it a 2D plot?
		if md.mesh.dimension()==2 or options.getfieldvalue('layer',0)>=1:
			is2d=1
		else:
			is2d=0

		#layer projection?
		if options.getfieldvalue('layer',0)>=1:
			 if 'latlon' in options.getfieldvalue('coord','xy').lower():
				 raise ValueError('processmesh error: cannot work with 3D mesh in lat-lon coords')
			 #we modify the mesh temporarily to a 2D mesh from which the 3D mesh was extruded
		   #Basile: does not seem necessary as we already picked x as x2d
		   # x=x2d
			 # y=y2d
			 # z=zeros(size(x2d))
			 # elements=elements2d
	else:
		#Process mesh for plotting 
		if md.mesh.dimension()==2:
			is2d=1
		else:
			# process polycollection here for 3D plot
			is2d=0
	
	#units
	if options.exist('unit'):
		unit=options.getfieldvalue('unit')
		x=x*unit
		y=y*unit
		z=z*unit

	#is model a member of planet class? (workaround until planet class defined)
	if md.__class__.__name__!='model':
		isplanet=1
	else:
		isplanet=0

	return x,y,z,elements,is2d,isplanet
