I am currently rewriting this function. I will add templates when it's done.
No part of the code assumes that we are fixed on the grid, so in the best of worlds templating this function should be trivial...