some refactoring and bugfixing