sub decode_mask($$$$) {
    my ($code, $width, $height, $pbmfile) = @_;
    my @img;
    my @colors = ("0 0 0", "0 0 128", "0 128 0", "0 128 128",
		  "128 0 0", "128 0 128", "192 128 0", "128 128 128",
		  "0 0 0", "0 0 255", "0 255 0", "0 255 255",
		  "255 0 0", "255 0 255", "255 255 0", "255 255 255");


    my $x=0, $y = 0;
    $width /= 8;

    my $i, $rep, $mask;
    while ($x < $width) {
	$i = next_char(\$code);
	if ($i < 128) {
	    $rep = $i;
	    while ($rep > 0) {
		$rep--;
		$img[$x][$y] = next_char(\$code);

		$y++;
		if ($y == $height) {
		    $x++;
		    $y = 0;
		}
	    }
	} else {
	    $rep = $i - 128;
	    $mask = next_char(\$code);
	    while ($rep > 0) {
		$rep--;
		$img[$x][$y] = $mask;

		$y++;
		if ($y == $height) {
		    $x++;
		    $y = 0;
		}
	    }
	}
    }

    open FILE, ">$pbmfile";
    print FILE "P4\n".($width*8)." $height\n";
    for ($y = 0; $y < $height; $y++) {
	for ($x = 0; $x < $width; $x++) {
	    print FILE chr($img[$x][$y]);
	}
    }
    close FILE;
}

sub decode_bmp($$$$) {
    my ($code, $width, $height, $xpm) = @_;
    my @img;


    my $x=0, $y = 0;
    
    my $i, $rep, $color;
    while ($x < $width) {
	$i = next_char(\$code);
	if ($i < 128) {
	    if ($i < 16) {
		$color = $i;
		$rep = next_char(\$code);
	    } else {
		$color = $i & 0xf;
		$rep = $i >> 4;
	    }
	    return 0 if $rep == 0;
	    while ($rep > 0) {
		$rep--;
		$img[$x][$y] = $color;

		$y++;
		if ($y == $height) {
		    $x++;
		    if ($x == $width) {
			return 0 if ($rep > 0);
		    }
		    $y = 0;
		}
	    }
	} else {
	    if ($i == 128) {
		$rep = next_char(\$code);
	    } else {
		$rep = $i & 0x7f;
	    }
	    return 0 if $rep == 0;
	    while ($rep > 0) {
		$rep--;
		$img[$x][$y] = $x > 0 ? $img[$x-1][$y] : 0;

		$y++;
		if ($y == $height) {
		    $x++;
		    if ($x == $width) {
			return 0 if ($rep > 0);
		    }
		    $y = 0;
		}
	    }
	}
    }

    open XPM, ">$xpm";
    print XPM << "EOF";
/* XPM */
static char *xpm_icon[] = {
/* columns rows colors chars-per-pixel */
"$width $height 17 1",
"  c #808080",
". c #000000",
"X c #0000ac",
"o c #00aa00",
"O c #00aaac",
"+ c #ac0000",
"\@ c #ac00ac",
"# c #ac5500",
"\$ c #acaaac",
"\% c #525552",
"& c #5255ff",
"* c #52ff52",
"= c #52ffff",
"- c #ff5552",
"; c #ff55ff",
": c #ffff52",
"_ c #ffffff",
/* pixels */
EOF

    my $colchars = '.XoO+@#$%&*=-;:_';
    for ($y = 0; $y < $height; $y++) {
	print XPM '"';
	for ($x = 0; $x < $width; $x++) {
	    if ($img[$x][$y] < 16 && $img[$x][$y] >= 0) {
		print XPM substr $colchars, $img[$x][$y], 1;
	    } else {
		print XPM " ";
	    }
	}
	print XPM "\",\n";
    }
    print XPM "};\n";
    close XPM;
    return 1;
}

    1;
