Few bug fixes and optimizations