Refactored into blob in hope that errors will be easyer to spot if code is closeto geather