refractor, and fix some bugs.