#!/usr/bin/python

import re
import subprocess
import os.path
import sys



class Result:

	def __init__(self,textline,value,desviation=0.0):

		self.regexp = re.compile(textline)
		self.value = value
		self.desviation = desviation

	def check(self,lines):

		correct = False

		for line in lines:

			result = self.regexp.search(line)
			if result:
				value = float(result.group(1))
				error = abs(value-self.value)


			
			
				if error <= self.desviation:
					correct = True

		
		return correct


class Test:

	def __init__(self,program,arguments,result):

		self.program = program
		self.arguments = arguments
		self.result = result


	def run(self,nprocs=[0]):

		# Message
		print "Checking:" , self.program
		print "------------------------"

		if not os.path.exists(self.program):
			print "Error: Program not found"
			sys.exit(0)

		# Loop for the processes
		for p in nprocs:
	
			# Create the execution line
			exelist = []
			if p > 0:
				exelist = ["mpiexec"]
				exelist.append("-n")
				exelist.append(str(p))
			exelist.append("./"+self.program)


			# Arguments
			for arg in self.arguments:
				exelist.append(arg)

			# Execute the program
			subp = subprocess.Popen(exelist, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
			lines = subp.stdout.readlines()
			subp.wait()


			correct = False
			if self.result != None:
				correct = self.result.check(lines)
			

			# Print the message
			if p == 0:
				print	"[Sequential] ",	
			else:
				print "[Procs " + str(p).rjust(4) + "] ",


			if correct:
				print "Ok"
			else:
				print "WRONG !!!"
				sys.exit(0)


		print

#############################33



# Arguments:
# - A protein sequence
# - B protein sequence
# - PAM matrix
# - Gap penalty
# - Size A
# - Size B
# - Iterations
arguments = [
	["inputset/a_500k","inputset/b_500k","inputset/pam_500k","-2","20","15","2"],
	["inputset/a_500k","inputset/b_500k","inputset/pam_500k","-1","50","40","10"],
	["inputset/a_500k","inputset/b_500k","inputset/pam_500k","-1","5000","5000","1"],
	]

# Results:
# - Regular expresion
# - Result value
resultline = "Last Alignment length: ([0-9\.]+)"
results = [
	Result(resultline,7),
	Result(resultline,52),
	Result(resultline,6175),
	]

# Processors
processors = [1,2,3,4,8]


# Run the tests
for (a,r) in zip(arguments,results):

	test = Test("SWseq_ref",a,r)
	test.run()

	test = Test("SWpar_ref",a,r)
	test.run(processors)

	test = Test("SWseq",a,r)
	test.run()

	test = Test("SWpar",a,r)
	test.run(processors)















