import shapefile
import os
from expwrite import expwrite

def shp2exp(shapefilename,*expfilename):
	'''
	Convert a shapefile to an .exp file.  Optionally, expfilename can be
	specified to give a name for the .exp file to be created, otherwise the
	.exp file will have the same prefix as the .shp file.

	Usage:
		shp2exp(shapefilename)
		shp2exp(shapefilename,expfilename)

	Examples:
		shp2exp('Domain.shp') % creates Domain.exp
		shp2exp('Domain.shp','DomainForISSM.exp')
	'''
	
	if not os.path.exists(shapefilename):
		raise IOError("shp2exp error message: file '%s' not found!" % parametername)
	if not len(expfilename):
		expfile=os.path.splitext(shapefilename)[0]+'.exp'
	else:
		expfile=expfilename[0]

	shp=shapefile.Reader(shapefilename)
	expdict=dict(closed=1,density=1)

	x=[]
	y=[]
	for i in range(len(shp.shapes())):
		geom=shp.shapes()[i].shapeType
		if geom==5: # polygon
			x=[p[0] for p in shp.shapes()[i].points]
			y=[q[1] for q in shp.shapes()[i].points]
			expdict['x']=x
			expdict['y']=y
			expdict['nods']=len(x)
		elif geom==3: # line
			x=[p[0] for p in shp.shapes()[i].points]
			y=[q[1] for q in shp.shapes()[i].points]
			x.append(x[0])
			y.append(y[0])
			expdict['x']=x
			expdict['y']=y
			expdict['nods']=len(x)
		elif geom==1: # point
			x.append(shp.shapes()[i].points[0][0])
			y.append(shp.shapes()[i].points[0][1])
			expdict['x']=x
			expdict['y']=y
			expdict['nods']=len(x)

	expwrite([expdict],expfile)
