ef _pos_match(pos_tuple):
    """
    This function returns the complete pos tuple for the partial pos
    tuple given to it.  It attempts to match it against the first
    non-null component of the given pos tuple.
    """
    if pos_tuple[0] == 's':
        pos_tuple = ('a', pos_tuple[1], pos_tuple[2])
    for n,x in enumerate(pos_tuple):
        if x is not None:
            break
    for pt in _pos_tuples():
        if pt[n] == pos_tuple[n]: return pt
    return None


HYPONYM = 0
HYPERNYM = 1
CLASS_REGIONAL = 2
PART_HOLONYM = 3
PART_MERONYM = 4
ATTRIBUTE = 5
SUBSTANCE_HOLONYM = 6
SUBSTANCE_MERONYM = 7
MEMBER_HOLONYM = 8
MEMBER_MERONYM = 9
VERB_GROUP = 10
INSTANCE_HYPONYM = 12
INSTANCE_HYPERNYM = 13
CAUSE = 14
ALSO_SEE = 15
SIMILAR = 16
ENTAILMENT = 17
ANTONYM = 18
FRAMES = 19
PERTAINYM = 20

CLASS_CATEGORY = 21
CLASS_USAGE = 22
CLASS_REGIONAL = 23
CLASS_USAGE = 24
CLASS_CATEGORY = 11

DERIVATIONALLY_RELATED_FORM = 25

INDIRECT_HYPERNYMS = 26


def lemma_property(word, synset, func):

    def flattern(l):
        if l == []:
            return []
        else:
            return l[0] + flattern(l[1:])

    return flattern([func(l) for l in synset.lemmas if l.name == word])


def rebuild_tree(orig_tree):
    node = orig_tree[0]
    children = orig_tree[1:]
    return (node, [rebuild_tree(t) for t in children])


def get_relations_data(word, synset):
    """
    Get synset relations data for a synset.  Note that this doesn't
    yet support things such as full hyponym vs direct hyponym.
    """
    if synset.pos() == wn.NOUN:
        return ((HYPONYM, 'Hyponyms',
                   synset.hyponyms()),
                (INSTANCE_HYPONYM , 'Instance hyponyms',
                   synset.instance_hyponyms()),
                (HYPERNYM, 'Direct hypernyms',
                   synset.hypernyms()),
                (INDIRECT_HYPERNYMS, 'Indirect hypernyms',
                   rebuild_tree(synset.tree(lambda x: x.hypernyms()))[1]),
#  hypernyms', 'Sister terms',
                (INSTANCE_HYPERNYM , 'Instance hypernyms',
                   synset.instance_hypernyms()),
#            (CLASS_REGIONAL, ['domain term region'], ),
                (PART_HOLONYM, 'Part holonyms',
                   synset.part_holonyms()),
                (PART_MERONYM, 'Part meronyms',
                   synset.part_meronyms()),
                (SUBSTANCE_HOLONYM, 'Substance holonyms',
                   synset.substance_holonyms()),
                (SUBSTANCE_MERONYM, 'Substance meronyms',
                   synset.substance_meronyms()),
                (MEMBER_HOLONYM, 'Member holonyms',
                   synset.member_holonyms()),
                (MEMBER_MERONYM, 'Member meronyms',
                   synset.member_meronyms()),
                (ATTRIBUTE, 'Attributes',
                   synset.attributes()),
                (ANTONYM, "Antonyms",
                   lemma_property(word, synset, lambda l: l.antonyms())),
                (DERIVATIONALLY_RELATED_FORM, "Derivationally related form",
                   lemma_property(word, synset, lambda l: l.derivationally_related_forms())))
    elif synset.pos() == wn.VERB:
        return ((ANTONYM, 'Antonym',
                   lemma_property(word, synset, lambda l: l.antonyms())),
                (HYPONYM, 'Hyponym',
                   synset.hyponyms()),
                (HYPERNYM, 'Direct hypernyms',
                   synset.hypernyms()),
                (INDIRECT_HYPERNYMS, 'Indirect hypernyms',
                   rebuild_tree(synset.tree(lambda x: x.hypernyms()))[1]),
                (ENTAILMENT, 'Entailments',
                   synset.entailments()),
                (CAUSE, 'Causes',
                   synset.causes()),
                (ALSO_SEE, 'Also see',
                   synset.also_sees()),
                (VERB_GROUP, 'Verb Groups',
                   synset.verb_groups()),
                (DERIVATIONALLY_RELATED_FORM, "Derivationally related form",
                   lemma_property(word, synset, lambda l: l.derivationally_related_forms())))
    elif synset.pos() == wn.ADJ or synset.pos == wn.ADJ_SAT:
        return ((ANTONYM, 'Antonym',
                   lemma_property(word, synset, lambda l: l.antonyms())),
                (SIMILAR, 'Similar to',
                   synset.similar_tos()),
                # Participle of verb - not supported by corpus
                (PERTAINYM, 'Pertainyms',
                   lemma_property(word, synset, lambda l: l.pertainyms())),
                (ATTRIBUTE, 'Attributes',
                   synset.attributes()),
                (ALSO_SEE, 'Also see',
                   synset.also_sees()))
    elif synset.pos() == wn.ADV:
        # This is weird. adverbs such as 'quick' and 'fast' don't seem
        # to have antonyms returned by the corpus.a
        return ((ANTONYM, 'Antonym',
                   lemma_property(word, synset, lambda l: l.antonyms())),)
                # Derived from adjective - not supported by corpus
    else:
        raise TypeError("Unhandles synset POS type: " + str(synset.pos()))


html_header = '''
<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01//EN'
'http://www.w3.org/TR/html4/strict.dtd'>
<html>
<head>
<meta name='generator' content=
'HTML Tidy for Windows (vers 14 February 2006), see www.w3.org'>
<meta http-equiv='Content-Type' content=
'text/html; charset=us-ascii'>
<title>NLTK Wordnet Browser display of: %s</title></head>
<body bgcolor='#F5F5F5' text='#000000'>
'''
html_trailer = '''
</body>
</html>
'''

explanation  = '''
<h3>Search Help</h3>
<ul><li>The display below the line is an example of the output the browser
shows you when you enter a search word. The search word was <b>green</b>.</li>
<li>The search result shows for different parts of speech the <b>synsets</b>
i.e. different meanings for the word.</li>
<li>All underlined texts are hypertext links. There are two types of links:
word links and others. Clicking a word link carries out a search for the word
in the Wordnet database.</li>
<li>Clicking a link of the other type opens a display section of data attached
to that link. Clicking that link a second time closes the section again.</li>
<li>Clicking <u>S:</u> opens a section showing the relations for that synset.
</li>
<li>Clicking on a relation name opens a section that displays the associated
synsets.</li>
<li>Type a search word in the <b>Word</b> field and start the search by the
<b>Enter/Return</b> key or click the <b>Search</b> button.</li>
</ul>
<hr width='100%'>
'''

# HTML oriented functions

def _bold(txt): return '<b>%s</b>' % txt

def _center(txt): return '<center>%s</center>' % txt

def _hlev(n,txt): return '<h%d>%s</h%d>' % (n,txt,n)

def _italic(txt): return '<i>%s</i>' % txt

def _li(txt): return '<li>%s</li>' % txt

def pg(word, body):
    '''
    Return a HTML page of NLTK Browser format constructed from the
    word and body

    :param word: The word that the body corresponds to
    :type word: str
    :param body: The HTML body corresponding to the word
    :type body: str
    :return: a HTML page for the word-body combination
    :rtype: str
    '''
    return (html_header % word) + body + html_trailer

def _ul(txt): return '<ul>' + txt + '</ul>'

def _abbc(txt):
    """
    abbc = asterisks, breaks, bold, center
    """
    return _center(_bold('<br>'*10 + '*'*10 + ' ' + txt + ' ' + '*'*10))

full_hyponym_cont_text = \
    _ul(_li(_italic('(has full hyponym continuation)'))) + '\n'


def _get_synset(synset_key):
    """
    The synset key is the unique name of the synset, this can be
    retrived via synset.name()
    """
    return wn.synset(synset_key)

def _collect_one_synset(word, synset, synset_relations):
    '''
    Returns the HTML string for one synset or word

    :param word: the current word
    :type word: str
    :param synset: a synset
    :type synset: synset
    :param synset_relations: information about which synset relations
    to display.
    :type synset_relations: dict(synset_key, set(relation_id))
    :return: The HTML string built for this synset
    :rtype: str
    '''
    if isinstance(synset, tuple): # It's a word
        raise NotImplementedError("word not supported by _collect_one_synset")

    typ = 'S'
    pos_tuple = _pos_match((synset.pos(), None, None))
    assert pos_tuple is not None, "pos_tuple is null: synset.pos(): %s" % synset.pos()
    descr = pos_tuple[2]
    ref = copy.deepcopy(Reference(word, synset_relations))
    ref.toggle_synset(synset)
    synset_label = typ + ";"
    if synset.name() in synset_relations:
        synset_label = _bold(synset_label)
    s = '<li>%s (%s) ' % (make_lookup_link(ref, synset_label), descr)
    def format_lemma(w):
        w = w.replace('_', ' ')
        if w.lower() == word:
            return _bold(w)
        else:
            ref = Reference(w)
            return make_lookup_link(ref, w)

    s += ', '.join(format_lemma(l.name()) for l in synset.lemmas())

    gl = " (%s) <i>%s</i> " % \
        (synset.definition(),
         "; ".join("\"%s\"" % e for e in synset.examples()))
    return s + gl + _synset_relations(word, synset, synset_relations) + '</li>\n'

def _collect_all_synsets(word, pos, synset_relations=dict()):
    """
    Return a HTML unordered list of synsets for the given word and
    part of speech.
    """
    return '<ul>%s\n</ul>\n' % \
        ''.join((_collect_one_synset(word, synset, synset_relations)
                 for synset
                 in wn.synsets(word, pos)))

def _synset_relations(word, synset, synset_relations):
    '''
    Builds the HTML string for the relations of a synset

    :param word: The current word
    :type word: str
    :param synset: The synset for which we're building the relations.
    :type synset: Synset
    :param synset_relations: synset keys and relation types for which to display relations.
    :type synset_relations: dict(synset_key, set(relation_type))
    :return: The HTML for a synset's relations
    :rtype: str
    '''

    if not synset.name() in synset_relations:
        return ""
    ref = Reference(word, synset_relations)

    def relation_html(r):
        if isinstance(r, Synset):
            return make_lookup_link(Reference(r.lemma_names()[0]), r.lemma_names()[0])
        elif isinstance(r, Lemma):
            return relation_html(r.synset())
        elif isinstance(r, tuple):
            # It's probably a tuple containing a Synset and a list of
            # similar tuples.  This forms a tree of synsets.
            return "%s\n<ul>%s</ul>\n" % \
                (relation_html(r[0]),
                 ''.join('<li>%s</li>\n' % relation_html(sr) for sr in r[1]))
        else:
            raise TypeError("r must be a synset, lemma or list, it was: type(r) = %s, r = %s" % (type(r), r))

    def make_synset_html(db_name, disp_name, rels):
        synset_html = '<i>%s</i>\n' % \
            make_lookup_link(
                copy.deepcopy(ref).toggle_synset_relation(synset, db_name).encode(),
                disp_name)

        if db_name in ref.synset_relations[synset.name()]:
             synset_html += '<ul>%s</ul>\n' % \
                ''.join("<li>%s</li>\n" % relation_html(r) for r in rels)

        return synset_html

    html = '<ul>' + \
        '\n'.join(("<li>%s</li>" % make_synset_html(*rel_data) for rel_data
                   in get_relations_data(word, synset)
                   if rel_data[2] != [])) + \
        '</ul>'

    return html


class Reference(object):
    """
    A reference to a page that may be generated by page_word
    """

    def __init__(self, word, synset_relations=dict()):
        """
        Build a reference to a new page.

        word is the word or words (separated by commas) for which to
        search for synsets of

        synset_relations is a dictionary of synset keys to sets of
        synset relation identifaiers to unfold a list of synset
        relations for.
        """
        self.word = word
        self.synset_relations = synset_relations

    def encode(self):
        """
        Encode this reference into a string to be used in a URL.
        """
        # This uses a tuple rather than an object since the python
        # pickle representation is much smaller and there is no need
        # to represent the complete object.
        string = pickle.dumps((self.word, self.synset_relations), -1)
        return base64.urlsafe_b64encode(string).decode()

    @staticmethod
    def decode(string):
        """
        Decode a reference encoded with Reference.encode
        """
        string = base64.urlsafe_b64decode(string.encode())
        word, synset_relations = pickle.loads(string)
        return Reference(word, synset_relations)

    def toggle_synset_relation(self, synset, relation):
        """
        Toggle the display of the relations for the given synset and
        relation type.

        This function will throw a KeyError if the synset is currently
        not being displayed.
        """
        if relation in self.synset_relations[synset.name()]:
            self.synset_relations[synset.name()].remove(relation)
        else:
            self.synset_relations[synset.name()].add(relation)

        return self

    def toggle_synset(self, synset):
        """
        Toggle displaying of the relation types for the given synset
        """
        if synset.name() in self.synset_relations:
            del self.synset_relations[synset.name()]
        else:
            self.synset_relations[synset.name()] = set()

        return self


def make_lookup_link(ref, label):
    return '<a href="lookup_%s">%s</a>' % (ref.encode(), label)


def page_from_word(word):
    """
    Return a HTML page for the given word.

    :param word: The currently active word
    :type word: str
    :return: A tuple (page,word), where page is the new current HTML page
             to be sent to the browser and
             word is the new current word
    :rtype: A tuple (str,str)
    """
    return page_from_reference(Reference(word))

def page_from_href(href):
    '''
    Returns a tuple of the HTML page built and the new current word

    :param href: The hypertext reference to be solved
    :type href: str
    :return: A tuple (page,word), where page is the new current HTML page
             to be sent to the browser and
             word is the new current word
    :rtype: A tuple (str,str)
    '''
    return page_from_reference(Reference.decode(href))

def page_from_reference(href):
    '''
    Returns a tuple of the HTML page built and the new current word

    :param href: The hypertext reference to be solved
    :type href: str
    :return: A tuple (page,word), where page is the new current HTML page
             to be sent to the browser and
             word is the new current word
    :rtype: A tuple (str,str)
    '''
    word = href.word
    pos_forms = defaultdict(list)
    words = word.split(',')
    words = [w for w in [w.strip().lower().replace(' ', '_')
                         for w in words]
             if w != ""]
    if len(words) == 0:
        # No words were found.
        return "", "Please specify a word to search for."

    # This looks up multiple words at once.  This is probably not
    # necessary and may lead to problems.
    for w in words:
        for pos in [wn.NOUN, wn.VERB, wn.ADJ, wn.ADV]:
            form = wn.morphy(w, pos)
            if form and form not in pos_forms[pos]:
                pos_forms[pos].append(form)
    body = ''
    for pos,pos_str,name in _pos_tuples():
        if pos in pos_forms:
            body += _hlev(3, name) + '\n'
            for w in pos_forms[pos]:
                # Not all words of exc files are in the database, skip
                # to the next word if a KeyError is raised.
                try:
                    body += _collect_all_synsets(w, pos, href.synset_relations)
                except KeyError:
                    pass
    if not body:
        body = "The word or words '%s' where not found in the dictonary." % word
    return body, word


