This code can be refactored to reduce duplication.