Fix loop caused by wrong logic