Fix looping logic