fix some bugs and make the code more readable