$usage = "Usage: combine.pl { 8 | 16 } < pixman-combine.c.template";

$#ARGV == 0 or die $usage;

# Get the component size.
$size = int($ARGV[0]);
$size == 8 or $size == 16 or die $usage;

$pixel_size = $size * 4;
$half_pixel_size = $size * 2;

sub mask {
    my $str = shift;
    my $suffix;
    $suffix = "ULL" if $size > 8;

    return "0x" . $str . $suffix;
}

# Generate mask strings.
$nibbles = $size / 4;
$mask = "f" x $nibbles;
$zero_mask = "0" x $nibbles;
$one_half = "8" . "0" x ($nibbles - 1);

print "/* WARNING: This file is generated by combine.pl from combine.inc.\n";
print "   Please edit one of those files rather than this one. */\n";
print "\n";

print "#line 1 \"pixman-combine.c.template\"\n";

$mask_ = mask($mask);
$one_half_ = mask($one_half);
$g_mask = mask($mask . $zero_mask);
$b_mask = mask($mask . $zero_mask x 2);
$a_mask = mask($mask . $zero_mask x 3);
$rb_mask = mask($mask . $zero_mask . $mask);
$ag_mask = mask($mask . $zero_mask . $mask . $zero_mask);
$rb_one_half = mask($one_half . $zero_mask . $one_half);
$rb_mask_plus_one = mask("1" . $zero_mask x 2 . "1" .  $zero_mask);

while (<STDIN>) {
    # Mask and 1/2 value for a single component.
    s/#define COMPONENT_SIZE\b/$& $size/;
    s/#define MASK\b/$& $mask_/;
    s/#define ONE_HALF\b/$& $one_half_/;

    # Shifts and masks for green, blue, and alpha.
    s/#define G_SHIFT\b/$& $size/;
    s/#define R_SHIFT\b/$& $size * 2/;
    s/#define A_SHIFT\b/$& $size * 3/;
    s/#define G_MASK\b/$& $g_mask/;
    s/#define R_MASK\b/$& $b_mask/;
    s/#define A_MASK\b/$& $a_mask/;

    # Special values for dealing with red + blue at the same time.
    s/#define RB_MASK\b/$& $rb_mask/;
    s/#define AG_MASK\b/$& $ag_mask/;
    s/#define RB_ONE_HALF\b/$& $rb_one_half/;
    s/#define RB_MASK_PLUS_ONE\b/$& $rb_mask_plus_one/;

    # Add 32/64 suffix to combining function types.
    s/\bCombineFunc\b/CombineFunc$pixel_size/;
    s/\bFbComposeFunctions\b/FbComposeFunctions$pixel_size/;
    s/combine_width/combine_$pixel_size/;
    s/_pixman_setup_combiner_functions_width/_pixman_setup_combiner_functions_$pixel_size/;
    s/UNc/UN$size/g;
    s/ALPHA_c/ALPHA_$size/g;
    s/RED_c/RED_$size/g;
    s/GREEN_c/GREEN_$size/g;
    s/BLUE_c/BLUE_$size/g;

    # Convert comp*_t values into the appropriate real types.
    s/comp1_t/uint${size}_t/g;
    s/comp2_t/uint${half_pixel_size}_t/g;
    s/comp4_t/uint${pixel_size}_t/g;

    # Change the function table name for the 64-bit version.
    s/pixman_composeFunctions/pixman_composeFunctions64/ if $size == 16;

    # Change the header for the 64-bit version
    s/pixman-combine.h/pixman-combine64.h/ if $size == 16;
    s/pixman-combine.h/pixman-combine32.h/ if $size == 8;

    print;
}
