seems to works well

Slight difference from the Java version around step 28, but it seems
to do the right thing.