Fixes #3228 .  This is a mammoth refactor!