def write_secondary_postScript(primitive, functionName, writefile):
    '''
    takes a primitive, a description string. converts it to js readable data

    input:      primitive ( a joined list with raw commands )
    input:      the name of the current function. (each graphical element)
    input:      writefile, is the file we are writing to.
    output:     straight to file.

    i'm not sure what is up with the coordinate system, it's not something i've
    been able to find any useful information on. Applying assumptions seems a little
    zealous. It seems like, if a primitive doesn't havea a fillColour, that unmodified
    point coordinates are ok.
    '''


    global dashModeOn
    global dashParameters
    global strokeWidth
    global currentColour

    # subdivide into function lines.
    primitive = regex_plotListString(primitive)

    
    writefile.write("\nfunction " + functionName + "(){\n")
    writefile.write(indent + "var point = new Point(0, " + rectHeight + ");\n")

    # each time this function is called, it means a new path primitive is
    # being requested. each primitive only has one path
    writefile.write(indent + "var path = new Path();\n")
    
    
    for instruction in primitive:

        instruction = instruction.rstrip()

        if instruction.startswith("[] 0.0 d"):
            dashModeOn = False
            continue

        if instruction.endswith(" d"):
            dashModeOn = True
            dashParameters = parse_dash_params(instruction)
            lineToWrite = indent + "path.dashArray = " + dashParameters + ";\n"
            writefile.write(lineToWrite)
            continue

        if instruction.endswith(" m"):
            lineArray = instruction.split()
            coordinates = pointify_coordinates(lineArray[0:2])
            lineToWrite = indent + "path.moveTo(" + coordinates + ");\n"
            writefile.write(lineToWrite)
            continue

        if instruction.endswith(" cm"):
            # print(indent + instruction + " (store some data, no idea)")
            continue

        if instruction.endswith("l"):
            lineArray = instruction.split()
            coordinates = pointify_coordinates(lineArray[0:2])
            lineToWrite = indent + "path.lineTo(" + coordinates + ");\n"
            writefile.write(lineToWrite)
            continue
        
        if instruction.endswith("c"):
            lineArray = instruction.split()
            coordinates = convert_to_curve_parameters(lineArray)
            lineToWrite = indent + "path.cubicCurveTo(" + coordinates + ");\n"
            writefile.write(lineToWrite)
            continue

        
        # stroke information
        if instruction.endswith("w"):
            strokeWidth = instruction.split()[0]
            lineToWrite = indent + "path.strokeWidth = " + strokeWidth + ";\n"
            writefile.write(lineToWrite)
            continue

        if instruction.endswith("S"):
            lineToWrite = indent + "path.strokeColor = " + currentColour + ";\n"
            writefile.write(lineToWrite)
            continue

        if instruction.endswith("J"):
            print(indent + instruction + " (a line cap)")
            continue

        if instruction.endswith("j"):
            print(indent + instruction + " (a line join)")
            continue

        if instruction.endswith("M"):
            lineArray = instruction.split()
            lineToWrite = indent + "path.miterLimit = " + lineArray[0] + ";\n"
            print(lineToWrite)
            continue

        # fixing
        if instruction.endswith(" g") or instruction.endswith(" rg"):
            currentColour = parse_colour_line(instruction)
            continue


        if instruction.endswith("f"):
            print("found fill colour for primitive: " + currentColour)
            lineToWrite = indent + "path.fillColor = " + currentColour + ";\n"
            writefile.write(lineToWrite)
            continue
        
        # stroke closing
        if instruction.endswith("h"):
            lineToWrite = indent + "path.closePath();\n"
            writefile.write(lineToWrite)
            continue


        print("if you see this, time to support extra commands")
        print(instruction + "####")
    
    writefile.write("}\n")
    writefile.write(functionName + "();\n")
    
    return
def write_primary_postScript(primitive, functionName, writefile):
    '''
    takes a primitive, a description string. converts it to js readable data

    input:      primitive ( a joined list with raw commands )
    input:      the name of the current function. (each graphical element)
    input:      writefile, is the file we are writing to.
    output:     straight to file.

    This function is distinct from the write_secondary_postScript function because
    it has to deal with multiple paths per shape, combining both functions into one
    is the end goal and they share a lot of similar variable names and strategies.
    '''

    # global dashModeOn
    # global dashParameters
    # global strokeWidth
    global currentColour

    # subdivide into function lines.
    primitive = regex_plotListString(primitive)

    # transverse the primitive
    for instruction in primitive:
        print(instruction)

        if instruction.endswith(" m"):
            lineArray = instruction.split()
            coordinates = pointify_coordinates(lineArray[0:2])
            lineToWrite = indent + "path.moveTo(" + coordinates + ");\n"
            writefile.write(lineToWrite)
            print(lineToWrite)
            continue
    

        if instruction.endswith("l"):
            lineArray = instruction.split()
            coordinates = pointify_coordinates(lineArray[0:2])
            lineToWrite = indent + "path.lineTo(" + coordinates + ");\n"
            writefile.write(lineToWrite)
            continue
        
        if instruction.endswith("c"):
            lineArray = instruction.split()
            coordinates = convert_to_curve_parameters(lineArray)
            lineToWrite = indent + "path.cubicCurveTo(" + coordinates + ");\n"
            writefile.write(lineToWrite)
            continue


        if instruction.endswith(" g") or instruction.endswith(" rg"):
            currentColour = parse_colour_line(instruction)
            continue


        if instruction.endswith("f"):
            print("found fill colour for primitive: " + currentColour)
            lineToWrite = indent + "path.fillColor = " + currentColour + ";\n"
            writefile.write(lineToWrite)
            continue
        
        # stroke closing
        if instruction.endswith("h"):
            lineToWrite = indent + "path.closePath();\n"
            writefile.write(lineToWrite)
            continue


        print(instruction + "### uncaught" )
    return
def write_primitive_postScript(primitive, functionName, writefile):


    global dashModeOn
    global dashParameters
    global strokeWidth

    print("function " + functionName + "(){\n")
    print(indent + "var point = new Point(0, " + rectHeight + ");\n")

    # each time this function is called, it means a new path primitive is
    # being requested. each primitive only has one path
    print(indent + "var path = new Path();\n")

    
    for instruction in primitive:

        if instruction.startswith("[] 0.0 d"):
            dashModeOn = False
            continue

        if instruction.endswith("d"):
            dashModeOn = True
            dashParameters = parse_dash_params(instruction)
            lineToWrite = indent + "path.dashArray = " + dashParameters + ";\n"
            print(lineToWrite)
            continue

        if instruction.endswith(" m"):
            lineArray = instruction.split()
            coordinates = pointify_coordinates(lineArray[0:2])
            lineToWrite = indent + "path.moveTo(" + coordinates + ");\n"
            print(lineToWrite)
            continue

        if instruction.endswith(" cm"):
            print(indent + instruction + " (store some data, no idea)")
            continue

        if instruction.endswith("l"):
            lineArray = instruction.split()
            coordinates = pointify_coordinates(lineArray[0:2])
            lineToWrite = indent + "path.lineTo(" + coordinates + ");\n"
            print(lineToWrite)
            continue
        
        if instruction.endswith("c"):
            lineArray = instruction.split()
            coordinates = convert_to_curve_parameters(lineArray)
            lineToWrite = indent + "path.cubicCurveTo(" + coordinates + ");\n"
            print(lineToWrite)
            continue

        
        # stroke information
        if instruction.endswith("w"):
            strokeWidth = instruction.split()[0]
            lineToWrite = indent + "path.strokeWidth = " + strokeWidth + ";\n"
            print(lineToWrite)
            continue

        if instruction.endswith("S"):
            lineToWrite = indent + "path.strokeColor = " + currentColour + ";\n"
            print(lineToWrite)
            continue

        if instruction.endswith("J"):
            print(indent + instruction + " (a line cap)")
            continue

        if instruction.endswith("j"):
            print(indent + instruction + " (a line join)")
            continue

        if instruction.endswith("M"):
            lineArray = instruction.split()
            # print(indent + instruction + " (set miter limit)")
            lineToWrite = indent + "path.miterLimit = " + lineArray[0] + ";\n"
            print(lineToWrite)
            continue

        
        # stroke closing
        if instruction.endswith("h"):
            lineToWrite = indent + "path.closePath();\n"
            print(lineToWrite)
            continue


        print("if you see this, time to support extra commands")
        print(instruction)

        
    
    print("\n}")
    print(functionName + "();\n")
    
    return
def write_postscript_functions(newPath, functionName, writefile):
    '''
    Create separated functions for each path/compound path, probably a backwards way..

    input: parsed List of path commands for each glyph ( one glyph may contain 1 or more paths)
    output: adds functions to the currently open file.

    This function should be extended to deal with line objects that have width and stroke properties.
    '''

    writefile.write("function " + functionName + "(){\n")

    numPaths = 0
    lineCounter = 0
    pathNames = []
    indent = "    "

    # start writing this path (newPath) to the open file.
    writefile.write(indent + "var point = new Point(0, " + rectHeight + ");\n")

    for line in newPath:

        # find a colour for this path.
        if line.endswith(" g") or line.endswith(" rg"):
            print("found colour information: " + line)
            global currentColour
            currentColour = parse_colour_line(line)
            continue

        # deals with the first new path creation.
        pathname = "path" + str(numPaths)
        if lineCounter == 0:
            lineToPrint = indent + "var " + pathname + " = new Path();\n"
            pathNames.append(pathname)
            writefile.write(lineToPrint)

        # catches the moveTo and lineTo strings.     
        lineArray = line.split()
        foundChar = lineArray[-1]
        if foundChar in ['m', 'l']:
            coordinates = pointify_coordinates(lineArray[0:2])
            command = set_command_value(foundChar)

            # print(str(lineCounter) + "/" + str(len(newPath)))
            if lineCounter >= len(newPath)-2:
                break
            else:
                lineToPrint = indent + pathname + command + coordinates + ");\n" 
                lineCounter += 1
                writefile.write(lineToPrint)
                continue        

        # catches the cubicCurveTo string.
        if foundChar == 'c':
            command = set_command_value(foundChar)
            coordinates = convert_to_curve_parameters(lineArray)
            lineToPrint = indent + pathname + command + coordinates + ");\n" 
            lineCounter += 1
            writefile.write(lineToPrint)
            continue

        # catches the closePath command.
        if foundChar == 'h':        
            lineToPrint = indent + pathname + ".closePath();\n"
            numPaths += 1
            lineCounter += 1    
            writefile.write(lineToPrint)

            if not lineCounter >= len(newPath)-2:
                writefile.write("\n")
                pathname = "path" + str(numPaths)  
                lineToPrint = indent + "var " + pathname + " = new Path();\n"
                pathNames.append(pathname)
                writefile.write(lineToPrint)
               

    # deal with compoundpath 
    if len(pathNames) > 1:
        paths = ", ".join(pathNames)
        
        # use the autosorting function,
        writefile.write("\n" + indent + "var unsortedPathList = [" + paths + "];\n")
        writefile.write(indent + "unsortedPathList = remove_empty_paths(unsortedPathList);\n")
        writefile.write(indent + "var sortedPathList = unsortedPathList.sort(sortOnBoundsSize);\n")
        writefile.write(indent + "var compoundPath = new CompoundPath(sortedPathList);\n")
        writefile.write(indent + "compoundPath.fillColor = " + currentColour + ";\n")
        writefile.write(indent + "compoundPath.strokeColor = " + currentColour + ";\n")
    else:
        writefile.write(indent + "path0.fillColor = " + currentColour + ";\n")

    writefile.write("}\n")
    writefile.write(functionName+"();\n")
    writefile.write("\n\n")
def write_primary_postScript(primitive, functionName, writefile):
    '''
    takes a primitive, a description string. converts it to js readable data

    input:      primitive ( a joined list with raw commands )
    input:      the name of the current function. (each graphical element)
    input:      writefile, is the file we are writing to.
    output:     straight to file.

    This function is distinct from the write_secondary_postScript function because
    it has to deal with multiple paths per shape, combining both functions into one
    would be ideal as they share a lot of similarities.

    Potentially i might be skipping a .closePath occasionally, [TODO]  fix.
    '''

    # global dashModeOn
    # global dashParameters
    # global strokeWidth
    global currentColour

    # subdivide into function lines.
    primitive = regex_plotListString(primitive)

    writefile.write("\nfunction " + functionName + "(){\n")
    writefile.write(indent + "var point = new Point(0, " + rectHeight + ");\n")

    # each time this function is called, it means a new path primitive is
    # being requested. each primitive only has one path
    writefile.write(indent + "var path0 = new Path();\n")



    # transverse the primitive
    pathCounter = 0
    commandCounter = -1
    for instruction in primitive:

        pathName = "path"+str(pathCounter)
        commandCounter += 1
        currentLine = commandCounter
        totalLines = len(primitive)-1
                
        if instruction.endswith(" m"):
            # this avoids writing a hardware assuming moveTo.
            if currentLine is not totalLines - 1:
                lineArray = instruction.split()
                coordinates = pointify_coordinates(lineArray[0:2])
                lineToWrite = indent + pathName + ".moveTo(" + coordinates + ");\n"
                writefile.write(lineToWrite)
                # print(lineToWrite)
            continue
    

        if instruction.endswith("l"):
            lineArray = instruction.split()
            coordinates = pointify_coordinates(lineArray[0:2])
            lineToWrite = indent + pathName + ".lineTo(" + coordinates + ");\n"
            writefile.write(lineToWrite)
            # print(lineToWrite)
            continue
        
        if instruction.endswith("c"):
            lineArray = instruction.split()
            coordinates = convert_to_curve_parameters(lineArray)
            lineToWrite = indent + pathName + ".cubicCurveTo(" + coordinates + ");\n"
            writefile.write(lineToWrite)
            # print(lineToWrite)
            continue


        if instruction.endswith(" g") or instruction.endswith(" rg"):
            currentColour = parse_colour_line(instruction)
            # print("currentColor: "+currentColour)
            continue

        # because fill is the last command of each 'filled' shape, we check how many
        # paths the shape has, if more than one we add the compound function, and
        # set the compound.fillColor instead.
        if instruction.endswith("f"):
            if pathCounter == 0:
                print("found fill colour for shape: " + currentColour)
                lineToWrite = indent + pathName + ".fillColor = " + currentColour + ";\n"
                writefile.write(lineToWrite)
                # print(lineToWrite)
                continue
            
            if pathCounter >= 1:
                print(pathCounter+1)

                pathList = ["path"+str(i) for i in range(pathCounter+1)]
                pathListString = ", ".join(pathList)
                
                lineToWrite = indent + "var unsortedList = [" + pathListString + "];\n"
                writefile.write(lineToWrite)

                lineToWrite = indent + "var sortedList = unsortedList.sort(sortOnBoundsSize);\n"
                writefile.write(lineToWrite)
                
                lineToWrite = indent + "var compoundPath = new CompoundPath(sortedList);\n"
                writefile.write(lineToWrite)

                lineToWrite = indent + "compoundPath.fillColor = " + currentColour + ";\n"
                writefile.write(lineToWrite)
                continue

            
        # stroke closing
        if instruction.endswith("h"):
            if currentLine is totalLines-2:
                continue
            else:
                lineToWrite = indent + pathName + ".closePath();\n"
                writefile.write(lineToWrite)

                pathCounter += 1
                pathName = "path"+str(pathCounter)
                writefile.write(indent + "var " + pathName + " = new Path();\n") 

                # print(lineToWrite)
            continue

        
        print(instruction + "### uncaught" )

    writefile.write("\n}\n")
    writefile.write(functionName + "();\n")

    return