more refactoring and bugfixing