import inspect


def update_doc_string(doc, extra, sections=None, signature=None):
    """
    Insert `extra` in the docstring `doc`, before the first matching section

    Searches for each section heading in the list `sections` in turn.
    If sections is not given, the default is `['Parameters', 'See also']`.
    If not sections are found, extra text is appended to end of docstring.
    """

    if sections is None:
        sections = ['Parameters', 'See also']

    try:
        doc = inspect.cleandoc(doc)
        extra = inspect.cleandoc(extra)
    except AttributeError:
        pass

    extra = '\n' + extra + '\n'

    lines = doc.split('\n')

    if signature is not None:
        lines[0] = signature

    for section in sections:
        indices = [i for i, line in enumerate(lines) if line == section]
        if len(indices) == 1:
            break
    else:
        indices = [len(lines) - 1]  # insert at end

    index, = indices
    doc = '\n'.join([line.rstrip() for line in lines[:index] + extra.split('\n') + lines[index:]])
    doc = doc.replace('\n\n\n', '\n\n')

    return doc