/* AM/FM 8 channel example - loader part */

#include <exec/types.h>
#include <exec/memory.h>
#include <dos/dos.h>
#include <proto/exec.h>
#include <proto/dos.h>
#include <stdio.h>
#include <stdlib.h>

extern void __asm play(void),endplay(void);

UWORD *sample[2],period1,period2;
ULONG slen[2];

/* halvesample() halves the volume of the sample, it has to be done
   in advance */

void halvesample(BYTE *sample,ULONG length)
{
	while(length--) *sample++ /= 2;
}

/* loadsample() load a sample into the memory */

BOOL loadsample(UWORD num,char *name)
{
	BPTR file;
	LONG len;
	if(file = Open(name,MODE_OLDFILE)) {
		Seek(file,0,OFFSET_END);
		if((len = Seek(file,0,OFFSET_BEGINNING)) > 0 &&
			(sample[num] = AllocMem(len,MEMF_CHIP|MEMF_PUBLIC))) {
			slen[num] = len;
			if(Read(file,sample[num],len) != len) {
				printf("read error!\n");
				Close(file);
				return(TRUE);
			}
		} else {
			printf("no memory!\n");
			Close(file);
			return(TRUE);
		}
		Close(file);
	} else {
		printf("file open failure! ('%s')\n",name);
		return(TRUE);
	}
	halvesample((UBYTE *)sample[num],len);
	return(FALSE);
}

/* frees the samples */

void freesamples(void)
{
	if(slen[0]) FreeMem(sample[0],slen[0]);
	if(slen[1]) FreeMem(sample[1],slen[1]);
}

/* the main routine */

void main(int argc,char *argv[])
{
	if(argc != 5) {
		printf("usage: example <sample1> <period1> <sample2> <period2>\n");
		return;
	}
	if((period1 = atoi(argv[2])) == 0 || (period2 = atoi(argv[4])) == 0) {
		printf("periods must be > 0!\n");
		return;
	}
	if(!loadsample(0,argv[1]) && !loadsample(1,argv[3])) {
		printf("Playing '%s' (period %d) and '%s' (period %d)\n",
			argv[1],period1,argv[3],period2);
		play();
		Delay(100);
		endplay();
	}
	freesamples();
	exit(0);
}
