Mainly refactoring, with a couple of small bugfixes.