import os, sys, subprocess, time, shutil, filecmp, pymatrices, pycomparator

args={}
args["MSR"] = []
commonstring = ""

def getArgs(cfgfile):
	for line in open(cfgfile,"r"):
		line=line.strip()
		if len(line) == 0:
			continue
		[arg,val] = line.split("=",1)
		if arg == "MSR":
			args[arg].append(val)
		else:
			args[arg] = val

def print_cmp(kbest1, kbest2):

	maxlen = max(len(kbest1), len(kbest2))
	for i in xrange(maxlen):
		if i < len(kbest2):
			w2,r2 = kbest2[i]
		else:
			w2 = " --- "
			r2 = 0
		if i < len(kbest1):
			w,r = kbest1[i]
		else:
			w = " --- "
			r = 0

		print '\t\t%*s\t%.4f\t%*s\t%.4f' % (30,w.decode('utf8'),r,30,w2.decode('utf8'),r2)

def main():
	if len(sys.argv)<2:
		print "Usage: " + sys.argv[0] + " <cfg_file>"
		sys.exit(1)
	getArgs(sys.argv[1])
	words = []
	for line in open(args["words"],"r"):
		line = line.strip()
		words.append(line)
	pMatrix = pymatrices.LoadSuperMatrix(args["mdir"],args["mname"],True, True)	
	i = 0
	for MSR in args["MSR"]:
		pComparClear = pycomparator.FunctionFactory.CreateFunction(MSR, pMatrix)
		pComparTrans = pycomparator.FunctionFactory.CreateFunction(MSR, pMatrix)
		start = time.time()
		pComparTrans.WeightMatrixCopy()
		working = time.time() - start
		print "Matrix transformed for " + MSR + " in " + str(working) + " seconds."
		print "\n\nTesting", MSR
		equal = True
		processed = 0
		avgTransform = 0
		avgClean = 0
		for word in words:
			print "\tProcessing word: " + word
			start = time.time()
			kbestClear = pycomparator.generate_kbest(pComparClear, word, 20)
			working = time.time() - start
			avgClean += working
			print "\tK Best list without transformation fetched in %.2f seconds." % (working,)
			start = time.time()
			kbestTrans = pycomparator.generate_kbest(pComparTrans, word, 20)
			working = time.time() - start
			avgTransform += working
			print "\tK Best list with transformation fetched in %.2f seconds." % (working,)
			equal = (kbestClear == kbestTrans)
			if equal:
				print "\n\tResults are transformation - independent for MSR: " + MSR
				print_cmp(kbestTrans, [])
			else:
				print "\n\t!!! Results vary for MSR: " + MSR + " !!!"
				print_cmp(kbestClear, kbestTrans)
			processed += 1
		avgTransform /= processed
		avgClean /= processed
		print "Generating k best lists took on average " + str(avgClean) + " seconds without and " + str(avgTransform) + " seconds with using the transformMatrix option."
if __name__ == "__main__":
	main()
	
