Changing to non-recursive topological sort function