Refactored part of grid code