Fix nested for infinite loop