Reordered code to prevent stack overflows

By changing the method slightly, the stack only fill up at half
the speed from the previous implementation. This should hopefully
prevent most overflows on complex documents.