Refactoring and minor bugfixes