Minimal patch against r51213 to fix the bug
The code that lays out the TOC corrects non-continuous sequences, for example a level-2 heading followed by a level-4. In looking over that code to answer a question as to how exactly that works, I found a bug in an odd case.
=== A ===
==== B ====
===== C =====
== D ==
Generates this TOC layout:
1.1 B 1.1.1 C 1.1.2 D
By any logic, it should do this instead:
1.1 B 1.1.1 C
The attached patch fixes this. This probably makes the special case for $toclevel == 2 && $level <= $levelCount obsolete too, I'll attach that patch momentarily.