Many bugfixes and refactorings.