#!/usr/bin/env python 
'''
Copyright (C) 2005 Aaron Spike, aaron@ekips.org (used dxf_outlines.py as start example)
HPGL  file created by Inkscape http://www.InkScape.org
HPGL output Python extension by Luberth Dijkman 
http://www.Sticker.Tk 
http://www.GravoMaster.com
This hpgl save python extension was made for inkscape version 0.45
'''
import inkex, simplepath, cubicsuperpath, re

uuconv = {'in':90.0, 'pt':1.25, 'px':1, 'mm':3.5433070866, 'cm':35.433070866, 'pc':15.0}
def unittouu(string):
    unit = re.compile('(%s)$' % '|'.join(uuconv.keys()))
    param = re.compile(r'(([-+]?[0-9]+(\.[0-9]*)?|[-+]?\.[0-9]+)([eE][-+]?[0-9]+)?)')

    p = param.match(string)
    u = unit.search(string)    
    if p:
        retval = float(p.string[p.start():p.end()])
    else:
        retval = 0.0
    if u:
        try:
            return retval * uuconv[u.string[u.start():u.end()]]
        except KeyError:
            pass
    return retval

class MyEffect(inkex.Effect):
    def __init__(self):
        inkex.Effect.__init__(self)
        self.dxf = ''
    def output(self):
        print self.dxf
    def dxf_add(self, str):
        self.dxf += str
    def dxf_line(self,csp):
        line = "\nPD%i,%i;" % (csp[0][0],csp[0][1])
        self.dxf_add(line)
    
    def effect(self):
        

        self.dxf_add("\nHPGL  file created by Inkscape http://www.InkScape.org\nHPGL output Python extension by Luberth Dijkman http://www.Sticker.Tk http://www.GravoMaster.com\n This hpgl save python extension was made for inkscape version 0.45\n 1 plotter unit = 0.025mm (~0.00098inch) \n40 plotter units = 1mm\n1016 plotter units = 1 inch \n3.39 plotter-units = 1 dot at 300 dots per inch\n")
        
        scale = 25.4/90.0*40
        h = unittouu(inkex.xml.xpath.Evaluate('/svg/@height',self.document)[0].value)

        path = '//path'
        for node in inkex.xml.xpath.Evaluate(path,self.document):
            d = node.attributes.getNamedItem('d').value
            sim = simplepath.parsePath(d)
            simplepath.scalePath(sim,scale,-scale)
            simplepath.translatePath(sim,0,h*scale)            
            p = cubicsuperpath.CubicSuperPath(sim)
            for sub in p:
                for i in range(len(sub)-1):
                    s = (sub[i])
                    e = (sub[i+1])
                    if s[1] == s[2] and e[0] == e[1]:
                        self.dxf_line([s[1],e[1]])
                    
        self.dxf_add("\nPU0,0;\n\nEndOffFile\n")


e = MyEffect()
e.affect()

