Implement most of the fixes from @tikue