Several fixes and optimizations