#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char	*version = "version 1.0";
char	*name = "sndcmpx";

void main(argc, argv)
int argc;
char *argv[];
{
short crunch = 0;
unsigned char crunched = 0;
FILE *in_handle;
FILE *out_handle;
char outname[20];
char *s;

	if (argc < 2) {
		printf("%s %s\n", name, version);
		printf("Usage: %s filename\n", name);
		exit(0);
	}

	if ((in_handle = fopen(argv[1], "rb")) == NULL)
	{
		fprintf(stderr, "Could not open input file.\r\n\0");
		exit(-1);
	}

	strcpy(outname, argv[1]);
	if ((s = strrchr(outname, '.')) != NULL)
		*s = '\0';

	strcat(outname, ".cmp");	/* Add filename extension */
	
	if ((out_handle = fopen(outname, "wb")) == NULL)
	{
		fprintf(stderr, "Could not open output file.\r\n\0");
		exit(-1);
	}
	
	while (fread(&crunch, 2, 1, in_handle) == 1)
	{
#if __MSDOS__	/* convert 16-bit Motorola value to 16-bit Intel */
		crunch = ((crunch << 8) & 0xff00) | ((crunch >> 8) & 0x00ff);
#endif

		crunched = (char)(sqrt((double)abs(crunch/2)));
		if (crunched == 128)
			crunched = 127;
		crunched = crunched << 1;
		if (crunch < 0)
			crunched = crunched | 0x1;
		
		fwrite(&crunched, 1, 1, out_handle);
	}
		
	fclose(in_handle);
	fclose(out_handle);
        exit(0);
}
