bugfixes and some refactoring