Various bugfixes and optimizations