#!/usr/bin/perl

use GD;

GD::Image->trueColor(1);

if (!$ARGV[0]) {
	print "usage: png_lsb.pl inputfile\n";
	exit;
}

my $filename = "$ARGV[0]";

print "$filename\n";

my $image_original;

if ($filename =~ /png$/i) {
	$image_original = GD::Image->newFromPng($filename, 1);
} elsif ($filename =~ /jpg$/i) {
	$image_original = GD::Image->newFromJpeg($filename, 1);
}

my ($width,$height) = $image_original->getBounds();

my $image_red = new GD::Image($width,$height, 1) || die;
my $image_green = new GD::Image($width,$height, 1) || die;
my $image_blue = new GD::Image($width,$height, 1) || die;
my $image_rgb = new GD::Image($width,$height, 1) || die;
my $bit_shift = 0;
foreach my $h ( 0 .. $height ) {
	foreach my $w ( 0 .. $width ) {
		my $index = $image_original->getPixel($w,$h);
		my ($r,$g,$b) = $image_original->rgb($index);

		if ($h < 1) {
			printf( "[%04u,%04u](%03u,%03u,%03u)\n", 
				$w,$h, $r,$g,$b);
			#printf( "(%04u,%04u) (%03u,%03u,%03u) (b%08b,b%08b,b%08b) (b%08b,b%08b,b%08b) (%03u,%03u,%03u)\n", $w,$h, $r,$g,$b, $r,$g,$b, ($r & 1<<$bit_shift)>>$bit_shift,($g & 1<<$bit_shift)>>$bit_shift,($b & 1<<$bit_shift)>>$bit_shift,  (($r & 1<<$bit_shift)>>$bit_shift)*255, (($g & 1<<$bit_shift)>>$bit_shift)*255, (($b & 1<<$bit_shift)>>$bit_shift)*255);
		}

		
		$image_red->setPixel($w,$h,$image_red->colorExact( (($r & 1<<$bit_shift)>>$bit_shift)*255,(($r & 1<<$bit_shift)>>$bit_shift)*255,(($r & 1<<$bit_shift)>>$bit_shift)*255));		
		$image_green->setPixel($w,$h,$image_green->colorExact( (($g & 1<<$bit_shift)>>$bit_shift)*255,(($g & 1<<$bit_shift)>>$bit_shift)*255,(($g & 1<<$bit_shift)>>$bit_shift)*255));		
		$image_blue->setPixel($w,$h,$image_blue->colorExact( (($b & 1<<$bit_shift)>>$bit_shift)*255,(($b & 1<<$bit_shift)>>$bit_shift)*255,(($b & 1<<$bit_shift)>>$bit_shift)*255));		
		$image_rgb->setPixel($w,$h,$image_blue->colorExact( (($r & 1<<$bit_shift)>>$bit_shift)*255,(($g & 1<<$bit_shift)>>$bit_shift)*255,(($b & 1<<$bit_shift)>>$bit_shift)*255));		
	}
}

my $png_data = $image_red->png();
open (DISPLAY,">$filename".".red.png") || die;binmode DISPLAY;
print DISPLAY $png_data;
close DISPLAY;

my $png_data = $image_green->png();
open (DISPLAY,">$filename".".green.png") || die;
binmode DISPLAY;
print DISPLAY $png_data;
close DISPLAY;

my $png_data = $image_blue->png();
open (DISPLAY,">$filename".".blue.png") || die;
binmode DISPLAY;
print DISPLAY $png_data;
close DISPLAY;

my $png_data = $image_rgb->png();
open (DISPLAY,">$filename".".rgb.png") || die;
binmode DISPLAY;
print DISPLAY $png_data;
close DISPLAY;

