Some refactorings and bugfixes...