Fix infinite while loop issue