Starting neatening this up at last. There's a good few points with too many nested loops.