#!/usr/bin/env python

# Read a pickled dictionary, and output a bunch of *.tex files
# into the specified directory.

import os, sys
import pickle

def main ():
    if len(sys.argv) < 3:
        print 'Usage: %s database-filename example-dir' % sys.argv[0]
        sys.exit(1)
    
    db_file = sys.argv[1]
    example_dir = sys.argv[2]

    # Delete all *.tex files
    for fn in os.listdir(example_dir):
	if fn.endswith('.tex'):
	    p = os.path.join(example_dir, fn)
	    os.remove(p)
	    
    # Read dictionary
    input = open(db_file, 'rb')
    db = pickle.load(input)
    input.close()
    
    # Output files
    for module in db:
	examples = db[module]
	
	# XXX sort examples in some way?
	
	def tex_escape (t):
	    t = t.replace('%', '\%')
	    t = t.replace('$', '\$')
	    return t
	    
	# Write file containing examples for this module
	p = os.path.join(example_dir, module + '.tex')
	output = open(p, 'w')
	for (url, document_title, document_url,
             author, title, excerpt) in examples:

            attribution = ""
            if document_title:
                attribution += ' from "%s"' % tex_escape(document_title)
                if document_url:
                    attribution += ' (\url{%s})' % (tex_escape(document_url))
            if author:
                attribution += " by %s" % (tex_escape(author))

            if attribution:
                attribution = ',' + attribution
                
	    if excerpt is None:
		output.write("\seeurl{%s}{%s%s.}\n" % (tex_escape(url),
                                                      tex_escape(title),
                                                      attribution,
                                                      ))
	    else:
		output.write("\seeurl{%s}{%s%s.\n\n%s}\n" % (tex_escape(url),
                                                            tex_escape(title),
                                                            attribution,
                                                            tex_escape(excerpt)))
		

	output.close()
	

if __name__ == '__main__':
    main()
    
