tidy up code so loop looks less confusing.