Contributed by Ewan Higgs and Steve Loughran. (cherry picked from commit c1d24f848345f6d34a2ac2d570d49e9787a0df6a)