Refactor writer

some tests and bugfixes of the writer... ready to merge (though there could be more tests and bugfixes ;)