Fix bug "array index out of bounds"

Index stays within grid size.

Patch by Clemens Müllner.