A bunch of bug fix and refactor