Various bug fixes and optimizations