tidied up script, plus some other minor changes