Bug fixes and optimizations