#!/usr/bin/env python
# @author Cesar Fuguet <cesar.fuguet-tortolero@lip6.fr>
# @date   28 August, 2014
# @desc   generate output file containing a table with the format below:
#
#                              fault configurations
#                   | faultconfig 0 | faultconfig 1 | faultconfig M
#               ----------------------------------------------------
#               4   |    cycles     |    cycles     |    cycles
#  # clusters   16  |    cycles     |    cycles     |    cycles
#               64  |    cycles     |    cycles     |    cycles
#               N   |    cycles     |    cycles     |    cycles

import os
import sys

def parse_ffstend(configs, faultconfigs, confpath, outpath):
    # write header
    ffst_end = open(outpath, "w")
    ffst_end.write("#  ffst end (cycles)\n")
    ffst_end.write("{0}\n".format(len(faultconfigs)))
    for config in faultconfigs:
        ffst_end.write("{0}\n".format(config))

    # repeat while configurations is not empty
    quit = 0
    for x,y in configs:
        ffst_end.write("\n{0:<6}".format(str(x*y)))
        for f in xrange(len(faultconfigs)):
            temp = "config_{0}c{1}f/".format(x*y, f)
            confdir = os.path.join(confpath, temp)

            #  parse term log and get relevant information
            termname = os.path.join(confdir, "term")
            try:
                termlog = open(termname, "r")
            except IOError as e:
                print "IOError {0}: {1}".format(termname, e.strerror)
                quit = 1
                break

            found = False
            for line in termlog:
                partitions = line.partition(':')
                if partitions[0].strip() == "FFST (END)":
                    found = True
                    value = int(partitions[2])
                    ffst_end.write(" {0:<8}".format(value))
                    break

            if not found: ffst_end.write(" {0:<8}".format(-1))
            # end for faultconfig

        if quit: break
        # end for configs

    ffst_end.close()
    # end def parse_ffstend

if __name__ == "__main__":
    configs = []
    configs.append([2 , 2 ])
    configs.append([4 , 2 ])
    configs.append([4 , 4 ])
    configs.append([8 , 4 ])
    configs.append([8 , 8 ])
    configs.append([16, 8 ])
    configs.append([16, 16])

    faultconfigs = []
    faultconfigs.append('0 faulty core')
    faultconfigs.append('1 faulty core')
    faultconfigs.append('2 faulty cores')
    faultconfigs.append('1 faulty cluster (3 cores)')
    faultconfigs.append('2 faulty clusters (6 cores)')

    assert len(sys.argv) > 2, "Introduce config path and output path"

    parse_ffstend(configs, faultconfigs, sys.argv[1], sys.argv[2])

# vim: tabstop=4 : softtabstop=4 : shiftwidth=4 : expandtab
