a snipet from Gridify (simplified)