refactoring and bugfixing