Major refactoring and unit tests