#include <math.h>
#include "mex.h"
#include <stdio.h>
#include <string.h>
/* #define DEBUG 1 */

#define OBJ prhs[0]
#define OPT prhs[1]

void mexFunction(nlhs, plhs, nrhs, prhs)
int nlhs, nrhs;
mxArray *plhs[];
const mxArray *prhs[];
{
static char s[1024],s1[1024],*sp;
static int k,nrow,nnames;
mxArray *outarray;
double *yp;
FILE *fin;

if(nrhs<1)mexErrMsgTxt("Must have object name.");


/* get obj name */
if(!mxIsChar(OBJ))  mexErrMsgTxt("Object name must be a string.");
mxGetString(OBJ,s,255);
fprintf(stderr,"%s\n",s);

if(strstr(s,".mat")){
  strcpy(s1,"load ");
  strcat(s1,s);
  mexEvalString(s1);
  return;
}

strcpy(s1,BUILDMAT);
strcat(s1,"\"");
strcat(s1,s);
strcat(s1,"\"");
/* get options if present */
if(nrhs==2){
  if(!mxIsChar(OPT))  mexErrMsgTxt("Options must be a string.");
  mxGetString(OPT,s,255);
  strcat(s1," ");
  strcat(s1,s);
}

if(!(fin=popen(s1,"r")))
  mexErrMsgTxt("Cannot connect to buildmat.");
fread(&nnames,sizeof(int),1,fin);
fread(&nrow,sizeof(int),1,fin);
if(nnames == 0 || nnames>255) mexErrMsgTxt("Error in opening object.");

fprintf(stderr,"nnames= %d, nrows = %d\n",nnames,nrow);
outarray=mxCreateDoubleMatrix(nrow,1,mxREAL);
for(k=0;k<nnames;k++){
  sp=s;
  while(*sp = getc(fin))sp++;
  fprintf(stderr,"loading %s\n",s);
  mxSetName(outarray,s);
  yp=(double *)mxGetPr(outarray);
  if(nrow>0){
    fread(yp,nrow,sizeof(double),fin);
    mexPutArray(outarray,"caller");
  }
}
pclose(fin);
mxDestroyArray(outarray);
}
