Applied this to the trunk (with a few improvements).