Refactoring and bugfix