#include "BSprivate.h"

int BSnonlocalnz(BSspmat *,int *,BSprocinfo *);

/*+ BScount_nz - Count the number of nonzeroes in a sparse matrix
                 stored in the parallel format

    Input Parameters:
.   A - The sparse matrix (stored in parallel format)
.   procinfo - the usual processor info

    Returns:
	the number of nonzeros

+*/
int BScount_nz(BSpar_mat *A, BSprocinfo *procinfo)
{
	int	i;
	int	cl_ind, in_ind;
	int	size, num_cols;
	BScl_2_inode *clique2inode;
	BSnumbering *color2clique;
	BSinode *inodes;
	int	nnz;

	color2clique = A->color2clique;
	clique2inode = A->clique2inode;
	inodes = A->inodes->list;

	nnz = 0;
	for (i=0;i<color2clique->length-1;i++) {
		/* do some local work */
		for (cl_ind=color2clique->numbers[i];
			cl_ind<color2clique->numbers[i+1];cl_ind++) {
			if (procinfo->my_id == clique2inode->proc[cl_ind]) {
				size = clique2inode->d_mats[cl_ind].size;
				if(A->icc_storage) 
					nnz += (size*(size+1))/2;
				else
					nnz += (size*size);
			}
			for (in_ind=clique2inode->inode_index[cl_ind];
				in_ind<clique2inode->inode_index[cl_ind+1];in_ind++) {
				size = inodes[in_ind].length;
				num_cols = inodes[in_ind].num_cols;
				nnz += size*num_cols;
			}
		}
	}

	if(!A->icc_storage) nnz = (nnz + A->num_rows)/2;

	return(nnz);
}

/*+ BSnonlocalnz - Count the number of nonzeroes in a sparse matrix
                   stored in the original format

    Input Parameters:
.   A - The sparse matrix (stored in original format)
.   max_row_len - pointer to the the maximum length of any row
.                 set on output
.   procinfo - the usual processor info

    Returns:
    number of nonlocal nonzeros

+*/
int	BSnonlocalnz(BSspmat *A,int *max_row_len,BSprocinfo *procinfo)
{
	int	count;
	int	i, j;
	void	(*map)(int,int *,int *,BSprocinfo *,BSmapping *);
	BSsprow	*row;
	int	mrow_len = 0;
	int	*iwork;

	count = 0;
	for (i=0;i<A->num_rows;i++) {
		if (A->rows[i]->length > mrow_len) mrow_len = A->rows[i]->length;
	}
	MY_MALLOCN(iwork,(int *),sizeof(int)*mrow_len,1);
	map = A->map->fglobal2proc;
	for (i=0;i<A->num_rows;i++) {
		row = A->rows[i];
     	(*map)(row->length,row->col,iwork,procinfo,A->map); CHKERRN(0);
		for (j=0;j<row->length;j++) {
			if (iwork[j] != procinfo->my_id) count++;
		}
	}
	MY_FREE(iwork);
	(*max_row_len) = mrow_len;
	return(count);
}



syntax highlighted by Code2HTML, v. 0.9.1