Fix infinite loop error + bad array iteration