Refactored code to remove code duplication