Refactored code and added extra tests