Added tests and refactored code