Reuse of $i was causing infinite loop

Reuse of $i inside this subloop causes an infinite loop