# Extract  number of votes for each party's
# Congressional candidates in 2006 election from file.
# Make a list of the winner in each district.

# Function to extract name and votes from a line
def getVotes(line):
    words = line.split(" ")
    # Long lines have the data in them
    if len(words)>5:
        nameList = words[:-4]
        nameStr = ""
        for s in nameList:
            if s != "*":
                nameStr = nameStr + s + " "
        # Cut off trailing blank
        nameStr = nameStr.strip()
        voteStr = words[-3]
        voteStr = voteStr.replace(",","")
        votes = int(voteStr)
        return [nameStr,votes]
    else:
        return None

def store (record,dist):
    global dataBase
    if record != None:
        # item = [dist,record[0]]
        # dataBase = dataBase+[item]
        dataBase[record[0]] = dist


# Main program

# Part 1: Read the data from the file and make a database.

in_file = open("congress.2006.txt","r")


district = 0
winner = None
dataBase = {}

# Loop to read file
line = in_file.readline()
while line != "":
    # Lines indicating start of new congressional district
    if "Congressional" in line:
        # Finish up last district, if there is one...
        store(winner, district)
        # Start new district
        winner = None
        district = district + 1
    # Process vote count lines
    data = getVotes(line)
    if data != None:
        if winner == None or data[1] > winner[1]:
            winner = data
    # Get the next line
    line = in_file.readline()

# Store the last winner in the dataBase
store(winner, district)
print dataBase

# Part two: ask for a query and look it up. 
query = raw_input("Select a Congressperson: ")

if query in dataBase:
    district = dataBase[query]
    print query,\
              "is the Representative from District",district
else:
    print query,"is not a Representative."


in_file.close()
    
