#!/usr/athena/bin/perl

open(CFG, "$ENV{'HOME'}/.workspaces");
@config = (<CFG>);
close(CFG);

if(-e "/tmp/.workspaces.$ENV{'USER'}"){
    &readstate();
}
else{
    &initstate();
}

$xdpy = `/usr/X11/bin/xdpyinfo`;
$*=1;
$xdpy =~ /(\d+)x(\d+) pixels/;
$xsize = $1;


@windows = `/stuff/wtree`;

for (@windows){
    next unless /WM_STATE/;
    if(!/Window `([^']+)' \(([\da-f]+)\/(\d+)\) (\w+) (\w+) with WM_STATE/){
	next;
    }
    $name = $1;
    $wid = "0x".$2;
    if($wid eq "0x"){
	print "Error: $_\n";
    }
    $did = $3;
    $inst = $4;
    $class = $5;
    $name{$wid} = $name;
    $inst{$wid} = $inst;
    $class{$wid} = $class;

    if(!$sws{$wid}){
	$ws{$wid} = 10;
	$ws{$wid} = 2 if($class eq "XTerm");
	$ws{$wid} = 3 if($class eq "Emacs");
	$ws{$wid} = 4 if($class eq "Matlab");
	$ws{$wid} = 5 if($class eq "Netscape");
	$ws{$wid} = 6 if($class eq "Zwgc");
	
	$ws{$wid} = 1 if($name eq "Spare");
	$ws{$wid} = 1 if($name eq "ShortXTerm");
	$ws{$wid} = 1 if($name eq "BigXTerm");
	$ws{$wid} = 1 if($name eq "*Group*");
    }
    else{
	$ws{$wid} = $sws{$wid};
    }
    
       $state{$wid} = "shown" if($pleaseinit);
       $state{$wid} = "shown" if(!$state{$wid});
}

$action = $ARGV[0];
$group = $ARGV[1];

if($action eq "hide"){
    $xwitargs = "-rmove $xsize 0";
}
elsif($action eq "show"){
    $xwitargs = "-rmove -$xsize 0";
}

for $w (keys %name){
    if($ws{$w} == $group){
	if($action eq "hide"){
	    next if ($state{$w} eq "hidden");
	    $xwitargs = "-rmove $xsize 0";
	    $state{$w} = "hidden";
	}			# 
	elsif($action eq "show"){
	    next if ($state{$w} eq "shown");
	    $xwitargs = "-rmove -$xsize 0";
	    $state{$w} = "shown";
	}
	elsif($action eq "toggle"){
	    if($state{$w} eq "shown"){
		$xwitargs = "-rmove $xsize 0";
		$state{$w} = "hidden";
	    }
	    elsif($state{$w} eq "hidden"){
		$xwitargs = "-rmove -$xsize 0";
		$state{$w} = "shown";
	    }
	}
	`xwit -id $w $xwitargs`; # 
    }
}

&writestate();

sub readstate {
    open(WS, "/tmp/.workspaces.$ENV{'USER'}");
    while(<WS>){
	($wid, $ws, $state) = split;
	$sws{$wid} = $ws;
	$state{$wid} = $state;
    }
    close(WS);
}

sub initstate {
    $pleaseinit = 1;
}

sub writestate {
    open(WS, ">/tmp/.workspaces.$ENV{'USER'}");
    for $wid (keys %ws){
	print WS "$wid $ws{$wid} $state{$wid}\n";
    }
    close(WS);
}
