Several fixes and optimizations.