Performance improvements and code tidy up