Implement topological sort using Cormen/Tarjan algorithm to handle a->b->c dependencies and detect a->b->c->a cycles.

Noticed a couple of cases the existing algorithm doesn't handle - see test cases.
Please merge pull request. thanks.