Refactoring and bugfixes