Bug fixes and code tidy