#!/usr/bin/perl -w

use Tk;
use threads;
use threads::shared;

# run this way!
# ./pan.pl </dev/video0
# you must be using the version of setpwc that accepts "-d -" to use stdin
# the idea is that we could have something like gnomemeeting fork this
# application with stdin as a file handle into the open video device

$pan = 0;
$tilt = 0;

my $main = new MainWindow;
my $gpan:shared = 0;
my $gtilt:shared = 0;
my $action:shared = 1;
my $run:shared = 1;

$camthread = threads->new(\&panthread);

sub panthread {
    my $localaction = 0;
    my $localtilt;
    my $localpan;
    while($localaction != -1) {
        {
            lock($action);
            cond_wait($action);
            $localaction = $action;
            $action = 0;
        }
        if($localaction == 2) {
            @args = ("/usr/src/setpwc-0.6/setpwc", "-d", "-", "-t", "3");
            print "@args\n";
            system(@args);
        } elsif($localaction == 1) {
            {
                lock($gpan);
                lock($gtilt);
                $localtilt = $gtilt;
                $localpan = $gpan;
            }
            @args = ("/usr/src/setpwc-0.6/setpwc", "-d", "-", "-y", $localpan, "-z", $localtilt, "-W");
            print "@args\n";
            system(@args);
        }
        sleep(1);
    }
}

sub move {
    lock($action);
    lock($gpan);
    lock($gtilt);
    $action = 1;
    $gpan = $pan;
    $gtilt = $tilt;
    cond_signal($action);
}

sub myexit {
    # stop thread
    {
        lock($action);
        $action = -1;
        cond_signal($action);
    }
    sleep(1);
    exit;
}

sub center {
    $tilt = 0;
    $pan = 0;
    lock($action);
    $action = 2;
    cond_signal($action);
}

$main->Label(-text , 'Camera control!'
             )->pack;

$main->Scale(-label , 'Pan',
             -orient , 'horizontal',
             -from, '-7000',
             -to, '7000',
             -command , sub{move},
             -variable , \$pan,
             )->pack;

$main->Scale(-label , 'Tilt',
             -from, '2500',
             -to, '-3000',
             -command , sub{move},
             -variable , \$tilt,
             )->pack;

$main->Button(-text , 'Center',
              -command , sub{center}
              )->pack;

$main->Button(-text , 'Quit',
              -command , sub{myexit}
              )->pack;

MainLoop;
