Substantial refactoring

Perf may have regressed somewhat.