Various bugfixes and performance improvements