Bug fixes and code optimization