This is less clear to me, since it's not clear to me what the original code is trying to do with all the special cases. LGTM, but I'm not an expert in this code.
Very nice! Thank you for dusting off this old code
Reverted in b42b30c335bccccca95470aa47dade2e25cb8994 due to buildbots failing tests: