#!perl

require "./xbase.pl";
require "./xwdhead.pl";

$xopen = &xlib::x_open_display($ENV{"DISPLAY"});
die $xlib::status if not defined $xopen;

$dowind = $xlib::root_window;
print &xlib::x_beep($xopen,25),"\n";

if (! -r "/tmp/xx.p") {
    print "Constructing new dump...\n";
    print &xlib::getxwd_read("/tmp/xx.d"),"\n";
    $xw = $xlib::xwd_image_width;
    $xh = $xlib::xwd_image_height;
    $xdep = $xlib::xwd_image_depth;
    $image = $xlib::xwd_image;
    @points = ();
    for $yyy (0..$xh-1) {
	for $xxx (0..$xw-1) {
	    if (0==vec($image,$xxx+$xw*$yyy,1)) {
		push(@points,$xxx,$yyy);
	    }
	}
	print "y: $yyy points: ",scalar(@points),"\n";
    }
    print "points: ",scalar(@points),"\n";
    open(PT,">/tmp/xx.p"); 
    print PT "\$xw = $xlib::xwd_image_width\n";
    print PT "\$xh = $xlib::xwd_image_height\n";
    print PT "\$xdep = $xlib::xwd_image_depth\n";
    print PT "\@points = (",join(",",@points),")\n";
    close PT;
} else {
    do "/tmp/xx.p";
}
$dep = xlib::defaultrootdepth($xopen);
print "depth $dep xdep $xdep\n";
$pix = &xlib::x_create_pixmap($xopen, $xlib::root_window, 
			      $dep, # depth
			      $xw, $xh);
print "pix: $pix\n";
#print &xlib::x_clear_area($xopen, $pix,0, 0,0,0,0);
$GC = &xlib::x_create_gc($xopen, $pix,
			 $X::defines{"GCForeground"}
			 | $X::defines{"GCBackground"},
			 $xlib::root_white, $xlib::root_black);
$GCrev = &xlib::x_create_gc($xopen, $pix,
			    $X::defines{"GCForeground"}
			    | $X::defines{"GCBackground"},
			    $xlib::root_black, $xlib::root_white);
print &xlib::xpolyfillrects($xopen, $pix,$GCrev,0,0,$xw,$xh),"\n";
# $bpl = $xlib::xwddat->{"bytes_per_line"};
# &xlib::debugxlib($xlib::xwddat);
print "points: ",scalar(@points),"\n";
&xlib::xpolypoints($xopen, $X::defines{"CoordModeOrigin"}, $pix, $GC, @points);

# $image =~ tr/\001\000/\000\001/; # reverse video
# &xlib::convertimage($xopen, \$image, $xw, $xh, $xdep, $dep);
# $xlib::debugpkt = 1;
# &xlib::x_put_image($xopen, $pix,$GC,$X::defines{"ZPixmap"},$image,0,0,$xw,$xh,0,$dep,$bpl);
#$xlib::debugpkt = 0;

print &xlib::x_set_window_background_pixmap($xopen, $dowind,$pix),"\n";
print &xlib::x_clear_area($xopen, $dowind,0, 0,0,0,0);
# which is a special case - x,y,w,h == 0 :-)

$SIG{"ALRM"} = $SIG{"INT"} = sub {
    xlib::x_closedisplay($xopen);
    exit;
  };

alarm(5);

print "waiting...\n";
while(defined($st = xlib::handle_event($xopen))) { # assume error for now?
    print "event: $st\n";
}

# sun server gives:
# imageByteOrder: 1
# bitmapBitOrder: 1
# bitmapScanlineUnit: 32
# bitmapScanlinePad: 32
