#! /usr/bin/gawk -f
# Last edited on 1999-07-19 02:49:43 by stolfi

# Reads a file where each record contains a WORD and an INDEX,
# the latter being a real number between 0 and 1.
# Outputs the same data, where the INDEX has been replaced by 
# a saturated HTML color.

function compute_color(x,    k,s,t,r,g,b)
{
  # Computes an HTML color from a hue  "x".
  
  x -= int(x);
  while (x < 0) { x += 1; }
  while (x >= 1) { x -= 1; }
  x = 6*x;
  k = int(x); s = x - k; t = 1-s;
  if (k==0)
    { r = 1; g = s; b = 0; }
  else if (k==1)
    { r = t; g = 1; b = 0; }
  else if (k==2)
    { r = 0; g = 1; b = s; }
  else if (k==3)
    { r = 0; g = t; b = 1; }
  else if (k==4)
    { r = s; g = 0; b = 1; }
  else if (k==5)
    { r = 1; g = 0; b = t; }
  else
    { printf "error - bad x = %8.4f", x > "/dev/stderr"; exit 1; }
  
  return ( intensity_to_hex(r) intensity_to_hex(g) intensity_to_hex(b));
}

function intensity_to_hex(y)
{
  # Quick and dirty gamma correction:
  y = sqrt(y);
  
  # Scaling 0..255:
  y = int(255*y + 0.5);
  if (y < 0) { y = 0; }
  if (y > 255) { y = 255; }
  return sprintf("%02x", y);
}

/^[#]/ { print; next; }

/^ *$/ { printf "\n"; next; }

/./ {
  if (NF != 2) 
    { printf "bad NF\n" > "/dev/stderr"; exit 1; }
  print $1, compute_color($2);
}