#!/usr/bin/env python
'''
svg -> _start_ _node_ _end_
_node_ -> _node_ _OP_ _node_ | _TERM_
_TERM_ -> 0..9
_OP_ -> * | +

'''

_start = '''<?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 width="100%" height="100%" version="1.1"
     xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink">
  <desc>Arithmetic Parse Tree</desc>

  <!-- Begin  parse tree data -->
'''

_end = '</svg>'

def _t(x, y, s):
    return '<text font-size="30" x="%s" y="%s">%s</text>\n' % (x, y, s)

def _node(args, x, y, depth):
    op, n1, n2 = args[0], args[1], args[2]
    x_n1 = int(x-100/depth)
    x_n2 = int(x+100/depth)
    y_child = y + 80
    if type(n1) is list:
        n1_s = _node(n1, x_n1, y_child, depth+1)
    else:
        n1_s = _t(x_n1, y_child, n1)
    if type(n2) is list:
        n2_s = _node(n2, x_n2, y_child, depth+1)
    else:
        n2_s = _t(x_n2, y_child, n2)
    s = _t(x, y, op)
    s += n1_s
    s += n2_s
    line_fmt = '<path d="M %d %d L %d %d" stroke="black" ' \
        + 'stroke-width="1"/>\n'
    s += line_fmt % (x+5, y + 15, x_n1+8, y_child - 25)
    s += line_fmt % (x+5, y + 15, x_n2+8, y_child - 25)
    return s

DATA = ['*', ['+', '2', '3'], ['-', '7', ['*', '8', '9']]]

print _start + _node(DATA, 200, 30, 1) + _end
    
