package Image::Quantize::PNG;
require Exporter;
require Image::Quantize;
our @ISA = qw(Exporter Image::Quantize);
our @EXPORT_OK = qw//;
use warnings;
use strict;
use Carp;

use Image::PNG::Libpng ':all';
use Image::PNG::Const ':all';

sub new
{
    my ($class, %options) = @_;
    my $r = internal_new_png ();
    return $r;
}

sub quantize
{
    my ($self, $png, %options) = @_;
    my $outpng = create_write_struct ();
    my ($in_png, $in_info) = $png->get_internals ();
    my ($out_png, $out_info) = $outpng->get_internals ();
    my ($image_data, $row_pointers) =
        quantize_internal ($self, $in_png, $in_info, $out_png, $out_info);
    # Transfer the ownership of the data to $out_png so it's freed
    # when that is. This needs to be done because we may quantize
    # another image before we write out $outpng, so if the memory is
    # stored inside $self, then it may be overwritten by the next
    # quantization before $outpng is written out. To cut a long story
    # short, we save the Perl programmer from thinking about memory
    # management issues by shifting the responsibility for this
    # allocated memory to $outpng.
    $outpng->set_image_data ($image_data);
    $outpng->set_row_pointers ($row_pointers);
    return $outpng;
}

sub quantize_file
{
    my ($self, %options) = @_;
    my $in = $options{in};
    if (! -f $in) {
	croak "File '$in' not found";
    }
    my $out = $options{out};
    my $inpng = read_png_file ($in, transforms => PNG_TRANSFORM_EXPAND);
    my $opng = $self->quantize ($inpng, %options);
    $opng->write_png_file ($out);
}

1;
