Changes and bugfixes done in my own time

A series of commits that fix some bugs, implement refactorings, and enable unit testing of parts of the code.