Refactoring, add some functional tests.