Added protection for infinite loops