Refactor and added more test coverage