Bug fixes and some optimizations