#!/usr/bin/perl

use strict;
use warnings;

print <<'.';
<html>
<head>
<title>ATI PDF</title>
<style>
th { text-align: left; vertical-align: top }
td { text-align: left; vertical-align: top }
</style>
</head>
<body>
.

my $pages = do $ARGV[0];

print '<table border="1">';

my $cur_text;

foreach my $page (@$pages) {
    $page->{num} < 8 and next;
    print qq(<tr><th colspan="4">page $page->{num}</th></tr>\n);
    my $cur_table;
    my $cur_col;
    foreach my $text (@{$page->{text}}) {
        defined $text->{table} or next;

        $cur_table = $text->{table};
        if ($text->{col} eq "heading") {
            print qq(<tr><th colspan="4">$text->{text}</th></tr>\n);
            next;
        }
        if ($text->{col} == 0 and (not defined $cur_col or $cur_col != 0)) {
            defined $cur_col and print "</td></tr>\n";
            print "<tr><td>";
            $cur_text = '';
        } elsif (defined $cur_col) {
            if ($text->{col} == $cur_col) {
                print "<br>\n";
                if (length $cur_text > 10 and $cur_col == 1) {
                    die "error on page $page->{num}";
                }
            }
            if ($text->{col} != 0 and $cur_col != $text->{col}) {
                print "</td>\n<td>";
                $cur_text = '';
            }
        }
        $text->{text} =~ s/&/&amp;/g;
        print $text->{text};
        $cur_text .= $text->{text};
        $cur_col = $text->{col};
    }
    if (defined $cur_table) {
        print "</td></tr>";
    }
}

print "</table>";
print "</body></html>";
