Bugfixes and optimization