﻿#!/usr/bin/perl -w
use strict;
use warnings;
use utf8;
use open qw(:std :utf8);
use integer;


# Filter_4_06_tables.pl
# 2010-06-16
# Wolfgang Schmidle

# This Script transforms <tb> into xhtml


# text input

my @text;
while(<>) { push @text, $_; }


# go through the text

my $inTable = 0;
my $colspan = 0;

my $i = 0;

my $spalte = 1;
my $breite = 0;
my $inhalt = "";
my %vertical = ();
my %rowspan = ();
my $actualCell = "";
my $cellAbove = "";
my $firstCell = "";


# add an # at the beginning of each line and search for cells with rowspan > 1

LINE: foreach (@text) {

	$i++;
	
	if (m!<tb[ >]!) { $inTable = 1; }
	if (m!</tb>!) { $inTable = 0; }
	next unless $inTable;
	
	next unless m!#!;
	
	unless (m!^##!) { $_ = "# " . $_; }

	next unless m!# "!;
	 
	$spalte = 1;
	$breite = 0;
	CELL: while (m!(#+)([^#]*)!g)	{
		$spalte += $breite;
		$breite = length $1;
		$inhalt = $2;
		if ($inhalt =~ m! "[ \n]!) {
			$actualCell = $i . " $spalte $breite";
			$cellAbove = $i-1 . " $spalte $breite";
			if (exists $vertical{$cellAbove}) {
				$vertical{$actualCell} = $vertical{$cellAbove} + 1;
				$firstCell = $i-$vertical{$actualCell} . " $spalte $breite";
				$rowspan{$firstCell}++;
			} else {
				$vertical{"$i $spalte $breite"} = 1;
				$firstCell = $i-1 . " $spalte $breite";
				$rowspan{$firstCell}++;
			}
		}
	}
}

# check whether the corresponding first lines exist and fill in the rowspan information

my $supposedSpalte = 0;
my $supposedBreite = 0;

ROWSPAN: foreach my $key (keys %rowspan) {

	$rowspan{$key}++;

	($i, $supposedSpalte, $supposedBreite) = $key =~ m!(\d+) (\d+) (\d+)!;
	$i--;
	$_ = $text[$i];
	
#	print "$i, $supposedSpalte, $supposedBreite: $_\n";
	
	$spalte = 1;
	$breite = 0;
	CELL: while (m!(#+)!g)	{
		$spalte += $breite;
		$breite = length $1;

		next CELL if $spalte < $supposedSpalte;
		if ($spalte > $supposedSpalte) { die "line $i: incorrect vertical cell:\n$_"; }
		if ($breite != $supposedBreite) { die "line $i: incorrect vertical cell:\n$_"; }
		
		substr($text[$i], pos, 0) = "/$rowspan{$key}/";

		next ROWSPAN;
	}
	die "line $i: incorrect vertical cell:\n$_";
}

# print @text;


$inTable = 0;

foreach (@text) {
	
	if (m!<tb[ >]!) { 
		s!<tb([ >])!<xhtml:table$1!;
		$inTable = 1;
		next;
	}
	next unless $inTable;
	
	if (m!</tb>!) { 
		s!</tb>!</xhtml:table>!;
		$inTable = 0;
		next;
	}
	
	chomp;
	
	# headings !!!
	
	$_ = "<tr><td>$_</td></tr>\n";	
#	s!<td># !<td></td><td> !;
	s!#+ " ?!!g;
	s! #! </td><td>#!g;
	s!>#([ /<])!>$1!g;    # kein colspan="1"
	
	while (m!>(#+)!) {
		my $colspan = length $1;
		s!>(#+)! colspan="$colspan">!;
	}
	s!>/(\d+)/! rowspan="$1">!g;


	
	s!\\\\!<lb/>!g;

	s!<td> !<td>!g;
	s! </td>!</td>!g;

	s!<tr([ >])!  <xhtml:tr$1!g;
	s!</tr>!\n  </xhtml:tr>!g;
	s!<td([ >])!\n    <xhtml:td xml:space="preserve"$1!g;
	s!</td>!</xhtml:td>!g;




	# Schummel
	
	s!<(\d\d\d)>!&lt;$1&gt;!g;
	s!<lb/>!<br/>!g;
}

# text output

print @text;


# TO DO:
# ...
