
#include <exec/types.h>
#include <exec/memory.h>
#include <devices/audio.h>
#include <fcntl.h>
#include "globals.h"

#define LEFT0  1
#define RIGHT0 2
#define LEFT1  4
#define RIGHT1 8

#ifdef  TRUE
#undef  TRUE
#undef  FALSE
#endif

#define TRUE   1
#define FALSE  0

extern struct   MsgPort *CreatePort();
extern UBYTE    *AllocMem();
static UBYTE allocationMap[] = { LEFT0, LEFT1, RIGHT0, RIGHT1 };
static UBYTE *beepdata = NULL, *oldbeep = NULL, sdata;
static short beepinit  = FALSE;
static struct IOAudio *ioa = NULL;          /* Audio IO control block */


InitBeep()
{
/* allocate memory for Audio IO control block pointer -- longword aligned */
   if((ioa = (struct IOAudio *)AllocMem((long)sizeof(struct IOAudio),
                 MEMF_CHIP | MEMF_CLEAR)) == NULL)
      return FALSE;

   if((beepdata =(UBYTE *)AllocMem(BEEPSIZE,MEMF_CHIP | MEMF_CLEAR)) == NULL)
   {
      FreeMem(ioa,(long)sizeof(struct IOAudio));
      ioa = NULL;
      return FALSE;
   }
   beepdata[ 0 ] = 100;

/* open the audio device */
   ioa->ioa_Request.io_Message.mn_Node.ln_Pri  = 10;   /* any channel */
   ioa->ioa_Request.io_Message.mn_ReplyPort    = CreatePort("Comm.snd",0L);
   if(ioa->ioa_Request.io_Message.mn_ReplyPort == 0)
   {
      FreeMem(ioa,(long)sizeof(struct IOAudio));
      FreeMem(beepdata,BEEPSIZE);
      ioa = NULL;
      return FALSE;
   }

   ioa->ioa_Data   = allocationMap;
   ioa->ioa_Length = sizeof(allocationMap);
   if(OpenDevice(AUDIONAME,0L,ioa,0L))
   {
      FreeMem(ioa,(long)sizeof(struct IOAudio));
      FreeMem(beepdata,BEEPSIZE);
      DeletePort((long)ioa->ioa_Request.io_Message.mn_ReplyPort);
      ioa = NULL;
      return FALSE;
   }
   ioa->ioa_Request.io_Command = CMD_WRITE;
   ioa->ioa_Request.io_Flags = ADIOF_PERVOL;
   ioa->ioa_Period = install.period;
   ioa->ioa_Volume = install.volume;
   ioa->ioa_Cycles = install.cycles;
   ioa->ioa_Length = install.length;
   ioa->ioa_Data   = beepdata;

   return TRUE;
}

/*************
    clean up
*************/
Close_Beep()
{
   if(ioa)                       /* if memory allocated */
   {
      if(beepinit && CheckIO(ioa) == FALSE)
          WaitIO(ioa);
      CloseDevice(ioa);
      if(ioa->ioa_Request.io_Message.mn_ReplyPort)
         DeletePort((long)ioa->ioa_Request.io_Message.mn_ReplyPort);
      FreeMem(ioa->ioa_Data,ioa->ioa_Length);
      FreeMem(ioa,(long)sizeof(struct IOAudio));
   }
}


Beep()
{
   if(ioa == NULL)  return FALSE;

   ioa->ioa_Request.io_Command = CMD_WRITE;
   ioa->ioa_Request.io_Flags   = ADIOF_PERVOL;

   if(beepinit)
   {
     if(CheckIO(ioa) == FALSE)
       return TRUE;
     WaitIO(ioa);
   }
   BeginIO(ioa);             /* play it SAM... */
   beepinit = TRUE;
   return TRUE;
}

