There's quite a big similarity between this and the stateful code.  Can we commonize?