#!/usr/bin/env python3

import sys
from enum import Enum

csv = False
tabular = True

class State(Enum):
    AWAITING_SYS = 0
    AWAITING_SYS_NAME = 1
    AWAITING_ROW = 2
    AWAITING_ROW_NAME = 3
    AWAITING_FILE = 4

def die():
    print('invalid sequence of parameters')
    sys.exit(1)

state = State.AWAITING_SYS
systems = []

for arg in sys.argv[1:]:
    if state is State.AWAITING_SYS:
        if '--sys' in arg:
            state = State.AWAITING_SYS_NAME
            continue
        else: die()
    elif state is State.AWAITING_SYS_NAME:
        state = State.AWAITING_ROW
        systems.append((arg, []))
    elif state is State.AWAITING_ROW:
        if '--row' in arg:
            state = State.AWAITING_ROW_NAME
            continue
        else: die()
    elif state is State.AWAITING_ROW_NAME:
        state = State.AWAITING_FILE
        systems[-1][1].append((arg, []))
    elif state is State.AWAITING_FILE:
        if '--row' in arg:
            state = State.AWAITING_ROW_NAME
            continue
        if '--sys' in arg:
            state = State.AWAITING_SYS_NAME
            continue
        systems[-1][1][-1][1].append(arg)

def csv_print(*args, **kwargs):
    if csv:
        print(*args, **kwargs)

def tabular_print(*args, **kwargs):
    if tabular:
        print(*args, **kwargs)

# debug
#print(systems)

# CSV printing mode
csv_print('System;', end = '')
[ csv_print(f'{row[0]};', end = '') for row in systems[0][1][:-1] ]
csv_print(systems[0][1][-1][0])

for system in systems:
    #tabular_print(f'# {system[0]}')
    counts = []
    for row in system[1]:
        total_count = 0
        for filepath in row[1]:
            with open(filepath) as fp:
                total_count += sum([ int(line.strip().split(' ')[0]) for line in fp ])
        counts.append(total_count)
        tabular_print(f'{row[0]};{total_count}')
    if not system is systems[-1]:
        tabular_print()

    # CSV printing mode
    csv_print(f'{system[0]};', end = '')
    [ csv_print(f'{c};', end = '') for c in counts[:-1] ]
    csv_print(counts[-1])
