Fix some bugs. Optimize code.