a range of optimizations and fixes