Bug fixes and optimization