#!/usr/bin/perl

open(XKEY, "/stuff/xkey|");
$start = $lastaction = time();
while(<XKEY>){
    ($type, $v) = split;
    if($type eq "WindowSwitch"){
	$v = "emacs" if($v =~ /emacs/);
	$v = "emacs" if($v =~ /java/);
	$v = "emacs" if($v =~ /\.pl/);
	$v = "emacs" if($v =~ /\*Group\*/);
	$v = "emacs" if($v =~ /\*Minibuf.+\*/);
    }
    if((time()-$lastaction) > 45){
	# Been idle more than a minute
	$d = time()-$entered;
	$entered = time();
	push(@beenin, $d);
	$timein{"idle"}+=(time()-$lastaction);
    }
    $lastaction = time();

    if($type eq "WindowSwitch"){
 	if($entered == 0){
	    $curwindow = $v;
	    $entered = time();
	}
	if($v ne $curwindow){
	    # I've been active in the window for @beenin + time()-$entered
	    for $t (@beenin){
		$timein{$curwindow} += $t;
	    }
	    $timein{$curwindow} += (time()-$entered);
	    @beenin = ();
	    $curwindow = $v;
	    $entered = time();
	}				
    }
    $ct++;
    if($ct > 10){
	$ct = 0;
	$d = time()-$entered;
	$entered = time();
	$timein{$curwindow}+= ($d);
	for $t (@beenin){
	    $timein{$curwindow} += $t;
	}
	@beenin = ();
	$tot = time()-$start;
	print "------------------------------ $tot ($curwindow)\n";
	for $w (sort {$timein{$a} <=> $timein{$b}; } keys %timein){
	    $frac = int(100*$timein{$w}/($tot));
	    $wfil = $w . (" " x (20-length($w)));
	    print "$wfil $timein{$w} $frac %\n";
	}
    }
}
