# define errors (-1)
# define no_errors 0

# include <stdlib.h>
# include <string.h>

# include <sys/types.h>
# include <sys/audioio.h>
# include <sys/ioctl.h>
# include <fcntl.h>

# include <stdio.h>
# include <unistd.h>
 
# include "emulate.h"




int soundfd;

int init_card(char * arg)
{
    int frag;
    int flags;

    struct audio_info ai;


    if ((soundfd = open(arg, O_WRONLY | O_NONBLOCK )) == -1) 
    {
        printf ( "Couldn't open sound device %s \n", arg );
	return errors;
    }
    
     if ((flags = fcntl(soundfd, F_GETFL)) == -1) 
     {
        printf ( "Couldn't fcntl sound device %s \n", arg);
	close(soundfd);
	return errors;
    }                                                                                                                                                                    

      flags &= ~O_NONBLOCK;
    
    if (fcntl(soundfd, F_SETFL, flags) == -1) 
    {
        printf ("%Couldn't set sound device %s blocking", arg);
	close(soundfd);
	return errors;
    }

       AUDIO_INITINFO(&ai);
       
       ai.play.encoding = AUDIO_ENCODING_LINEAR;
       ai.play.precision = 16;
       ai.play.channels = 2;
       ai.play.sample_rate = 44100;
    
      if (ioctl(soundfd, AUDIO_SETINFO, &ai) == -1) 
      {
        printf ("Couldn't setup sound device %s", arg);
	close(soundfd);
	return errors;
    }    


   return no_errors;
  }

void play (char * buffer, int len)
{ 
    write(soundfd, buffer, len);
}

# define MAXCARDS 20
char *** cardslist;

char *** cards_list(void)
{
	if (cardslist) free(cardslist);
	
	    cardslist = (char ***) malloc(MAXCARDS * sizeof (char **));
	    
		for (int i=0; i<MAXCARDS; i++)
			cardslist[i]= (char**) malloc (2 * sizeof (char *));	
			    
				for (int i=0; i<MAXCARDS; i++)
				    {
					    for (int j=0; j<2; j++)
						    {
								cardslist[i][j]= (char*) malloc (101 * sizeof (char));
									    memset(cardslist[i][j], 0, 100);
										    }
											}
											
    											

    sprintf (cardslist[0][0], "/dev/audio");
    sprintf (cardslist[0][1], "/dev/audio");

    return ((char ***)cardslist);
}											