topological sorting + test + refactoring