Various fixes and code tidyups