--- /tmp/tableofcontents/tableofcontents.module	2007-02-05 06:02:59.000000000 +1100
+++ tableofcontents/tableofcontents.module	2007-04-03 14:03:21.061785914 +1000
@@ -34,6 +34,41 @@
   }
 }
 
+function tableofcontents_dump($toc,$level,&$i) {
+        $open_list = str_repeat(" ",$level)."<ol>\n";
+        $close_list = "";
+
+        // process header items until we find one that is lower then level $level
+        while ($j<count($toc) and $toc[$i]['level'] >= $level) {
+                if ($toc[$i]['level'] > $level) {
+                        // header is too deep => skip it
+                        $i = $i + 1;
+                        continue;
+                }
+
+                // ensure list is open
+                $result .= $open_list;
+                $open_list = "";
+                $close_list = str_repeat(" ",$level)."</ol>\n";
+
+                // open list item
+                $result .= str_repeat(" ",$level);
+                $result .= "<li><a href=\"#".$toc[$i]['anchor']."\">".$toc[$i]['heading']."</a>\n";
+
+                // process any on the next level
+                $i = $i + 1;
+                $result .= tableofcontents_dump($toc,$level+1,$i);
+
+                // close list item
+                $result .= str_repeat(" ",$level);
+                $result .= "</li>\n";
+        }
+        // ensure list is closed
+        $result .= $close_list;
+
+        return($result);
+}
+
 /**
  * Implementation of hook_filter().
  *
@@ -80,31 +115,12 @@
       // The obvious example is to put a shaded background behind the TOC.
       // In the future it would also be nice to have collapseable headings using javascript
       // for those really long documents.
-      $toc_html = "<div class=\"toc\">\n<h2>Table of Contents</h2>\n<ol>\n";
-      // Since we start at h2
-      $depth = 2;
-      foreach ($toc as $title) {
-       // We need to allow for nested lists
-       // It should be trivial to make the heading levels shown in the TOC user customizable
-        $curdepth = $title['level'];
-        if ($curdepth > $depth) {
-          $toc_html .= "<ol>\n";
-        }
-        else if ($curdepth < $depth) {
-          $toc_html .= "</ol>\n";
-        }
-        $depth = $curdepth;
-        // Insert the list element.
-        $toc_html .= "<li><a href=\"#".$title['anchor']."\">".$title['heading']."</a></li>\n";
-      }
-      // Did we recurse back out to h2 tags? If not, close open lists.
-      while ($depth > 1) {
-        $toc_html .= "</ol>\n";
-        $depth = $depth -1;
-      }
+      $i = 0;
+      $toc_html = "<div class=\"toc\">\n<h2>Table of Contents</h2>\n";
+      $toc_html .= tableofcontents_dump($toc,2,$i);
       $toc_html .= "</div>\n";
       // Find our previously changed string and replace with our generated TOC.
       return str_replace('\xFE!--tableofcontents--\xFF', $toc_html, $text);
   }
 }
-?>
\ No newline at end of file
+?>
