#!/usr/bin/python

import re, string, sys

glossary, files = sys.argv[1], sys.argv[2:]
keywords = dict()

def escape(w):
	s = w[0].isalpha() and r'\b' or ''
	e = w[-1].isalpha() and r'\b' or ''
	return '%s%s%s' % (s, re.escape(w), e)

for line in file(glossary):
	pair = filter(None, map(string.strip, line.split(':', 1)))

	if 2 == len(pair):
		word, text = pair
		keywords[word] = text.replace('"', '&quot;')

pattern = r'(%s)' % '|'.join(map(escape, keywords.keys()))
pattern = re.compile(pattern)

for name in files:
	print pattern.sub(
		lambda m: '<span class="glossary" title="%s">%s</span>' % (
		keywords[m.group(1)], m.group(1)),
		file(name).read())
