def endTagFormatting(self, token):
            """The much-feared adoption agency algorithm"""
            # http://www.whatwg.org/specs/web-apps/current-work/#adoptionAgency
            # XXX Better parseError messages appreciated.
            name = token["name"]

            outerLoopCounter = 0
            while outerLoopCounter < 8:
                outerLoopCounter += 1

                # Step 1 paragraph 1
                formattingElement = self.tree.elementInActiveFormattingElements(
                    token["name"])
                if (not formattingElement or 
                    (formattingElement in self.tree.openElements and
                     not self.tree.elementInScope(formattingElement.name))):
                    self.parser.parseError("adoption-agency-1.1", {"name": token["name"]})
                    return

                # Step 1 paragraph 2
                elif formattingElement not in self.tree.openElements:
                    self.parser.parseError("adoption-agency-1.2", {"name": token["name"]})
                    self.tree.activeFormattingElements.remove(formattingElement)
                    return

                # Step 1 paragraph 3
                if formattingElement != self.tree.openElements[-1]:
                    self.parser.parseError("adoption-agency-1.3", {"name": token["name"]})

                # Step 2
                # Start of the adoption agency algorithm proper
                afeIndex = self.tree.openElements.index(formattingElement)
                furthestBlock = None
                for element in self.tree.openElements[afeIndex:]:
                    if element.nameTuple in specialElements:
                        furthestBlock = element
                        break
                # Step 3
                if furthestBlock is None:
                    element = self.tree.openElements.pop()
                    while element != formattingElement:
                        element = self.tree.openElements.pop()
                    self.tree.activeFormattingElements.remove(element)
                    return
                commonAncestor = self.tree.openElements[afeIndex-1]

                # Step 5
                #if furthestBlock.parent:
                #    furthestBlock.parent.removeChild(furthestBlock)

                # Step 5
                # The bookmark is supposed to help us identify where to reinsert
                # nodes in step 12. We have to ensure that we reinsert nodes after
                # the node before the active formatting element. Note the bookmark
                # can move in step 7.4
                bookmark = self.tree.activeFormattingElements.index(formattingElement)

                # Step 6
                lastNode = node = furthestBlock
                innerLoopCounter = 0
                
                index = self.tree.openElements.index(node)
                while innerLoopCounter < 3:
                    innerLoopCounter += 1
                    # Node is element before node in open elements
                    index -= 1
                    node = self.tree.openElements[index]
                    if node not in self.tree.activeFormattingElements:
                        self.tree.openElements.remove(node)
                        continue
                    # Step 6.3
                    if node == formattingElement:
                        break
                    # Step 6.4
                    if lastNode == furthestBlock:
                        bookmark = (self.tree.activeFormattingElements.index(node)
                                    + 1)
                    # Step 6.5
                    #cite = node.parent
                    clone = node.cloneNode()
                    # Replace node with clone
                    self.tree.activeFormattingElements[
                        self.tree.activeFormattingElements.index(node)] = clone
                    self.tree.openElements[
                        self.tree.openElements.index(node)] = clone
                    node = clone

                    # Step 6.6
                    # Remove lastNode from its parents, if any
                    if lastNode.parent:
                        lastNode.parent.removeChild(lastNode)
                    node.appendChild(lastNode)
                    # Step 7.7
                    lastNode = node
                    # End of inner loop 

                # Step 7
                # Foster parent lastNode if commonAncestor is a
                # table, tbody, tfoot, thead, or tr we need to foster parent the 
                # lastNode
                if lastNode.parent:
                    lastNode.parent.removeChild(lastNode)

                if commonAncestor.name in frozenset(("table", "tbody", "tfoot", "thead", "tr")):
                    parent, insertBefore = self.tree.getTableMisnestedNodePosition()
                    parent.insertBefore(lastNode, insertBefore)
                else:
                    commonAncestor.appendChild(lastNode)

                # Step 8
                clone = formattingElement.cloneNode()

                # Step 9
                furthestBlock.reparentChildren(clone)

                # Step 10
                furthestBlock.appendChild(clone)

                # Step 11
                self.tree.activeFormattingElements.remove(formattingElement)
                self.tree.activeFormattingElements.insert(bookmark, clone)

                # Step 12
                self.tree.openElements.remove(formattingElement)
                self.tree.openElements.insert(
                  self.tree.openElements.index(furthestBlock) + 1, clone)
The much-feared adoption agency algorithm
html5lib/html5parser.py