Some bug fixes and performance improvements