#include "mex.h"


void commonNeighbors(mwIndex* ir, mwIndex* jc, double* pr, double *numNeighbors, mwSize n, mwIndex* ir_out, mwIndex* jc_out, double* pr_out)
{
	//double averageNeighbors;
	int minNumNeighbors;
	int currCol = 0, nnzCurrCol, startIdx, stopIdx, i, j, currRow;
	int nnz = jc[n];
	jc_out[n] = jc[n];
	
	printf("nnz = %d\n", nnz);
	for (currCol = 0; currCol < n; currCol++)
	{
		jc_out[currCol] = jc[currCol];
		/*
		printf("jc_out[currCol] = %d, ", jc_out[currCol]);
		printf("currCol = %d\n ", currCol);
         */
		nnzCurrCol = jc[currCol + 1] - jc[currCol];
		/*printf("nnzCurrCol = %d ", nnzCurrCol);*/
		startIdx = jc[currCol];
		/*printf("startIdx = %d ", startIdx);*/
		stopIdx = jc[currCol + 1];
		/*printf("stopIdx = %d\n", stopIdx);*/
		
		for(i = startIdx; i < stopIdx; i++)
		{
			currRow = ir[i];
			//averageNeighbors = (numNeighbors[currRow] + numNeighbors[currCol]) / 2;
			minNumNeighbors = numNeighbors[currRow];
			if (minNumNeighbors > numNeighbors[currCol])
			{
					minNumNeighbors = numNeighbors[currCol];
			}
			
			/*printf("currRow = %d, currCol = %d, average neighbors = %f\n", currRow, currCol, averageNeighbors);*/
			//pr_out[i] = pr[i] / averageNeighbors;
			pr_out[i] = pr[i] / minNumNeighbors;
			ir_out[i] = ir[i];
		}		
	}  
}


/* The gateway function 
//this function accepts two parameters:
//1. a sparse affinity matrix (should be the number of common neighbors between nodes i and j
//2. an array with the number of neighbors of each node
*/
void mexFunction( int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[])
{
/* variable declarations here */
mwIndex* ir;
mwIndex* jc;
double* pr;
mwIndex* ir_out;
mwIndex* jc_out;
double* pr_out;
double* numNeighbors;
mwSize n;
int i;


/*printf("nlhs = %d, nrhs = %d\n", nlhs, nrhs);*/

ir = mxGetIr(prhs[0]);
jc = mxGetJc(prhs[0]);
pr = mxGetPr(prhs[0]);
numNeighbors = mxGetPr(prhs[1]);
n = mxGetN(prhs[1]);

plhs[0] = mxCreateSparse(n,n, jc[n], mxREAL);

ir_out = mxGetIr(plhs[0]);
jc_out = mxGetJc(plhs[0]);
pr_out = mxGetPr(plhs[0]);

/*
//printf("pr_out = %d", pr_out);
//printf("n = %d\n",n);
//printf("ir[0] = %d, jc[0] = %d, pr[0] = %f\n", ir[0], jc[0], pr[0]);
//printf("numNeighbors[0] = %f, numNeighbors[1] = %f\n", numNeighbors[0], numNeighbors[1]);
 */

commonNeighbors(ir, jc, pr, numNeighbors, n, ir_out, jc_out, pr_out);



}


