Fix merge bug and refactor