Fix nested looping logic