'''A program that shows how data can be saved between runs
of a program.  We use the cPickle module to do the saving and reloading
because it is easier than doing it "by hand".

The particular data being saved is quite silly, but of course this
general technique can be used to save the contents of any variables.
'''

import cPickle
import os.path

if __name__ == "__main__":
    
    # Phase 1: Load up existing data from the last time
    # we ran the program (or initialize to empty if this
    # is the first run.
    if os.path.exists('data.pkl'):
        input_file = open('data.pkl', 'r')
        # Notice that we re-load the variables in the same order in which
        # we dumped them.
        majors = cPickle.load(input_file)
        colleges = cPickle.load(input_file)
        input_file.close()
    else:
        majors = {}
        colleges = {}
    
    # Phase 2: Do whatever the program was intended for,
    # which includes updating the data.
    print "Adding new info about students ..."
    name = raw_input("Name (or 'quit'): ")
    while name != "quit":
        majors[name] = raw_input("Major: ")
        colleges[name] = raw_input("College: ")
        name = raw_input("Name: ")
        
    print "Looking up students' info ..."
    name = raw_input("Name (or 'quit'): ")
    while name != "quit":
        if majors.get(name):
            print "%s's major is %s" % (name, majors[name])
            print "%s's college is %s" % (name, colleges[name])
        else:
            print "Sorry, I have no record of %s" % (name)
        name = raw_input("Name (or 'quit'): ")
        
    # Phase 3: Save the up-to-date version of the data
    # so that the next time we run the program we can
    # start with that data.
    output_file = open('data.pkl', 'w')
    cPickle.dump(majors, output_file)
    cPickle.dump(colleges, output_file)
    output_file.close()