#!/usr/bin/perl
# 
# This file is part of Games-Risk
# 
# This software is Copyright (c) 2008 by Jerome Quelin.
# 
# This is free software, licensed under:
# 
#   The GNU General Public License, Version 3, June 2007
# 

use 5.010;
use strict;
use warnings;

use File::Slurp;
use File::Temp  ();
use Image::Magick;
use Image::Size;
use Path::Class;
use YAML        qw{ DumpFile };

my $imgpath = file( shift );
my $dst     = dir( shift )  or die "$0 map_source.gif dst/\n";

my %infos = ();
foreach my $grey ( 1 .. 254 ) {
    say "extracting country #$grey";
    my $out = $dst->file( "$grey.png" );
    my $tmp1 = File::Temp->new( SUFFIX => '.png' );
    my $tmp2 = File::Temp->new( SUFFIX => '.png' );
    my $tmp3 = File::Temp->new( SUFFIX => '.png' );
    system "convert $imgpath -matte \\( +clone -fuzz 0% -transparent rgb\\($grey,$grey,$grey\\) \\) -compose DstOut -composite $tmp1";
    my $output = qx{ convert $tmp1 +repage -trim  info:- };
    system "convert $tmp1 +repage -trim  $tmp2";
    system "convert $tmp2 -fill rgb\\(255,255,255\\) -opaque rgb\\($grey,$grey,$grey\\) $tmp3";
    system "convert $tmp3 -transparent rgb\\(0,0,0\\) $out";
    
    if ( not $output =~ /\s\d+x\d+\+(\d+)\+(\d+)\s/ ) {
        say "removing last country, which was empty";
        unlink $out;
        last;
    }

    $infos{$grey}{coordx} = $1;
    $infos{$grey}{coordy} = $2;
}

print DumpFile( $dst->file('countries.yaml'), \%infos );
exit;


my ($xlen, $ylen) = imgsize( "$imgpath" );
my $image = Image::Magick->new;

$image->Read( $imgpath );

# create a transparent canvas
#convert share/maps/risk_map.gif -alpha transparent trans_alpha.png


foreach my $grey ( 1 .. 254 ) {
    my ($minx, $miny, $maxx, $maxy) = ($xlen, $ylen, 0, 0);
    foreach my $i ( 0 .. $xlen ) {
        say $i;
        foreach my $j ( 0 .. $ylen ) {
            my ($g) = map { $_ * 255 } $image->GetPixel(x=>$i, y=>$j, channel=>'Gray');
            next unless $g == $grey;
            $minx = $i if $i < $minx;
            $miny = $j if $j < $miny;
            $maxx = $i if $i > $maxx;
            $maxy = $j if $j > $maxy;
        }
    }
    my $new = $image->Clone;
    $new->Crop( x=>$minx, y=>$miny, widht=>$maxx-$minx, height=> $maxy-$miny );
    $new->Write( "tmp/$grey.png" );
}

__END__
my  $image = Image::Magick->new;
$image->Read( @ARGV );
die $image->Identify;
my  @pixels = $image->GetPixels(map=>'I', normalize=>1);
binmode STDOUT;
print pack('B*',join('',@pixels));
  
__END__




$image = Image::Magick->new;
$x = $image->Read('girl.png', 'logo.png', 'rose.png');
warn "$x" if "$x";

$image=Image::Magick->new(size=>'384x256');

$x = $image->Crop(geometry=>'100x100+100+100');
warn "$x" if "$x";

$x = $image->Write('x.png');
warn "$x" if "$x";

$image = Image::Magick->new;
$image->Set(size=>'100x100');
$image->ReadImage('xc:white');
$image->Set('pixel[49,49]'=>'red');
@pixels = $image->GetPixel(x=>1,y=>1);

$image->SetPixel(x=>1,y=>1,color=>\@pixels);
