Various refactoring and bugfixes