import os
import copy

def compare_wordcounts(a, b):
    if a[1]>b[1]:
        return 1
    elif a[1]<b[1]:
        return -1
    else:
        return 0

print "starting"
dir = os.path.expanduser("~/courses/COMP150/comp150-book/source/")
alicefile = open(os.path.expanduser(dir + "alice.txt"))
alicetext = alicefile.read()
words = alicetext.split()

wordcount = dict()
for i in words:
    wordcount[i] = wordcount.get(i,0)+1

wordcountlist = wordcount.items()
wordcountlist.sort(compare_wordcounts)

codewords = copy.deepcopy(words)

index_dict = dict()
for i in range(0,len(wordcountlist)):
    index_dict[wordcountlist[i][0]] = i

print "coding"
for i in range(0,len(codewords)):
    codewords[i] = chr(index_dict[codewords[i]])

outfile = open(dir + "alice.coded", "wb")
outfile.write(" ".join(codewords))
outfile.close()

print "finished"
