The vast majority of the changes in this commit were originally done by Shawn Hoffman in commit c86846cf9c995d8e0463419bd9477b0dae884929.