// MBCreateGIdx.c	
// Create contingent gene-index in the order of the orginal gene-ID.
//
//   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 MBCreateGIdx(double origID[],double gIdx[],int nobs)
{
    int n, preGIdx, preOrigID;

    preGIdx = 1;
    preOrigID = (int)origID[0];
    for(n=0; n<nobs; n++)
    {
        if( preOrigID == (int)origID[n] )
        {
            gIdx[n] =  preGIdx;
        }
        else
        {
            preOrigID = (int)origID[n];
            preGIdx = preGIdx + 1;
            gIdx[n] = preGIdx;
        }
    }
}

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    double *origID, *gIdx;
    int nobs;

    // 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: origID
    origID = mxGetPr(prhs[0]);

    plhs[0] = mxCreateDoubleMatrix(nobs,1,mxREAL);
    gIdx = mxGetPr(plhs[0]);

    MBCreateGIdx(origID,gIdx,nobs);
}
