#!/usr/bin/perl -l
use strict;
use warnings;

open STDIN, "-|", "jbofihe", "-x", "-b", "-ie";

print "<html><body>";

my $level = 0;
my ($loj, $english, $role, $levels) = ("") x 4;
my @role;

while (<>){
  next if /^$/;
  $loj .= $_;
  $english .= <>;
  $role .= <>;
  $levels .= <>;
  chomp ($loj, $english, $role, $levels);
}

#consolidate it all into one line!

my @starts;
my @ends;
my @levels;

while ($levels =~ /(\d+)/g){
push @starts, $-[1];
push @ends, $+[1];
push @levels, $1;
}
push @starts, (length $loj)+1;

for my $i (0..$#levels){
if ($levels[$i] > $level){
  #entering a new scope
  my $color = join "", map {("A".."F")[rand 6]} 1..6;
  print "<td><table style=\"border: solid;\" bgcolor=\"#$color\"><tr><td>";
  my $text = substr($role, $ends[$i]+1, $starts[$i+1]-$ends[$i]-1);
  $text =~ s/^\s+//;
  $text =~ s/\s+$//;
  if ($text){
      $role[$levels[$i]] = "<tr><td align=center colspan=2>$text</td></tr>";
  }
} else {
  print $role[$levels[$i]] if $role[$levels[$i]];
  print "</td></tr></table><td>";
}
#for ($loj, $english){
{
    $_ = substr($loj, $ends[$i]+1, $starts[$i+1]-$ends[$i]-1);
    s/^\s+//;
    s/\s+$//;
    s!\b([a-z']+)\b!<a href="http://jbovlaste.lojban.org/dict/$1">$1</a>!g;
    s!\b([A-Z]+)\b!<a href="http://jbovlaste.lojban.org/dict/\L$1"><font color=\"#888888">$1</font></a>!g;
    print "$_<br />" if $_;
}
{
    my $text = substr($english, $ends[$i]+1, $starts[$i+1]-$ends[$i]-1);
    $text =~ s/^\s+//;
    $text =~ s/\s+$//;
    print "$text<br />" if $text;
}

$level = $levels[$i];
}

print "<pre>
$loj
$english
$role
$levels
</pre>";

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