improved for end conditions