fix bugs, refactor code