Amended code provided by pull request  from dodgy manual merge