#!/usr/bin/perl
use warnings;
use strict;

use Image::Magick;
use List::Util qw(min max);

# input: BMP filename specified on the last argument
# output: EPS at stdout.

# we only care about the last argument.
my $bmpfile = $ARGV[-1];

my %mag;			# $mag{$rgb} => $mag
my %rgb;			# $rgb{$mag} => $rgb
my @pxmag;			# $pxmag[$x][$y] => 0 .. 1
my @px;				# $px[$x][$y] => 0, 1

my $p = new Image::Magick;
$p->Read($bmpfile);
my ($w, $h) = $p->Get('width', 'height');
for (my $y = 0; $y < $h; $y += 1) {
    for (my $x = 0; $x < $w; $x += 1) {
	my ($r, $g, $b) = $p->GetPixel(x => $x, y => $h - 1 - $y);
	my $mag = ($r + $g + $b) / 3;
	my $rgb = join($;, $r, $g, $b);
	$mag{$rgb} = $mag;
	$rgb{$mag} = $rgb;
	$pxmag[$x][$y] = $mag;
    }
}

my $min_mag = min(values(%mag));
my $max_mag = max(values(%mag));
my $avg_mag = ($min_mag + $max_mag) / 2;

for (my $y = 0; $y < $h; $y += 1) {
    for (my $x = 0; $x < $w; $x += 1) {
	if ($pxmag[$x][$y] < $avg_mag) {
	    $px[$x][$y] = 1;
	} else {
	    $px[$x][$y] = 0;
	}
    }
}

print(<<'END');
%!PS-Adobe-3.0 EPSF-3.0
%%Creator: Adobe Illustrator by AutoTrace version 0.31.1
%%Title: 
%%CreationDate: Thu Aug 28 08:09:29 2014
%%BoundingBox: 0 0 $w $h
%%DocumentData: Clean7Bit
%%EndComments
%%BeginProlog
/bd { bind def } bind def
/incompound false def
/m { moveto } bd
/l { lineto } bd
/c { curveto } bd
/F { incompound not {fill} if } bd
/f { closepath F } bd
/S { stroke } bd
/*u { /incompound true def } bd
/*U { /incompound false def f} bd
/k { setcmykcolor } bd
/K { k } bd
%%EndProlog
%%BeginSetup
%%EndSetup
0.000 0.000 0.000 0.498 k
*u
END

for (my $y = 0; $y < $h; $y += 1) {
    for (my $x = 0; $x < $w; $x += 1) {
        if ($px[$x][$y]) {
            printf("%d %d m\n", $x, $y);
            printf("%d %d l\n", $x, $y + 1);
            printf("%d %d l\n", $x + 1, $y + 1);
            printf("%d %d l\n", $x + 1, $y);
            printf("%d %d l\n", $x, $y);
        }
    }
}

print(<<'END');
*U
%%Trailer
%%EOF
END
