Refactored to allow better testing