#-*- mode: perl; perl-indent-level: 4; cperl-indent-level: 4 -*-
#
# Subroutines for converting R documentation into HTML, LaTeX, Nroff
# and R (Examples) format
#
# Copyright (C) 1997 Friedrich Leisch
# Modifications for Windows (C) 1998, 1999 B. D. Ripley
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	See the GNU
# General Public License for more details.
#
# A copy of the GNU General Public License is available via WWW at
# http://www.gnu.org/copyleft/gpl.html.	 You can also obtain it by
# writing to the Free Software Foundation, Inc., 59 Temple Place,
# Suite 330, Boston, MA  02111-1307  USA.
#
# ${R_HOME}/bin/build-help
# Usage:  build-help [options]  [pkg] [lib]
# Install all help files for package pkg to library lib
# (defaults are `${R_HOME}/src/library/base' and the default library,
#  `${R_HOME}/library', respectively).

use File::Basename;
use Cwd;
use Getopt::Long;

fileparse_set_fstype; # Unix, in case one gets anything else.
$OSdir = "windows";


@knownoptions = ("rhome:s", "html", "nroff", "latex", "example", "debug",
		 "dosnames", "htmllists", "chm");
GetOptions (@knownoptions) || usage();

$cwd=getcwd();
if($opt_rhome){
    $R_HOME=$opt_rhome;
    print STDERR "R_HOME from --rhome: `$R_HOME'\n" if $opt_debug;
}
# removed, as getting this set wrong caused havoc.
#elsif($ENV{"R_HOME"}){
#    $R_HOME=$ENV{"R_HOME"};
#    print STDERR "R_HOME from ENV: `$R_HOME'\n" if $opt_debug;
#}
else{
    chdir(dirname($0) . "/../../..");
    $R_HOME=getcwd();
    print STDERR "R_HOME: `$R_HOME'\n" if $opt_debug;
}
$R_HOME =~ s+\\+/+g; # Unix-style path

require "$R_HOME/etc/Rdconvlib.pl";
require "$R_HOME/etc/buildlib.pl";

chdir($cwd);
print STDERR "Current directory (cwd): '$cwd'\n" if $opt_debug;

$tmpdir=$ENV{"TEMP"};
if(!$tmpdir) {
    if ($^O eq "Unix") {$tmpdir = "/tmp";}
    else {$tmpdir = "c:/windows/temp";}
}
$tmpdir =~ s+\\+/+g;
#print "temp=$temp\n";
-d $tmpdir  or die "TEMP is set to `$tmpdir' which is not a directory\n";

# if option --htmllists is set we only rebuild some list files and
# exit

if($opt_htmllists){
    build_htmlpkglist("$R_HOME/library");

    %anindex = read_anindex("$R_HOME/library");
    %htmlindex = read_htmlindex("$R_HOME/library");

    build_htmlfctlist("$R_HOME/library");

    exit 0;
}

# default is to build all documentation formats
if(!$opt_html && !$opt_nroff && !$opt_latex && !$opt_example && !$opt_chm){
    $opt_html = 1;
    $opt_nroff = 1;
    $opt_latex = 1;
    $opt_example = 1;
    $opt_chm = 1;
}

($pkg, $lib, @mandir) = buildinit();
$dest = "$lib/$pkg";
print STDERR "Destination `dest'= `$dest'\n" if $opt_debug;

if($opt_chm) {
    $chmdir = "../chm";
    mkdir($chmdir, 755);
    open_hhp($pkg);
}
build_index();

if($opt_chm) {build_chm_toc();}

if ($opt_latex) {
    $latex_d="$dest/latex";
    mkdir "$latex_d", $dir_mod || die "Could not create $latex_d: $!\n";
}
if ($opt_example) {
    $Rex_d="$dest/R-ex";
    mkdir "$Rex_d", $dir_mod || die "Could not create $Rex_d: $!\n";
}

print " >>> Building/Updating help pages for package `$pkg'\n";
print "     Formats: ";
print "text " if $opt_nroff;
print "html " if $opt_html;
print "latex " if $opt_latex;
print "example " if $opt_example;
print "chm " if $opt_chm;
print "\n";


# get %htmlindex and %anindex

%anindex = read_anindex($lib);
if($opt_html){
    %htmlindex = read_htmlindex($lib);
    build_htmlfctlist($lib);
} elsif ($opt_chm) {
    %htmlindex = read_htmlindex($lib);
}

format STDOUT =
  @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< @<<<<<< @<<<<<< @<<<<<< @<<<<<< @<<<<<<
  $manfilebase, $textflag, $htmlflag, $latexflag, $exampleflag, $chmflag
.

foreach $manfile (@mandir) {
    if($manfile =~ /\.[Rr]d$/) {
	$manfilebase = basename($manfile, (".Rd", ".rd"));
	$manage = (-M $manfile);

	$textflag = $htmlflag = $latexflag = $exampleflag = $chmflag = "";

	if($opt_nroff){
	    my $targetfile = $filenm{$manfilebase};
	    $destfile = "$dest/help/$targetfile";
	    if(fileolder($destfile, $manage)) {
		$textflag = "text";
		$tmpfile = "$tmpdir/nr1";
		$tmp2 = "$tmpdir/nr2";
		Rdconv($manfile, "nroff", "", "$tmpfile", $pkg);
# Unix needs / : some Win32 Perls need \
		if(!($^O eq "Unix")) {
		    $tmp2 =~ s+/+\\+g;
		}
		$cmd = "tbl $tmpfile | troff -Tlatin1 -ms | grotty -buo > $tmp2";
		system("$cmd") ==0 or die "cannot execute nroff cmd\n";
		unlink($tmpfile);
		open hlpfile, "<$tmp2" || die "Couldn't open '$tmp2'\n";
		open dest, ">$destfile" || die "Couldn't open '$destfile'\n";
		$keep = $/; undef $/;
		while (<hlpfile>) {
		    s/\xAD/-/go;	    # ISO Latin hyphen to -
		    s/\n*$/\n\n/s;          # remove all trailing blank lines
		    s/\n\s*\n\s*\n/\n\n/sg; # convert two blank lines into one
		    print dest $_;
		}
		$/ = $keep;
		close hlpfile;
		close dest;
		unlink($tmp2);
	    }
	}

	if($opt_html){
	    my $targetfile = $filenm{$manfilebase};
	    $misslink = "";
	    $destfile = "$dest/html/$targetfile.$HTML";
	    if(fileolder($destfile,$manage)) {
		$htmlflag = "html";
		print "\t$destfile" if $opt_debug;
		Rdconv($manfile, "html", "", "$destfile", $pkg);
	    }
	}

	if($opt_chm){
	    my $targetfile = $filenm{$manfilebase};
	    $misslink = "";
	    $destfile = "../chm/$targetfile.$HTML";
	    print hhpfile "$targetfile.$HTML\n";
	    if(fileolder($destfile,$manage)) {
		$chmflag = "chm";
		print "\t$destfile" if $opt_debug;
		Rdconv($manfile, "chm", "", "$destfile");
	    }
	}

	if($opt_latex){
	    my $targetfile = $filenm{$manfilebase};
	    $destfile = "$dest/latex/$targetfile.tex";
	    if(fileolder($destfile,$manage)) {
		$latexflag = "latex";
		Rdconv($manfile, "latex", "", "$destfile");
	    }
	}
	if($opt_example){
	    my $targetfile = $filenm{$manfilebase};
	    $destfile = "$dest/R-ex/$targetfile.R";
	    if(fileolder($destfile,$manage)) {
		Rdconv($manfile, "example", "", "$destfile");
		if(-f$destfile) {$exampleflag = "example";}
	    }
	}

	write if ($textflag || $htmlflag || $latexflag || 
		  $exampleflag || $chmflag);
	print "     missing link(s): $misslink\n" 
	    if $htmlflag && length($misslink);
    }
}

sub usage {

    print "Usage:  build-help [--rhome dir] [--html] [--nroff] [--latex]\n" .
      "                   [--example] [--dosnames] [--htmllists] [--debug]\n" .
      "                   [pkg] [lib]\n";

    exit 0;
}

sub open_hhp {
    my $pkg = $_[0];

    open hhpfile, ">../chm/$pkg.hhp" 
	|| die "Couldn't open the chm project file\n";
    print hhpfile "[OPTIONS]\n", "Auto Index=Yes\n",
    "Contents file=$pkg.toc\n",
    "Compatibility=1.1 or later\n",
    "Compiled file=$pkg.chm\n",
    "Default topic=00Index.html\n",
    "Display compile progress=No\n",
    "Full-text search=Yes\n",
    "Full text search stop list file=..\\..\\..\\gnuwin32\\help\\R.stp\n",
    "\n\n[FILES]\n00Index.html\n";
}


sub build_chm_toc {
    open tocfile, ">../chm/$pkg.toc"
	|| die "Couldn't open the chm toc file";
    print tocfile
	"<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML//EN\">\n",
	"<HEAD></HEAD><HTML><BODY>\n<UL>\n";
    print tocfile
	"<LI> <OBJECT type=\"text/sitemap\">\n",
	"<param name=\"Name\" value=\"Package $pkg:  Contents\">\n",
	"<param name=\"Local\" value=\"00Index.html\">\n",
	"</OBJECT>\n";
    print tocfile
	"<LI> <OBJECT type=\"text/sitemap\">\n",
	"<param name=\"Name\" value=\"Package $pkg:  R objects\">\n",
	"</OBJECT>\n";
    print tocfile "<UL>\n";   # contents of a book
    foreach $alias (sort foldorder keys %aliasnm) {
	print tocfile
	    "<LI> <OBJECT type=\"text/sitemap\">\n",
	    "<param name=\"Name\" value=\"$alias\">\n",
	    "<param name=\"Local\" value=\"$aliasnm{$alias}.html\">\n",
	    "</OBJECT>\n";
    }
    print tocfile "</UL>\n";  # end of a book
    print tocfile
	"<LI> <OBJECT type=\"text/sitemap\">\n",
	"<param name=\"Name\" value=\"Package $pkg:  Titles\">\n",
	"</OBJECT>\n";
    print tocfile "<UL>\n";   # contents of a book
    foreach $title (sort foldorder keys %title2file) {
	print tocfile
	    "<LI> <OBJECT type=\"text/sitemap\">\n",
	    "<param name=\"Name\" value=\"$title\">\n",
	    "<param name=\"Local\" value=\"$title2file{$title}.html\">\n",
	    "</OBJECT>\n";
    }
    print tocfile "</UL>\n";  # end of a book
    print tocfile "</UL>\n</BODY></HTML>\n";
    close tocfile;
}

