#!/usr/bin/env perl
use strict;
use warnings;
use bytes; # Need LANG=C as well.
use Imager;

# If no arguments given, slurp STDIN, and split it across
# greyscale PNG files: 0.png, 1.png, ... .

# If arguments are given, assume they're image filenames:
# read them in, write the raw data to stdout.

if (@ARGV) {
    my $data = from_img_filenames(@ARGV);
    print $data;
} else {
    local $/;  my $data = <>;
    my @imgs = to_imgs($data,352,288);
    for my $n (0..$#imgs) {
        $imgs[$n]->write(file=>"$n.png",type=>'png');
    }
}
exit;

sub from_img_filenames {
    return from_imgs(
        map {
            my $img = new Imager;
            $img->open(file=>$_) or die $img->errstr;
            $img;
        } @_
    );
}

sub from_imgs {
    my $data = "";
    map {
        my $chunk;
        $_->write(data=>\$chunk,type=>'raw');
        $data .= $chunk;
    } @_;
    return $data;
}

sub to_imgs {
        my ($data,$x,$y) = @_;

        my $nbytes = length $data;
        my $npixels = $x*$y;
        my $nfullimgs=int($nbytes/$npixels);

        local $|=1;
        print STDERR "$nbytes bytes $npixels pixels $nfullimgs full images\n";

        my @imgs;

        for my $n (0..$nfullimgs-1) {
            my $chunk = substr($data,$n*$npixels,$npixels);
            my $img = new Imager;
            $img->read(data=>$chunk,type=>'raw',xsize=>$x,ysize=>$y,
            datachannels=>1,storechannels=>1,bits=>8);
            push @imgs,$img;
        }
        print STDERR "ponk\n";

        if (my $overflow = $nbytes-$npixels*$nfullimgs) {
            my $padding = "\x00" x ($npixels-$overflow);
            my $chunk = substr($data,($nfullimgs-1)*$npixels,$overflow)
                      . $padding;
            my $img = new Imager;
            $img->read(data=>$chunk,type=>'raw',xsize=>$x,ysize=>$y,
            datachannels=>1,storechannels=>1,bits=>8);
            push @imgs,$img;

        }
        return @imgs;
}
