#!/usr/bin/perl -s

$attribs = 'border=1';

$tbc = 'tsv2html';	$thc = "${tbc}_th";
$trc = "${tbc}_tr";	$tdc = "${tbc}_td";

# tsv2html - filter tab-separated text into an HTML table
# Steve Kinzler, steve@kinzler.com, Mar 07/Jun 17
# https://kinzler.com/me/home.html#unix

die "usage: $0 [ -m ] [ -n ] [ -r ] [ -R ] [ -c ]
       [ -C ] [ -l ] [ -L ] [ file ... ]
	-m	hyperlink common URLs in the data
	-n	substitute any literal '\\n' in the data to '<br>'
	-r	highlight the first row as titles
	-R	highlight the second row as titles
	-c	highlight the first column as titles
	-C	highlight the second column as titles
	-l	remove := labels on each field value
	-L	highlight first row := labels as a new title row\n" if $h;

print "<table class=\"$tbc\"", $attribs ? ' ' : '', "$attribs>\n";
while (<>) {
	chop;
	@_ = split(/\t/);
	if ($L && $. == 1) {
		print "<tr class=\"$trc\">";
		foreach (@_) {
			$lbl = /(.*):=/ ? $1 : '';
			print "<th class=\"$thc\">", &htmlencode($lbl),
			      "</th>";
		}
		print "</tr>\n";
	}
	print "<tr class=\"$trc\">";
	$rtd = ($r && $. == 1 || $R && $. == 2) ? 'th' : 'td';
	$i   = 0;
	foreach (@_) { $i++;
		s/.*:=// if $l;
		$td = ($c && $i == 1 || $C && $i == 2) ? 'th' : $rtd;
		print "<$td class=\"", ($td eq 'th') ? $thc : $tdc, '">',
		      &htmlencode($_), "</$td>";
	}
	print "</tr>\n";
}
print "</table>\n";

###############################################################################

sub htmlencode {
	local($in) = join('', @_); local(@out) = ();
	if ($m) {
	    while ($in =~ s,(.*?(\\n|\b))(https?:/[^\s'"`<>()\[\\\]{}]*),,s) {
		($_, $url) = ($1, $3); $u = $url;
		      s/&/&amp;/g;	 s/</&lt;/g;	   s/>/&gt;/g;
		$u =~ s/&/&amp;/g; $u =~ s/</&lt;/g; $u =~ s/>/&gt;/g;
		push @out, $_, ($url) ? "<a href=\"$url\">$u</a>" : ();
	    }
	}
	$in =~ s/&/&amp;/g; $in =~ s/</&lt;/g; $in =~ s/>/&gt;/g;
	$in = join('', @out, $in);
	$in =~ s/\\n/<br>/g if $n;
	$in;
}
