fixing infinite loop in some strange cases.