#
#
import os
from math import *
os.system("pwd")
#  Assume all '.dat' files in this directory are grade lists
#  Concatenate them and store the result in a file called 'allgrades'
#  You could also write
#     cat grade[0-9].dat > allgrades
#
os.system("cat *.dat > allgrades")

gradefile = open("allgrades", 'r')         # open the file allgrades
gradelist = [int(k) for k in gradefile]    # read in all data and
gradefile.close()                          # close the file
gradesqlist = [k*k for k in gradelist]
gradelist.sort() # to find the median

n      = len(gradelist)
mean   = float(sum(gradelist))/n
sdev   = sqrt( float(sum(gradesqlist)) / n  -  mean*mean )
median = gradelist[n/2]
statstring = "mean = %4.1f        sdev = %4.1f       median =%3d"%(
    mean, sdev, median)

curve = [0 for i in range(101)]
for g in gradelist: curve[g]+=1
    
#########################  Produce the eps file   ######################
def lineto(P):
    global outfile
    outfile.write("%6.2f %6.2f lineto\n"%(20+2*P[0], 20+2*P[1]))
def moveto(P):
    global outfile
    outfile.write("%6.2f %6.2f moveto\n"%(20+2*P[0], 20+2*P[1]))

outfilename = "histogram.eps"
outfile=open(outfilename, "w")
outfile.write("""%!PS-Adobe-2.0 EPSF-2.0
%%Title: curve.eps
%%BoundingBox: 0 0 240 120
/Helvetica findfont  8 scalefont   setfont
""")
    
unitBoxHeight = 30.0/max(curve)

#Draw boxes:
outfile.write("0 0 1 setrgbcolor\n")
for i in range(101):
    if curve[i]>0:
        moveto([i-1,0])
        lineto([i,0])
        lineto([i,curve[i]*unitBoxHeight])
        lineto([i-1,  curve[i]*unitBoxHeight])
        outfile.write("closepath fill\n")

#draw score axis
outfile.write("0 0 0 setrgbcolor\n")
moveto([-1,0])
lineto([101,0])
outfile.write("stroke\n0.5 setlinewidth\n")
for i in range(11):
    moveto([10*i, 0])
    lineto([10*i, -2])
    outfile.write("stroke\n")
for i in range(11):
    moveto([10*i-2, -6])
    outfile.write( "(%2d) show\n"%(10*i) )

#Print stats
outfile.write("40 100 moveto\n(%s) show\n"%(statstring))

#Finish up
outfile.write("showpage\n")
outfile.close()

#Mac specific: this open the eps file in Preview.app
#on linux use ghostview to view the picture.
os.system("open "+outfilename)
