Refactoring and add tests