fixed bug; the algorithm should now be able to handle loops