Bugfixes and refactorings