#!/usr/bin/perl

use strict;
use warnings;
use POSIX qw(strftime);

my $depth = 0;
my $section = 1;
my $note = 1;
my $abstract = 0;
my $tag = "content000";
my $nl = 0;
my $expand = "cat";
my $last_alpha = 0;
my $file_count = 0 ;
my $date = '';
my $author = 'Dr. Who <who@who.am.i>';
my $incomment = 0;
my $o = '*';  # for Emacs default
my $title;
my $fh;
my $pre;
my %content;

use Getopt::Std;
our($opt_n, $opt_d, $opt_h, $opt_s);


getopts('ndhs:'); 

if ($opt_h) { 
print <<"EOF";
    -h for this
    -n generate new line
    -d create file for each section ( for dvd list )
    -s separator ( default '-' )
EOF
    exit;	
}
if ($opt_n) { $nl = 1; }
if ($opt_s) { $o = $opt_s; }

sub opening {
print $fh <<RogueRogue;
<html>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
RogueRogue
# <!--Æþ¸ý--->
}

sub closing {
    print $fh "</div>";
    if (!$opt_d && (keys %content) > 2) {
	print $fh "\n" if (! $nl);
#	print $fh "<h2><a name=\"content\">Content</h2>\n";
	print $fh "<ol class=\"side\">\n";
	print $fh "$title\n";
	for (sort keys %content ) {
	    print $fh "<li><a href=\"#$_\">",$content{$_},"</a>\n";
	}
	print $fh "</ol>\n";
    }

    print $fh "\n" if (! $nl);
    print $fh "<hr/> $author /  $date\n" ;
    printf $fh "</body></html>\n";
}

sub open_output {
  my ($out) = @_;
  my $arg = $out;
  $out =~ s/\.ind$//;
  $out =~ s/\.index$//;
  if ($opt_d) {
      $out .= sprintf("_%05d",$file_count++);
  }
  $out .=  ".html";
  open($fh,">",$out); 
}

sub o2html {
my($arg, $current) = @_;

$arg =~ /^(.*)\/.*?/;
my $dir = $1;
$dir = "." if (! $dir);
$incomment = 0;
$title = '';
my $section_title = '';
my $pre = '';
my $paragraph = 0;

%content = ();

&opening;

line: while (<$current>) {
    chop;	# strip record separator
    if (/^\<\!\-\-\-/) {
        $incomment = 1;
    }
    if (/-\-\-\>/) {
        $incomment = 0;
    }
    if(!/^</) {
	s/&/\&amp;/g;
	s/</\&lt;/g;
	s/>/\&gt;/g;
	s%href="([^"]+")\s*([^\s]*)%<a href="$1">$2</a>%g;
    }
    s/<image/<img/g;
    if (m/<img.*src="*([^>"\s]*)"*[^>]*>/i) {
        my $fig = $1; my $alt = $2;
        &fig($dir, $fig, $alt);
    } elsif (m/<img.*src="*([^>"\s]*)"*[^>]*alt="*([^>"]*)"*[^>]*>/i) {
        my $fig = $1; my $alt = $2;
        &fig($dir, $fig, $alt);
    } elsif (m/<center>\s*<img.*src="*([^>"\s]*)"*[^>]*alt="*([^>"]*)"*[^>]*>\s*<\/center>/i) {
        my $fig = $1; my $alt = $2;
        &fig($dir, $fig, $alt);
    } elsif (m/<center>\s*<img.*src="*([^>"\s]*)"*[^>]*>\s*<\/center>/i) {
        my $fig = $1; my $alt = $2;
        &fig($dir, $fig, $alt);
    } elsif (m/<img/) {
        print "img not matched $_";
    } elsif (m/<image/) {
        print "use <img..> img not matched $_";
    }

    if( (!/^\s/) && (!/^$/) && $pre) {
	print $fh "\n" if (! $nl || $last_alpha);
	print $fh "</pre>\n";
	$pre = 0;
    }
    if (/^\Q$o\E*input: (.*)/o) {
	open(my $fdbase,"$expand $1|") or die("can't open $!");
	# push(@depend,$1);
#	print STDOUT "$1 ";
	o2html($arg, $fdbase);
	next line;
    }
    if (/^\Q$o$o\E*title:\s*(.*)/o) {
	$title = $1; # substr($_, 8, length($_) - 7);
	&title($title);
	next line;
    }
    if (/^\Q$o$o\E*comment-begin:/o) {
	while (<$current>) {
	    next line if (/^\Q$o\E*comment-end:/) ;
	}
	last line;
    }
    if (/^\Q$o$o\E*date:/o) {
        my $tmp;
	for ($tmp = 1; substr($_, $tmp, 1) eq $o; $tmp++) {
	    ;
	}
	$tmp += 5;
        # override file date
	$date = substr($_, $tmp, length($_) - $tmp + 1);
	next line;
    }
    if (/^\Q$o$o\E*number:/o) {
#        my $tmp;
#	for ($tmp = 1; substr($_, $tmp, 1) eq $o; $tmp++) {
#	    ;
#	}
#	$tmp += 7;
#	$number = substr($_, $tmp, length($_) - $tmp + 1);
	next line;
    }
    if (/^\Q$o$o\E*note:/o) {
	$note = 2;
	print $fh "\n" if (! $nl || $last_alpha);
	printf $fh "<quote>\n";
	next line;
    }
    if (/^\Q$o$o\E*author:/o) {
        my $tmp;
	for ($tmp = 1; substr($_, $tmp, 1) eq $o; $tmp++) {
	    ;
	}
	$tmp += 7;
	$author = substr($_, $tmp, length($_) - $tmp + 1);
	print $fh "\n" if (! $nl);
	printf $fh "<author>$author</author>\n";
	
	next line;
    }
    if (/^\Q$o$o\E*abstract:/o) {
	$abstract = 1;
	print $fh "\n" if (! $nl);
	printf $fh "<quote>\n";
	next line;
    }
    if (/^\Q$o$o\E*table:\s(.*)/o) {
	my @buf = ();
	my $title = $1;
	while (<$current>) {
	    last if (/^\Q$o$o\E*table-end:/o) ;
	    push(@buf,$_);
	}
	&tab2html($title, @buf);
	last if (eof);
	next line;
    }
    if (/^\Q$o\E/o) {
        next line if ($incomment);
        if ($opt_d) {
	    &closing;
	    &open_output($arg);
	    &opening;
        }
	if ($abstract == 1) {
	print $fh "\n" if (! $nl);
	    printf $fh "</quote>\n";
	    $abstract = 0;
	}
	if ($note) {
	    if ($note == 2) {
	print $fh "\n" if (! $nl);
		printf $fh "</quote>\n";
	    $note = 0;
	    }
	}
	for ($depth = 1; substr($_, $depth, 1) eq $o; $depth++) {
	    ;
	}
	$section_title = substr($_, $depth, length($_) - $depth + 1);
	if(! defined($title)) {
	    &title($section_title);
	}
	print $fh "\n" if (! $nl);
	print $fh "<hr/>\n";
	print $fh "<h$depth><a name=\"",$tag, "\">",$section_title,
	      "</a></h",$depth,">\n";
	$section++;
	$content{$tag} = " " x $depth . $section_title;
	$tag++;
        if (! $title) {
            &title($section_title);
        }
	next line;
    } elsif (/^\s/) {
	if(! $pre) {
	print $fh "\n" if (! $nl);
	    print $fh "<pre>\n";
	    $pre = 1;
	}
	$paragraph = 0;
	print $fh $_,"\n";
    } elsif (/^$/) {
	if(! $pre && ! $paragraph) {
	    print $fh $_;
	    print $fh "\n" if (! $nl);
	    print $fh "<p>\n";
	    $paragraph = 1;
	}
    } elsif (/^\<a/i) {
	print $fh $_,"\n";
        next if ($incomment);
        next if (! /<\/a>/i);  # no one linier
        # add link
	$content{$tag} = " " x $depth . " * ". $_. "\n";
	$tag++;
    } elsif (!/^\Q$o\E/o) {
	print $fh "\n" if ($nl || $last_alpha);
	print $fh $_;
	$paragraph = 0;
    }
  } continue {
    $last_alpha = /[.,!?a-zA-Z0-9]$/;
  }

  &closing;
}

foreach my $arg (@ARGV) {
  open(my $fdbase,"$expand $arg | nkf -w |") or die("$arg cannot open $!");
  my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
                      $atime,$mtime,$ctime,$blksize,$blocks)
                          = stat($arg);
  die "can't open $arg" if (! defined $mtime);
  $date = strftime "%a %b %e %H:%M:%S %Y", localtime($mtime);

  &open_output($arg);
  &o2html($arg, $fdbase);
}

sub title {
	$title = $_[0];
if (! $opt_d) {
	print $fh <<"EOFEOF";
<head>
<STYLE type="text/css">
.main { width:80%; }
.side { top:0px; width:20%; position:fixed; left:80%; }
</STYLE>
EOFEOF
} else {
	print $fh <<"EOFEOF";
<head>
EOFEOF
}
	print $fh <<"EOFEOF";
<title>$title</title>
</head>
<body>
<div class="main">
<h1>$title</h1>
EOFEOF
	
}


sub tab2html {
    my ($title, @line) = @_;
    my (@array,$count, $max);

    print $fh "<table border=\"1\" cellspacing=\"0\">\n";
    print $fh "<caption>",$title,"</caption>\n";
    $max = 0;
    my $i=0;
    foreach (@line){
	next if (/^#/);
	chop;
	s/\&/\&amp;/g;
	s/\</\&lt;/g;
	s/\>/\&gt;/g;
	s/([ ]*\t)*$//;
	next if (/^\s*$/) ;
	@{$array[$i]} = split("\t");
	$count = @{$array[$i]};
	$max = ($max>$count)? $max : $count;
	$i++;
    }
    # check for colspan
    for(my  $j=0;$j<=$#array;$j++) {
	for(my $i=0;$i<$max;$i++) {
	    next if (!defined( $array[$j][$i]));
	    $_ = $array[$j][$i];
	    next if (/^\-$/);
	    next if (/^\"$/);
	    my $colspan = 1;
	    my $k = $i;
	    $colspan++ while (defined($array[$j][++$k]) && $array[$j][$k] =~ /^\-$/);
	    if ($colspan>1) {
		$array[$j][$i] = "<td colspan=$colspan>".$_."</td>\n";
	    } else {
		$array[$j][$i] = "<td>".$_."</td>\n";
	    }
	}
    }
    # check for rowspan
    for(my $i=0;$i<$max;$i++) {
	for(my $j=0;$j<=$#array;$j++) {
	    next if (!defined( $array[$j][$i]));
	    $_ = $array[$j][$i];
	    next if (/^\"$/);
	    next if (/^\-$/);
	    my $rowspan = 1;
	    my $k = $j;
	    $rowspan++ while (defined($array[++$k][$i]) && $array[$k][$i] =~ /^\"$/);
	    if ($rowspan>1) {
		$array[$j][$i] =~ s/^\<td/\<td rowspan\=${rowspan}/;
	    }
	}
    }

    for my $line (@array) {
	print $fh "<tr>";
	print $fh grep(!(/^"$/ || /^$o$/), @{$line});
	print $fh "</tr>\n";
    }
    print $fh "</table>\n";
}

sub fig
{
        my ($dir, $fig,$alt) = @_;
        $fig =~ /(.*)\..*?$/;
        my $name = $1;
# print "$dir/$name\n";
        if ( -f "$dir/$name.svg" ) {
$_ = << "EOFEOF";
<object data=\"$name.svg\" type=\"image/svg+xml\" width=\"100%\" height=\"600\"></object>
EOFEOF
        }
}

# end
