Even more code refactoring.
Various bugfixes.