Refactored code, added tests