#!/usr/bin/env perl
# Convert a subset of nroff markup (phw's style, pretty much) to MoinMoin wiki
# markup.
use strict;

$/ = undef;
$_ = <>;

my @hs = ();
sub header ($$) {
	my ($level, $text) = @_;

	if ($level > scalar(@hs)) {
		push @hs, 0;
	} elsif ($level < scalar(@hs)) {
		pop @hs;
	}
	@hs[-1] += 1;

	my $e = "=" x ($level + 1);
	my $pos = join(".", @hs);
	return "\n[[Anchor(sec$pos)]]\n$e $pos. $text $e";
}

s/^\.\\".*$//mg;
s/^\.NH (\d+)\n(.*?)$/header($1, $2)/meg;
s/^\.LP$//mg;
s/^\.bp$//mig;
s/^\.DS$/{{{/mg;
s/^\.DE$/}}}/mg;
s/\\s-1\\&\\f\(CR(.*?)\\fR\\s\+1/{{{$1}}}/gs;
s/\\s-1\\&\\f\(CO(.*?)\\fR\\s\+1/''$1''/gs;
s/\\fH(.*?)\\f[RP]/$1/gs;
s/\\fI(.*?)\\f[RP]/''$1''/gs;
s/\\fB(.*?)\\f[RP]/'''$1'''/gs;
s/\\\(em/&mdash;/g;
s/\\\(\*b/&#x03B2;/g;
s/\\\(\*l/&#x03BB;/g;
s/\\\(\*p/&#x03C0;/g;

s/^\\fR//mg;

s/{{{\s*{{{/\n\n{{{/g;
s/}}}\s*}}}/}}}\n\n/g;
s/\n\n+/\n\n/g;

print;
