#!/usr/bin/python3
# requires svg.path, install it like this: pip3 install svg.path

# converts a list of path elements of a SVG file to simple line drawing commands
from svg.path import parse_path
from xml.dom import minidom
from math import sqrt

# load and parse the SVG file
doc = minidom.parse('vcv.svg')
path_strings = [path.getAttribute('d') for path
                in doc.getElementsByTagName('path')]
doc.unlink()

# extract all path elements and create lines array
lines = []
for path_string in path_strings:
    path = parse_path(path_string)
    for e in path:
        if type(e).__name__ == 'Line':
            x0 = e.start.real
            y0 = -e.start.imag
            x1 = e.end.real
            y1 = -e.end.imag
            lines.append([[x0, y0], [x1, y1]])

# function to iterate all lines
def iterate(fun):
    for line in lines:
        p0, p1 = line
        x0, y0 = p0
        x1, y1 = p1
        dx = x0 - x1
        dy = y0 - y1
        fun(x0, y0, x1, y1)
    
# calculate length sum
line_sum = 0
def line_length(x0, y0, x1, y1):
    dx = x0 - x1
    dy = y0 - y1
    return sqrt(dx * dx + dy * dy)
def sum_length(x0, y0, x1, y1):
    global line_sum
    line_sum = line_sum + line_length(x0, y0, x1, y1)
iterate(sum_length)

# output the drawing commands
line_sum2 = 0
x = ""
y = ""
def move(x0, y0, x1, y1):
    global line_sum, line_sum2, x, y
    l = line_length(x0, y0, x1, y1)
    l_from = line_sum2 / line_sum
    line_sum2 = line_sum2 + l
    l_to = line_sum2 / line_sum
    dx = x1 - x0
    dy = y1 - y0
    dl = l_to - l_from
    print(dx, dy, dl)
    sx = dx / dl
    sy = dy / dl
    if dx == 0:
        x = x + "(x>=%.2f&x<%.2f)*%.2f+" % (l_from, l_to, x0)
    else:
        x = x + "(x>=%.2f&x<%.2f)*((x-%.2f)*%.2f+%.2f)+" % (l_from, l_to, l_from, sx, x0)
    if dy == 0:
        y = y + "(y>=%.2f&y<%.2f)*%.2f+" % (l_from, l_to, y0)
    else:
        y = y + "(y>=%.2f&y<%.2f)*((y-%.2f)*%.2f+%.2f)+" % (l_from, l_to, l_from, sy, y0)
iterate(move)
print(x)
print(y)
