'Assign a figure number to each figure under a numbered toctree.'

def assign_figure_numbers(self, env):

    rewrite_needed = []
    assigned = set()
    old_fignumbers = env.toc_fignumbers
    env.toc_fignumbers = {}
    fignum_counter = {}
    def get_section_number(docname, section):
        anchorname = ('#' + section['ids'][0])
        secnumbers = env.toc_secnumbers.get(docname, {})
        if (anchorname in secnumbers):
            secnum = secnumbers.get(anchorname)
        else:
            secnum = secnumbers.get('')
        return (secnum or tuple())
    def get_next_fignumber(figtype, secnum):
        counter = fignum_counter.setdefault(figtype, {})
        secnum = secnum[:env.config.numfig_secnum_depth]
        counter[secnum] = (counter.get(secnum, 0) + 1)
        return (secnum + (counter[secnum],))
    def register_fignumber(docname, secnum, figtype, fignode):
        env.toc_fignumbers.setdefault(docname, {})
        fignumbers = env.toc_fignumbers[docname].setdefault(figtype, {})
        figure_id = fignode['ids'][0]
        fignumbers[figure_id] = get_next_fignumber(figtype, secnum)
    def _walk_doctree(docname, doctree, secnum):
        for subnode in doctree.children:
            if isinstance(subnode, nodes.section):
                next_secnum = get_section_number(docname, subnode)
                if next_secnum:
                    _walk_doctree(docname, subnode, next_secnum)
                else:
                    _walk_doctree(docname, subnode, secnum)
                continue
            elif isinstance(subnode, addnodes.toctree):
                for (title, subdocname) in subnode['entries']:
                    if (url_re.match(subdocname) or (subdocname == 'self')):
                        continue
                    _walk_doc(subdocname, secnum)
                continue
            figtype = env.get_domain('std').get_figtype(subnode)
            if (figtype and subnode['ids']):
                register_fignumber(docname, secnum, figtype, subnode)
            _walk_doctree(docname, subnode, secnum)
    def _walk_doc(docname, secnum):
        if (docname not in assigned):
            assigned.add(docname)
            doctree = env.get_doctree(docname)
            _walk_doctree(docname, doctree, secnum)
    if env.config.numfig:
        _walk_doc(env.config.master_doc, tuple())
        for (docname, fignums) in iteritems(env.toc_fignumbers):
            if (fignums != old_fignumbers.get(docname)):
                rewrite_needed.append(docname)
    return rewrite_needed
