
/*
 * savemat - C language routine to save a matrix in a MAT-file.
 *
 * Here is an example that uses 'savemat' to save two matrices to disk,
 * the second of which is complex:
 *
 *	FILE *fp;
 *	double xyz[1000], ar[1000], ai[1000];
 *	fp = fopen("foo.mat","wb");
 *	savemat(fp, 2000, "xyz", 2, 3, 0, xyz, (double *)0);
 *	savemat(fp, 2000, "a", 5, 5, 1, ar, ai);
 *      fclose(fp);
 *
 * Author J.N. Little 11-3-86
 */

#include <stdio.h>

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;

savemat(fp, type, pname, mrows, ncols, imagf, preal, pimag)
FILE *fp;       /* File pointer */
int type;       /* Type flag: Normally 0 for PC, 1000 for Sun, Mac, and	 */
		/* Apollo, 2000 for VAX D-float, 3000 for VAX G-float    */
		/* Add 1 for text variables.	 */
		/* See LOAD in reference section of guide for more info. */
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 */
{
	Fmatrix x;
	int mn;
	
	x.type = type;
	x.mrows = mrows;
	x.ncols = ncols;
	x.imagf = imagf;
	x.namlen = strlen(pname) + 1;
	mn = x.mrows * x.ncols;

	fwrite(&x, sizeof(Fmatrix), 1, fp);
	fwrite(pname, sizeof(char), (int)x.namlen, fp);
	fwrite(preal, sizeof(double), mn, fp);
	if (imagf) {
	     fwrite(pimag, sizeof(double), mn, fp);
	}
}

