private static int applyMaskPenaltyRule1Internal(ByteMatrix matrix, boolean isHorizontal) {
    int penalty = 0;
    int numSameBitCells = 0;
    int prevBit = -1;
    // Horizontal mode:
    //   for (int i = 0; i < matrix.height(); ++i) {
    //     for (int j = 0; j < matrix.width(); ++j) {
    //       int bit = matrix.get(i, j);
    // Vertical mode:
    //   for (int i = 0; i < matrix.width(); ++i) {
    //     for (int j = 0; j < matrix.height(); ++j) {
    //       int bit = matrix.get(j, i);
    int iLimit = isHorizontal ? matrix.getHeight() : matrix.getWidth();
    int jLimit = isHorizontal ? matrix.getWidth() : matrix.getHeight();
    byte[][] array = matrix.getArray();
    for (int i = 0; i < iLimit; ++i) {
      for (int j = 0; j < jLimit; ++j) {
        int bit = isHorizontal ? array[i][j] : array[j][i];
        if (bit == prevBit) {
          numSameBitCells += 1;
          // Found five repetitive cells with the same color (bit).
          // We'll give penalty of 3.
          if (numSameBitCells == 5) {
            penalty += 3;
          } else if (numSameBitCells > 5) {
            // After five repetitive cells, we'll add the penalty one
            // by one.
            penalty += 1;
          }
        } else {
          numSameBitCells = 1;  // Include the cell itself.
          prevBit = bit;
        }
      }
      numSameBitCells = 0;  // Clear at each row/column.
    }
    return penalty;
  }