/*
 * sparse2dot(A, fname)
 *
 * Generate a dot language file for the graph represented by a
 * sparse matrix.
 *
 * Inputs:
 *   A     - Adjacency matrix (column major)
 *   fname - Output file name
 */

#include <mex.h>
#include <stdio.h>

void sparse2dot(char* fname, int* jc, int* ir, double* cost, int n)
{
    FILE* fp = fopen(fname, "w");
    int i, j;

    fprintf(fp, "digraph matlab {\n");
    for (j = 0; j < n; ++j) {
        for (i = jc[j]; i < jc[j+1]; ++i) {
	    fprintf(fp, "  N%d -> N%d  [ label=\"%e\" ]\n",
	            j+1, ir[i]+1, cost[i]);
	}
    }
    fprintf(fp, "}\n");

    fclose(fp);
}


void mexFunction(int nlhs, mxArray** plhs,
                 int nrhs, const mxArray** prhs)
{
    int n;
    char fname[128];

    if (nrhs != 2)
        mxErrMsgTxt("Too few arguments");
    if (!mxIsNumeric(prhs[0]) || !mxIsSparse(prhs[0]) || 
        mxGetM(prhs[0]) != mxGetN(prhs[0]))
        mxErrMsgTxt("Graph must be a square matrix");
    if (!mxIsChar(prhs[1]))
        mxErrMsgTxt("File name must be a string");

    n = mxGetN(prhs[0]);
    mxGetString(prhs[1], fname, 128);

    sparse2dot(fname, mxGetJc(prhs[0]), mxGetIr(prhs[0]), mxGetPr(prhs[0]), n);
}

