Bug fixes and minor optimizations