Loop not terminating