fix some bugs, modularize some functions