# convert eps(pepacra) to svg(inkscape)
# (c) masahiko
# date-written 2009-04-23
# up-to-date 2011-2-26

import sys
import string

def header():
	return '''<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" 
  "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink"
	 width="744.09448" height="1052.3622"
     viewBox="-25 -800 550 850">
  <title>svg sample</title>
<defs>
<style type="text/css"><![CDATA[
    .Face { fill:#aabbff; stroke:none; }
    .Mountain { fill:none; stroke:#666666; stroke-dasharray:9,2,1,2;}
    .Valley { fill:none; stroke:#666666; stroke-dasharray:4,4;}
    .Cut { fill:none; stroke:#000000; }
]]></style>
</defs>
'''

def tail():
	return '''</svg>
'''

def hanten(y):
	temp = -float(y)
	yy = "%f" % temp
	return yy

def eps2svg(name):
	print 'convert', name, '.eps to .svg ... ',
	infile = open(name+'.eps', 'r')
	outfile = open(name+'.svg', 'w')
	outfile.write( header() )
	d = ''
	s = 'Cut'
	while 1:
		temp = infile.readline()
		if temp == '': break
		tok = string.split(temp)
		if string.find(temp, 'newpath') >= 0:		# newpath
			if d != '':
				outfile.write('<path class="Face" d="' + d + '" />\n')
			d = ''
		elif string.find(temp, 'moveto') >= 0:		#  121.4 308.0 moveto
			d = 'M ' + tok[0] + ' ' + hanten(tok[1])
		elif string.find(temp, 'lineto') >= 0:		#  121.4 308.0 lineto
			d = d + ' L ' + tok[0] + ' ' + hanten(tok[1])
		elif string.find(temp, 'closepath') >= 0:	# closepath
			d = d + ' Z'
		elif string.find(temp, 'fill') >= 0:		# fill
			if d != '':
				outfile.write('<path class="Face" d="' + d + '" />\n')
			d = ''
		elif string.find(temp, 'setdash') >= 0:		# [?] 0 setdash
			if len(tok) > 5:
				s = 'Mountain'
			elif len(tok) > 3:
				s = 'Valley'
			else:
				s = 'Cut'
		elif string.find(temp, 'stroke') >= 0:		# stroke
			if d != '':
				outfile.write('<path class="' + s + '" d="' + d + '" />\n')
			d = ''
	outfile.write( tail() )
	infile.close()
	outfile.close()
	print 'done'

# --- command

if len(sys.argv) < 2:
	print 'usage: python eps2svg.py filename ...'
else:
	for name in sys.argv[1:]:
		ex = string.find(name, '.eps')
		if ex == 0:
			ex = string.find(name, '.EPS')
		if ex >= 0:
			eps2svg(name[0:ex])
		else:
			eps2svg(name)
