Applied to trunk (with a few changes).