This is direct refactoring of Martin's old code. I'm not sure what exceptions miht be thrown here.