Fix a series of bugs: #78, #79, #81, #82