Some fixes and optimizations