/*
 * loadmat - C language routine to load a matrix from a MAT-file.
 *
 * Here is an example that uses 'loadmat' to load a matrix from a MAT-file:
 *
 *	FILE *fp;
 *	char name[20];
 *	int type, mrows, ncols, imagf;
 *	double *xr, *xi;
 *	fp = fopen("foo.mat","r");
 *	loadmat(fp, &type, name, &mrows, &ncols, &imagf, &xr, &xi);
 *      fclose(fp);
 *	free(xr);
 *	if (imagf) free(xi);
 *
 * The 'loadmat' routine returns 0 if the read is successful and 1 if
 * and end-of-file or read error is encountered.  'loadmat' can be called
 * repeatedly until the file is exhausted and an EOF is encountered.
 *
 * Author J.N. Little 11-3-86
 */

#include <stdio.h>
extern char *malloc();

typedef struct {
     long type;   /* type */
     long mrows;  /* row dimension */
     long ncols;  /* column dimension */
     long imagf;  /* flag indicating imag part */
     long namlen; /* name length (including NULL) */
} Fmatrix;

loadmat(fp, type, pname, mrows, ncols, imagf, preal, pimag)
FILE *fp;       /* File pointer */
int *type;      /* Type flag: see reference section of guide */
int *mrows;     /* row dimension */
int *ncols;     /* column dimension */
int *imagf;     /* imaginary flag */
char *pname;    /* pointer to matrix name */
double **preal;  /* pointer to real data */
double **pimag;  /* pointer to imag data */
{
	char *malloc();
	Fmatrix x;
	int mn, namlen;

	/*
	 * Get Fmatrix structure from file
	 */
	if (fread((char *)&x, sizeof(Fmatrix), 1, fp) != 1) {
		return(1);
	}
	*type = x.type;
	*mrows = x.mrows;
	*ncols = x.ncols;
	*imagf = x.imagf;
	namlen = x.namlen;
	mn = x.mrows * x.ncols;

	/*
	 * Get matrix name from file
	 */
	if (fread(pname, sizeof(char), namlen, fp) != namlen) {
		return(1);
	}

	/*
	 * Get Real part of matrix from file
	 */
	if (!(*preal = (double *)malloc(mn*sizeof(double)))) {
		fprintf(stderr,"\nError: Variable too big to load\n");
		return(1);
	}
	if (fread(*preal, sizeof(double), mn, fp) != mn) {
		free(*preal);
		return(1);
	}

	/*
	 * Get Imag part of matrix from file, if it exists
	 */
	if (x.imagf) {
		if (!(*pimag = (double *)malloc(mn*sizeof(double)))) {
			printf("\nError: Variable too big to load\n");
			free(*preal);
			return(1);
		}
		if (fread(*pimag, sizeof(double), mn, fp) != mn) {
			free(*pimag);
			free(*preal);
			return(1);
		}
	}
	return(0);
}
