import re


def parse_annotations(docstring, keys, empty=False, inline_type=False):
    """
        Parses ":key name: description" lines into a dictionary mapping name to
        a description.

        If empty is specified, look statements without a name such as
        ":key: description".

        If inline_type is specified, allow an optional type to be specified
        parsing ":key type name: description" or ":key type: description".
    """
    assert docstring is not None

    found = {}

    for key in keys:
        if empty:
            regexp = ('^\s*:\s*%s(?P<type>[^:]*?)\s*:\s*(?P<desc>.*?)\s*$'
                      % key)
        else:
            regexp = ('^\s*:\s*%s\s+(?P<type>[^:]*?)(?P<name>[^\s:]+)\s*:'
                      '\s*(?P<desc>.*?)\s*$' % key)
        regexp = re.compile(regexp, re.MULTILINE)

        def replace(match):
            d = match.groupdict()

            if empty:
                name = len(found)
            else:
                name = d['name'] or None

            if inline_type:
                found[name] = (d['type'] or None, d['desc'] or None)
            else:
                found[name] = d['desc'] or None
            return ""

        docstring = regexp.sub(repl=replace, string=docstring)

    return docstring, found