Fix a range of bugs