Re-apply some fixes lost in a previous merge