Refactoring and added unit tests