refactor grid code