Refactored for testability.