refactoring, reduced the amount of times the matrix is traversed from 4 to 1