Refactor code and fix bug