#!/usr/bin/python

# Download amstracker from http://www.kernelthread.com/software/ams/
# Put amstracker and bumptunes.py in the same directory. Go to this directory
# in the Terminal and type:
# ./amstracker -u 0.1 -s | python bumptunes.py
# Hit ctrl-c to exit.

THRESHOLD = 3 # lower numbers makes this more sensitive
COMPONENT = 1 # three dimensions: sideways: 0, forward/back: 1, up/down: 2

# two types of behaviour:
# bump: go to the next track whenever the machine is bumped
# nextprev: rock backwards to go to next track, forwards for previous track
BEHAVIOR = "bump" 

import sys, os

def run_command(command):
	script = os.popen("osascript", "w")
	script.write('tell application "iTunes"\r\n')
	script.write("%s\r\n" % command)
	script.write('end tell\r\n')
	script.close()

since = 0
while 1:
	try:
		line = sys.stdin.readline()
		since += 1
		x = int(line.split()[COMPONENT])
		if abs(x) > THRESHOLD and since > 5: # ignore commands for 0.5 seconds
			if "bump" == BEHAVIOR:
				run_command("next track")
			elif "nextprev" == BEHAVIOR:
				if x > 0:
					run_command("next track")
				else:
					# first command goes to beginning of current track,
					# next command goes to the actual previous track
					run_command("previous track")
					run_command("previous track")
			since = 0
	except KeyboardInterrupt:
		sys.exit(0)
	except:
		pass