Many bug fixes and code optimizations