fix bug and refactor