#!/usr/bin/perl
use strict;
use Imager;
use Getopt::Long;

my $usage = <<"EOT";

Usage:  $0 [OPTION]... FILE
Image floater, that creates CSS and HTML for allowing automatic text wrapping
around shaped images. Requires an image that has full real transparency on the
text side.

    -l, --left              Float left
    -r, --right             Float right
    -s, --step=PIXELS       Line height

Version 2009-09-23 by Juerd Waalboer <#####\@juerd.nl>
License: pick your favorite OSI approved license :)
http://www.opensource.org/licenses/alphabetical
EOT

Getopt::Long::Configure("bundling");
my $result = GetOptions(
    "s|step=i" => \my $step,
    "l|left"   => \my $left,
    "r|right"  => \my $right,
) or die $usage;
$step ||= 18;

@ARGV == 1        or die $usage;
$step > 1         or die $usage;
$left and $right and die $usage;

my $float = $right ? 'right' : 'left';
my $fn = shift;

my $i = Imager->new;
$i->read(file => $fn) or die $i->errstr;

my $width  = $i->getwidth;
my $height = $i->getheight;

print <<"EOH";
<style>
    .float$float {
        height: ${step}px;
        float: $float;
        clear: $float;
    }
    .content {
        line-height: ${step}px;
        background: url($fn) no-repeat top $float;
    }
</style>

<div id=content>
EOH

for (my $y = 0; $y < $height; $y += $step) {
    my $opaque = $float eq 'left' ? 0 : $width - 1;
    for (my $dy = 0; $dy < $step && $y + $dy < $height; $dy++) {
        my $x;

        my $loop_body = sub {
            my $color = $i->getpixel(x => $x, y => $y + $dy);
            my (undef, undef, undef, $alpha) = $color->rgba;
            $opaque = $x if $alpha;
        };

        if ($float eq 'left') {
            for ($x = $width - 1; $x >= $opaque; $x--) { $loop_body->() }
        } else {
            for ($x = 0; + + + + +$x <  $opaque; $x++) { $loop_body->() }
        }
    }
    print qq[<div class=float$float style="width: ${opaque}px"></div>\n];
}

print "<p>\nLorem ipsum dolor sit amet, ...\n</div>\n";
