#! /usr/bin/env python

import signal
import sys
import re
import os
import random
import math
import types
pathname = os.path.dirname(sys.argv[0])
fullpath = os.path.abspath(pathname)
os.sys.path = os.sys.path + [fullpath + "/../../exact/src"]
import exact

#
# Process the output log
#
def process_log(OUTPUT,logfile):
	status = 1
	enum=""
        leak_flag=False
        valgrind_leaks="-1"
        valgrind_errors="-1"
	if os.path.exists(logfile):
	   INPUT = open(logfile,"r")
	   for line in INPUT:
	     #print "LINE",line
	     words = re.split('[ \t]+',line.strip())
	     if len(words) < 2:
	        continue

	     if len(words) > 3 and words[2] == "Value" and words[3] == "=":
	        status = 0
	        print >>OUTPUT, "Value numeric/double " + words[4]

	     elif words[0] == "CPU" and words[1] == "RunTime=":
	        print >>OUTPUT, "\"CPU RunTime\" numeric/double " + words[2]

	     elif words[0] == "CPU" and words[1] == "TotalTime=":
	        print >>OUTPUT, "\"CPU TotalTime\" numeric/double " + words[2]

	     elif words[0] == "WallClock" and words[1] == "TotalTime=":
	        print >>OUTPUT, "\"WallClock TotalTime\" numeric/double " + words[2]

	     elif words[0] == "Created":
	        print >>OUTPUT, "\"Subproblems Created\" numeric/integer " + words[1]

	     elif words[0] == "Bounded":
	        print >>OUTPUT, "\"Subproblems Bounded\" numeric/integer " + words[1]

	     elif words[0] == "Split":
	        print >>OUTPUT, "\"Subproblems Split\" numeric/integer " + words[1]

	     elif words[0] == "Dead":
	        print >>OUTPUT, "\"Subproblems Dead\" numeric/integer " + words[1]

	     elif words[0] == "Started" and words[1] == "Bounding":
	        print >>OUTPUT, "\"Subproblems Started Bounding\" numeric/integer " + words[2]

	     elif words[0] == "Started" and words[1] == "Splitting":
	        print >>OUTPUT, "\"Subproblems Started Splitting\" numeric/integer " + words[2]

             elif words[0] == "EnumerationCount:":
                print >>OUTPUT, "EnumerationCount numeric/integer",words[1]

             elif words[0] == "Value:" and words[2] == "Solution:":
                enum = enum + line

             elif words[0] == "Seed:":
                print >>OUTPUT, "Seed numeric/integer",eval("int(" + words[1] + ")")

             #
             # When running under AMPL, the first set of valgrind statistics is the
             # one's that we want
             #
             elif words[1] == "ERROR" and words[2] == "SUMMARY:" and valgrind_errors == "-1":
                valgrind_errors = words[3]
             elif leak_flag==True and words[1] == "definitely" and valgrind_leaks == "-1":
                valgrind_leaks = words[3]
                leak_flag=False

             elif words[1] == "LEAK" and words[2] == "SUMMARY:":
                leak_flag=True

        #
        # Remove commas from valgrind #'s
        #
        p = re.compile( ',' )
        valgrind_errors = p.sub( "", valgrind_errors)
        valgrind_leaks = p.sub( "", valgrind_leaks)
        print >>OUTPUT, "\"Valgrind Errors\" numeric/integer " + valgrind_errors
        print >>OUTPUT, "\"Valgrind Leaks\" numeric/integer " + valgrind_leaks

        if enum != "":
           print >>OUTPUT, "EnumeratedPoints text/string \"\"\""
	   print >>OUTPUT, enum.strip()
	   print >>OUTPUT, "\"\"\""
	print >>OUTPUT, "exit_status numeric/integer " + `status`;


##
## MAIN
##
#
# Setup signal handler
#
if sys.version_info[0:2] >= (2,4):
   signal.signal(signal.SIGTERM, exact.signal_handler)
   signal.signal(signal.SIGINT, exact.signal_handler)
#
# Process factors
#
(factor,option) = exact.process_input_file(sys.argv[2])
#print "HERE",option["seed"]
option.set("seed", int(option["seed"]))
#print "HERE",option["seed"]
#
# Generate log file
#
#
# Compute a simple randomized scalar, and evaluate it with (x-1)^2
#
if "EXACT_DRIVER" in os.environ.keys():
   driver = os.environ["EXACT_DRIVER"]
else:
   driver = ""
if sys.argv[1] == "--knapsack" or sys.argv[1] == "--qsa":
   cmd = driver;
   if sys.argv[1] == "--knapsack":
      cmd = cmd + " ../../knapsackTest" 
   else:
      cmd = cmd + " ../../QSATest" 
   for key in option.keys():
     if key[0] != '_':
        try:
           cmd = cmd + " --" + key + "=\"" + option[key] + "\""
        except:
           cmd = cmd + " --" + key + "=" + `option[key]` + ""
   if option["_data"][0] == "/":
      cmd = cmd + " " + option["_data"]
   else:
      cmd = cmd + " ../../" + option["_data"]
   cmd = cmd
else:
   raise IOError, "Unknown option " + sys.argv[1]
print "Command Line: " + cmd
try:
   exact.run_command(cmd,os.path.basename(sys.argv[4]), cwd=fullpath + "/" + os.path.dirname(sys.argv[2]))
except OSError:
   pass

#
# Generate a measurements file (*.out)
#
OUTPUT = open(sys.argv[3],"w")
process_log(OUTPUT,sys.argv[4])
OUTPUT.close()
