more refactoring, unittests and bug fixes.