Overall refactoring with added unit tests