/*
  mat2ussmat deleteme.mat deleteme_uss.mat              Steve Mann,  1990 DEC
  mat2ussmat - saves space by reading in double and writing out unsigned 16 bit
*/

#include <stdio.h>
#define DEBUG 1

main(argc,argv)
int argc;
char *argv[];
{
	FILE *fp, *fopen();
	char name[20];
	int type, mrows, ncols, imagf;
	double *xr, *xi;
        /* biggest array without core dump is 262144 bytes */
        unsigned short xrint[262144], xiint[262144];  /* malloc later */
        long MN, mn;    /* prod of mcol and nrows... bightness of data */

        fprintf(stderr,"declared biggest array possible without get core\n");
        fprintf(stderr,"more than 262144 gives core dump.  Try malloc?\n");

        if (argc < 3) {     /* help */
            fprintf(stderr,"%s reduces storage requirement of matrices 1/4\n",
                argv[0]);
            fprintf(stderr,"use: %s deleteme.mat deleteme_new.mat\n", argv[0]);
            exit(-1);   /* no error exit */
        }

	fp = fopen(argv[1],"r");
        if (fp==NULL)  {perror(argv[0]);  exit(-1);}
	if (loadmat(fp, &type, name, &mrows, &ncols, &imagf, &xr, &xi)) {
		printf("\nRead error\n");
	}
	fclose(fp);

        type = type + 40;  /* indicate unsigned 16 bit integers */

        MN = mrows*ncols;
        for (mn =0 ; mn<MN; mn++) {
            xrint[mn] = (unsigned short) xr[mn];
            if (DEBUG) fprintf(stderr,"%d\n",xrint[mn]);
          if (imagf)   xiint[mn] = (unsigned short) xi[mn];
        }

 	fp = fopen(argv[2],"w");
 	savematuss(fp, type, name, mrows, ncols, imagf, xrint, xiint);
	fclose(fp);
	free(xr);
	if (imagf) {
		free(xi);
	}
        fprintf(stdout,"Converted %d byte dbl data to quarter the data: %d byte of unsigned short\n",MN*8,MN*2);
}

