some optimisations and tidyup