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.
IIRC I used 1e12 to avoid overflows, not sure if it could be a problem.