Refactor grid calculation