Remove duplicate code. Cache results for first/last row/column. Doing loop only once.