Refactored to reduce method complexity.