added "loop" prevention algorithm