Refactored method to reduce nesting.