Fixed tons of bugs in cycle-checking algorithm, added tests