rewrite of graph merging code