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

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

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

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


/* get obj name */
if(!mxIsString(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,s);
/* get options if present */
if(nrhs==2){
  if(!mxIsString(OPT))  mexErrMsgTxt("Options must be a string.");
  mxGetString(OPT,s,255);
  strcat(s1," ");
  strcat(s1,s);
}

startchild(s1,&fout,&fin);
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);
yp=mxCalloc(1,nrow*sizeof(double));
for(k=0;k<nnames;k++){
  sp=s;
  while(*sp = getc(fin))sp++;
  fprintf(stderr,"loading %s\n",s);
  if(nrow>0){
    fread(yp,nrow,sizeof(double),fin);
    mexPutFull(s,1,nrow,yp,NULL);
  }
}
fclose(fin);
}
