Further tidy-up, uses function and a nested loop (sorry!)