More bugfixes and refactoring