/*
 *  init.c - Initializes the sounddriver.
 *
 *  (C) 1994 Mikael Nordqvist (d91mn@efd.lth.se, mech@df.lth.se)
 */

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

#include "mod.h"

/* Define a large bufffer (so there are no unwanted flushes) */
#define MY_SEQ_BUF_LEN 4096

SEQ_DEFINEBUF(MY_SEQ_BUF_LEN);
int seqfd, mixerfd, gus_dev=-42;

extern struct options opt;

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

    if((seqfd=open("/dev/sequencer", O_RDWR, 0)) == -1)
	error("Unable to open sequencer.\n");

    fcntl(seqfd, F_SETFL, O_NONBLOCK);

    if(ioctl(seqfd, SNDCTL_SEQ_NRSYNTHS, &nr) == -1)
	error("Unable to find out # of synth-devices.\n");

    for(i=0; i < nr; ++i) {
	si.device=i;
	if(ioctl(seqfd, SNDCTL_SYNTH_INFO, &si) == -1)
	    error("Unable to get synth_info.\n");
	
	if(si.synth_type == SYNTH_TYPE_SAMPLE &&
	  si.synth_subtype == SAMPLE_TYPE_GUS) {
	    gus_dev=i;
	    break;
	}
    }

    if(gus_dev == -42)
	error("Unable to find a GUS on this system.\n");

    ioctl(seqfd, SNDCTL_SEQ_RESET, 0);
    
    if((mixerfd=open(MIXER_NAME, O_RDWR, 0)) != -1) {
	if(!(ioctl(mixerfd, SOUND_MIXER_READ_DEVMASK, &mixer_devmask) != -1 &&
	     (mixer_devmask & SOUND_MASK_SYNTH)))
	{
	    close(mixerfd);
	    mixerfd=-1;
	}
    }
}

void cleanup_sound(void) 
{
    if(mixerfd != -1)
	close(mixerfd);
    close (seqfd);
}
