added loop detection