#!/usr/bin/python

print  """
Tap a steady beat on any key.
Hit 'q' to stop and print the estimated tempo of your beat.
"""

## This is almost entirely based on the 'keypress' entry in python FAQ, by
## Andrew Kuchling.

import os
import sys
import termios
import time

fd = sys.stdin.fileno()
# Get 2 copies of termios info... one to modify, one to restore
old = termios.tcgetattr(fd)
new = termios.tcgetattr(fd)
# turn off "canonical mode" & "echo"
new[3] = new[3] & ~termios.ICANON & ~termios.ECHO
# I have no idea what these do-- not in python docs or 'man termios'
new[6][termios.VMIN] = 1
new[6][termios.VTIME] = 0
termios.tcsetattr(fd, termios.TCSANOW, new)

times = [] # save the time when keys are pressed.
try:
    while 1:
        c = os.read(fd, 1)
        when = time.time()
        if c == "q":
            break
        else:
            times.append(when)
            print "%s %f" % (c, when)
finally:
    # be sure to restore tty attributes no matter what!
    termios.tcsetattr(fd, termios.TCSAFLUSH, old)

diffs = []
for i in range(len(times) -1):
    diffs.append(times[i + 1] - times[i])

sum = 0
for d in diffs:
     sum = sum + d

estimate = 60.0 / (sum / len(diffs)) 
print "\n\nestimate is: %f" % estimate

