Nested loops optimized