Heavily refactor and include new tests.