#!/usr/bin/perl -w
# ./debian/generate-man
# Generate a manual page for DS9 from HTML documentation.
# This is a work of Justin Pryzby during the year of 2005, 
# patched by Ole Streicher 2012, hereby placed into the public domain.

use strict;

my $s=`html2text ds9/doc/ref/command.html |grep -Ev '^ *\\* \\[[0-9]+\\]'` || die;

my @opts=split("\n", `fgrep "<a href=\\"#" ds9/doc/ref/command.html | cut -d\\# -f2|cut -d\\" -f1` || die);

print <<EOF;
.TH DS9 1 "03 Jul 2012"
.SH NAME
ds9 \- image tool for astronomy
.SH SYNOPSIS
.B ds9
.RI [ options ]
.br
.SH DESCRIPTION
.B DS9
DS9 is the modern image tool used by astronomers for visualization of
astronomical data.  It supports a plethora of command line options,
which may be used in a script\-like fashion.  An instance of the
program is entirely controllable from the commandline with the XPA
tools.

.SH OPTIONS
.TP

EOF
$s=~s/zoom/THE_START/s;
$s=~s/.*THE_START//s;

foreach my $opt (@opts) {
	chomp $opt;
	$opt=~s/[ 	]*$//;

	$s=~m/(\n[ 	]*$opt[	 \n].*)/s || next;
	my $optinfo=$1;

	foreach my $opt2 (@opts) {
		chomp $opt2;
		$opt2=~s/[ 	]$//;
		next if $opt2=~m/^$opt$/;
		$optinfo=~s/\n[	  ]*$opt2[ \n	]*.*$//s;
	}

	$optinfo=~s/$opt//s;
	$optinfo=~s/[	  ]+/ /sg;

	print "\n.TP";
	print "\n.BR \\-$opt\n";

	$optinfo=~s/^[ 	\n]*//s;
	$optinfo=~s/\n+/\n/sg;
	$optinfo=~s/Syntax:/\n.RS 4\n.B Syntax\n.RS 4/sg;
	$optinfo=~s/Example:/\n.RE\n.RE\n.RS 4\n.B Example:\n.RS 4/sg;
	$optinfo=~s/\$(ds9.*?)\n/\n.RS 0\n$1\n.RE\n/gs;
	$optinfo=~s/\$(ds9.*?)$/\n.RS 0\n$1\n.RE\n/gs;

	# Workaround
	$optinfo=~s/-/\\-/gs;
	$optinfo=~s/([|,>\]])/$1 /gs;
	$optinfo=~s/\\\$/\$/gs;

	print "$optinfo";
	print "\n.RE\n.RE\n\n";
}

print <<EOF;
.SH FILES
The complete text of the DS9 manual may be found on Debian systems at
/usr/share/doc/saods9/ref/.

.SH AUTHOR
DS9 is a product of the Smithsonian Astrophysical Observatory.

.PP
This manual page was generated from the DS9 HTML documentation by a
script written by Justin Pryzby and Ole Streicher.

.SH "SEE ALSO"
.IR xpaget (1),
.IR xpaset (1),
.IR xpaaccess (1),
.IR xpamb (1),
.IR xpainfo (1),
.IR xpans (1),
.IR xpachanges (7),

EOF
