/*
 * BPM Counter
 * (c) 2006 Gregor Jehle <gjehle@gmail.com>
 *
 */

#include <sys/time.h>
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>

#define AVGBUF (8)
#define min(a,b) (a<b?a:b)

void quit(int sig)
{
        printf("\n\n");
        exit(0);
}

int main() {
        int counter=0,i;
        int counterb[AVGBUF];
        struct timeval time[AVGBUF];
        struct timezone tz;

        signal(SIGINT,quit);

        printf("Hit enter key for each significant beat\n");

        while(getc(stdin)) {
                ++counter; counterb[counter%AVGBUF] = counter;
                const int cur = counter%AVGBUF;
                const int old = (counter+1)%AVGBUF;
                gettimeofday(time+cur,&tz);
                if(counter>AVGBUF) {
                        double diffmsec = (double)(time[cur].tv_sec - time[old].tv_sec)*1000.
                                         +(double)(time[cur].tv_usec- time[old].tv_usec)/1000.;
                        int counts = counterb[cur]-counterb[old];
                        double bpm = counts/diffmsec*1000.*60.;
                        printf("BPM: %4.4g",bpm);
                } else {
                        printf("BMP: Learning... %d",AVGBUF-counter+1);
                }
        }
        return 0;
}