#!../src/tops  -s ../sys  -u ../usr -i

psource("internal_idx.n")

function chk_spadd_ijv(n) {  {# {{{1 #}
    (A_nRows  ) = integer(n*rand) + 1;
    (A_nCols  ) = integer(n*rand) + 1;
    (A_rho    ) = rand;
    (B_nRows  ) = integer(n*rand) + 1;
    (B_nCols  ) = integer(n*rand) + 1;
    (B_rho    ) = rand;
    {# 
       Select internal row and column indices out of the range 1..2*n 
       so that about half the terms are likely to overlap.
     #}
    (A_row_idx) = endmost(shuffle(items(1, 2*max(A_nRows, B_nRows))), A_nRows);
    (A_col_idx) = endmost(shuffle(items(1, 2*max(A_nCols, B_nCols))), A_nCols);
    (B_row_idx) = endmost(shuffle(items(1, 2*max(A_nRows, B_nRows))), B_nRows);
    (B_col_idx) = endmost(shuffle(items(1, 2*max(A_nCols, B_nCols))), B_nCols);
    (A        ) = add_idx(sprand(A_nRows,A_nCols,A_rho), A_row_idx, A_col_idx);
    (B        ) = add_idx(sprand(B_nRows,B_nCols,B_rho), B_row_idx, B_col_idx);
    (Cdn      ) = indexed_add(dense(A), dense(B));
    (Csp      ) = spadd_ijv(A, B);
    (x,i,j    ) = maxfetch(abs(Cdn - dense(Csp)));
    .(format(A_nRows  , " %2.0f x"));
    .(format(A_nCols  , " %2.0f "));
    .(format(A_rho    , " [%4.3f] + "));
    .(format(B_nRows  , " %2.0f x"));
    .(format(B_nCols  , " %2.0f "));
    .(format(B_rho    , " [%4.3f] ="));
    .(format(rows(Csp), " %2.0f x"));
    .(format(cols(Csp), " %2.0f "));
    .(" spadd_ijv");
    .(format(x        , " %8.6f"));
    nl;
}  {# 1}}} #}

  Size  = 10;
  nIter = 50;

  k = 0;
  BEGIN();
  WHILE(k < nIter);
      k++;
      .(format(k    , "%3.0f. "));
      chk_spadd_ijv(Size);
  REPEAT;
