Small bugfixes and minor refactoring