Okay.

I'm a bit worried about having all this at the same level. Splitting this out in a different function can help to have a better understanding.
Other than that, the reasoning seems complex but at the same time I can't come up with a better solution just by thinking about it, so I'm encline to merge this.