Refactoring and fixes