This function is hard to view as a diff, as I revised large parts of it.  The general flow is essentially the same, though.