Now that I understand it & it works, it's time to rewrite sanely.
Or rather, it will be time to do it later today.