#include <stdio.h>
#include <stdlib.h>
#include <zx81.h>

#if 0
#define	AY_REG	0xdf
#define AY_DATA	0xdb
#else
#define	AY_REG	0xdb
#define AY_DATA	0xdf
#endif

/*
 * Registers
 */

#define	REG_TONE_A_LOW	0
#define	REG_TONE_A_HIGH	1
#define	REG_TONE_B_LOW	2
#define	REG_TONE_B_HIGH	3
#define	REG_TONE_C_LOW	4
#define	REG_TONE_C_HIGH	5
#define	REG_NOISE	6
#define REG_MIXER	7
#define REG_AMP_A	10
#define REG_AMP_B	11
#define REG_AMP_C	12
#define REG_ENV_A	13
#define REG_ENV_B	14
#define REG_ENV_C	15
#define REG_IOA		16
#define REG_IOB		17

#define freq2div(freq)	((16100000 / freq) - 16)

main()
{
	int i;
	int tone, tonehigh, tonelow;

	printf("Starting test.\n");
	
/* Initialise the AY chip */

/*
 *	Mixer - All channels on and I/O ports output.
 */

	outp(AY_REG, REG_MIXER);
	outp(AY_DATA, 0xc0);

/*
 *	Set all the audio channel output amplifiers to 11!
 */

	outp(AY_REG, REG_AMP_A);
	outp(AY_DATA, 0x0f);

	outp(AY_REG, REG_AMP_B);
	outp(AY_DATA, 0x0f);

	outp(AY_REG, REG_AMP_C);
	outp(AY_DATA, 0x0c);

/* Channel A - Middle C */

	tone = freq2div(261);
	tonehigh = tone / 256;
	tonelow	= tone - (tonehigh * 256);

	outp(AY_REG, REG_TONE_A_HIGH);
	outp(AY_DATA, tonehigh);

	outp(AY_REG, REG_TONE_A_LOW);
	outp(AY_DATA, tonelow);

/* Channel B - C one octave above */

	tone = freq2div(523);
	tonehigh = tone / 256;
	tonelow	= tone - (tonehigh * 256);

	outp(AY_REG, REG_TONE_B_HIGH);
	outp(AY_DATA, tonehigh);

	outp(AY_REG, REG_TONE_C_LOW);
	outp(AY_DATA, tonelow);

/* Channel C - E */

	tone = freq2div(329);
	tonehigh = tone / 256;
	tonelow	= tone - (tonehigh * 256);

	outp(AY_REG, REG_TONE_C_HIGH);
	outp(AY_DATA, tonehigh);

	outp(AY_REG, REG_TONE_C_LOW);
	outp(AY_DATA, tonelow);

/*
 * Keep cycling Port A through a count forever.
 */

#define WIBBLE 0

	while(1)
	{
		for (i = 0; i < 256; i++)
		{
			outp(AY_REG,REG_IOA);
#if WIBBLE
			printf("%d\n",i);
			sleep(1);
#endif
			outp(AY_DATA, i);
#if WIBBLE
			sleep(1);
#endif
		}
	}

}
