Add more explanatory text and re-organise so the code can be read in
the order of explanation.