fixed bug of not returning on end condition