OK, here is a patch that I think should be good to push, tested against Emacs 28 and 26.3.