Refactored for ease of testing