Reimplementation of graph stuff (almost done)