#!perl
package xlib;

#   read(XWDFILE,$dat,$X::xsizeof{"XWDFileHeader"}) || return "read:$!";
#   read(XWDFILE,$win_nam, $xwddat->{"header_size"} - $xwddat->{"sizeof"})
#   read(XWDFILE,$xwd_colors, $X::xsizeof{"xColorItem"} * $xwddat->{"ncolors"})
#   read(XWDFILE,$xwd_image, $xwddat->{"bytes_per_line"} * $xwd_image_height)

sub getxwd_read {
    my($fname) = @_;
    open(XWDFILE,$fname) || die "getxwd_read: $fname: $!";
    sub xread {
	my $v=""; my $sz = shift;
	read(XWDFILE,$v,$sz) || die "xread: $!";
	return $v;
    }
    getxwd_core(\&xread);
}

sub getxwd_str {
    my($xwdbits)=@_;
    my $ptr = 0;
    sub xsubstr {
	my $sz = shift;
	my $v = substr($xwdbits,$ptr,$sz);
	$ptr += $sz;
	return $v;
    }
    getxwd_core(\&xsubstr);
}

sub getxwd_core {
    my($readfn)=@_;
    my($dat) = "";
    $win_nam="";
    $xwd_colors="";
    $xwd_image="";

    $dat = &$readfn($X::xsizeof{"XWDFileHeader"});
    $xwddat = xlibconvert("XWDFileHeader",$dat);
    
    if ($X::defines{"XWD_FILE_VERSION"} != 
	$xwddat->{"file_version"}) {
	$X::xpackof{"XWDFileHeader"} =~ s/L/N/g;
	$xwddat = xlibconvert("XWDFileHeader",$dat);

	if ($X::defines{"XWD_FILE_VERSION"} != 
	    $xwddat->{"file_version"}) {
	    return "xwud: XWD file format version missmatch.";
	}
    }
    if ($xwddat->{"header_size"} < $xwddat->{"sizeof"}) {
	return "xwud: XWD header size is too small.";
    }
    $win_nam = &$readfn($xwddat->{"header_size"} - $xwddat->{"sizeof"});

    $xwd_image_width = $xwddat->{"pixmap_width"};
    $xwd_image_height = $xwddat->{"pixmap_height"};
    $xwd_image_depth = $xwddat->{"pixmap_depth"};

# coincidentally, XColorItem is the same as XColor...
    $xwd_colors = &$readfn($X::xsizeof{"xColorItem"} * $xwddat->{"ncolors"});
    $xwd_image  = &$readfn($xwddat->{"bytes_per_line"} * $xwd_image_height);
    return "OK";
}

1;
