#!/usr/bin/perl

use strict;

use Pod::Html;

my $base = "doc/";
#chdir $base;

foreach ( qw( amfch 
              lib/AMF/Parser.pm lib/AMF/Record.pm 
              lib/AMF/AdjContainer.pm
              lib/AMF/2ReDIF.pm ) ) {
  my $file = $_;
  my $name = $file;

  if ( $file =~ m!lib/(.+)\.pm$! ) {
    $name = $1;

  } elsif ( $file =~ m!(.+)\.pl$! ) {
    $name = $1
  } else {
    $name = $_;
  }

  my $page = join '', $base, $name, ".html";
  my $pagedir;

  if ( $name =~ m!/! ) {
    my @elem = split '/', $name;
    pop @elem;
    $pagedir = join '/', @elem;
    force_dir( $base, $pagedir );
  } else { 
    $pagedir = '';
  }

#  print "page: $name, file: $page, dir: $pagedir\n";

  my @para = (
              "--infile=$file", 
              "--outfile=$page", 
#              "--htmldir=HTMLROOT",
              "--htmlroot=HTMLROOT",
#              "--podroot=.",
              "--podpath=."
             );

  print join ' ', @para;
  print "\n";

  pod2html( @para );

  if ( open FILE, $page ) {
    my $text = join '', <FILE>;
    close FILE;


    $text =~ s! href="HTMLROOT/\./doc/([^"]+)"! 
      " href=\'" . get_relative( $pagedir, $1 ) . "'" !ge;

    $text =~ s! href="HTMLROOT/\./lib/([^"]+)"! 
      " href=\'" . get_relative( $pagedir, $1 ) . "'" !ge;

    $text =~ s!<a href="HTMLROOT/([^"]+)">([^>]+)</a>!$2!g;


    open FILE, ">$page";
    print FILE $text;
    close FILE;
  }

}

sub p { print @_, "\n"; }

sub get_relative {
  my $from = shift;
  my $dest = shift;

#  p "linking from $from to $dest";

  my $link = '';

  my @fdirs = split '/', $from;
  my @ddirs = split '/', $dest;

  $link = pop @ddirs;
  my $prefix = '';

  my $from_level = scalar @fdirs;
  my $dest_level = scalar @ddirs;

  my $common = '';
  my $cnt = 0;
  

  ### count common steps
  while ( 1 ) {
    if ( $cnt > $#ddirs ) { last; }

    if ( $ddirs[$cnt] ne $fdirs[$cnt] ) { last; }
      
    $common .= $ddirs[$cnt] . "/";
#   p "$ddirs[$cnt] part is common";

    $cnt++;
  }


  ### count steps up
#  if ( length( $common ) < length( $from ) ) {
  if ( $from_level > $cnt ) {
    $prefix = "../" x ($from_level-$cnt);    
  }

  while ( $cnt <= $#ddirs ) { 
    $prefix .= $ddirs[$cnt] . "/";
    $cnt++;
  }
      
  return "$prefix$link";
}


sub force_dir {
  my $base = shift;
  my $dir  = shift;
  
  $base =~ s+/$++g;
  $dir  =~ s+^/|/$++g;
  
  my @dirs = split '/', $dir;

  foreach ( @dirs ) {
    $base .= '/' . $_;
    next if -d $base;
    mkdir $base or die "can't create '$base' dir";
  }
}
