Pretty much all of this code was moved from elsewhere.