#!/usr/bin/perl
use strict;

my $stable;
my $action;
$action = $ARGV[0];

if ($action eq "") {
	print "Possible action arguments are: \"places\" - \"itunes\" - \"dashboard\" - \"desktop\" - \"expose\"\n";
} else {
	open F,"./AMSTracker -s -u0.01 |";
	while(<F>) {
	    my @a = /(-?\d+)/g;
	    print, next if @a != 3;
	
	    # we get a signed short written as two unsigned bytes
	    $a[0] += 256 if $a[0] < 0;
	    my $x = $a[1]*256 + $a[0];
	
	    if(abs($x) < 20) { 
		$stable++; 
	    } 
	
	    if(abs($x) > 40 && $stable > 40) {
		$stable = 0;
		if ($action eq "places") {
			my $foo = $x < 10 ? '28' : '29';
			system "osascript -e 'tell application \"System Events\" to keystroke (ASCII character $foo) using control down'";
		} elsif ($action eq "itunes") {
			system "osascript -e 'tell application \"iTunes\"' -e 'next track play' -e 'end tell'";
		} elsif ($action eq "dashboard") {
			system "osascript -e 'tell application \"System Events\" to key code 111'";
		} elsif ($action eq "desktop") {
			system "osascript -e 'tell application \"System Events\" to key code 103'";
		} elsif ($action eq "expose") {
			system "osascript -e 'tell application \"System Events\" to key code 100'";
		}
	    }
	}
}
