Fixed the bugs suggested by agentzh, and the optimizations.