fix bug and refactor code