/* Output to SB DAC using DMA mode */

#include <stdio.h>
#include <dos.h>
#include <conio.h>
#include <io.h>
#include <alloc.h>
#include <dos.h>
#include <stdlib.h>
#include <alloc.h>

#include "sb.h"

extern int optind;    /* index of which argument is next      */
extern char *optarg;  /* pointer to argument of current option */
extern int opterr;    /* allow error message  */
int getopt(int argc, char *argv[], char *optionS);

void main(int argc, char *argv[])
{
    FILE *f;
    signed char far *raw, far *aligned;
    long sample_len;
    register int j, i;
    unsigned sl, tmp, nr, sr=11000;
    unsigned char tm;
    unsigned long physical, aligned_physical;
    char ch;
    int stereo = 0, error = 0;

    while((ch = getopt(argc,argv,"sr:")) != EOF)
    {
	switch(ch)
	{
	    case 's':
		stereo = 1;
		break;
	    case 'r':
		sr = atoi(optarg);
		break;
	    case '?':
		error++;
		break;
	}
    }
    if(error || optind == argc)
    {
	puts("Usage: dacdma [-r rate] [-s] sample");
	exit(1);
    }

    if(Sb_Get_Params())
    {
        puts("BLASTER environment variable not set.");
        exit(1);
    }

    if(Sb_Init())
    {
	printf("Could not find Soundblaster!\n");
	exit(1);
    }
    printf("Found Soundblaster at address %xh, IRQ %d, DMA %d.\n",
	SbIOaddr,SbIRQ,SbDMAchan);

    printf("Sample rate = %d Hz\n",sr);
    printf("Output is %s.\n",(stereo) ? "stereo" : "mono");

    f = fopen(argv[optind],"rb");
    if(f == NULL)
    {
	printf("Could not open sample file %s\n",argv[1]);
	exit(1);
    }
    sample_len = filelength(fileno(f));
    if(sample_len > 64000)
        sl = 64000;
    else
        sl = (int)sample_len;

    raw = (signed char far *)farmalloc((unsigned long)sl + 65535L);
    physical = ((unsigned long)FP_OFF(raw)) + (((unsigned long)FP_SEG(raw)) << 4);
    aligned_physical = physical+0x0FFFFL;
    aligned_physical &= 0xF0000L;
    aligned=MK_FP((unsigned )((aligned_physical >> 4) & 0xFFFF),0);

    nr = fread(aligned,1,sl,f);

    fclose(f);

    printf("Playing sample\n");

    Sb_Init_Voice_DMA(NULL);   /* Use default interrupt handler */

    Sb_Sample_Rate(sr);
    Sb_Voice(1);

    Sb_OutVoice_DMA(aligned,sl,stereo);

    while(!kbhit() && !Sb_DMA_Complete())
	;
    if(!Sb_DMA_Complete())
    {
	Sb_Halt_DMA();
	getch();
    }

    Sb_Voice(0);

    printf("Done.\n");

    Sb_DeInit_Voice_DMA();

    farfree(raw);

    exit(0);
}
