Added tests, refactored code for better testability