Refactored to remove duplicated code.