#include "mex.h"
#include "matrix.h"
#include "wfdb/wfdb.h"

/*
 * WFDB_strecg.c
 *
 * Convert WFDB mnemonics to annotation codes.
 * Return as array.
 *
 */
 
/* Define order of input variables */
#define ANN_INPUT 0

/* Define order of output variables */
#define CODE_OUTPUT 0

void mexFunction( int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[] )
{
  unsigned int nanns, i;
  mxArray *cell;
  char *annot;
  unsigned int annot_length;

  /* Check for correct total number of input arguments. */
  if (nrhs != 1)
    {
      mexErrMsgTxt("One input argument required.");
    }

  if (mxIsCell(prhs[ANN_INPUT]))
    {
      nanns = mxGetM(prhs[ANN_INPUT]) * mxGetN(prhs[ANN_INPUT]);
      plhs[CODE_OUTPUT] = mxCreateDoubleMatrix(nanns, 1, mxREAL);
      for (i = 0; i < nanns; i++)
	{
	  cell = mxGetCell(prhs[ANN_INPUT], i);
	  annot_length = (mxGetM(cell) * mxGetN(cell)) + 1;
	  annot = mxCalloc(annot_length, sizeof(char));
	  mxGetString(cell, annot, annot_length);
	  *(mxGetPr(plhs[CODE_OUTPUT]) + i) = strecg(annot);
	}
    }  
  else
    {
      annot_length = (mxGetM(prhs[ANN_INPUT]) * mxGetN(prhs[ANN_INPUT])) + 1;
      annot = mxCalloc(annot_length, sizeof(char));
      mxGetString(prhs[ANN_INPUT], annot, annot_length);
      plhs[CODE_OUTPUT] = mxCreateDoubleScalar(strecg(annot));
    }

}
