Refactored to reduce code duplication.