Factor out grid code