Added a check to end endless loop that sometimes occurs in corner cases