#!/usr/bin/python

# dictionary.py by Nadeem Abdul Hamid, August 2006
# based on code by Saketh Bhamidipati, 2005

"""
This program will read in a word list from a file and construct as
output an HTML file (web page) containing the definitions of all
the words, as found at dictionary.reference.com.
"""

import sys
from urllib2 import *


def buildDictURL( word ):
    return 'http://dictionary.reference.com/search?q=%s' % word;


def lookupWord( word, outFileHandle ):
    inDef = False    # flag to indicate that we are reading in the
                     # definitions portion of the web page and it should
                     # be printed to the output file

    dict_url = buildDictURL( word )
    for line in urlopen( dict_url ):
        if '<!-- begin ahd4 -->' in line:
            inDef = True
        elif '<!-- end ahd4 -->' in line:
            inDef = False

        if inDef:
            outFileHandle.write( line )


def lookupWords( inFileHandle, outFileHandle ):
    outFileHandle.write('<html>\n<body>')

    for word in inFileHandle.readlines():
        lookupWord( word, outFileHandle )

    outFileHandle.write('</body>\n</html>');


def main(argv=sys.argv):
    if len(argv) == 3:
        try:
            inFileH = file( argv[1], 'r' );
            outFileH = file( argv[2], 'w' );
            lookupWords( inFileH, outFileH );
            inFileH.close();
            outFileH.close();
        except IOError, e:
            print "Sorry, an exception occurred:", e
    else:
        # print usage message
        print \
"""
  dictionary.py, 2006 Nadeem Abdul Hamid
  Usage:
         dictionary.py inFileName outFileName
"""



if __name__ == '__main__':
    main();
