Minor bugfixes and refactoring