Refactor, cleanup and add more tests.