Various speed optimizations and test fixes.