Added check for infinite loops