Fix some minor bugs and refactor the logic