# gmplot2.py
# Written by Todd Wareham for CS 2500
"""
Given a plot specification file as a command-line argument, plots the 
 specified functions in the specified range in one plot. If an additional 
 command-line argument plot-file is also given, saves plot to that file in 
 the format specified by the file's extension.

Note that this is implemented using x-data/function plotting, where x-data is
 explicitly created as a NumPy-style array.
"""

from pylab import *


## Plot-line style constant dictionaries

lineColor = {"blue" : "b", "green" : "g", "red" : "r", "cyan" : "c", 
             "magenta" : "m", "yellow" : "y", "black" : "k"}

lineStyle = {"solid" : "-", "dashed" : "--", "dash-dot" : "-.", 
             "dotted" : ":", "none" : ""}

markerStyle = {"point" : ".", "circle" : "o", "triangle" : "^", 
               "square" : "s", "pentagon" : "p", "hexagon" : "h",
	       "plus" : "+", "cross" : "x", "diamond" : "D"}


if len(sys.argv) not in [2, 3]:
    print "usage: ", sys.argv[0], " nlim {plot-file}"
    sys.exit(1)

## Read plot-spefication file

nlim = flim = 0
x = []
plotList = []
legList = []

count = 1

for line in file(sys.argv[1]):
    if count == 1:
        nlim, flim = [int(x) for x in line.split()]

## Set up plot data

        x = arange(1, (nlim + 1), 2)

## Describe plot characteristics

        xlabel("x")
        ylabel("f(x)")
        title("function plots")

    else:

## Create plotted line

        funcStr, rlineColor, rlineStyle, rmarkerStyle = \
            [y for y in line.split()]

        plotLineSpec = lineColor[rlineColor] + lineStyle[rlineStyle] + \
	               markerStyle[rmarkerStyle]

        plotList += plot(x, eval(funcStr), plotLineSpec)
	legList.append(funcStr)

    count = count + 1

if flim != -1: ylim(0, flim)

legend(plotList, legList, loc="upper left")

## Display plotted figure

print ">>> Creating requested plot ..."

show()

## Save plotted figure

if len(sys.argv) == 3:
    print ">>> Saving requested plot ..."
    savefig(sys.argv[2])

print ">>> Plotting finished"

