Refactored for easier testing.