Refactored the deeply nested branches into early returns.