Fix bugs, refactor