Fix infinite loop bug