I think
joost is right. Take a look at the module
Graph, the method for "topological sort". That can return the modules in order of dependency, in that no module depends on something that comes later in the list. After you added all the modules and dependecies as nodes and connections to a graph first, of course.