Some final refactoring and bugfixes.