Fix bug causing not exit from final loop