#!/usr/bin/perl

use strict;

my $file;
my @block = ();	# all blocks to documentate

while (<>) {
	s/\n$//;
	$file = $_;
	my $line = 0;

	my $have_block = 0;
	my $first_lines = 0;
	my $par_started = 0;
	my $first_par = 0;
	my $head = "";	# block header
	my $def = "";	# defined at ...
	my $desc = "";	# block description

	open IN, "<$file";

	while (<IN>) {
		# prepare line
		$line++;
		s/^[\t ]*//;
		s/[ \t\n]*$//;
		
		# check for starting line
		if (not $have_block and /^\/\*MSG\*/) {
			s/^\/\*MSG\*[ \t]+//;
			$head = "$_\n";
			$def = "Defined in $file (line $line).\n";
			$desc = "";
			$have_block = 1;
			$par_started = 0;
			$first_par = 1;
		}

		# check for ending line -- print block
		elsif ($have_block and /^\*\/$/) {
			@block = (@block, ".P\n.P\n.B $head.RS\n$desc.P\n$def.RE\n");
			$have_block = 0;
		}

		# empty lines
		elsif ($have_block and /^\*$/) {
			$par_started = 1;
		}
		
		# description
		elsif ($have_block and /^\*[ \t]*/) {
			s/^\*[ \t]*//;
			$desc = "$desc.P\n" if $par_started;
			$desc = "$desc.I " if $first_par;
			$desc = "$desc$_\n";
			$first_par = 0;
			$par_started = 0;
		}
	}
	close IN;
}

# print everything
print <<eof;
.TH NETBOARD-MESSAGES 1

.SH NAME
Netboard messages

.SH DESCRIPTION

Every part and backend of Netboard uses messages to comunicate each other. This
document describes
.B all
messages that Netboard GUI understands and/or produces.

Hint: GUI can show communication in real time. Try to enable logging in
configuration menu.
eof
foreach (sort @block) {
	print;
}
print <<eof;

.SH SEE ALSO

Netboard's homepage:
.BR http://jk.myserver.cz/programy/netboard/

eof

