Refactored function into smaller units.