Fix and test topological sort and related tests