/*************************************************************************
 ***                        bell.c                       (JJB TEMPLAR) ***
 *** Date begun: 26/8/89.                                              ***
 *** Last modified: 26/8/89.                                           ***
 *************************************************************************/

#include <exec/types.h>
#include <exec/memory.h>
#include <devices/audio.h>
#include <intuition/intuition.h>

#include <proto/exec.h>
#include <proto/intuition.h>

extern struct Window    *Window;
extern int              quiet;

int     audio;      /* Flag: 1 means can use audio bell */
int     gotdev;     /* Flag: 1 means succeeded to open device */
UBYTE   allocmap[] = {0x01,0x02,0x04,0x08};
BYTE    sinedat[] = {0,90,127,90,0,-90,-127,-90};

struct IOAudio  *audIO;
UBYTE           *auddat;
struct MsgPort  *audport;

void    initbell();
void    bell();
void    freebell();

void    initbell() /*====================================================*/
{
register int    j;
    if (quiet) return;
    if (!(audIO = (struct IOAudio *)AllocMem(sizeof(*audIO),MEMF_PUBLIC|MEMF_CLEAR)))
        return;     /* Failed to get IO structure */
    if (!(auddat = AllocMem(sizeof(sinedat),MEMF_CHIP))) goto ERROR;

    for (j = 0; j < sizeof(sinedat); j++) auddat[j] = sinedat[j];
    audIO->ioa_Length = 4;      audIO->ioa_Data = allocmap;
    audIO->ioa_Request.io_Message.mn_Node.ln_Pri = 127;

    if (!(audport = CreatePort("ty audio bell",0))) goto ERROR;
    audIO->ioa_Request.io_Message.mn_ReplyPort = audport;

    if (OpenDevice(AUDIONAME,0,audIO,0)) goto ERROR;
    gotdev = 1;         /* So freebell() knows to close device */

    audio = 1;          /* So I know I can use the audio bell */
    return;
ERROR:
    freebell();
}

void    bell() /*========================================================*/
{
    if (!audio) DisplayBeep(Window->WScreen);
    else {
        audIO->ioa_Request.io_Command = CMD_WRITE;
        audIO->ioa_Request.io_Flags = ADIOF_PERVOL;
        audIO->ioa_Data = auddat;
        audIO->ioa_Length = sizeof(sinedat);
        audIO->ioa_Period = 447;        /* From HRM */
        audIO->ioa_Volume = 64;         /* Max vol */
        audIO->ioa_Cycles = 250;        /* 1 second? */
        BeginIO(audIO);
        if (WaitIO(audIO)) freebell();  /* Error check */
    }
}

void    freebell() /*====================================================*/
{
    if (gotdev) CloseDevice(audIO);
    if (audport) DeletePort(audport);
    if (auddat) FreeMem(auddat,sizeof(sinedat));
    if (audIO) FreeMem(audIO,sizeof(*audIO));
    gotdev = audio = 0;
    audport = NULL;     auddat = NULL;      audIO = NULL;
}
