fix bugs in loop logic

the old logic is not right