Code tidied somewhat