Massive refactoring: Unit testing and bugfixes