#!/usr/local/bin/perl
#
#
# Time-stamp:   <2000-12-15, 20:22:35, mrz@isun34>
#
#
# [2000-12-15]  rgb2hex+tex.pl
#               (C) René Scholz  <http://www.thur.de/~Voland/>
#
# Use:  - convert decimal RGB values to hexadecimal
#       - print the decimal and hexadecimal RGB values of given
#         color name
#       - print \definecolor's for latex for including given
#         color names in .tex files (for \usepackage{color})
###############################################################

($NAME=$0)=~s|.*/||;      # get basename from $0

use strict;
use Getopt::Std;
use vars qw ($RGBFILE $USAGE $NAME $color $colname $r $g $b %DC
	     $opt_h $opt_H $opt_r $opt_l $opt_c);


$USAGE=<<EOUSAGE;
Usage: $NAME [options]

Options: -h         Show this help.
         -r file    Use rgb.txt from this file
         -c color   Use color, ex.: -c red  |  -c 100x100x100
                    (use -c . to get all entries)
         -l         Create \\definecolor's for latex for color -c

EOUSAGE
#'

die $USAGE unless(@ARGV);
getopts('hHlc:r:');
die $USAGE if($opt_h || $opt_H || $opt_c eq "");

$RGBFILE = $opt_r ne "" ? $opt_r : "/usr/openwin/lib/X11/rgb.txt";


############################## MAIN ##########################

$color=$opt_c;
  
if($color=~/^\D\w*/) {
  open(R, $RGBFILE) or die "Can't open rgb.txt file $RGBFILE: $!\n";
  while(<R>) {
    next unless(/$color/i);
    chomp;
    s/^\s+|\s+$//;
    ($r,$g,$b, @_) = split(/\s+/);
    $colname = join(" ",@_);
    if($opt_l) {
      $colname = join("",  map($_=ucfirst($_), split(/\s+/, $colname)));
      $r/=255; $b/=255; $g/=255;
      $DC{$colname}="\\definecolor{$colname}{rgb}{$r, $g, $b}\n";
    }
    else {
      $_       = 20-length($colname);
      $colname.=":" . " " x $_;
      printf "$colname %3.3d %3.3d %3.3d  --->  #%2.2lx%2.2lx%2.2lx\n", $r,$g,$b, $r,$g,$b;
    }
  }
  close(R);
  if($opt_l) { foreach (sort keys %DC) { print $DC{$_}; } }
}
else {
  ($r,$g,$b, @_) = split(/x/, $color);
  printf "%3.3d %3.3d %3.3d  --->  #%2.2lx%2.2lx%2.2lx\n", $r,$g,$b, $r,$g,$b;
}