Lots of bugfixes and refactoring