Some refactorings, added unit tests.