#!/usr/bin/python
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0

# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/

import sys
import re

"""Baby Names exercise

Define the extract_names() function below and change main()
to call it.

For writing regex, it's nice to include a copy of the target
text for inspiration.

Here's what the html looks like in the baby.html files:
...
<h3 align="center">Popularity in 1990</h3>
....
<tr align="right"><td>1</td><td>Michael</td><td>Jessica</td>
<tr align="right"><td>2</td><td>Christopher</td><td>Ashley</td>
<tr align="right"><td>3</td><td>Matthew</td><td>Brittany</td>
...

Suggested milestones for incremental development:
 -Extract the year and print it
 -Extract the names and rank numbers and just print them
 -Get the names data into a dict and print it
 -Build the [year, 'name rank', ... ] list and print it
 -Fix main() to use the extract_names list
"""

def extract_names(filename):
  """
  Given a file name for baby.html, returns a list starting with the year string
  followed by the name-rank strings in alphabetical order.
  ['2006', 'Aaliyah 91', Aaron 57', 'Abagail 895', ' ...]
  """
  # +++your code here+++
  f = open(filename, 'rU')
  file_strings = f.read()
  nr_dict = {}

  tuples = re.findall(r'(Popularity in )(\d\d\d\d)', file_strings)
  year = tuples[0][1]
  print year
  tuples = re.findall(r'<td>(\d+)</td><td>(\w+)</td><td>(\w+)</td>', file_strings)

  for i in range(1,3):
    for nr_tuple in tuples:
      nr_dict[nr_tuple[i]] = nr_tuple[0]
  print nr_dict.items()

  return [] 


def main():
  # This command-line parsing code is provided.
  # Make a list of command line arguments, omitting the [0] element
  # which is the script itself.
  args = sys.argv[1:]

  if not args:
    print 'usage: [--summaryfile] file [file ...]'
    sys.exit(1)

  # Notice the summary flag and remove it from args if it is present.
  summary = False
  if args[0] == '--summaryfile':
    summary = True
    del args[0]

  # +++your code here+++
  # For each filename, get the names, then either print the text output
  # or write it to a summary file
  for filename in args:
    name_list = extract_names(filename)

    if summary == False:
      print name_list
    else:
      print name_list
      #write the text output to a file
  
if __name__ == '__main__':
  main()

@@ -1342,16 +1342,33 @@
 ict = %7B%7D
+%0A  output_ls = %5B%5D
 %0A%0A  tupl
@@ -1456,18 +1456,31 @@
 %5D%0A  
-print 
+output_ls.append(
 year
+)%0A
 %0A  t
@@ -1652,23 +1652,29 @@
 uple%5B0%5D%0A
+%0A
   
-pr
+for key 
 in
-t
  nr_dict
@@ -1678,14 +1678,61 @@
 ict.
-items(
+keys():%0A    output_ls.append(key + ' ' + nr_dict%5Bkey%5D
 )%0A%0A 
@@ -1739,18 +1739,25 @@
  return 
-%5B%5D
+output_ls
  %0A%0A%0Adef 

Build the [year, 'name rank', ... ] list and print it