Technically, you just have to model your system with a graph and detect wether you are in a loop, or not, and if not, find a topological sorting for it. That's it.