Some bug fixes and performance improvement