#!/usr/bin/perl -w

# Based on Erling Ellingsen's SmackBook Pro scripts:
#   http://blog.medallia.com/2006/05/smacbook_pro.html
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# USAGE:
#
# Save this script into a file called smaxpose.command, and make 
# it executable with the Terminal command: 
#
#   chmod +x smaxpose.command
#
# Then, run it from the Terminal or double-click it in the Finder.

use strict;
my $stable;

# Get AMSTracker from Amit Singh's site:
# http://www.osxbook.com/software/sms/amstracker/
# and put the binary in your PATH (/usr/local/bin is fine)
#
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) > 30 && $stable > 30) {
	$stable = 0;
        `osascript -e 'tell application \"System Events\" to key code 101'`
    }
}

