Various fixes and optimizations