Little refactoring and bugfixes