As I read it, it seems that you sort the array of entries the way you want it, and then you go through it, noticing the breaks, and subtotaling & totaling as appropriate. This all makes sense as far as it goes.
One question would be what the end product should be -- what the user should see and how they'll see it. Your script does all that, but it has no output (that I noticed), so you set no field values in any entries of any libraries, and you don't emit any messages. Note that the entries array is always generated in entry creation DateTime order. After you sort it, it's yours, but it doesn't change the library data.
Usually, it comes down to this. Ideally, you use entries list tools to sort, group, and filter the data the way you want and use aggregation (Edit Library screen) to make the aggregation bars contain the values you want to see. If you set up groups & filters properly, you'll likely get what you want with no scripting.
If you do feel you need scripting, the output will likely need to be in library fields, in either the current or some other library, like a summary or rollup library. You'll need to use the Entry object's set() method to set those values. The messaging feature is below minimal, mainly useful just for debugging or saying "Done" or something.
So, think/learn about sorting, grouping, filtering, & filter tabs, then aggregation, and then let's talk about what works for you and what else you want beyond that.