Various refactorings and additional unit tests.