With a bit of head scratching, this whole process can be solved using Mathematica or similar with about 10 lines of code. (ChatGPT tried hard but couldn't make the code work so I had to do it the old fashioned way, like some kind of barbarian.)