Bugfixes and minor refactoring