Refactored to reduce duplicated code.