Bug fixes and code optimizations