My attempt. Passes the tests.

Best viewed not as a patch but as the whole thing.