fix infinite loop in some cases