Soplwang pullreq revisited

I've tried to resolve merge conflicts. The test that @soplwang added does not pass however. That could be due to other changes that have happened recently. If anyone would have a look, perhaps @kkoopa, that would be really helpful.