I'm a terrible algorithmist, so who knows if this is correct, but it seems to work in my cursory testing.