#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <malloc.h>
#include <ioctl.h>
#include <sys/time.h>
#include <sys/asound.h>

#ifdef __USAGE
#endif

int main( int argc, char *argv[])
{
	int fd, c, sr = 8000, bsize = 4096, n, N = 0;
	struct timeval btime, dtime;
	snd_pcm_format_t	fmt;
	snd_pcm_record_params_t param;
	snd_pcm_record_status_t status;
	fd_set rfd;
	unsigned long long usec, stime, itime;
	float	csr, bps;
	char *buf;
		
	while(( c = getopt(argc, argv, "s:b:")) != -1) {
		switch(c) {
			case 's':
				sr = atoi(optarg);
				break;
			case 'b':
				bsize = atoi(optarg);
				break;
			default:
				break;
		}	
	}
	if ((buf = malloc(bsize)) == NULL)
		return perror("alloc of buffer"), -1;

	if ((fd = open("/dev/pcm00",O_RDONLY)) == -1)
		return perror("open"), -1;

	fmt.format = SND_PCM_SFMT_S16_LE;
	fmt.rate = sr;
	fmt.channels = 2;
	
	if (ioctl(fd, SND_PCM_IOCTL_RECORD_FORMAT, &fmt) == -1)
		return perror("ioctl: record format"), -1;

	param.fragment_size = bsize;
	param.fragments_min = 1;
	if (ioctl(fd, SND_PCM_IOCTL_RECORD_PARAMS, &param) == -1)
		return perror("ioctl: record params"), -1;

	if (ioctl(fd, SND_PCM_IOCTL_RECORD_STATUS, &status) == -1)
		return perror("ioctl: record params"), -1;
	printf("Real sample rate = %d\n",status.rate);
	sleep(1);
	FD_ZERO(&rfd);
	FD_SET(fd, &rfd);
	gettimeofday(&btime, NULL);
	while( select( fd + 1, &rfd, NULL, NULL, NULL) != -1 ) {
		gettimeofday(&dtime, NULL);
		usec = (dtime.tv_sec - btime.tv_sec) * 1000000 + dtime.tv_usec - btime.tv_usec;
		if ((n = read(fd, buf, bsize)) < bsize)
			printf("read = %d\n",n);
		N+=n;
		bps = N/(usec/1000000.0);
		csr = bps/4.0;
		printf("sample rate = %8.2f\n",csr);
	}
	return( 0 );
}
