Fix for document inversion

Fixes #51
Introduce safer cleanup method