Bug fixes and tidyups