#include <tos.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "mc_drive.h"


#define DEVICE	1
#define LESE_ABBRUCH 1000
#define	r_buff  12000
#define	s_buff_size  6000
IOREC	*iorec;

/* header file for dealing with the cookie jar */
#define BP _BasPag

extern void MSEND(int len,char *buf); /* schnell und trickreich in ASS */
void MIDEIN(void);

static long install_buffers(void) 
{
	iorec=Iorec(0);
	if (iorec->ibufsiz<r_buff)
	{
		iorec->ibuf=Malloc(r_buff);
		iorec->ibufsiz=r_buff;
	}
    iorec->ibufhd=0;         /* nchste Schreibposition */
   	iorec->ibuftl=0;         /* nchste Leseposition    */
    iorec->ibuflow=r_buff-40;        /* Marke fr Xon           */
   	iorec->ibufhi=r_buff-10;         /* Marke fr Xoff          */
	
	iorec=(IOREC *) (14+(long)(iorec));
	if (iorec->ibufsiz<s_buff_size)
	{
		iorec->ibuf=Malloc(s_buff_size);
		iorec->ibufsiz=s_buff_size;    /* Min = 4000 Bytes fr Sende-Puffer*/
   }
    iorec->ibufhd=0;          /* nchste Schreibposition */
   	iorec->ibuftl=0;          /* nchste Leseposition    */
    iorec->ibuflow=s_buff_size-40; /* Marke fr Xon           */
   	iorec->ibufhi=s_buff_size-10;  /* Marke fr Xoff          */
    return(0);
}

int fil_request(void)
{
 return(Bconstat (DEVICE));
}

int mdstat(void)
{
 return(Bconstat (DEVICE));
}

long   LESE(int len,char *buff)
{
int i=0;
long err1=0;
do 
{
  if (Bconstat(DEVICE)<0)
  {
   buff[i]=(char)Bconin(DEVICE);
   i++;
   err1=0;
  }
  else err1++;
} while ((err1<LESE_ABBRUCH) && (i<len));
if (err1>=LESE_ABBRUCH)  return(err1);
                else return(0);
}



void MIDEIN(void)
{
  while (Bconstat(DEVICE)<0)
  {
   (void)Bconin(DEVICE);
  }
}

static long install_cookies(void)
{
	COOKIE  *cokie;
	long	found=0;
	int		i=16;
		
	cokie=*CJAR;
	if (!cokie)
	{
		*CJAR=cokie=Malloc(i*8);
		if (cokie)
		{
			cokie->tag.aslong = 0;
			cokie->value=i;
		}
	}
	if (cokie) 
	{
		while (cokie->tag.aslong != 0) 
		{
			if (!strncmp(cokie->tag.aschar, "MCDR",4))
			{
				cokie->value=(long)&port;
				found=1;
			}
			cokie++;
		}
		if (!found)
		{
			strncpy(cokie->tag.aschar,"MCDR",4);
			found=cokie->value;
			cokie->value=(long) &port;
			cokie++;
			cokie->tag.aslong = 0; 
			cokie->value=found; 
		}
	return(0);
	}
	return(-1);
}

void main(void)
{
	Cconws("Schnittstellentreiber\r\n");
	Cconws("    --Seriell--\r\n");
	Cconws("  fr MIDI_COM.ACC\r\n");
	(void)Supexec(install_buffers);
	(void)Supexec(install_cookies);
	Ptermres(256L + BP->p_tlen + BP->p_dlen + BP->p_blen, 0);
}