Refactor graph and add tests