# nameparse4.py
# Written by Todd Wareham for CS 2500
"""
Given the name of a textfile of proper names (one per line) consisting
 of a last name and a first name composed of up to three first names and/or
 initials as a command-line argument, print reversed form of
 each proper name in given file with initial randomly-selected nickname.
"""

import sys
import re
import random


def procName(m):
    nickname = {"H": ["Horrifyin'", "Happy"], 
                "T": ["Terrific", "Truckin'"]}
    lastName = m.group(1)
    firstNames = m.group(2)
    if m.group(3) != None:
        firstNames += (" " + m.group(3))
        if m.group(4) != None:
            firstNames += (" " + m.group(4))
    return random.sample(nickname[firstNames[0]], 1)[0] + " " + firstNames + " " + lastName


    
if len(sys.argv) != 2:
    print "usage: ", sys.argv[0], " name-file"
    sys.exit(1)

lastNameP   = "([A-Z][a-z]+)"
firstNameP  = r"([A-Z]\.|[A-Z][a-z]+)"
firstNamesP = firstNameP + "(?: " + firstNameP + ")?" + "(?: " + firstNameP + ")?"
nameP       = lastNameP + ", " + firstNamesP
r = re.compile(nameP)

for line in open(sys.argv[1]):
    print line.rstrip(), " --> ", r.sub(procName, line.rstrip())

