'''
Created on Nov 1, 2011

These functions are being provided to you and should not
need modification.

@author: rcd, rodger
'''
import tkFileDialog
import urllib
import matplotlib.pyplot as plt 


def get_file (name=''):
    """
    Get a file for reading
    Files can come from a variety of sources:
    - internet, via URL
    - local computer, via file name
    - local computer, chosen by the user
    """
    if name == '':
        return tkFileDialog.askopenfile()
    elif name.startswith('http'):
        return urllib.urlopen(name)
    else:
        return open(name)

def get_lines (file):
    """
    Given a file that is open for reading, read it line by line 
      and return a list of all the lines.
    Note, this function closes the file before returning --- it will need 
      to be opened again before using it again
    """
    result = [line.strip() for line in file.readlines()]
    file.close()
    return result

def get_words (file):
    """
    Given a file that is open for reading, read it word by word
      and return a list of all the words.
    Note, this function closes the file before returning --- it will need 
      to be opened again before using it again
    """
    result = file.read().split()
    file.close()
    return result

def createBarChart(name, ranks, start, end, maxRank):
    ''' 
    Given a name and a list of that name's rankings from the years start to end,
      it plots a barchart showing the name's popularity
    The parameters are:
     - name, a string of a person's first name
     - ranks, a list of integer rankings from 1 to maxRank.
       These are rankings of the name's popularity over several years.
     - start is the first year of data considered
     - end is the last year of data considered
     - maxRank is one more than the maximum possible rank a name can have
       This last value means the name is not in the top 500 ranking.
    '''
    # reverse ranks for graphing (i.e., #1 makes a big bar, not small)
    reverseRanks = [maxRank-x for x in ranks]
    # plot graph
    barLocations = [x for x in range(len(reverseRanks))]
    plt.bar(barLocations, reverseRanks)
    # add some labels for clarity
    plt.title(name)
    plt.xlabel('Years')
    plt.ylabel('Popularity')
    xLabels = [str(x) for x in range(start, end+1, 5)]
    yLabels = [str(maxRank-x) for x in range(1, maxRank, 50)]
    plt.xticks(range(1, end-start+2, 5), xLabels)
    plt.yticks(range(1, maxRank, 50), yLabels)
    # display graph
    plt.show()
