Make some performance improvements and fix some bugs.