/* playsound.c - Contains forkable sound playing function for gtkicq */
#ifdef HAVE_CONFIG_H
	#include <config.h>
#endif

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include "gtkicq.h"
#include "playsound.h"

#define B_FREQ 500
#define B_LENGTH 100

void playsound( char *file )
{
	FILE *soundfile, *devaudio, *devconsole;

#ifdef TRACE_FUNCTION
	printf( "playsound\n" );
#endif

	if( !sound_toggle )
		return;

	if( sound_pid )
		return;

       /* original code didn't handle fork failure sanely. ++bsa */
       switch( sound_pid = fork() )
	{
	case -1:
		sound_pid = 0;
	case 0:
		break;
	default:
		return;
	}

	soundfile = fopen( file, "r" );
	devaudio = fopen( "/dev/audio", "w" );

	if( soundfile && devaudio )
	{
		char buffer[1024];
		int nchars;

		while( (nchars = fread(buffer, 1, 1024, soundfile)) > 0 )
			fwrite( buffer, 1, nchars, devaudio );
	}
	else
	{
		devconsole = fopen( "/dev/console", "w" );
		if( devconsole )
		{
			fprintf( devconsole, "\33[10;%d]\33[11;%d]\a\33[10]\33[11]", B_FREQ, B_LENGTH );
			fclose( devconsole );
		}
	}

	if( soundfile )
		fclose( soundfile );
	if( devaudio )
	{
		fflush( devaudio );
		fclose( devaudio );
	}

	_exit(0);

}
