Several bugfixes and generally optimizations.