#!/usr/bin/python
import os
import string
import types
import os.path
import sys
import math

# Used by Read_res_file
def Get_line(input):
    line = input.readline()
    if line:
        line = string.split(line,'\n')[0]
    return line

# Extracts the statistics from the input file, averages them, and
# outputs the results in the result file
def Read_res_file(fname, resfile):
    order = ["Total time", "Total distance", "Speed", "Max speed",
             "Lateral balance", "Left turns", "Right turns",
             "Left leans", "Right leans", "Leaning angle to the left",
             "Frames leaning left", "Leaning angle to the right",
             "Frames leaning right", "Times it left the road",
             "Frames spent out of the road", ]
    input=open(fname, "r")
    complete = {}
    incomplete={}
    res = {}
    count_com = 0
    count_incom = 0
    line = 1
    while line:
        line = input.readline()
        if not line:
            break
        if string.find(line, "Average speed:") != -1:
            value = float(string.split(string.split(line,":")[1])[0])
            res["Speed"] = value
            value = float(string.split(line,":")[2])
            res["Max speed"] = value
        elif string.find(line, "Average lateral balance:") != -1:
            value = float(string.split(line,": ")[1])
            res["Lateral balance"] = value
        elif string.find(line, "Total distance covered:") != -1:
            value = float(string.split(line,": ")[1])
            res["Total distance"] = value
        elif string.find(line, "Total time:") != -1:
            value = float(string.split(line,": ")[1])
            res["Total time"] = value
        elif string.find(line, "Times left the road:") != -1:
            value = float(string.split(string.split(line,": ")[1])[0])
            res["Times it left the road"] = value
            value = float(string.split(line,": ")[2])
            res["Frames spent out of the road"] = value
        elif string.find(line, "Total left leans:") != -1:
            value = float(string.split(string.split(line,": ")[1])[0])
            res["Left leans"] = value
            value = float(string.split(line,": ")[2])
            res["Right leans"] = value
        elif string.find(line, "Total left turns:") != -1:
            value = float(string.split(string.split(line,": ")[1])[0])
            res["Left turns"] = value
            value = float(string.split(line,": ")[2])
            res["Right turns"] = value
        elif string.find(line, "Average lean angle when leaning left:") != -1:
            value = float(string.split(string.split(line,": ")[1])[0])
            res["Leaning angle to the left"] = value
            value = float(string.split(string.split(line,", ")[1])[1])
            res["Frames leaning left"] = value
        elif string.find(line, "Average lean angle when leaning right:") != -1:
            value = float(string.split(string.split(line,": ")[1])[0])
            res["Leaning angle to the right"] = value
            value = float(string.split(string.split(line,", ")[1])[1])
            res["Frames leaning right"] = value
        elif string.find(line, "Circuit is completed") != -1:
            count_com = count_com + 1
            for key in res.keys():
                if complete.has_key(key):
                    complete[key] += res[key]
                else:
                    complete[key] = res[key]
        elif string.find(line, "Circuit is not completed") != -1:
            count_incom = count_incom + 1
            for key in res.keys():
                if incomplete.has_key(key):
                    incomplete[key] += res[key]
                else:
                    incomplete[key] = res[key]
    output = open(resfile, "w")
    output.write("Average results from \n%s\n\n" %(fname))
    output.write("Number of completed circuits: %d\n" %(count_com))
    output.write("Number of incomplete circuits: %d\n\n" %(count_incom))
    if count_com:
        output.write("Average results for the completed circuits:\n")
        for key in order:
            line = "%s\t" %(key)
            value = complete[key]/count_com
            line = "%s%g\n" %(line, value)
            output.write(line)
    output.write("\n")
    if count_incom:
        output.write("Average results for the incomplete circuits:\n")
        for key in order:
            line = "%s\t" %(key)
            value = incomplete[key]/count_incom
            line = "%s%g\n" %(line, value)
            output.write(line)
    output.close()

def ComputeStdev(fname, key, value_com, value_incom):
    input=open(fname, "r")
    complete = 0.0
    incomplete = 0.0
    count_com = 0
    count_incom = 0
    line = 1
    value = 0.0
    while line:
        line = input.readline()
        if not line:
            break
        if string.find(line, key) != -1:
            value = float(string.split(string.split(line,":")[1])[0])
        elif string.find(line, "Circuit is completed") != -1:
            count_com = count_com + 1
            complete += (value - value_com) * (value - value_com)
        elif string.find(line, "Circuit is not completed") != -1:
            count_incom = count_incom + 1
            incomplete += (value - value_incom) * (value - value_incom)
            
    if count_com:
        complete = math.sqrt(complete) / count_com
        print "Std dev for the %d completed circuits: %g" % (count_com,
                                                             complete)
    if count_incom:
        incomplete = math.sqrt(incomplete) / count_incom
        print "Std dev for the %d incomplete circuits: %g" % (count_incom,
                                                              incomplete)
    return [complete, incomplete, count_com, count_incom]
        
if __name__ == '__main__' : 
    infile = ""
    outfile = ""
    argv = sys.argv
    if len(argv) > 1:
        infile = argv[1]
        if len(argv) > 2:
            outfile = argv[2]
    if not infile:
        print "enter the imput file within quotes"
        infile = input()
    if not outfile:
        print "enter the output file within quotes"
        outfile = input()
    Read_res_file(infile, outfile)
    
