#! /usr/bin/python

import sys
from string import split, strip

def fix(filename, lines):
    last_point = None
    in_curve = 0
    closed = 0
    for i in range(len(lines) - 1, -1, -1):
        line = strip(lines[i])
        if line == 'bC()':
            closed = 1
        if line[:3] in ('bs(', 'bc('):
            if not in_curve and closed:
                # line is the last line of a curve object. remember the
                # end point
                args = split(line[3:-1], ',')
                last_point = args[-3:-1]
                in_curve = 1
        else:
            in_curve = 0
        if line in ('b()', 'bn()'):
            # The beginning of a curve object. If the first segment in
            # the curve object is a bezier object, insert a line segment
            # to last_point before it.
            if lines[i + 1][:3] == 'bc(':
                print "%s:%d: Curve starts with a line segment" % (filename,
                                                                   i + 1)
                if last_point:
                    segment = "bs(%s,%s,0)\n" % tuple(last_point)
                    lines.insert(i + 1, segment)
                    print "%s:%d:    fixed" % (filename, i + 1)
                else:
                    print ("%s:%d:" % (filename, i + 1)
                           + "can't be fixed because the curve is not closed")

def main():
    infile = sys.argv[1]
    if len(sys.argv) > 2:
        outfile = sys.argv[2]
    else:
        outfile = infile
    lines = open(infile).readlines()
    fix(infile, lines)
    open(outfile, "w").writelines(lines)

    
main()
