Bugfixes and minor optimizations