#!/usr/bin/perl
# hdbd64.pl - Generate palette of readable text/background colors
# 2014 David Meyer <[email protected]>  +JMJ
#
# Original name: textpltt.pl
#
# Source: Richard H. Hall. Color Combinations and Readability.
#         Missouri University of Science and Technology.
#         <http://web.mst.edu/~rhall/web_design/color_readability.html>
#         accessed December 30, 2014.

sub abs {
   my($a) = @_;
   if ($a < 0) {return -1 * $a;}
   else {return $a;}
}

sub bright {
   my($r, $g, $b) = @_;
   return ($r * 299 + $g * 587 + $b * 114) / 1000;
}

sub byte {
   my($b) = @_;
   return $b * 16 + $b;
}

sub bytesc {
   my($b) = @_;
   return $b == 255 ? 15 : ($b == 170 ? 10 : ($b == 85 ? 5 : $b));
}

sub colorsc {
   my($r, $g, $b) = @_;
   return sprintf("#%x%x%x", bytesc($r), bytesc($g), bytesc($b));
}

sub max {
   my($a, $b) = @_;
   if ($a < $b) {return $b;}
   else {return $a;}
}

print <<EOF;
<table>
<tr><th>BG<br/>color</th><td colspan=3>Text color<br/>Hue difference<br/>Brightness diff.</td></tr>
EOF

$combos = 0;

# $bgr, $bgg, $bgb: Background red, green, blue
# $fgr, $fgg, $fgb: Foreground red, green, blue

$bgcd_prev = "";

for $bgr (0, 85, 170, 255) {
   for $bgg (0, 85, 170, 255) {
       for $bgb (0, 85, 170, 255) {
           for $fgr (0, 85, 170, 255) {
               for $fgg (0, 85, 170, 255) {
                   for $fgb (0, 85, 170, 255) {

                       # Hue difference ...
                       $hd = max($fgr-$bgr, $bgr-$fgr) +
                           max($fgg-$bgg, $bgg-$fgg) +
                           max($fgb-$bgb, $bgb-$fgb);

                       # Brightness difference ...
                       $bd = abs(bright($fgr, $fgg, $fgb) -
                                 bright($bgr, $bgg, $bgb));

                       # Readability ...
                       if ($hd >= 500 && $bd >= 125) {$read = 1;}
                       else {$read = 0;}

                       if ($read) {
                           $bgcd = colorsc($bgr, $bgg, $bgb);
                           $fgcd = colorsc($fgr, $fgg, $fgb);
                           if ($bgcd ne $bgcd_prev) {
                               print "</tr>\n<tr><th>$bgcd</th>\n";
                               $bgcd_prev = $bgcd;
                           }
                           printf("<td style='background-color:%s;color:%s'>%s<br/>%d %d</td>\n", $bgcd, $fgcd, $fgcd, $hd, $bd);
                           ++ $combos;
                       }
                   }
               }
           }
       }
   }
}

print <<EOF;
</tr>
</table>
<p>$combos combinations</p>
EOF