Bugfixes

More refactoring and bug fixes.