Grid template

The logic is the same, but the API changes because of the template, and some code has been moved from implementation to header files.