Many bug fixes and optimizations