#!/usr/bin/env python

from string import *
import sys, math 
#import Gnuplot

def read_SVG(filename):
   global points
   #
   # SVG parser
   #
   file = open(filename,'r')
   str = file.readlines()
   file.close()
   points = [[]]
   polypiece = -1
   # all this parsing lifted out of cam.py
   for line in range(len(str)):
      if (find(str[line],"<svg") != -1):
         start = find(str[line],'width="')
	 if (find(str[line],'mm',start+7) != -1):
 	    end = find(str[line],'mm',start+7)
  	    width = float(str[line][start+7:end])
  	    #print "   width: %.3fmm"%width
	    width = width/25.4
	 elif (find(str[line],'in',start+7) != -1):
 	    end = find(str[line],'in',start+7)
  	    width = float(str[line][start+7:end])
  	    #print "   width: %.3fin"%width
	 elif (find(str[line],'"',start+7) != -1):
 	    end = find(str[line],'"',start+7)
  	    width = float(str[line][start+7:end])
  	    #print "   width: %.3f"%width
         start = find(str[line],'height="')
	 if (find(str[line],'mm',start+8) != -1):
 	    end = find(str[line],'mm',start+8)
  	    height = float(str[line][start+8:end])
  	    #print "   height: %.3fmm"%height
	    height = height/25.4
	 elif (find(str[line],'in',start+8) != -1):
 	    end = find(str[line],'in',start+8)
  	    height = float(str[line][start+8:end])
  	    #print "   height: %.3fin"%height
	 elif (find(str[line],'"',start+8) != -1):
 	    end = find(str[line],'"',start+8)
  	    height = float(str[line][start+8:end])
  	    #print "   height: %.3f"%height
         if (find(str[line],'viewBox="') != -1):
            s0 = find(str[line],'viewBox="')
  	    s1 = find(str[line],' ',s0+1)
	    s2 = find(str[line],' ',s1+1)
	    s3 = find(str[line],' ',s2+1)
	    s4 = find(str[line],'"',s3+1)
	    view_xmin = float(str[line][s0+9:s1])
	    view_ymin = float(str[line][s1+1:s2])
	    view_width = float(str[line][s2+1:s3])
	    view_height = float(str[line][s3+1:s4])
	    #print "   view: %d %d %d %d"%(view_xmin,view_ymin,view_width,view_height)
	 else:
	    view_xmin = 0
	    view_ymin = 0
	    view_width = width
	    view_height = height
      elif (find(str[line],'<polyline') != -1):
         start = 8+find(str[line],'points="')
         end = find(str[line],'"',start+1)
	 polypiece += 1
	 points.append([])
	 while 1:
            comma = find(str[line],',',start)
            space = find(str[line],' ',start)
	    if (space > end):
	       space = end
  	    x = float(str[line][start:comma])
	    y = float(str[line][comma+1:space])
	    x = width*(x - view_xmin)/view_width
	    y = height*(view_ymin-y)/view_height

	    #print "appending point (x,y): %d %d"%(x,y)
	    
	    points[polypiece].append([x,y])
	    start = space+1
	    if (space == end):
	        break
      elif (find(str[line],'<rect') != -1):
         print "SVG rectangle not yet implemented"
      elif (find(str[line],'<line') != -1):
         print "SVG line not yet implemented"
      elif (find(str[line],'<circle') != -1):
         print "SVG circle not yet implemented"
      elif (find(str[line],'<polygon') != -1):
         print "SVG polygon not yet implemented"
      elif (find(str[line],'<ellipse') != -1):
         print "SVG ellipse not yet implemented"
         
   print "there were", polypiece+1, "polyline pieces found"


def showpoints():
    print len(points)
    print "points[0] has %d"%len(points[0])
    print "points[1] has %d"%len(points[1])
    print "points[2] has %d"%len(points[2])

    for i in range(len(points)):
        print "**This is points[", i, "]"
        for n in points[i]:
                    print n
  
def linecalcs():
    # want a structure that captures slope and offset and endpoints
    # lines[poly][slope, offset, inequality direction, point 1, point 2]
    # inequality direction means y < mx+b or y > mx+b;
    #  -1 means <, 1 means >

    global lines
    lines=[[]]
    for poly in range(len(points)-1):
        #print "** polypiece", poly
        i = 0
        lines.append([])
        while (i+1 < len(points[poly])):        
            x1 = points[poly][i][0]
            y1 = points[poly][i][1]
            x2 = points[poly][i+1][0]
            y2 = points[poly][i+1][1]

            if x1 == x2:     # vertical line, inf slope
                slope = 0       # later, I'll always check for vert lines
                offset = 0
                if y1 > y2:     # vector points down
                    ineq = -1
                else:
                    ineq = 1
            elif y1 == y2:   # horizontal line, zero slope
                slope = 0
                offset = y1
                if x1 > x2:      # vector points left
                    ineq = 1
                else:            # vector points right
                    ineq = -1
            else:            # line is some kind of diagonal
                slope = (y2 - y1) / (x2 - x1)
                offset = y1 - ( slope * x1 )

                if slope < 0:
                    x_normal = x1
                    y_normal = y2
                else:
                    x_normal = x1
                    y_normal = y2

                if y_normal > slope * x_normal + offset:
                    ineq = 1
                else:
                    ineq = -1

            # pack it all into the data structure
            # lines[poly][slope, offset, inequality direction, point 1, point 2]
            lines[poly].append([slope, offset, ineq, x1, y1, x2, y2])
            
            #print "i:", i, "\n\t", x1, y1, "\t\t|", slope, offset
            #print "\t", x2, y2, "\t\t|", ineq

            i+=1

def printseg():
# lines[slope, offset, inequality direction, x1, y1, x2, y2]
    for poly in range(len(lines)-1):
        print "\nPOLYLINE PIECE", poly
        for segment in lines[poly]:
            if segment[3] == segment[5]:        # vertical line
                print "x",
                if segment[2] > 0:
                    print ">",
                else:
                    print "<",
                print segment[3], "\t",
                print min(segment[4], segment[6]), "<= y <=", max(segment[4], segment[6])
            elif segment[0] == 0:               # horizontal line
                print "y",
                if segment[2] > 0:
                    print ">",
                else:
                    print "<",
                print segment[4], "\t",
                print min(segment[3], segment[5]), "<= x <=", max(segment[3], segment[5])                 
            else:
                print "y",
                if segment[2] > 0:
                    print ">",
                else:
                    print "<",
                print segment[0], "x +", segment[1], "\t",
                print min(segment[3], segment[5]), "<= x <=", max(segment[3], segment[5]), ";",      
                print min(segment[4], segment[6]), "<= y <=", max(segment[4], segment[6])
            

def makeplot():
	g = Gnuplot.Gnuplot()
	g.plot(sin(x))


filename=sys.argv[1]
print "Opening file: ", filename,
read_SVG(filename)
#showpoints()
linecalcs()
printseg()
