Fix loop end logic.