class Kramdown::Converter::Html

def generate_toc_tree(toc, type)

def generate_toc_tree(toc, type)
  sections = Element.new(type, nil, {:attr => {:id => 'markdown-toc'}})
  stack = []
  toc.each do |level, id, children|
    li = Element.new(:li, nil, {:level => level})
    a = Element.new(:a, nil, {:attr => {:href => "##{id}"}})
    a.children += children
    li.children << a
    li.children << Element.new(type)
    success = false
    while !success
      if stack.empty?
        sections.children << li
        stack << li
        success = true
      elsif stack.last.options[:level] < li.options[:level]
        stack.last.children.last.children << li
        stack << li
        success = true
      else
        item = stack.pop
        item.children.pop unless item.children.last.children.size > 0
      end
    end
  end
  while !stack.empty?
    item = stack.pop
    item.children.pop unless item.children.last.children.size > 0
  end
  sections
end