use strict;
use warnings;
use PDL::Doc;
use Getopt::Std;
use Config;
use Cwd;

require PDL; # always needed to pick up PDL::VERSION

our $opt_v = 0;

getopts('v');
my $dirarg = shift @ARGV;
my $outdb  = shift @ARGV;
my $outindex  = shift @ARGV;

unless (defined $dirarg) {
	($dirarg = $INC{'PDL.pm'}) =~ s/[\/\\]*PDL\.pm$//i;
	if ($dirarg =~ /^blib/) { $dirarg .= ",blib/script,blib/lib/Inline" }
	umask 0022;
	print "DIR = $dirarg\n";
}
my @dirs = split /,/,$dirarg;
unless (defined $outdb) {
	$outdb = "$dirs[0]/PDL/pdldoc.db";
	print "DB  = $outdb\n";
}

unlink $outdb if -e $outdb;
my $onldc = PDL::Doc->new;

foreach my $dir (@dirs) {
    $onldc->scantree($dir =~ /script|Inline$/ ? $dir : $dir."/PDL",$opt_v);
    $onldc->scan($dir."/PDL.pm",$opt_v) if (-s $dir."/PDL.pm");
}

print STDERR "saving...\n";
$onldc->savedb($outdb);
my @mods = $onldc->search('module:',['Ref'],1);
my @mans = $onldc->search('manual:',['Ref'],1);
my @scripts = $onldc->search('script:',['Ref'],1);
my $outdir = "$dirs[0]/PDL";
# ($outdir = $INC{'PDL.pm'}) =~ s/\.pm$//i;
$outindex="$outdir/Index.pod" unless (defined $outindex);
unlink $outindex if -e $outindex;  # Handle read only file
open my $podfh, ">", $outindex or die "couldn't open $outindex: $!";
my $pod;

$pod = <<'EOPOD';

  =head1 NAME

  PDL::Index - an index of PDL documentation

  =head1 DESCRIPTION

  A meta document listing the documented PDL modules and
  the PDL manual documents

  =head1 PDL manuals

EOPOD
$pod =~ s/^  //gm;
print $podfh $pod;

print $podfh "=over 4\n\n";
for (@mans) {
  my $ref = $_->[2]->{Ref};
  $ref =~ s/Manual:/L<$_->[0]> -/;
  print $podfh "=item *\n\n$ref\n\n";
}

$pod = <<'EOPOD';
  =back

  =head1 PDL scripts

EOPOD
$pod =~ s/^  //gm;
print $podfh $pod;

print $podfh "=over 4\n\n";
for (@scripts) {
  my $ref = $_->[2]->{Ref};
  $ref =~ s/Script:/L<$_->[0]> -/;
  print $podfh "=item *\n\n$ref\n\n";
}

$pod = <<'EOPOD';
  =back

  =head1 PDL modules

EOPOD
$pod =~ s/^  //gm;
print $podfh $pod;

print $podfh "=over 4\n\n";
for (@mods) {
  my $ref = $_->[2]->{Ref};
  next unless $_->[0] =~ /^PDL|Inline::Pdlpp/;
  $ref =~ s/Module:/L<$_->[0]> -/;
  print $podfh "=item *\n\n$ref\n\n";
}

$pod = <<EOPOD;
  =back

  =head1 HISTORY

  Automatically generated by scantree.pl for PDL version $PDL::VERSION.

EOPOD
$pod =~ s/^  //gm;
print $podfh $pod;

close $podfh;

#add the newly-created PDL::Index to the doc database
$onldc->scan($outindex,$opt_v) if (-s $outindex);
$onldc->savedb($outdb);
1;
