Fix the bugs in loop state logic