Fix a number of bugs