Refactored code, added unit tests