added grid boundary detection