#!/usr/bin/python

import sys, os
import time
import subprocess

def main():
	indir = sys.argv[1]
	outfile = open(sys.argv[2],"w")

	matrixdict = {}
	functiondict = {}
	testdict = {}

	if not os.path.isdir(indir):
		print indir + " is not a valid directory."
		sys.exit(1)
	logindex = open(os.path.join(indir,"log_index.txt"),"r")
	for line in logindex:
		line = line.strip()
		if line == "Filename;matrix;function;wbst test" or line == "":
			continue
		(filename,matrix,function,test) = line.split(";")
		matrixdict[filename] = matrix
		functiondict[filename] = function
		testdict[filename] = test
		
	outfile.write("matrix1;matrix2;msr1;msr2;test;chi;difference\n")
	for filename1 in os.listdir(indir):
		if "log" not in filename1 or filename1 == "log_index.txt":
			continue
		for filename2 in os.listdir(indir):
			if filename2 <= filename1 or "log" not in filename2 or filename2 == "log_index.txt":
				continue
			if not testdict[filename1] == testdict[filename2]:
				continue
			tmpfile = "tmp.txt"
			filename1full = os.path.join(indir,filename1)
			filename2full = os.path.join(indir,filename2)
			print "Executing " + "python wbst_aggreement.py " + filename1full + " " + filename2full + " > " + tmpfile
			agrprocess = subprocess.Popen("python wbst_aggreement.py " + filename1full + " " + filename2full + " > " + tmpfile, shell = True)
			
			while agrprocess.poll() == None:
				time.sleep(1)
			for line in open(tmpfile,"r"):
				if "Difference" in line:
					chi = line.split("for")[1].strip()
					outfile.write(matrixdict[filename1] + ";" + matrixdict[filename2] + ";" + functiondict[filename1] + ";"\
					+ functiondict[filename2] + ";" + testdict[filename1] + ";" + chi + ";")
					if " not " in line:
						outfile.write("-\n")
					else:
						outfile.write("+\n")

if __name__ == "__main__":
	main()
