Fix some bugs and reorganize the code