Optimizations and minor bug fixes