A few fixes and optimizations