Refactor. Add tests. Now working.