#!/usr/bin/perl 

use Getopt::Std;
getopt ('rn:');

unless ($opt_r) {
		while (<>) {
			last if /^\s*$/ || ($opt_n && !/^$opt_n/);
			chomp;
			push @synopsis, $_; # header synopsys
		}

		if (!/^\s*$/) {
			chomp;
			push @name, $_;
			while (<>) {
				last if /^\s*$/;
				chomp;
				push @name, $_; # header name
			}

			$name = join (' ', @name);
		}

		$name = pop @synopsis if !$name;
		$name = "$opt_n - \l$name" if $opt_n;

		print <<HEAD;

=head1 NAME

$name

=head1 SYNOPSIS

HEAD

		print $_, "\n\n" for @synopsis;
		print "\n";

		$head = "DESCRIPTION";
}

$head_printed = 0;
$in_list = 0;

while (<>) {
	if (/^\s*$/) {
		if ($in_list) {
			$in_list = 0;
			print "\n=back\n\n";
		}
		print "\n\n";
		next;
	}
	chomp;

	if (/^([[:upper:]]{2,}\w+):?\s*$/) {
		# section
		$head = $1;
		$head_printed = 0;
	} else {
		if (!$head_printed) {
			$head_printed = 1;
			print "\n=head1 $head\n\n";
		}
		if (!/^(?:\t| {2}| {4})[#\$]/) {
				if (/^
						(?:\t{1,2}|\s{2}(?!\w)|\s{4}|\s{8})
						(?:
							(?: ([-*])\s+ | (\d)[.)]?\s* | (.+?)\s{2,} ) (.*)
							|(-\w+\s+\w+)
						)
					/x) {
					# list of items/options

					$i = $1 || $2 || $3 || $5;
					if (!$i && $in_list) {
						$i = $4;
						$j = "";
					} else {
						$j = $4;
					}
					if (!$in_list) {
						$in_list = 1;
						$over = 4;
						$over = 8 if /\t\t| {8}/;
						print "\n=over $over\n";
					}
					if ($i) {
						if ($i eq '-') {
							$i = '.';
						} else {
							$i = "B<< $i >>";
						}
						print "\n=item $i\n\n";
						$_ = $j;
					}
				} elsif ($in_list) {
					if (/^\s\s(\S.*)$/) {
						print "\n=item B<< $1 >>\n\n";
						$_ = "";
					} elsif (/^\s{4}(.*)/) {
						$_ = $1;
					}
				}
		}

		s/^\s*//;

		if (!/^[#\$]/ || $in_list) {
			s/ (
				(?<![^\s'"`]) [[:upper:]]{2,}
				(?:
					[[:upper:]]+ \w*
					|[-\d]
					|\s+ (?= [[:upper:]] | \d )
				)*
               )
			\b /I<< \1 >>/gx; #names
			s/ (?<![\w\d]) (-\w+) /B<< \1 >>/gx; #options
		} elsif (!$in_list) {
			s/(.*)/ \1/; # quoted text
		}

		print $_, "\n";
	}
}

