Further refactoring and addition of unittests