Added somewhat crude loop detection