/*
  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>
#include <malloc.h>

#define DEBUG 1
#define DEBUGEVERYPEL 0

void main(argc,argv)
  int argc;
#if 0
  /* const char *const only works with gcc;*/
  const char *const argv[];
  /* gcc no work with loadmat.c, savemat.c; Matlab loads but strange result */
#endif
  char *argv[];
{
	FILE *fp, *fopen();
	char name[20];
	int type, mrows, ncols, imagf;
	double *xr, *xi;
        long MN, mn;    /* prod of mcol and nrows, and running index of same*/
#if 0   /* fixed arrays beyond certain size do not work */
        unsigned short xrint[262144], xiint[262144];  /* malloc later */
        /* changed to malloc which appears just after MN gets set */
#endif
        unsigned short *xrint, *xiint;

        if (argc < 3) {     /* help */
            fprintf(stderr,"%s: reduces storage requirement of matrices 1/4\n",
                argv[0]);
            fprintf(stderr,"use: %s deleteme.mat deleteme_uss.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);

        /* fprintf(stderr,"type was = %d\n",type); */
        type = type + 40;  /* indicate unsigned 16 bit integers */
        /* fprintf(stderr,"type now is = %d\n",type); */
        MN = mrows*ncols;
        xrint = (unsigned short *) malloc(MN * sizeof(unsigned short));
        xiint = (unsigned short *) malloc(MN * sizeof(unsigned short));
        for (mn =0 ; mn<MN; mn++)
        {
          xrint[mn] = (unsigned short) xr[mn];
          if (DEBUGEVERYPEL) 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(stderr,"%s: converted %d by %d (%d bytes of) dbl precis. to\n",
                argv[0], mrows,ncols,MN*8);
        fprintf(stderr,"%s: 1/4 amount of data: %d bytes of unsigned shorts\n",
                argv[0], MN*2);
        fprintf(stderr,"%s: Decimals TRUNCATED.\n", argv[0]);
        fprintf(stderr,"%s: Values <0 or > 65535 CLIPPED modulo 65536\n",
                argv[0]);
}


