Several bugfixes and optimizations.