Reduced nesting and added some comments for clarification.