Bugfixes and optimizations