This mostly reverts 5643a3b51be338196d0b292d5626ad43648448d3 and 81e1a35c364e5353d2bf99368ad30a4184fbb653. Thanks Carl Meyer for review. Backport of 5980b05c1fad69eef907e0076aa2dc837edab529 from master