Fix infinite loop by using index