Bugfixes and refactoring