Beware of bugs in the above code; I have only proved it correct, not tried it.
Don't hurry your code. Make sure it works well and is well designed. Don't worry about timing.
"Legacy code" often differs from its suggested alternative by actually working and scaling.
I was eventually persuaded of the need to design programming notations so as to maximize the number of errors which cannot be made, or if made, can be reliably detected at compile time.
Never test for an error condition you don't know how to handle.
You can't trust code that you did not totally create yourself.
If you want more effective programmers, you will discover that they should not waste their time debugging, they should not introduce the bugs to start with.
My bugs don't have bugs.