Refactored to remove duplicate code.