Refactor code, fix bugs