#!/usr/bin/perl -w

# Quickly coded up by Martijn van Oosterhout <kleptog@svana.org> 10 August 2008
# Licence: BSD

use strict;

if( $#ARGV != 7 )
{
  print STDERR "build_tileset layer x y z endz userid directory output\n";
  print STDERR "Example: ./build_tileset tile 1022 1034 12 17 1234 temp_foo output_1022_1034\n";
  exit(1);
}

my($layer,$x,$y,$z,$endz,$userid,$dir,$outfile) = @ARGV;

my @offsets;
my $currpos = 5472;

open my $fh, ">$outfile.temp" or die "Couldn't open '$outfile' ($!)\n";
seek $fh, $currpos, 0 or die;

my $levels = $endz-$z;
for my $iz (0 .. $levels)
{
  my $width = 2**$iz;
  for my $iy (0 .. $width-1)
  {
    for my $ix (0 .. $width-1)
    {
      push @offsets, $currpos;
      
      my $filename = sprintf "%s/%s_%d_%d_%d.png", $dir, $layer, $x*$width+$ix, $y*$width+$iy, $z+$iz;
      
      open my $png, "<$filename" or die "Couldn't open file $filename ($!)\n";
      
      my $length = -s $png;
      
      my $buffer;
      if( read($png, $buffer, $length) != $length )
      { die "Read failed from $filename ($!)\n" }
      
      print $fh $buffer or die "write failed ;on output ($!)\n";
      $currpos += $length;
    }
  }
}
push @offsets, $currpos;

if( scalar( @offsets ) != 1366 )
{ die "Bad number of offsets: ".scalar( @offsets )."\n" }

seek $fh, 0, 0 or die;
print $fh pack("CxxxVV*", 1, $userid, @offsets) or die;
close $fh or die;

rename "$outfile.temp", $outfile or die;