#!/usr/bin/env python
"parse input into output as described by kata.txt and settings.py"

from __future__ import print_function

from parse.generators.lines_from_path import lines_from_path
from parse.generators.entries_from_lines import entries_from_lines
from parse.generators.figures_from_entries import figures_from_entries
from parse.generators.superpositions_from_figures import superpositions_from_figures
from parse.generators.accounts_from_superpositions import accounts_from_superpositions
from parse.generators.results_from_accounts import results_from_accounts
from parse.options import in_path_and_out_path

def parse(input_path, output_path):
    "Parse Lines in input into Results in output"

    lines = lines_from_path(input_path)
    entries = entries_from_lines(lines)
    figures = figures_from_entries(entries)
    superpositions = superpositions_from_figures(figures)
    accounts = accounts_from_superpositions(superpositions)
    results = results_from_accounts(accounts)
    _output_to_file_or_stdout(results, output_path)

def _output_to_file_or_stdout(results, path):
    "print results to path or (default of) StdOut"
    if path is None:
        _output_to_stdout(results)
    else:
        _output_to_file(results, path)

def _output_to_stdout(results):
    "print results to StdOut"
    for result in results:
        print(result)

def _output_to_file(results, path):
    "print results to file at path"
    with open(path, 'w') as out_file:
        for result in results:
            print(result, file=out_file)

if __name__ == '__main__':
    parse(*in_path_and_out_path())
