improve grid function