correct some bugs and rewrite the code