Stephen core

Stephen's core implementation, much better than anything I'll ever write. Let's merge it.