Some bug fixes and optimizations.