#!/usr/bin/perl -w

use strict;

sub add_indent { local $_ = shift; s/^ /  /mg; $_ }

print <<EOP;
=head1 NAME

Term::GnuplotTerminals - documentation of C<gnuplot> output devices

EOP

for my $file (sort <gnuterm/term/*.trm>) {
  open F, $file or die "Cannot open '$file': $!";
  my $name;
  while (<F>) {
    $name = $1, last if /^\s*START_HELP\s*\(\s*(.*?)\s*\)/;
  }
  my $got = "";
  my $finished = 0;
  while (<F>) {
    # last if /^\s*(END_HELP\s*\(|\#\s*endif)/;	# Malformed: mac
    $finished = 1, last if /^\s*(END_HELP\s*\()/;	# Malformed: mac
    $got .= $_;
    # print "$file: $_"
  }
  close F or die "Cannot close '$file': $!";

  $got or warn("No docs found in '$file'\n");
  $got or next;
  $finished or warn("No end of docs found in '$file'\n");
  $got .= ",";

  # Some chunks may be surrounded by #ifdefs.  Keep them...
  $got =~ s/^(\s*#\s*(if\w*|else|elif|endif)\b.*)/"",\n"  $1",\n"",/gm;

  # Sometimes there is a leading ,
  $got =~ s/^\s*,\s*//gm;

  my $help = "";
  $help .= "$1\n"
    while $got =~ s!\A\s*(?:/\*.*?\*/\s*)*\"(((?>[^\"\\]+)|\\[\\\"])*)\"\s*(,\s*|$)!!sm;
  $got and warn("Malformed docs in '$file':\n$got\n");

  $help =~ s/\\([\\\"])/$1/g;
  $help =~ s/^\t/        /mg;		# Do not like leading TABs

  # Interchange #if and the section
  $help =~ s/(?:\A|\n)\n[ \t]+#\s*(if.*)\n{2,}(\d+[ \t]+.*\n)/\n\n$2\n\n  #$1\n\n/mg;

  # First line = level name, then lines starting with '?', then text
  my @help = split /^(?>(\d+)(?>\s+)(.+))\n(\n\s+#\s*if.*\n+)*(?:\?(?>.*)\n)+/m, $help;
  $help[0] eq '' or warn "Malformed leader of help in '$file': '$help[0]'\n";
  shift @help;

  while (@help) {
    my ($level, $name, $ifdef, $text) = (shift @help, shift @help, shift @help, shift @help);
    $ifdef = '' unless defined $ifdef;
    $text = "$ifdef$text";
    # Process tables:
    $text =~ s/
               ^\@start\s+table\b(?>.*)\n	# First line
               ((?>((\ (?>.*)|)\n)*))		# Interactive form
               [\s\S]*?				# Skip to the ...
	       ^\@end\s+table\b.*		# Last line
              /add_indent($1)/mgxe;
    # Remove extra indentations
    $text =~ s/^ //mg;

    # Remove empty #if's
    $text =~ s/(\A|\n)\n[ \t]+#\s*(if.*)\n{2,}( +#[ \t]*endif\b.*\n)/\n\n/mg;

    # Add an extra newline on boundary of indented/non-indented text
    $text =~ s/^(\S(?>.*)\n) /$1\n /mg;
    $text =~ s/^( (?>.+)\n)(\S)/$1\n$2/mg;
    # Actual pages have a lot of `foo: <bar>`, we do not translate them correct
    # Need to handle `foo` `bar\nbaz` `bar` correctly, thus anchor at paragraph
    1 while $text =~ s/
			^(?<![^\n]\n)(?=\S)	# Start of text paragraph
			((?:.|\n(?!\n))*?)	# Some part of text paragraph
			`([\s\S]*?)`		# Possibly multiline
		      /${1}C<$2>/mgx;
    print <<EOP;
=head$level $name

$text


EOP
  }
}

print <<EOP;
=head1 AUTHOR

Autogenerated from F<*.trm> files in C<gnuplot> terminals subdirectory by

  $0 > GnuplotTerminals.pod

=head1 SEE ALSO

L<Term::Gnuplot>.

EOP

