Updated end conditions code