use strict;

my $status = 0;
my $x = 0;
my $y = 0;
my $w = 0;
my $h = 0;

my $mx = 0;
my $my = 0;
my $dx = 0;
my $dy = 0;

my @c = ();
my @l = ();

my @cc = ();
my @cl = ();

while (<>)
{
	if ($status == 0)
	{
		if (m/name="(.*?)".*parent-style-name="occupazione"/)
		{
			push @cc, $1;
		}
		elsif (m/name="(.*?)".*parent-style-name="letto"/)
		{
			push @cl, $1;
		}
		elsif (m/draw:style-name="(.*?)".*?svg:width="(.*?)cm".*?svg:height="(.*?)cm".*?svg:x="(.*?)cm".*?svg:y="(.*?)cm"/)
		{
			my $found = 0;
			my $style = $1;
			$w = $2;
			$h = $3;
			$x = $4;
			$y = $5;

			$mx = $x + $w if $x + $w > $mx;
			$my = $y + $h if $y + $h > $my;

			$dx = $x if $dx == 0 || $x < $dx;
			$dy = $y if $dy == 0 || $y < $dy;

			foreach (@cc)
			{
				$status = 1 if $style eq $_;
			}
			foreach (@cl)
			{
				$status = 2 if $style eq $_;
			}
		}
	}
	elsif ($status == 1 || $status == 2)
	{
		m/>(.*?)</;
		my $l = $1;

		my %o = (
			n => $l,
			x => $x,
			y => $y,
			w => $w,
			h => $h
		);

		push @c, \%o if $status == 1;
		push @l, \%o if $status == 2;

		$status = 0;
	}
}

print "{\"c\":[";

$mx -= $dx;
$my -= $dy;

for (my $a = 0; $a < scalar @c; $a ++)
{
	my %o = %{ @c[$a] };

	my $n = $o{n};
	my $l = 100 * ($o{x} - $dx) / $mx;
	my $t = 100 * ($o{y} - $dy) / $my;
	my $r = 100 * ($mx - ($o{x} - $dx) - $o{w}) / $mx;
	my $b = 100 * ($my - ($o{y} - $dy) - $o{h}) / $my;

	my $orient = "V";
	$orient = "H" if $o{w} > $o{h};

	print "\t{\"id\":\"$n\",\"left\":\"$l%\",\"top\":\"$t%\",\"bottom\":\"$b%\",\"right\":\"$r%\",\"orient\":\"$orient\"}";
	print "," if $a < scalar @c - 1;
	
}

print "],\"l\":[";

for (my $a = 0; $a < scalar @l; $a ++)
{
	my %o = %{ @l[$a] };

	my $n = $o{n};
	my $l = 100 * ($o{x} - $dx) / $mx;
	my $t = 100 * ($o{y} - $dy) / $my;
	my $r = 100 * ($mx - ($o{x} - $dx) - $o{w}) / $mx;
	my $b = 100 * ($my - ($o{y} - $dy) - $o{h}) / $my;

	my $orient = "V";
	$orient = "H" if $o{w} > $o{h};

	print "\t{\"id\":\"$n\",\"left\":\"$l%\",\"top\":\"$t%\",\"bottom\":\"$b%\",\"right\":\"$r%\",\"orient\":\"$orient\"}";
	print "," if $a < scalar @l - 1;
}
print "]}";

