Major rewrite, using networkx.