Refactored code and added/fixed tests