Miscellaneous optimizations and fixes