#!/usr/local/bin/perl
# rlumin.pl - Generate color relative luminance chart
# Copyright 2015 David Meyer <papa@sdf.org> +JMJ
# (License and documentation at bottom of file.)

# Source: Ben Caldwell et al. ed. Web Content Accessibility 
#         Guidelines (WCAG) 2.0. World Wide Web Consortium (W3C).
#         December 11, 2008.
#         <http://www.w3.org/TR/2008/REC-WCAG20-20081211/>
#         accessed January 7, 2015.

use strict;
use warnings;

our %bytesc = (
    0   => 0,
    17  => 1,
    68  => 4,
    119 => 7,
    187 => 11,
    255 => 15
    );

our(@color, %rlumin);

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

sub lumc {
    my($c) = @_;
    my $cn = $c/255;
    if ($cn <= .03928) {return $cn/12.92;}
    else {return (($cn+.055)/1.055)**2.4;}
}

sub rlumin {
    my($r, $g, $b) = @_;
    return .2126 * lumc($r) + .7152 * lumc($g) + .0722 * lumc($b);
}

our($r, $g, $b);

for $r (0, 17, 68, 119, 187, 255) {
    for $g (0, 17, 68, 119, 187, 255) {
	for $b (0, 17, 68, 119, 187, 255) {
	    my $colorsc = colorsc($r, $g, $b);
	    push @color, $colorsc;
	    $rlumin{$colorsc} = rlumin($r, $g, $b);
	}
    }
}

our @lcolor = sort {$rlumin{$a} <=> $rlumin{$b}} @color; 

print "<body style='background-color:#555;color:#fff;'>\n<ol>\n";

for my $c (@lcolor) {
    my $fg = $rlumin{$c} < .35 ? '#fff' : '#000';
    print "<li style='background-color:$c;margin:2px;padding:10px;'><span style='color:$fg;'>$c $rlumin{$c}</span></li>\n";
}

print "</ol>\n</body>\n";

exit 0

__END__

# Documentation #####################################################
=head1 NAME

template.pl - Perl script template (command line)

=head1 SYNOPSIS/USAGE

=head1 DESCRIPTION

Mark up code elements with C<>, file names with F<> (or C<> for
readability), command names with B<>. Also I<> for italics, U<> for
underline. Entities: E<lt> ('<'), E<gt> ('>').

=head1 OPTIONS

=item B<-o> I<value>, B<--option>=I<value>

=head1 RETURN VALUE

=head1 ERRORS

=head1 DIAGNOSTICS

=head1 EXAMPLES

=head1 ENVIRONMENT

=over 6

=item VARIABLE

Description of usage of environment variable C<VARIABLE>.

=back

=head1 FILES

=head1 BUGS, LIMITATIONS, AND CAVEATS

=head1 NOTES

=head1 AUTHOR

David Meyer <papa@sdf.org>

=head1 HISTORY

=head1 COPYRIGHT AND LICENSE

Copyright 201x David Meyer

=head1 SEE ALSO



# Emacs control #####################################################
#Local variables:
#mode: perl
#End: