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

my $title;
my @rows;
while (<>) {
    if (m#<title>([^<]+)</title>#) {
        $title = $1;
        next;
    }
    if (m#^<tr>#) {
        push @rows, grep {defined} parse_row();
        next;
    }
}

unless ($title and @rows) {
    print STDERR <<EOUSAGE;
USAGE: $0 [source html]

$0 will read the given file, or STDIN for selenium HTML, 
as generated by Selenium Recorder.

The output will be selenium wiki syntax, compatible with
selenium-regen.

Example:

  $0 foo.html > foo.wiki

EOUSAGE
}

print "| $title |\n";
foreach my $r (@rows) {
    print "| ", join(' | ', @$r), " |\n";
}

sub parse_row {
    my ($cmd, @opts);
    my $row = '';
    while (<>) {
        $row .= $_;
        last if m#^</tr>#;
        if (m#\s*<td>([^<]+)</td>#) {
            if (defined $cmd) {
                push @opts, $1;
            }
            else {
                $cmd = $1;
            }
            next;
        }
    }
    unless (defined $cmd and @opts) {
        warn "Could not parse row: $row\n";
        return;
    }
    return [ $cmd, @opts ];
}
