#!/usr/bin/env python

"""Usage: t-rext [OPTIONS] FILES

Adjusts spacing (and other factors) to make a generated text more presentable.
"""

from os.path import realpath, dirname, join
import sys

sys.path.insert(0, join(dirname(realpath(sys.argv[0])), '..', 'src'))

# ----------------------------------------------------------------- #

from argparse import ArgumentParser
import codecs
import sys

from t_rext.processors import (
    CapitalizationProcessor,
    EllipsisFixer,
    TidyPunctuationLineFilter,
    TidyStartOfLineProcessor,
    QuoteOrienterLineFilter,
    LinesToParagraphsRegrouper,
)


def main(args):
    argparser = ArgumentParser(usage=__doc__.strip())

    argparser.add_argument('--version', action='version', version="%(prog)s 0.3")

    (options, args) = argparser.parse_known_args(args)

    for filename in args:
        with codecs.open(filename, 'r', encoding='UTF-8') as f:
            for para in LinesToParagraphsRegrouper(f):
                proc = QuoteOrienterLineFilter(para)
                proc = TidyStartOfLineProcessor(proc)
                proc = TidyPunctuationLineFilter(proc)
                proc = CapitalizationProcessor(proc)
                proc = EllipsisFixer(proc)
                for line in proc:
                    try:
                        sys.stdout.write(line)
                    except UnicodeEncodeError:
                        sys.stdout.write(line.encode('utf-8'))
                    sys.stdout.write('\n')


if __name__ == '__main__':
    main(sys.argv[1:])
