#!/usr/bin/perl -w
use strict;
use warnings;
use Image::Magick;
# number of color components in RGB
use constant NC    => 3;

my $infile=shift;
my $outfile=shift;

if(not -e $infile) { die "input file not found";}

use Time::HiRes;
sub bench
{
	my($func)=shift;
	my $t=[Time::HiRes::gettimeofday()];
	my @result=&$func(@_);
	print "bench: $func ".Time::HiRes::tv_interval($t)."\n";
	return @result;
}

sub compare_rows(@@)
{
   my($a,$b)=@_;
   my $diff=0;
   for(my $i=$#$a; $i>=0; --$i) {
#      $diff+=abs($a->[$i]<=>$b->[$i]);
	if($a->[$i] != $b->[$i]) {return 1} # Optimierung
   }
   return $diff;
}

sub bmwflip(@$$)
{
   my($allpixels,$width,$height)=@_;
   my @new;
   for my $x (0..$width-1) {
      for my $y (0..$height-1) {
         for my $n(0..NC-1) {
            $new[($y+$x*$height)*NC+$n] = $allpixels->[($x+$y*$width)*NC+$n];
         }
      }
   }
   return (\@new,$height,$width);
}

sub bmwtoimage(@$$)
{
   my($allpixels,$width,$height)=@_;
   my $q=new Image::Magick(size=>$width."x$height");
#   $q->Read('xc:yellow');
#   $q->Read('/home/wiedemann/temp/Luftbild-2-originalprojektion.png');
   $q->Set(magick=>"RGB", depth=>8, type=>"TrueColor", 
	compression=>"Zip", # optional
	);
#   my $rgbpixels=pack("C*", map{$_/257} @$allpixels); # 65535/255 = 257
   $q->BlobToImage(pack("C*", map{$_/257} @$allpixels));
   $q->Write($outfile);
}

sub dropduplines(@$$)
{
   my($allpixels,$width,$height)=@_;
   my @newpixels;
   my $prevline;
   my $count=0;
   my $prevwant=1;
   foreach my $y (0..$height-1) {
      my $offs=$y*$width*NC;
      my $pixels = [@{$allpixels}[$offs..$offs+NC*$width-1]];
      my $want=1;
      if($prevline && $prevwant) {
         my $diff=compare_rows($prevline, $pixels);
#         print "$diff\n";
         if(!$diff) { # was a dup
            $want=0;
         } 
      } 
      if($want) {
         push(@newpixels, @$pixels);
         $count++;
      }
      $prevwant=$want;
      $prevline=$pixels;
   }
   return(\@newpixels, $count);
}


my $p = new Image::Magick(type=>"TrueColor");
$p->Read($infile);
#$p->Set(depth=>8, type=>"TrueColor");
my ($width,$height)=$p->Get("width","height");
#my ($width,$height)=(1175,1175);
my @allpixels = $p->GetPixels(map=>'RGB', x=>0, y=>0, height=>$height, width=>$width, normalize=>"false");

my ($new,$count)=dropduplines(\@allpixels, $width, $height);
$height=$count;
print "$count\n";
($new,$width,$height)=bmwflip($new, $width, $height);
#($new,$width,$height)=bench(\&bmwflip,$new, $width, $height);
($new,$count)=dropduplines($new, $width, $height);
print "$count\n";
$height=$count;
($new,$width,$height)=bmwflip($new, $width, $height);

bmwtoimage($new, $width, $height);
exit 0;

