Refactor and improve test coverage