rewrite of document handling and other stuff