#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/soundcard.h>
#include <sys/ultrasound.h>
#include <limits.h>

#include "mod.h"

SEQ_DEFINEBUF(2048);
int seqfd, gus_dev=-42;

void init_sound(void)
{
    int nr, i;
    struct synth_info si;

    if((seqfd=open("/dev/sequencer", O_WRONLY, 0)) == -1) {
	perror("Unable to open sequencer.");
	exit(1);
    }

    if(ioctl(seqfd, SNDCTL_SEQ_NRSYNTHS, &nr) == -1) {
	perror ("Unable to find out # of synth-devices.");
	exit (1);
    }

#if 0
    printf("This machine has %d synthesizer devices configured.\n",nr);
#endif
    
    for(i=0; i < nr; ++i) {
	si.device=i;
	if(ioctl(seqfd, SNDCTL_SYNTH_INFO, &si) == -1) {
	    perror("Unable to get synth_info.");
	    exit (1);
	}

	if(si.synth_type == SYNTH_TYPE_SAMPLE &&
	    si.synth_subtype == SAMPLE_TYPE_GUS) {
	    gus_dev=i;
	    break;
	}
    }

    if(gus_dev == -42) {
	perror("Unable to find a GUS on this system.");
	exit (1);
    }

    SEQ_VOLUME_MODE(gus_dev, VOL_METHOD_LINEAR);
    
#if 0    
    printf("%s [Voices = %d] [Sample memory = %dk]\n",si.name,si.nr_voices,
	   si.instr_bank_size);

    printf("GUS ready.\n");
#endif
}


void cleanup_sound(void) {
    close (seqfd);
}

/* This is seqbuf_dump() used by the SEQ_DUMPBUF macro. */

void seqbuf_dump()
{
    if (_seqbufptr)
	if(write(seqfd, _seqbuf, _seqbufptr) == -1) {
	    perror("Unable to write(sequencer)");
	    exit(1);
	}
    _seqbufptr = 0;
}
