eliminated some looping to find the edges of the network (by labeling the graph with the current 'ends'). This should speed things up. I also repaired some of the "from-to" relations to make sure they are correctly ordered.
Finally, added "next" instead of "last" since the latter was resulting in escapes from the loops prematurely.