/*	Serial.C

	Routines for reading and writing MIDI over the serial port.
	These are untested, but should work!

	© 1989  Blue Ribbon Bakery
*/

#include <intuition/intuition.h>
#include <hardware/custom.h>
#include <exec/ports.h>
#include <exec/interrupts.h>
#include <exec/memory.h>
#include <exec/execbase.h>
#include <hardware/intbits.h>
#include <libraries/dos.h>
#include <string.h>

extern struct Custom custom;

static struct Interrupt midiintin;

static void midiincode()

/*	Midi in interrupt routine.
*/

{
    register unsigned short data;
    geta4();
    for (data = custom.serdatr;data & 0x4000;data = custom.serdatr) {
	if (data & 0x8000) {
	    /* Overflow error. */
	}
	custom.intreq = INTF_RBF;
	data &= 0xFF;
	    /* Process the byte. */
    }
}

struct Interrupt *oldserin = 0;

void stealint()

/*	To receive MIDI on the serial port, install your
	interrupt handler with this routine.  It replaces the
	currently active handler with your own.  When done, you
	must reinstall the previous handler and remove yours.
*/

{
    midiintin.is_Node.ln_Name = "Midi receiver";
    midiintin.is_Node.ln_Pri = 20;
    midiintin.is_Node.ln_Type = NT_INTERRUPT;
    midiintin.is_Code = midiincode;
    Disable();
    oldserin = (struct Interrupt *) SetIntVector(INTB_RBF,&midiintin);
    Enable();
    custom.serper = 114; 
    custom.intena = INTF_SETCLR | INTF_RBF;
}

static void releaseint()

/*	When done receiving, call this routine to return the
	serial interrupt to the previous handler.
*/

{
    custom.intena = INTF_RBF;
    Disable();
    SetIntVector(INTB_RBF,oldserin);
    Enable();
}

sendmidibyte(data)

/*	Send one MIDI byte out the serial port.  */

char data;

{
    while (!(custom.serdatr & 0x2000));
    custom.serdat = data | 0x300;
}
