'Returns the sort input values in topologically sorted order'

def sorted(self):

    order = [(self.first, self.last)]
    roots = []
    graph = {}
    names = [self.first, self.last]
    names.extend(self.names)
    for (a, b) in self.order:
        order.append((a, b))
    def add_node(node):
        if (node not in graph):
            roots.append(node)
            graph[node] = [0]
    def add_arc(fromnode, tonode):
        graph[fromnode].append(tonode)
        graph[tonode][0] += 1
        if (tonode in roots):
            roots.remove(tonode)
    for name in names:
        add_node(name)
    (has_before, has_after) = (set(), set())
    for (a, b) in order:
        if ((a in names) and (b in names)):
            add_arc(a, b)
            has_before.add(a)
            has_after.add(b)
    if (not self.req_before.issubset(has_before)):
        raise ConfigurationError(('Unsatisfied    before    dependencies:    %s' % ',    '.join(sorted((self.req_before - has_before)))))
    if (not self.req_after.issubset(has_after)):
        raise ConfigurationError(('Unsatisfied    after    dependencies:    %s' % ',    '.join(sorted((self.req_after - has_after)))))
    sorted_names = []
    while roots:
        root = roots.pop(0)
        sorted_names.append(root)
        children = graph[root][1:]
        for child in children:
            arcs = graph[child][0]
            arcs -= 1
            graph[child][0] = arcs
            if (arcs == 0):
                roots.insert(0, child)
        del graph[root]
    if graph:
        cycledeps = {}
        for (k, v) in graph.items():
            cycledeps[k] = v[1:]
        raise CyclicDependencyError(cycledeps)
    result = []
    for name in sorted_names:
        if (name in self.names):
            result.append((name, self.name2val[name]))
    return result
