Rewrite of Ians code