"""
HFGL to DXF file converter example
Written by Marlena Abraham

To use this script:
	- Save your .plt file to this folder
	- Run 'python hpgl2dxf.py [input_filename] [destination_name].dxf'
	- Close preview window
	- Open your new [destination_name].dxf file in your favorite DXF viewer.
"""

import sys
import time
import re
from Tkinter import *
from dxfwrite import DXFEngine as dxf

# a Point object saves a set of coordinates with its pen up/down bool
class Point:
	def __init__(self, in_x, in_y, isDown):
		self.x = in_x
		self.y = in_y
		self.penDown = isDown


# open the HPGL file and save the coordinates as an array of points
with open(sys.argv[1], 'r') as f:
	coords = []
	for nextLine in f:
		# Check if pen up or pen down line (starts with "PU"/"PD")
		pu_check = bool(re.match(r'PU ', nextLine, re.M|re.I))
		pd_check = bool(re.match(r'PD ', nextLine, re.M|re.I))
		if pu_check | pd_check:
			s1 = nextLine[3:-2]
			temp_coords = str.split(s1, ",")
			coords.append(Point(float(temp_coords[0])/100.0, float(temp_coords[1])/100.0, pd_check))

# Using DXFEngine, build and save a .dxf file
drawing = dxf.drawing(sys.argv[2])
drawing.header['$LUNITS'] = 4   # units in millimeters
drawing.add_layer('LINES')

for j in xrange(len(coords)):
	if coords[j].penDown:
		drawing.add(dxf.line((coords[j-1].x, coords[j-1].y),
			                 (coords[j].x, coords[j].y),
			                 color=1,
			                 layer='LINES'))

drawing.save()

# Using Tkinter, view a preview of the design
master = Tk()

w = Canvas(master, width=800, height=800)
w.pack()
for i in xrange(len(coords)):
	if coords[i].penDown:
		# multiply coords by 10 to fit the gear preview on screen
		w.create_line(int(10*coords[i-1].x), 
					  int(10*coords[i-1].y), 
					  int(10*coords[i].x), 
					  int(10*coords[i].y),
					  fill='red')
mainloop()
