#!/usr/bin/python

import sys, os, subprocess, shutil, time

class MSRTestConfig:
	def __init__(self, infile = None):
		self.infile = infile
		self.msrs = {}
		self.targetwords = {}
		self.outpath = ""
		self.matrixdir = ""
		self.matrixname=  ""
		self.transformMatrix = "1"
		self.resulttype = "supermatrix"
		self.kbestresults = "90000000"
		self.minimumsimilarity = "0.001"

	def getKey(self, line):
		return line.split("=",1)[0]

	def getVal(self, line):
		return line.split("=",1)[1]

	def getKeyVal(self, line):
		return line.split("=",1)

	def processLine(self, line):
		if line.strip() == "":
			return
		if line[0] == "#":
			return
		(key, val) = self.getKeyVal(line)
		key = key.strip()
		val = val.strip()
		if key == "msr":
			(msr, name) = val.split('\t')
			self.msrs[msr] = name
		elif key == "targetWords":
			(wordfile, name) = val.split('\t')
			self.targetwords[wordfile] = name
		elif key == "outPath":
			self.outpath = val
		elif key == "matrixDir":
			self.matrixdir = val
		elif key == "matrixName":
			self.matrixname = val
		elif key == "transformMatrix":
			self.transformmatrix = val
		elif key == "resultsType":
			self.resulttype = val
		elif key == "kBestResults":
			self.kbestresults = val
		elif key == "minimumSimilarity":
			self.minimumsimilarity = val
		elif key == "commandPrefix":
			self.commandprefix = val
		else:
			print "Error: unknown key: " + key
			sys.exit(-1)

	def processFile(self):
		if self.infile == None:
			print "Error: No configuration file specified."
			sys.exit(-1)
		for line in self.infile:
			self.processLine(line)

def runTests(config):
	for msr in config.msrs:
		for wordfile in config.targetwords:
			omatrixname = config.msrs[msr] + "_" + config.targetwords[wordfile]

			odir = os.path.join(config.outpath, omatrixname)
			if not os.path.isdir(odir):
				os.mkdir(odir)

			shutil.copy(os.path.join(config.matrixdir, os.path.join(config.matrixname, "boundary.txt")),os.path.join(odir, "boundary.txt"))
			shutil.copy(os.path.join(config.matrixdir, os.path.join(config.matrixname, "row_features.csv")),os.path.join(odir, "row_features.csv"))
			os.popen("ln -s " + os.path.join(odir, "row_features.csv") + " " + os.path.join(odir, "column_features.csv"))
			shutil.copy(os.path.join(config.matrixdir, os.path.join(config.matrixname, "info.txt")),os.path.join(odir, "info.txt"))
			shutil.copy(os.path.join(config.matrixdir, os.path.join(config.matrixname,config.matrixname + ".rlabel")),os.path.join(odir, omatrixname + ".rlabel"))
			os.popen("ln -s " + os.path.join(odir, omatrixname + ".rlabel") + " " + os.path.join(odir, omatrixname + ".clabel"))

			ofile = "matrix_crs.mat"
			ofile = os.path.join(odir, ofile)
			cmd = config.commandprefix + " --matrix-dir " + config.matrixdir + " --matrix-name " + config.matrixname + " --results-file " + ofile \
			+ " --results-type " + config.resulttype + " --k-best-results " + config.kbestresults + " --minimum-similarity " + config.minimumsimilarity \
			+ " --transform-matrix " + config.transformmatrix + " --target-words-file " + wordfile + " --measure-of-relatedness " + msr 
			
			#print "RUNNING " + cmd

			cmdProcess = subprocess.Popen(cmd, shell=True)
			while cmdProcess.poll() == None:
				#wait untill matrix is calculated
				time.sleep(1)
			
			#print "RUNNING " + "ln -s " + ofile + " " + os.path.join(odir, "matrix_ccs.mat")			

			os.popen("ln -s " + ofile + " " + os.path.join(odir, "matrix_ccs.mat"))
		
def main():
	if len(sys.argv) != 2:
		try:
			cfgfile = open("msrs.cfg","r")
		except:
			print "Usage: " + sys.argv[0] + " <config_file>"
			sys.exit(-1)
	else:
		try:
			cfgfile = open(sys.argv[1],"r")
		except:
			print "Could not open configuration file."
			sys.exit(-1)
	cfg = MSRTestConfig(cfgfile)
	cfg.processFile()
	runTests(cfg)



if __name__ == "__main__":
	main()
