Some bug fixes and minor optimizations.