#!perl
package xlib;


sub getxwd_read {
    local($fname)=@_;
    local($dat);
    open(XWDFILE,$fname);

    read(XWDFILE,$dat,$xsizeof{"XWDFileHeader"}/8) || return "read:$!";
    @xwddat = unpack($xpackof{"XWDFileHeader"},$dat);
    
    if ($defines{"XWD_FILE_VERSION"} != 
	&xindexof("XWDFileHeader","file_version",@xwddat)) {
	$xpackof{"XWDFileHeader"} =~ s/L/N/g;
	@xwddat = unpack($xpackof{"XWDFileHeader"},$dat);

	if ($defines{"XWD_FILE_VERSION"} != 
	    &xindexof("XWDFileHeader","file_version",@xwddat)) {
	    return "xwud: XWD file format version missmatch.";
	}
    }
    if (&xindexof("XWDFileHeader","header_size",@xwddat)
	< $xsizeof{"XWDFileHeader"}/8) {
	return "xwud: XWD header size is too small.";
    }
    read(XWDFILE,$win_nam,
	 &xindexof("XWDFileHeader","header_size",@xwddat) 
	 - $xsizeof{"XWDFileHeader"}/8) || return "read:$!";

    $xwd_image_width = &xindexof("XWDFileHeader","pixmap_width",@xwddat);
    $xwd_image_height = &xindexof("XWDFileHeader","pixmap_height",@xwddat);
    $xwd_image_depth = &xindexof("XWDFileHeader","pixmap_depth",@xwddat);

# coincidentally, XColorItem is the same as XColor...
    read(XWDFILE,$xwd_colors,
	 $xsizeof{"xColorItem"}/8 
	 * &xindexof("XWDFileHeader","ncolors",@xwddat))
	|| return "colorread:$!";

    read(XWDFILE,$xwd_image,
	 &xindexof("XWDFileHeader","bytes_per_line",@xwddat)
	 * $xwd_image_height) || return "imageread:$!";
    "OK";
}

sub getxwd_str {
    local($xwdbits)=@_;
    local($dat,$ovv,$ovd);

#    read(XWDFILE,$dat,$xsizeof{"XWDFileHeader"}/8) || return "read:$!";
    $dat = substr($xwdbits,0,$ovv=$xsizeof{"XWDFileHeader"}/8);
    @xwddat = unpack($xpackof{"XWDFileHeader"},$dat);
    
    if ($defines{"XWD_FILE_VERSION"} != 
	&xindexof("XWDFileHeader","file_version",@xwddat)) {
	$xpackof{"XWDFileHeader"} =~ s/L/N/g;
	@xwddat = unpack($xpackof{"XWDFileHeader"},$dat);

	if ($defines{"XWD_FILE_VERSION"} != 
	    &xindexof("XWDFileHeader","file_version",@xwddat)) {
	    return "xwud: XWD file format version missmatch.";
	}
    }
    if (&xindexof("XWDFileHeader","header_size",@xwddat)
	< $xsizeof{"XWDFileHeader"}/8) {
	return "xwud: XWD header size is too small.";
    }
    $win_nam = substr($xwdbits,$ovv,$ovd=
		      &xindexof("XWDFileHeader","header_size",@xwddat) 
		      - $xsizeof{"XWDFileHeader"}/8);
    $ovv+=$ovd;

    $xwd_image_width = &xindexof("XWDFileHeader","pixmap_width",@xwddat);
    $xwd_image_height = &xindexof("XWDFileHeader","pixmap_height",@xwddat);
    $xwd_image_depth = &xindexof("XWDFileHeader","pixmap_depth",@xwddat);

# coincidentally, XColorItem is the same as XColor...
    $xwd_colors = substr($xwdbits,$ovv,$ovd=
			 $xsizeof{"xColorItem"}/8 
			 * &xindexof("XWDFileHeader","ncolors",@xwddat));
    $ovv+=$ovd;

    $xwd_image = substr($xwdbits,$ovv,$ovd=
			&xindexof("XWDFileHeader","bytes_per_line",@xwddat)
			* $xwd_image_height);
    "OK";
}

1;
