#!/afs/athena/contrib/perl/p
#
# usage:  $0 file.ppm > file.cmap

$flagsize = 1000;

$_=<>;
/^P3\s/ || die "Wrong magic number!\nexiting";

@data = split(/\s+/);
shift(@data);
while (! @data) { &append(); }

$xsize = shift(@data);
while (! @data) { &append(); }

$ysize = shift(@data);
while (! @data) { &append(); }

$dummy = shift(@data);
while (! @data) { &append(); }

print STDERR "${xsize}x${ysize}   (color range: 0-$dummy)\n";

while ($#data < 2) { &append(); }

$|=1;
$loop = 1;
while ($loop) {
    @oldata=@data;
    if ($oldata[0] eq "") { print STDERR "warning!\n"; }
    $a=shift(@data); ($a eq "") && die "BSU1: (".join(",",@oldata).")";
    $b=shift(@data); ($b eq "") && die "BSU2: (".join(",",@oldata).")";
    $c=shift(@data); ($c eq "") && die "BSU3: (".join(",",@oldata).")";
    ++$count{$a,$b,$c};
    if ((++$i % $flagsize)== 0) {print STDERR "$i... ";}
    while (($#data < 2)&& $loop) { &append(); }
}
print STDERR "done.\n";

if (@data) { die "Left-over entries: (".join(",",@data).")"; }

@cnt=%count;
while(@cnt) {
    @rgb = split($;,shift(@cnt));
    printf "%3d %3d %3d\t\t\tcolor%d\n", @rgb, ++$ncol;
    printf STDERR "%3d %3d %3d\t\t\t# = %d\n", @rgb, shift(@cnt);
}



sub append
{
    if ($_=<>) {
	s/#.*\n//;
	s/^\s+//;
	s/\s+$//;
	push (@data, split(/\s+/));
    }
    else {
	die "Unexpected EOF encountered while reading data file" unless $loop;
	$loop = 0;
    }
}
