Refactored and added test cases.