Refactoring and tests