Misc fixes and optimizations