bugfixes and refactoring