bugfixes and a tiny bit of refactoring