/* sample src which plays wave files */


#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/asound.h>
#ifdef __QNXNTO__
#else
#include <sys/select.h>
#include <perror.h>
#define err(x) perror(x)
#endif

#ifdef __USAGE
#endif

int main( int argc, char **argv)
{
	int buffsize;
	char *buf;
	int audiow,audior, n, N = 0, bsize;
	fd_set rfds, wfds;
	snd_pcm_format_t pbformat;
	snd_pcm_playback_params_t pbparams;
	snd_pcm_record_params_t rcparams;
	struct snd_pcm_record_status recstatus;
		
	if ( (audiow = open( "/dev/pcm00", O_WRONLY)) == -1)
		return err("device open write");

	if ( (audior = open( "/dev/pcm00", O_RDONLY)) == -1)
		return err("device open read");


	if ( argc > 1)
		bsize = atoi(argv[1]);
	else
		bsize = 16384;
	buffsize=2000;
	printf("bsize = %d\n",bsize);
	
	pbformat.rate = 44100;
	pbformat.channels = 2;
	pbformat.format = SND_PCM_SFMT_S16_LE;
	
 	if ( ioctl( audiow, SND_PCM_IOCTL_PLAYBACK_FORMAT, &pbformat) == -1)
		return err("PB FORMAT");

	if ( ioctl( audior, SND_PCM_IOCTL_RECORD_FORMAT, &pbformat) == -1)
		return err("RC FORMAT");
	
	pbparams.fragment_size = bsize;
	pbparams.fragments_max = 1;
	pbparams.fragments_room = 1;

	//debugdebug very small buffer.....
	rcparams.fragment_size= bsize;
	rcparams.fragments_min = 1;


 	if ( ioctl( audiow, SND_PCM_IOCTL_PLAYBACK_PARAMS, &pbparams) == -1)
		return err("PB PARAMS");

	if ( ioctl( audior, SND_PCM_IOCTL_RECORD_PARAMS, &rcparams) == -1)
		return err("RC PARAMS");

	if ( ioctl( audior, SND_PCM_IOCTL_RECORD_STATUS, &recstatus) == -1)
		return err("RC STATUS");

	printf("actual frag size = %d\n",recstatus.fragment_size);

	buf = malloc(buffsize);
	FD_ZERO(&rfds);
	FD_ZERO(&wfds);
	n = 1;

	while(1) {
		int remain=buffsize;
		while(remain){
			N=read( audior,buf, buffsize );
			write(audiow, buf, N);
		}
	}
	return 0;
}
