#! /usr/bin/perl
# This short script creates fixed look-up tables for xcftools
#
# This file was written by Henning Makholm <henning@makholm.net>
# It is hereby in the public domain.
# 
# In jurisdictions that do not recognise grants of copyright to the
# public domain: I, the author and (presumably, in those jurisdictions)
# copyright holder, hereby permit anyone to distribute and use this code,
# in source code or binary form, with or without modifications. This
# permission is world-wide and irrevocable.
#
# Of course, I will not be liable for any errors or shortcomings in the
# code, since I give it away without asking any compenstations.
#
# If you use or distribute this code, I would appreciate receiving
# credit for writing it, in whichever way you find proper and customary.

use strict ; use warnings ;

sub shipsubarray (@) {
    while( @_ > 1 && $_[$#_] == 0 ) {
        pop @_ ;
    }
    my $last = pop @_ ;
    print "  {" ;
    my $left = 75 ;
    for my $d ( (map{ $_ . "," } @_), "$last}," ) {
        if( length($d) > $left ) {
            print "\n   " ;
            $left = 75 ;
        }
        print $d ;
        $left -= length($d) ;
    }
    print "\n" ;
}

my $precompute_it = 1 ;
if( open CONFIGH, "<", "config.h" ) {
    $precompute_it = 0 ;
    while( <CONFIGH> ) {
        if( /\#\s*define\s+PRECOMPUTED_SCALETABLE/ ) {
            $precompute_it = 1 ;
            last ;
        }
    }
    close CONFIGH ;
}

print "/* Autogenerated by $0 */\n" ;
print "#include \"pixels.h\"\n" ;
print "#ifdef PRECOMPUTED_SCALETABLE\n" ;
if( $precompute_it ) {
    print "const uint8_t scaletable[256][256] = {\n" ;
    for my $p ( 0..255 ) {
        shipsubarray( map { int(($p*$_+127)/255) } ( 0 .. 255 ) );
        # This formula has the property that
        # scaletable[p][q] + scaletable[255-p][q] == q
        # for all uint8_t values of p and q.
        # This is important in order that a partially transparent
        # pixel does not change the color of the underlying pixel
        # unless the two pixels have different colors.
    }
    print "};\n" ;
} else {
    print "#error PRECOMPUTED_SCALETABLE was not defined at generation time\n";
}
print "#endif\n" ;

if(0) {

print "const uint8_t divtable[256][256] = {\n" ;
for my $p ( 0..255 ) {
    shipsubarray( map { $_ >= $p ? 255 : int(0.5 + 255*$_/$p) }
                  ( 0 .. 255 ) );
}
print "};\n" ;

}

print "const rgba graytable[256] = {\n" ;
for my $p ( 0..255 ) {
    print "   (rgba)$p << RED_SHIFT | (rgba)$p << GREEN_SHIFT | (rgba)$p << BLUE_SHIFT,\n" ;
}
print "};\n" ;
