Fixed infinite loop in grid generation