refactoring and more bugfixes