#!/usr/bin/perl

use strict;
use warnings;
use Carp;

croak "Merges and tiles multiple SVG files into a single SVG file.
A square grid is used (4x4, 5x5 etc...), assumes input SVGs are the same size.
Usage: $0 input1.svg input2.svg [...] > tiled.svg\n" unless @ARGV;

my ($header, $body, $footer);

my $index = 0;
my $body_all;

my $grid = sqrt (scalar @ARGV);
$grid = int ($grid +1) if $grid > int ($grid);

for my $path_svg (@ARGV)
{
    open my $SVG, '<', $path_svg or croak "$!";
    my @lines = (<$SVG>);
    close $SVG;

    my $xml = join '', @lines;
    $xml =~ s/(\r|\l|\n)//xg;
    $xml =~ s/[[:space:]]+/ /xg;
    $xml =~ s/>[[:space:]]</></xg;

    ($header, $body, $footer) = $xml =~ /(.*<svg[[:space:]].*?>|.*<svg>)(.*)(<\/svg>.*)/x;

    my ($width, $units_h) = $header =~ /[[:space:]]width="([0-9.-]*)([a-zA-Z]*)"/x;
    my ($height, $units_v) = $header =~ /[[:space:]]height="([0-9.-]*)([a-zA-Z]*)"/x;

    my $new_width = $width * $grid;
    my $new_height = $height * $grid;

    $header =~ s/[[:space:]]width="[a-zA-Z0-9.-]*"/ width="$new_width"/x;
    $header =~ s/[[:space:]]height="[a-zA-Z0-9.-]*"/ height="$new_height"/x;
    $header =~ s/[[:space:]]viewBox="[ a-zA-Z0-9.-]*"//x;

    my $offset_x = ($index % $grid) * $width;
    my $offset_y = int ($index / $grid) * $height;
    $body = "<g transform=\"translate($offset_x,$offset_y)\">$body</g>";
    $body_all .= $body;
    $index++;
}

print $header;
print $body_all;
print $footer;

0;
