Optimize and fix some bugs.