#!/usr/bin/perl -w

######################################################################
#  This script takes care of the problem of small numbers (bug #....)
#  in the svg produced by dia by multiplying all distance units
#  by a factor of 100.
#
#  This script is in the public domain.
#  Dov Grobgeld <dov.grobgeld (a) gmail.com>
#  Wednesday 2006-06-14 09:46
######################################################################

use strict;

# Factor to multiply distance factors by
my $factor = 100;

# Regexp for matching floating point numbers
my $num= '\d+\.?\d*';

# Read in the file and prepare for parsing
my $in = join("", <>);
my $len = length($in);
my $out;

# Parse until end of file
$in=~ /\A/gc;  # Get rid of warning
while(pos($in) < $len) {
    # skip white space
    $in=~ /\G\s*/gsc && do {
	$out .= $&;
    };
    $in=~ /\G<svg.*?>/gsc && do {
	my $svg=$&;
	$svg=~ s/(viewBox\s*=\s*\")(.*?)(\")/$1.fixnum($2).$3/e;
	$out.= $svg;
	  
	next;
    };
    $in=~ /\G<(rect).*?>/gsc && do {
	my $svg = $&;
	foreach my $tag (qw(x y width height stroke-width)) {
	    $svg=~ s/($tag\s*=\s*\")(.*?)(\")/$1.fixnum($2).$3/e;
	}
	$out .= $svg;
	next;
    };
    $in=~ /\G<(line).*?>/gsc && do {
	my $svg = $&;
	foreach my $tag (qw(x1 x2 y1 y2 stroke-width)) {
	    $svg=~ s/($tag\s*=\s*\")(.*?)(\")/$1.fixnum($2).$3/e;
	}
	$out .= $svg;
	next;
    };
    $in=~ /\G<(polygon).*?>/gsc && do {
	my $svg = $&;
	foreach my $tag (qw(stroke-width)) {
	    $svg=~ s/($tag\s*=\s*\")(.*?)(\")/$1.fixnum($2).$3/e;
	}
	$svg =~ s/($num),($num)/fixnum($1).",".fixnum($2)/ge;
	$out .= $svg;
	next;
    };
    $in=~ /\G<(text).*?>.*?<\/text>/gsc && do {
	my $svg = $&;
	foreach my $tag (qw(x y font-size)) {
	    $svg=~ s/($tag\s*=\s*\")(.*?)(\")/$1.fixnum($2).$3/e;
	}
	$out .= $svg;
	next;
    };
    $in=~ /\G<(path).*?>/gsc && do {
	my $svg = $&;
	foreach my $tag (qw(stroke-width)) {
	    $svg=~ s/($tag\s*=\s*\")(.*?)(\")/$1.fixnum($2).$3/e;
	}
	$svg =~ s/($num),($num)/fixnum($1).",".fixnum($2)/ge;
	$out .= $svg;
	next;
    };
    # Copy unhandled tags
    $in=~ /\G<.*?>/gsc && do {
	$out .= "$&";
	next;
    };
};

print $out;

# multiply all space sep numbers by a factor
sub fixnum {
    my @num = split(' ', shift);
    my $ret = "";

    @num = map { sprintf("%.1f", $_ * $factor)} @num;

    return join(" ", @num);
}
