#!/usr/bin/python
#
# Inkscape SVG to "qd" format converter
# Programmed and designed by Matti 'ccr' Hamalainen
# (C) Copyright 2012-2013 Tecnic Software productions (TNSP)
#
import sys
import re
import xml.etree.ElementTree as ET


def bf(x) :
   return int(round(float(x)))


def printVertex(v) :
   if type(v) is list :
      return "{:.2f},{:.2f},{:.2f}".format(v[0], v[1], v[2])
   else :
      return v


def getTransform(elem) :
   if "transform" in elem.attrib :
      ntrans = elem.attrib["transform"]
      tmatch = re.compile(r"translate\((.*?)\)", re.IGNORECASE)
      for trns in tmatch.finditer(ntrans) :
         coord = trns.group(1).split(",")
         return [float(coord[0]), float(coord[1]), 0]
   return None


def getStyle(elem) :
   style = {}
   if "style" in elem.attrib :
      for elem in elem.attrib["style"].split(";") :
         kv = elem.split(":")
         style[kv[0]] = kv[1]
   return style


def printVertices(type, vertices, width, level) :
   if len(vertices) > 0 :
      list = map(lambda v:printVertex(v), vertices)
      str = "# "+ type
      if type == "m" :
         str = "R"
      elif type == "M" :
         str = "L"
      elif type == "c" :
         str = "R"
      print "{}{}{} {} {}".format("  "*level, str, len(vertices)-1, " ".join(list), width)


def printPath(path, level) :
   style = getStyle(path)
   width = bf(style["stroke-width"])

   trans = getTransform(path)
   if trans :
      print "{}G{}".format("  "*level, printVertex(trans))

   vertices = []
   type = ""
   for elem in path.attrib["d"].split(" ") :
      if elem == "m" or elem == "M" :
         printVertices(type, vertices, width, level)
         vertices = []
         type = elem
      elif elem == "z" :
         vertices.append("Z")
      elif elem == "c" or elem == "C" :
         print "Curves not supported! Path ID '{}':\n{}".format(path.attrib["id"], path.attrib["d"])
         sys.exit(0)
      else :
         tmp = elem.split(",")
         px = float(tmp[0])
         py = float(tmp[1])
         vertices.append([px, py, 0])

   printVertices(type, vertices, width, level)
   if trans :
      print "{}E\n".format("  "*level)


###
### Iterate XML document tree elements
###
def iterateDocument(elems, level) :
   for elem in elems:
      if elem.tag == "{http://www.w3.org/2000/svg}g" :
         print "\n{}# GROUP".format("  "*level)
         tmp = getTransform(elem)
         if tmp :
            print "{}G{}".format("  "*level, printVertex(getTransform(elem)))
            iterateDocument(elem, level + 1)
            print "{}E\n".format("  "*level)
         else :
            iterateDocument(elem, level)
      elif elem.tag == "{http://www.w3.org/2000/svg}path" :
         printPath(elem, level)


###
### The "main program"
###
if len(sys.argv) != 2 :
   print "Usage: "+sys.argv[0]+" <input.svg>"
   sys.exit(1)
   
# Parse input XML to a tree
tree = ET.parse(sys.argv[1])

# Iterate through the document
iterateDocument(tree.getroot(), 0)
