refactored to remove some code duplication