refactored code and added tests.