I have no idea about your material, i never seen it.
And i mean not optimize , just split material into section (with named reroutes), then pack common pieces into functions, organize it. When you do it all you will see structure in that stuff, and may get ideas how to do it all better.