#!/usr/bin/perl -w

use strict;
use GD;
use vars qw( $Image $Output $Width $Height );
use vars qw( $OutputW $OutputX $OutputY );

$OutputW = 1024;
$OutputX = 0;
$OutputY = 0;

sub OutputChar {
  my ($character, $from, $to) = @_;
  my $charWidth = $to - $from;
  
  if ($OutputX + $charWidth > $OutputW) {
    $OutputX = 0;
    $OutputY += $Height;
  }
  
  $Output->copy($Image, $OutputX, $OutputY, $from, 1, $charWidth, $Height -1 );
#  print "$OutputX, $OutputY, $from, 1, $charWidth, $Height\n";
  print OUTPUT "[$OutputX, $OutputY, $charWidth, $Height],\n";
  $OutputX += $charWidth;
}

sub CopyPalette {
  my ($numColors, @color, $i);
  
  $numColors = $Image->colorsTotal;
  for ($i = 0; $i < $numColors; ++$i) {
    @color = $Image->rgb($i);
    $Output->colorAllocate(@color);
  }
}



my $filename = $ARGV[0] || '../data/font2.png';
$OutputW = $ARGV[1] || $OutputW;
print "Processing $filename\n";

$Image = GD::Image->newFromPng( $filename, 1);
$Width = $Image->width;
$Height = $Image->height;
print "Image is $Width x $Height\n";
$Output = GD::Image->newTrueColor( $OutputW, int($Width * $Height / $OutputW * 1.2) );
print "Output is $OutputW x ", $Output->height, "\n";
$Output->alphaBlending(0);
$Output->filledRectangle(0,0,$OutputW,$Output->height, 0xffff00ff);

my ($charColor, $spacingColor, $i, $character, $from, $to);
$spacingColor = $Image->getPixel(0,0);
do { $charColor = $Image->getPixel($i++,0); } while ($spacingColor == $charColor);

print "Character color is $charColor; spacing color is $spacingColor\n";
open OUTPUT, ">out.txt";

# FIND CHARACTER POSITIONS

&OutputChar(32, 0, $i);
$character = 33;
while ($i < $Width) {
  while ($i < $Width and $Image->getPixel($i,0) == $spacingColor) { ++$i; }
  $from = $i;
  last if $i >= $Width;
  while ($i < $Width and $Image->getPixel($i,0) != $spacingColor) { ++$i; }
  $to = $i;
  print "Char\t$character ", chr($character), "\t$from\t$to\n";
  &OutputChar($character, $from, $to);
  ++$character;
}


close OUTPUT;
open OUTPUT, ">out.png"  or die;
binmode OUTPUT;
$Output->saveAlpha(1);
print OUTPUT $Output->png;
close OUTPUT;
