/*
 * WFDB_sampfreq.c
 *
 */
 
#include "mex.h"
#include "matrix.h"
#include "wfdb/wfdb.h"

/* Define order of input variables */
#define RECORD_INPUT 0

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

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

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

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

      freq = sampfreq(record);
    }
  else
    freq = sampfreq(NULL);

  if (freq < 0)
    switch ((int)freq)
      {
      case -1:
	mexErrMsgTxt("Failure: unable to read header file");
      case -2:
	mexErrMsgTxt("Failure: incorrect header file format");
      default:
	mexPrintf("Error code: %d\n", freq);
	mexErrMsgTxt("Unknown error");
      }
  else
    plhs[FS_OUTPUT] = mxCreateDoubleScalar(freq);
}
