#!/usr/athena/bin/perl

open(SERPOLL, ">/dev/ttyS0");
$pid = open(SERDAT, "cat /dev/ttyS0|");
$|=1;
select(SERDAT); $|=1; select(STDOUT);
while(1){
    print SERPOLL "R\n";
    select(undef, undef, undef, .2);
    print "Poll ";
    $l1 = (<SERDAT>);
    print "l1: $l1\n";
    if(length($l1) < 10){
	print "l1 broken $l1\n";
#	&reset();
	$l1 = (<SERDAT>) ;
#	next;
    }
    print "... ";
    $l2 = (<SERDAT>);
    print "l2 $l2\n";
    if(length($l2) < 10){
	print "l2 broken $l2\n";
	&reset();
#	$l2 = (<SERDAT>) ;
	next;
    }

    $rin = 0;
    vec($rin, fileno(SERDAT), 1) = 1;
#    while($n = select($rout = $rin, undef, $rout=$rin, 0)>0){
#	print "Crap $n\n";
#	$crap = (<SERDAT>);
#    }


    chop($l1);
    chop($l2);
#    print "$offset\t$curslope\t$mean $l1 $l2\n";
    $ntick = int((($curslope+1.5)*10));
#    print "-" x $ntick;
#    print " $curslope\n";
    if($curslope < -1.5){
	print "Wheee!\n";
    }
    $dat = "$l1 $l2";
    next if $d[1] > 65000;
    @d = split(" ", $dat);
    $sum += $d[1];
    $dp++;
    $mean = $sum/$dp;
    $offset = int($d[1]-$mean+.5);
    if($#loff >= 0){
	$curslope = ($curslope+(($offset-&mean(@loff))*.01))/1.01;
    }
    else{
	$curslope = 0;
    }
#    $score = 8 if($score > 8);
#    $score = -5 if ($score < -5);
    $ldp = $d[1];
    push(@loff, $offset);
    if($#loff > 2){
	shift @loff;
    }
}

sub mean {
    @v = @_;
    $msum = $mct = 0;
    foreach $v (@v){
	$msum += $v;
	$mct++;
    }
    return $msum/$mct;
}



sub reset {
    close(SERPOLL);
    kill(1, $pid);
    open(SERDAT);
    open(SERPOLL, ">/dev/ttyS0");
    $pid = open(SERDAT, "cat /dev/ttyS0|");
}
