Fix a bug (and added test) with grid-based topology building