. . . was way harder than I thought. My solution here.