Refactor and add some new tests