nested detect loops
cleaned up