Refactored code and fixed tests