Here's the final algorithm(s) written up, including source code!

cohost.org/tomforsyth/post/648