Tidy up the structure of the chart generating code