#include <err.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sys/param.h>
#include <sys/mman.h>
#include <machine/cpufunc.h>

#define BASE	0x200

static void
Tell(const char *what)
{
	int k;

	if (0) {
		printf("%s\t", what);
		for (k = 1; k < 6; k++)
			printf(" %02x", inb(BASE + k));
	printf("\n");
	}
}

static void
Poll(void)
{
	int j, k, l;

	j = 0;
	do {
		if (++j > 1000)
			break;
		l = inb(BASE + 1);
		if (0) {
			printf("POLL\t %02x", l);
			for (k = 2; k < 6; k++) {
				printf(" %02x", inb(BASE + k));
			}
			printf("\n");
		}
	} while (!(l & 0x40));
}

int
main(int argc __unused, char **argv __unused)
{
	FILE *f;
	u_int u;

	f = fopen("/dev/io", "r");

	u = inl(0x6000 + 0x30);
	u &= ~(1 << 19);
	u |= 1 << 19;
	outl(0x6000 + 0x30, u);
	u = inl(0x6000 + 0x30);

	outb(0x15c, 0x07); outb(0x15d, 0x06);		/* ACB2 */
	outb(0x15c, 0x60); outb(0x15d, BASE >> 8);	/* base addr MSB */
	outb(0x15c, 0x61); outb(0x15d, BASE & 0xff);	/* base addr LSB */
	outb(0x15c, 0x30); outb(0x15d, 0x01);		/* enable */
	outb(0x15c, 0xf0); outb(0x15d, 0x02);		/* internal pull-up */

	outb(BASE + 5, 0); 

	Tell("DIS");

	outb(BASE + 5, 0xfe | 0x01); 

	Tell("ENA");

	usleep(100000);
	outb(BASE + 3, 0x01); 
	Tell("START");
	Poll();
	outb(BASE + 0, 0x90);
	Tell("ADR");
	Poll();
	outb(BASE + 0, 0x00);
	Tell("reg");
	Poll();
	outb(BASE + 3, 0x02); 
	Tell("STOP");

	outb(BASE + 3, 0x01); 
	Tell("START");

	Poll();

	outb(BASE + 0, 0x91);
	Tell("ADR");

	Poll();

	outb(BASE + 3, 0x10); 
	Tell("NAK");

	u = inb(BASE + 0) << 8;

	Tell("DATA");

	Poll();

	u |= inb(BASE + 0);

	Tell("DATA");

	outb(BASE + 3, 0x02); 
	Tell("STOP");

	printf("%f\n", u / 256.0);


	outb(BASE + 5, 0); usleep(100000);

	return (0);
}

