#!/usr/local/bin/perl
#
#   This perl script creates a inverted dbm database from the
# X11 name to rgb dbm database in the X11 library. This database
# is used to map pixel values back into color values.
#
#  Anthony Thyssen          3 Oct 1993     anthony@cit.gu.edu.au
#
$RGB = "/usr/lib/X11/rgb";
$COLOR = "/usr/tmp/color";   # in temp -- built is not present yet
$pixel_t = 'H12';

umask(022);              # make database readable by all

if ( -f $COLOR . ".dir" ) {
  die "Color database is already in existance -- build abort\n";
}
print "Creating the reverse rgb database - color\n";

dbmopen(%RGB, $RGB, undef) || die "Unable to open RGB database\n";
dbmopen(%COLOR, $COLOR, 0666) || die "Unable to create COLOR database\n";

while ( ($c1, $pixel) = each %RGB ) {
  $c1 =~ tr/A-Z/a-z/;             # color name is lower case
  $c2 = $COLOR{$pixel};   # get name for pixel is already in database
  if ( ! defined $c2 ) {
    # no name conflict
    $C1 = $c1;
  }
  else {
    # name already in database -- name conflict exists
    # print 'Pixel #', unpack($pixel_t, $pixel), " has multiple color names\n";
    $t  = ( $c1 =~ /[0-9]/ ) ? 0 : 1;  # flag if any numbers are present
    $t += ( $c2 =~ /[0-9]/ ) ? 0 : 2;
    if ( $t == 1 || $t == 2 ) {
      # only one of the colors as a number associated
      $C1 = ( $t == 1 ) ? $c1 : $c2;
      $C2 = ( $t == 1 ) ? $c2 : $c1;
      print 'Picking non-numbered color "',$C1,'" instead of "',$C2,"\"\n";
    }
    elsif ( length $c1 != length $c2 ) {
      # color names have differant length
      $C1 = (length $c1 > length $c2) ? $c1 : $c2;
      $C2 = (length $c1 > length $c2) ? $c2 : $c1;
      print 'Picking longer name "', $C1, '" over "', $C2, "\"\n";
    }
    elsif ( $c1 =~ /gr[ae]y/ && $c2 =~ /gr[ae]y/ ) {
	# Color Grey VS Gray naming problem -- pick grey
	$C1 = ($c1 =~ /grey/) ? $c1 : $c2;
	$C2 = ($c1 =~ /grey/) ? $c2 : $c1;
	print 'Grey selection of "', $C1, '" over "', $C2, "\"\n";
    }
    else {
      # No method to pick one name over another
      $C1 = $c1;
      warn 'UNABLE TO CHOOSE!  Using color already in the', "\n";
      warn "\t", 'database "',$c1, '" instead of "',$c2, "\"\n";
    }
  }
  $COLOR{$pixel} = $C1;

  # Uncomment to see the database entry added -- for debugging
  # printf( STDERR "%-20s #%s\n", $C1, unpack( $pixel_t, $pixel ) );
}

dbmclose( %COLOR );
dbmclose( %RGB );

print "Created color database\n";

exit 0;