Refactoring the code, added tests