/****************************************************************************/
/*                                                                          */
/*	SOUND.C : C functions for digitized sound.                             */
/*                                                                          */
/*                                                                          */
/*	(c) Herv‚ Soulard, Version 1.0 - 10/01/1991                            */
/*	                   Version 1.1 - 01/02/1991                            */
/*                                                                          */
/****************************************************************************/


#include <fcntl.h>
#include <sys\types.h>
#include <sys\stat.h>
#include <io.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <dos.h>
#include <process.h>
#include <malloc.h>

#include "sound.h"

#define SIZE	16384

static byte	convTab[256];

int readSound(char *fSound, struct sound *sSound)
{
	int			fd;
	byte _huge	*ptr;
	unsigned int	part;
	unsigned long	i;
	char			fName[255];
	
	strcpy(fName, fSound);
	strcat(fName, ".psf");

	if (_dos_open(fName, O_RDONLY, &fd) != 0) {
		perror(fSound);
		exit(1);
	}
	
	lseek(fd, SEEK_SET, 0);
	_dos_read(fd, sSound, sizeof(struct sound), &part);
	
	if (!strcmp(sSound->ident, IDENT)) {
		for (i = 0; i < 256; i++) 
			convTab[i] = (char)(((i * sSound->timer) / 256 ) + 1);

		ptr = sSound->buffer = (byte _huge *)halloc(sSound->nbValues+1, 1);
		if (ptr == NULL) {
			perror("Can't allocate memory");
			exit(1);
		}

		do {
			_dos_read(fd, ptr, SIZE, &part);
			ptr += part;
		}
		while (part == SIZE);
	
		ptr = sSound->buffer;

		for (i = 0; i < sSound->nbValues; i++, ptr++)
			*ptr = convTab[*ptr];
		*ptr = '\0';
		
		_dos_close(fd);
		return (1);
	}
	else {
		_dos_close(fd);
		return (0);
	}
}


void closeSound(struct sound *sSound)
{
	hfree(sSound->buffer);
}