Merged in the code from James.