# This file is for functions used to manipulate the name replacement
# dictionary used by other scripts in here.

import re
import string

def ReadDict(fn, wordChars = r'[\w]'):
    ret = {}

    f = open(fn)
    line = f.readline()
    while line:
        # Trim off comments
        line = re.sub(r'([^#]*)#.*', r'\1', line)

        tokens = string.split(line)
        if len(tokens) >= 2:
            if re.match('^(?:%s)+$' % wordChars, tokens[0]):
                ret[tokens[0]] = tokens[1:]
            else:
                print "# WARNING: dict key '%s' had bad char(s) (not %s) in it" % (tokens[0], wordChars)

        line = f.readline()

    byVal = {}
    for key in ret.keys():
        if byVal.has_key(ret[key][0]): byVal[ret[key][0]].append(key)
        else: byVal[ret[key][0]] = [key]

    for val in byVal.keys():
        if len(byVal[val]) > 1:
            print "# WARNING: Dup substitution value (%s) for keys: %s" % \
                  (val, string.join(byVal[val]))
        
    return ret
