Rewritten to interact with the document as little as possible.

Big performance boost.