Fix loop logic