refactored code to reduce repetition