refactored to reduce code duplication