refactor for cpgrid support to apply to master

This is the same pull request as pull request #496, but this time it is updated to cleanly apply to the current master.