#include <fcntl.h>
#include <sys\types.h>
#include <sys\stat.h>
#include <io.h>
#include <stdlib.h>
#include <stdio.h>
#include <dos.h>
#include <process.h>
#include <malloc.h>


#include "sound.h"

#define SIZE	32768L


byte convTab[256];


void convertFile(char *inSound, unsigned int wave, char *outSound, char *name)
{
	int			inFd;
	int			outFd;
	
	int			mult = 1;
	
	byte _huge	*inPtr;
	
	struct stat	fStat;
	
	unsigned int	part = SIZE;
	unsigned int	tmp;
	unsigned int	newWave = wave;
	
	struct sound	header;
	
	
	if (wave < 15000) {
		while (newWave < 22000) {
			mult++;
			newWave = wave * mult;
		}
		wave = newWave;
	}
	
	if (mult > 4) {
		printf("Frequency to low\n");
		exit(1);
	}


	if (stat(inSound,&fStat) != 0) {
		perror(inSound);
		exit(1);
	}

	inPtr  = (byte _huge *)halloc(SIZE, sizeof(byte));

	if (inPtr == NULL) {
		perror("Can't allocate memory");
		exit(1);
	}
	
	if (_dos_open(inSound, O_RDONLY, &inFd) != 0) {
		perror(inSound);
		exit(1);
	}

	if (_dos_creatnew(outSound, _A_NORMAL, &outFd)) {
		perror(outSound);
		exit(1);
	}
	_dos_close(outFd);
	
	if (_dos_open(outSound, O_RDWR, &outFd) != 0) {
		perror(outSound);
		exit(1);
	}
	
	strcpy(header.ident,IDENT);
	header.mult = mult;
	header.nbValues = 0;
	header.hertz = wave;
	header.timer = (1193180L / wave);
	strncpy(header.memo, name, 254);

	_dos_write(outFd, &header, sizeof(struct sound), &tmp);
	
	while (part == SIZE) {
		_dos_read(inFd, inPtr, (unsigned int)SIZE, &part);
		header.nbValues += part;
		_dos_write(outFd, inPtr, part, &tmp);
	}

	lseek(outFd, SEEK_SET, 0);
	_dos_write(outFd, &header, sizeof(struct sound), &tmp);

	_dos_close(inFd);
	_dos_close(outFd);

	hfree(inPtr);
}





main(int argc, char *argv[])
{
	if (argc != 5) {
		printf ("\nusage : convert <inFile> <hertz> <outFile> <name>\n");
		printf ("            inFile  : name of source file\n");
		printf ("            hertz   : frequency of source file\n");
		printf ("            outFile : name of converted file\n");
		printf ("            name    : comment for converted file\n");
		exit (1);
	}

	if (strlen(argv[4]) > 250) {
		printf("Name is limited to 250 characters.\n");
		exit (-1);
	}
	
	convertFile(argv[1], atoi(argv[2]), argv[3], argv[4]);
	exit(1);
}
