General tidy of code and some speed improvements.