avoid dead loop

add some conditions to avoid dead loop.