fixed bug for end condition