Beware of bugs in the above code; I have only proved it correct, not tried it.