refactored code so there are only 2 loops used to scan grid