Refactoring the graph building code