Optimizations and fixes