refactored to remove duplication and clarify responsibilities