refactor end conditions