#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/soundcard.h>

#define DSPDEV "/dev/dsp0"

int fd;

unsigned short
read_dspdata(unsigned short addr)	/* Reads a word form data memory */
{
	copr_debug_buf rec;

	rec.parm1 = addr;

	if (ioctl(fd, SNDCTL_COPR_RDATA, &rec)==-1)
	{
		perror("Read DSP data from " DSPDEV);
		exit(-1);
	}

	return rec.parm1;
}

void
write_dspdata(unsigned short addr, unsigned short data)
{
	copr_debug_buf rec;

	rec.parm1 = addr;
	rec.parm2 = data;

	if (ioctl(fd, SNDCTL_COPR_WDATA, &rec)==-1)
	{
		perror("Read DSP data from " DSPDEV);
		exit(-1);
	}
}

unsigned int
read_dspcode(unsigned short addr)	/* Reads a word form program memory */
{
	copr_debug_buf rec;

	rec.parm1 = addr;

	if (ioctl(fd, SNDCTL_COPR_RCODE, &rec)==-1)
	{
		perror("Read DSP code from " DSPDEV);
		exit(-1);
	}

	return rec.parm1;
}

void
reload(void)
{
	int f, i;

	copr_buffer buf;

	if ((f=open("/E/analog/spasm/cwmon.ld", O_RDONLY, 0))==-1)
	{
		perror("/E/analog/spasm/cwmon.ld");
		exit(-1);
	}

	if ((buf.len = read(f, buf.data, sizeof(buf.data)))==-1)
	{
		perror("/E/analog/spasm/cwmon.ld");
		exit(-1);
	}

	if (buf.len == sizeof(buf.data))
	{
		fprintf(stderr, "Error: Code too long\n");
		exit(-1);
	}

	close(f);

	buf.flags = CPF_FIRST|CPF_LAST;
	if (ioctl(fd, SNDCTL_COPR_LOAD, &buf)==-1)
	{
		perror("Code load " DSPDEV);
		exit(-1);
	}
}

int
main(int argc, char *argv[])
{
	int i, blk;

	if ((fd=open(DSPDEV, O_RDWR, 0))==-1)
	{
		perror(DSPDEV);
		exit(-1);
	}

#if 1
	reload();
#else
	if (ioctl(fd, SNDCTL_COPR_RESET, 0)==-1)
	{
		perror("Reset " DSPDEV);
		exit(-1);
	}
#endif

	for (i=0x3000;i<0x31f1;i++)
	{
	    int tmp;

	    if ((i % 8)==0) printf("\n%4x: ", i);

	    tmp = read_dspdata(i);
	    if (tmp == i)
	       printf("------ ");
	    else
	       printf("%06x ", read_dspdata(i));
	}
	printf("\n");

	close(fd);
	exit(-1);
}
