#!/usr/bin/env python
"""Convert RazerS gapped params .dat file to C++ fragment."""

USAGE = 'dat2cpp.py INPUT.dat'

__author__ = 'Manuel Holtgrewe <manuel.holtgrewe@fu-berlin.de>'

import os.path
import re
import sys

def parseFile(f, n, d):
    res = []
    header = f.readline()
    ws = f.readline()
    assert not ws.strip()
    for line in f:
        errors, shape, t, loss_rate, pot_mat = tuple([x.strip() for x in line.split()])
        errors = int(errors)
        t = int(t)
        loss_rate = float(loss_rate)
        pot_mat = int(pot_mat)
        res.append(tuple([n, '\'%s\'' % d, errors, '"' + shape + '"', t, loss_rate, pot_mat]))
    return res

def main():
    # Check arguments.
    if len(sys.argv) == 1:
        print >>sys.stderr, USAGE
        return 1
    # Process each file.
    records = []
    paths = sys.argv[1:]
    for path in paths:
        fname = os.path.basename(path)
        t = re.match('results_N([0-9]+)_([LH])', fname).groups()
        n = int(t[0])
        d = t[1]
        with open(fname, 'rb') as f:
            records += parseFile(f, n, d)
    print '/* Gapped params.  Generated by dat2cpp.py. */\n'
    for r in sorted(records):
        print '{ %s },' % ', '.join(map(str, r))
    print '{ 0, \'\\0\', 0, 0, 0, 0, 0 } /* terminator */'

if __name__ == '__main__':
    sys.exit(main())
