#include <exec/types.h>
#include <functions.h>
#include <exec/memory.h>
#include <exec/interrupts.h>
#include <hardware/custom.h>
#include <hardware/intbits.h>
#include <libraries/dos.h>
#include <stdio.h>

#define LVODisplayBeep -96

long beep_sigbit = 0;
long beep_sigmask = 0;
struct Task *chatterbox_task = NULL;

extern struct IntuitionBase *IntuitionBase;

extern struct gab_info gab_data[N_GAB_TYPES];

void (*OldBeep)() = NULL;

MyBeep()
{
	assert((chatterbox_task != 0) && (beep_sigmask != 0));

	Signal(chatterbox_task,beep_sigmask);
}

CleanupSignals()
{
	if (beep_sigbit)
		FreeSignal(beep_sigbit);

	if (OldBeep)
		SetFunction(IntuitionBase,LVODisplayBeep,OldBeep);
}

/* Intuition library must have been opened before calling!
 * Config() must have run before calling to initialize the
 * number of samples that are to be called if beep is defined
 * in the config file.  If no samples are assigned to beep,
 * we do not replace the DisplayBeep function!
 */
InitSignals()
{

	assert(IntuitionBase);

	add_cleanup(CleanupSignals);

	/* allocate a signal */
	if ((beep_sigbit = AllocSignal(-1L)) < 0)
		panic("can't alloc signal");

	/* precompute the mask and store for convenience */
	beep_sigmask = (1 << beep_sigbit);

	/* get the task ID */
	chatterbox_task = FindTask(NULL);

	/* replace DisplayBeep with our beep routine, saving
	 * the old vector so we can replace it when we leave
	 */
	if (gab_data[GAB_BEEP].n_gab_items > 0)
		OldBeep = SetFunction(IntuitionBase,LVODisplayBeep,MyBeep);
}

