Fix bug and refactor