#!/usr/bin/env python
#-*- coding:utf-8 -*-

# filename  : capitalizer.py
# date created: 21-08-2012 19:19:36 IST
# purpose   : to capitalize words in a txt file, words which has less than
# 3 words are escaped.
# author    : Santosh Kumar <https://twitter.com/sntshk>
# copyright : Copyright (c) 2012-2013 Santosh Kumar <sntshkmr60@gmail.com>
# license   : See LICENSE file in root directory

from string import punctuation
from os import linesep
from sys import argv, stdin
from argparse import ArgumentParser, FileType, RawDescriptionHelpFormatter

parser = ArgumentParser(
    prog='capitalizr',
    description='capitalize words, leaving words less than 3 characters',
    formatter_class=RawDescriptionHelpFormatter,
    epilog='''examples:

    # Show capitalized text in terminal window
    $ capitalizr textfile.txt

    # Create another file with capitalized text
    $ capitalizr textfile.txt > outputfile.txt

    # Pipe over other terminal apps (e.g. `cat`)
    $ cat textfile.txt | capitalizr -

SEE PROJECT PAGE: http://git.io/-3fOzA FOR MORE INFO
''')

parser.add_argument(
    'inputfile',
    type=FileType('r'),
    nargs='?',
    default=stdin,
    help='file to be capitalized; usually a .txt file'
    )

parser.add_argument(
    '-o',
    dest='outputfile',
    nargs='?',
    help='file to store capitalized content.'
    )

parser.add_argument(
    '-t',
    '--threshold',
    type=int,
    default=3,
    dest='threshold',
    help='words with n or less letters escaped'
    )

parser.add_argument(
    '-v',
    '--version',
    action='version',
    version='%(prog)s 1.01.00'
    )

# Check if first argument is nothing, if so print help
if len(argv) < 2:
    parser.print_help()
else:
    # Parse the argument here, parsing it before the if block would create error
    args = parser.parse_args()
    # Check if output file is provided, if so write processed contents to it.
    if args.outputfile:
        # List to store the capitalised lines.
        lines = []
        for line in args.inputfile:
            # Clear the extra line after each line, see issue #1 and #3
            line = line.rstrip('\n')
            # Split words by spaces.
            words = line.split(' ')
            for i, word in enumerate(words):
                if len(word.strip(punctuation)) > args.threshold:
                    # Capitalise and replace words longer than 3 letters (counts
                    # without punctuation).
                    if word != word.upper():
                        words[i] = word.capitalize()
            # Join the capitalised words with spaces.
            lines.append(' '.join(words))
        # Join the capitalised lines by the line separator.
        capitalised = linesep.join(lines)
        # Do the actual work of writing to the file.
        with open(args.outputfile, 'w') as f:
            f.write(capitalised)
    else:
        if argv[1] == "-":
            pass
        else:
            for line in args.inputfile:
                # Clear the extra line after each line, see issue #1 and #3
                line = line.rstrip('\n')
                # Split words by spaces.
                words = line.split(' ')
                for i, word in enumerate(words):
                    if len(word.strip(punctuation)) > args.threshold:
                        # Capitalise and replace words longer than 3 letters (counts
                        # without punctuation).
                        if word != word.upper():
                            words[i] = word.capitalize()
                # Print the capitalised words with spaces.
                print(' '.join(words))
