import os

datadir = 'LispData'
numbins = str(2)
rootdir = '/home/jwood13/svns/wisp/var/jwood/lisp101/ml/' + datadir
walk = os.walk(rootdir)

# Results files
outfile1 = "results/defective.txt"
outfile2 = "results/flawless.txt"
# Header to flawless
resheader = "Set 1        Set 2            A     B     C     D     Pd     Pf   Prec    Acc  Bin   Fits   Rec\n"
try:
    outfile = open(outfile1, "a")
except IOError:
    print ("Error: You lack permission to write files here\n")
    exit()
outfile.write(resheader)
outfile.close()
# Header to defective
try:
    outfile = open(outfile2, "a")
except IOError:
    print ("Error: You lack permission to write files here\n")
    exit()
outfile.write(resheader)
outfile.close()

# Walk through main dir
for subdir, dirs, files in walk:
    # Not really needed but sort the dirs
    dirs.sort()
    for adir in dirs:
        # Subdir for files os walk
        subdir = rootdir + "/" + adir      
        # Walk through the subdir
        for subdir, dirs, files in os.walk(subdir):
            # Put the files in order
            files.sort()
            i = 0
            # Go through files 2 at a time and feed them to test2
            # by re-writing main each time
            while (i < len(files)):
                infile1  = datadir + "/" + adir + "/" + files[i]
                infile2  = datadir + "/" + adir + "/" + files[i+1]
                outline1 = "(load \"boot.lisp\")\n"
                outline2 = "(test2 \"" + infile1 + "\" \"" + infile2 + "\" " + numbins + "  \"" + outfile1 + "\" \"" + outfile2 + "\")"
                command  = "bash lisp"
                # Open and write main.lisp
                mainloc = "main.lisp"
                try:
                    outfile = open(mainloc, "w")
                except IOError:
                    print ("Error: You lack permission to write files here\n")
                    exit()              
                outfile.write(outline1)
                outfile.write(outline2)
                outfile.close()
                print (outline2)
                i += 2
                # call lisp (writes a row to the results each call) BROKEN!?
                out = os.popen(command)
                out.close()
        print
        # Add some nl after each datasets rows
        try:
            outfile = open(outfile1, "a")
        except IOError:
            print ("Error: You lack permission to write files here\n")
            exit()
        #outfile.write("\n")
        outfile.close()
        try:
            outfile = open(outfile2, "a")
        except IOError:
            print ("Error: You lack permission to write files here\n")
            exit()
        #outfile.write("\n")
        outfile.close()
        




                
            
