#include "mex.h"
#include "matrix.h"
#include "wfdb/wfdb.h"
#include <string.h>

/*
 * WFDB_getinfo.c
 *
 * Read info fields in a WFDB header file.
 * Return as character array or cell of character arrays.
 *
 */
 
/* Define order of input variables */
#define RECORD_INPUT 0

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

void mexFunction( int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[] )
{
  unsigned int ninfo, i;
  unsigned int record_length;
  char *record, *info;

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

  /* RECORD input must be a string. */
  if (mxIsChar(prhs[RECORD_INPUT]) != 1)
    mexErrMsgTxt("RECORD must be a string.");

  /* Get the length of the RECORD string and allocate memory. */
  record_length = (mxGetM(prhs[RECORD_INPUT]) *
		     mxGetN(prhs[RECORD_INPUT])) + 1;
  record = mxCalloc(record_length, sizeof(char));

  /* Get the RECORD string */
  mxGetString(prhs[RECORD_INPUT], record, record_length);

  /* ================== */
  /* Create INFO output */
  /* ================== */

  /* Set INFO output */
  ninfo = 0;
  if (info = getinfo(record))
    do
      ninfo++;
    while (info = getinfo(NULL));
  if (ninfo > 0)
    {
      plhs[INFO_OUTPUT] = mxCreateCellMatrix(ninfo, 1);
      info = getinfo(record);
      for (i = 0; i < ninfo; i++)
	{
	  mxSetCell(plhs[INFO_OUTPUT], i, mxCreateString(info));
	  info = getinfo(NULL);
	}
    }
  else
    {
      plhs[INFO_OUTPUT] = mxCreateString("");
    }

}
