#!/usr/bin/perl
#
# .h file on input (and name as arg), .3 file on output

use strict;
use warnings;


$_ = <STDIN>; chomp;
my ($name, $title) = (m#^/\*\* (.*?) - (.*) \*/$#);
print ".\\\"\n.\\\"\n.\\\" DO NOT MODIFY - AUTOGENERATED FROM .H FILES!\n.\\\"\n.\\\"\n";
print ".TH LIBAIO 3 2006-02-08\n";
print ".SH NAME\n";
print "$name \- $title\n";

my $descsect = 0;
my $subsect = 0;
my $preccom = 0;
my $preccod = 0;
my (@accum, @funs);
while (<STDIN>) {
	chomp;
test:
	if (m#^/\*!(.*?)\*/#) {
		$_ = $1;
		goto test;
	}

	m/^#include/ and next;
	m/^#if/ and next;
	m/^#endif/ and next;
	m/^#define.*__/ and next;
	m/^#$/ and next;

	if (m#^/\*\*\* SYNOPSIS \*/$#) {
		print ".SH SYNOPSIS\n";
		print ".B #include <libaio/$ARGV[0]>\n";
		print ".sp 1\n";
		next;
	}
	if (m#^/\*\| (.*) \*/$#) {
		$preccod and print ".br\n";
		$preccom = 0; $preccod = 1;
		print "\\fB\\fI$1\\fR\n";
		next;
	}

	if (m#^/\*([\*\+]) (.*) \*/$#) {
		$preccom = 0; $preccod = 0;
		unless ($descsect) {
			print ".SH DESCRIPTION\n";
			$descsect = 1;
		}
		$subsect = 1 + ($1 eq '+');
		print ".TP\n";
		print "\\fB$2\\fR\n";
		if ($subsect == 2) {
			print ".RS\n";
		}
		next;
	}
	s/@(\S+)\s*/\n.B $1\n/g;
	if (m#^/\* (.*)$#s) { #
		my $l = $1; $l =~ s#\*/$##;
		$preccod and print "\n";
		$preccod = 0;
		if ($subsect < 2) {
			$preccom and print ".PP\n";
			$preccom = 1;
			print "$l\n";
		} else {
			push(@accum, $l);
		}
		next;
	}
	if (m#^ \* (.*?)( \*/)?$#s) { #
		$preccod = 0;
		if ($subsect < 2) {
			print "$1\n";
		} else {
			$accum[@accum-1] .= "\n$1";
		}
		next;
	}
	if (m/^\s*$/) {
		if ($subsect == 2) {
			if (@funs == 1) {
				print ".TP\n";
				print "\\fB$funs[0]\\fR\n";
			} elsif (@funs > 1) {
				my $f = 1;
				foreach (@funs) {
					print ".TP\n";
					print "\\fB$_\\fR\n";
					if ($f) { $f = 0; print ".PD 0\n"; }
				}
				print ".PD\n";
			}
			print join("\n\n", @accum)."\n";
			@accum = @funs = ();
		}
		next;
	}

	s/;$//;
	if ($subsect < 2) {
		$preccom and print "\n";
		$preccod and print ".br\n";
		$preccom = 0; $preccod = 1;
		print "\\fB\\fI$_\\fR\n";
		next;
	} else {
		push(@funs, $_);
	}
}

print <<__EOT__ ;
.RE
.SH BUGS
None known.
.SH "SEE ALSO"
.BR libaio (7)
__EOT__
