Lots of tidying and bug fixes