Various bug fixes and performance tunings