/*
 * ==============================================================
 * bfs_mex.c The mex interface to the matlab bgl wrapper.
 *
 * David Gleich
 * 20 April 20020
 * =============================================================
 */

#include "mex.h"

#include "matlab_bgl.h"

#include <math.h>
#include <stdlib.h>

void expand_to_double(int* src, double* dst, int len, double offset)
{
    int i;
    for (i = len-1; i>=0; i--)
    {
        dst[i] = (double)src[i] + offset;
    }
}

/*
 * The mex function runs a max-flow min-cut problem.
 */
void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{
    int i;
    
    int mrows, ncols;
    
    int n,nz;
    
    /* sparse matrix */
    int *ia, *ja;
    
    
    /* output data */
    double *a, *ci;
    int *int_a;
     
    
    if (nrhs != 1) 
    {
        mexErrMsgTxt("1 inputs required.");
    }

    /* The first input must be a sparse matrix. */
    mrows = mxGetM(prhs[0]);
    ncols = mxGetN(prhs[0]);
    if (mrows != ncols ||
        !mxIsSparse(prhs[0]) ||
        !mxIsDouble(prhs[0]) || 
        mxIsComplex(prhs[0])) 
    {
        mexErrMsgTxt("Input must be a noncomplex square sparse matrix.");
    }
    
    n = mrows;
        
    
    
    /* Get the sparse matrix */
    
    /* recall that we've transposed the matrix */
    ja = mxGetIr(prhs[0]);
    ia = mxGetJc(prhs[0]);
    
    nz = ia[n];
        
    plhs[0] = mxCreateDoubleMatrix(n,1,mxREAL);
    a = mxGetPr(plhs[0]);
    ci = NULL;
    
    if (nlhs > 1)
    {
        plhs[1] = mxCreateDoubleMatrix(nz,1,mxREAL);
        ci = mxGetPr(plhs[1]);
    }
    
    int_a = (int*)a;
    for (i=0; i<n; i++)
    {
        int_a[i] = -1;
    }
    
    
    biconnected_components(n, ja, ia,
        (int*)a, (int*)ci);
    
    expand_to_double((int*)a, a, n, 1.0);
    if (nlhs > 1)
    {
        expand_to_double((int*)ci, ci, nz, 1.0);
    }
}


