// MBGetCategs.c	
// Get the categories in the order of the orginal values.
//
//   The algorithm for MicroBayes is described in the following paper
//
//   D. Zhang, M.T. Wells, C.D. Smart and W.E. Fry (2003). Bayesian
//       Normalization and Identification for Differential Gene
//       Expression Data.
//
//   PLASE CITE THIS PAPER AFTER YOU USE THIS SOFTWARE.
//
//	Dabao Zhang		March 6, 2003
//	Revised by Dabao Zhang
//       March 9, 2003 -- Consider genes' location effect
//
//	Copyright (c) 2003 by Dabao Zhang.

#include <math.h>
#include "mex.h"

void MBGetCategs(double origData[],double catData[],int nobs)
{
    int n, curIdx;
    double preOrig;

    preOrig = origData[0];
    curIdx = 0;
    catData[curIdx] = preOrig;
    for(n=0; n<nobs; n++)
    {
        if( preOrig != origData[n] )
        {
            preOrig = origData[n];
            curIdx = curIdx + 1;
            catData[curIdx] = preOrig;
        }
    }
}

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    double *origData, *catData, preOrig;
    int nobs, n, nCategs;

    // Check for proper number of arguments.
    if( nrhs!=1 )
    {
        mexErrMsgTxt("One input required.");
    }
    else if( nlhs>1 )
    {
        mexErrMsgTxt("Too many output arguments.");
    }

    nobs = mxGetM(prhs[0]);

    // RHS: origData
    origData = mxGetPr(prhs[0]);

    // Calculate number of categories
    preOrig = origData[0];
    nCategs = 1;
    for(n=0; n<nobs; n++)
    {
        if( preOrig != origData[n] )
        {
            preOrig = origData[n];
            nCategs = nCategs + 1;
        }
    }
    
    plhs[0] = mxCreateDoubleMatrix(nCategs,1,mxREAL);
    catData = mxGetPr(plhs[0]);

    MBGetCategs(origData,catData,nobs);
}
