Various tidyups, optimisations, and minor bugfixes