# Hey Emacs !  This is -*- perl -*- source code !

use SGMLS::Refs;

#$loutnsslevel=2;

sgml('start','');

sgml('start_element', sub {
    ($element,$event) = @_;
    my $name= $element->name;
    my $file= $event->file;
    my $line= $event->line;
    warn "unknown element $name at $file:$line\n" unless $unkwarndone{$name}++;
});

sgml('<DEBIANDOC>','');
sgml('<NAME>','');
sgml('<BOOK>','');
sgml('<COPYRIGHTSUMMARY>','');
sgml('<QREF>','');
sgml('<TOC>','');

my @paper = split(/\s/, `2>/dev/null paperconf -Ns`);

if ($#paper >= 0) {
    $pagespec = "
  \@PageType { $paper[0] }";

    if ($#paper > 1) {
    	$pagespec = "$pagespec \@PageWidth { $paper[1]p } \@PageHeight { $paper[2]p }";
    }
}

sgml('<TITLEPAG>', sub {
    $headinglevel= 0;
});
sgml('</TITLEPAG>', sub {
    output(
"\\documentclass[11pt,german,twoside,draft]{debiandoc}
\\renewcommand{\\DocumentTitle}{$title}
\\markboth{$title}{$title}
\\begin{document}

\\begin{titlepage}
\\begin{center}
{\\Huge \\vspace*{2ex} $title \\\\[2ex]}
");
    grep(output("{\\large $_ \\\\ }\n"), @authors);
    output("\\vspace*{1ex} $version \\\\\n") if length($version);
    output("\\vspace*{1ex} \\vfill \n \\begin{minipage}{0.9\\textwidth}\n $abstract \n\\end{minipage}\n\\vspace*{2ex} \n") if (defined($abstract));

    output("\n \\end{center}\n\\end{titlepage}\n"); 
});


sgml('end', sub {
    output("\n\\end{document}\n");
});

sgml('<TOC>', sub {
    ($element,$event) = @_;
    $tocdetail= numlevel(a('DETAIL'));
    output("\n\\setcounter{tocdepth}{1}% tocdetail=$tocdetail\n\\tableofcontents\n");
});
sgml('</TOC>', '');

sgml('<TOCENTRY>', sub {
    ($element,$event) = @_;
    $level= numlevel(a('LEVEL'));
    $tocsrid= a('SRID');
    $number= a('CHAPT').a('SECT');
    if ($level == -1) {
        output("% $number. ");
    } else {
        output("% $number. ");
    }
    $stat= 'p'; 
});
sgml('</TOCENTRY>', sub { 
    output("\n"); 
});

sub endinitial {
    return if $endinitialdone;
    if (defined($copyright)) {
	output("\\subsection*{Copyright} \n$copyright");
    }
    $endinitialdone= 1;
}

sgml('<CHAPT>', sub { my @t= @_; endinitial(); sect(-1,@t); });
sgml('<SECT>', sub { sect(0,@_); });
sgml('<SECT1>', sub { sect(1,@_); });
sgml('<SECT2>', sub { sect(2,@_); });
sgml('<SECT3>', sub { sect(3,@_); });
sgml('<SECT4>', sub { sect(4,@_); });
sub sect { ($headinglevel,$element,$event)= @_; }
sgml('<HEADING>', sub { startheading(a('SRID'),a('CHAPT').a('SECT')); });
sgml('</HEADING>', sub { endheading(); });

sub startheading {
    my ($pagemark,$number)= @_;
    output("\n") unless $stat =~ m/p/;

    $lastpagemark = $pagemark;
    if ($headinglevel < 0) {
	output ("\\chapter");
    }
    elsif ($headinglevel == 0) {
	output ("\\section");
    }
    elsif ($headinglevel == 1) {
	output ("\\subsection");
    }
    elsif ($headinglevel == 2) {
	output ("\\subsubsection");
    }
    elsif ($headinglevel == 3) {
	output ("\\paragraph");
    }
    else {
	output ("\\subparagraph");
    }
    output("{");
    $stat= 'h';
}
sub endheading {
    output("}\n");
    output("\\label{$lastpagemark}\n") if length($lastpagemark);

    $stat= '';
}

sgml('<REF>', sub {
    ($element,$event) = @_;
    $refname= a('SRID');
    odata('`');
});
sgml('</REF>', sub {
    odata("' "); output("\\vpageref{$refname}");
});

sgml('<MANREF>', sub {
    ($element,$event) = @_;
    startcourier(); odata(a('NAME').'('.a('SECTION').')'); endcourier();
});


sub startcourier {
    my ($theArg) = @_;
    output("\\texttt{");
    if (length($theArg)) {
	$theArg = sani($theArg, 0);
	output("$theArg");
    }
    $stat .= 'c';
}
   
sub endcourier {
    my ($theArg) = @_;
    $stat =~ s/.$//;
    output("}");
    output("$theArg") if length($theArg);
}

sgml('<AUTHOR>', sub { push_output('string'); $stat='d'; });
sgml('</AUTHOR>', sub { push(@authors,pop_output); });
sgml('<TITLE>', sub { push_output('string'); $stat='d'; });
sgml('</TITLE>', sub { $title= pop_output; });
sgml('<VERSION>', sub { push_output('string'); $stat='d'; });
sgml('</VERSION>', sub { $version= pop_output.''; $version =~ s/\s+$//; });
sgml('<ABSTRACT>', sub { push_output('string'); $stat='P'; });
sgml('</ABSTRACT>', sub { $abstract= pop_output; });
sgml('<COPYRIGHT>', sub { push_output('string'); $stat='P'; });
sgml('</COPYRIGHT>', sub { $copyright= pop_output; });
sgml('<DATE>', sub { chop($date= `date '+%d %B %Y'`); $date =~ s/^0//; odata($date); });

sgml('<EMAIL>', sub { startcourier(); odata('<'); });
sgml('</EMAIL>', sub { odata('>'); endcourier(); });
sgml('<TT>', sub { startcourier(); });
sgml('</TT>', sub { endcourier(); });
sgml('<FTPSITE>', sub { startcourier("ftp://"); });
sgml('</FTPSITE>', sub { endcourier("\"\""); });
sgml('<FTPPATH>', sub { startcourier(); });
sgml('</FTPPATH>', sub { endcourier(); });
sgml('<HTTPSITE>', sub { startcourier("http://"); });
sgml('</HTTPSITE>', sub { endcourier("\"\""); });
sgml('<HTTPPATH>', sub { startcourier(); });
sgml('</HTTPPATH>', sub { endcourier(); });
sgml('<PRGN>', sub { startcourier(); });
sgml('</PRGN>', sub { endcourier(); });
sgml('<EM>', sub { startitalic(); });
sgml('</EM>', sub { enditalic(); });
sgml('<VAR>', sub { startitalic(); });
sgml('</VAR>', sub { enditalic(); });

sub startitalic {
    $stat.='i';
    output("\\textit{");
}
sub enditalic {
    output("}");
    $stat =~ s/.$//;
}

sgml('<EXAMPLE>', sub {
#    finishline();
    output("\\begin{dexample}\n");
    $stat .= 'x';
});
sgml('</EXAMPLE>', sub {
    $stat =~ s/.$//;
    output("\n\\end{dexample}");
});

sgml('<LIST>', sub { startlist('Bullet',@_); });
sgml('<ENUMLIST>', sub { startlist('Enum',@_); });
sgml('<TAGLIST>', sub { startlist('Tagged',@_); });
sgml('</LIST>', sub { endlist(); });
sgml('</TAGLIST>', sub { endlist(); });
sgml('</ENUMLIST>', sub { endlist(); });

sub startlist {
    push(@ltypes,$ltype);
    ($ltype,$element,$event) = @_;
    $incompact++ if $incompact || $element->attribute('COMPACT')->type eq 'TOKEN';
    if ($incompact) { finishline(); }
    elsif ($stat =~ m/t/) { output("% startlist\n"); }
    if ($ltype ne 'Tagged') {
	if ($incompact) {
	    output ($ltype eq 'Enum' ? "\\begin{dcompenumerate}\n" : "\\begin{dcompitemize}\n");
	}
	else {
	    output ($ltype eq 'Enum' ? "\\begin{denumerate}\n" : "\\begin{ditemize}\n");
	}
    }
    else {
	output("\\begin{description}");
    }
    push(@stats,$stat);
    push(@lhadtags,$lhadtags);
    $lhadtags= 0;
}
sgml('<TAG>', sub {
    if (!$incompact && $lhadtags==2) {
        output("%<TAG>\n");
    } elsif ($lhadtags) {
        output("%<TAG>\n");
    }
    output("\\item[");
});
sgml('</TAG>', sub {
    output("%</TAG>\n");
    $lhadtags= 1;
});
sgml('<ITEM>', sub {
    if ($ltype ne 'Tagged') {
        output("\\item ");
    } else {
        output($incompact ? "] %incompact\n" : "] %!incompact\n");
    }
    $stat= 'p';
});
sgml('</ITEM>', sub {
    if ($ltype ne 'Tagged') {
        output("%\n");
    } else {
        output("%\n"); #output($incompact ? "\n}}\n" : "\n}\n");
        $lhadtags= 2;
    }
});
sub endlist {
    if ($ltype ne 'Tagged') {
	if ($incompact) {
	    output ($ltype eq 'Enum' ? "\\end{dcompenumerate}\n" : "\\end{dcompitemize}\n");
	}
	else {
	    output ($ltype eq 'Enum' ? "\\end{denumerate}\n" : "\\end{ditemize}\n");
	}
    } else {
	output("\\end{description}");
        output($incompact ? "%$incompact\n" : "%!$incompact\n");
    }
    $stat= pop(@stats);
    $lhadtags= pop(@lhadtags);
    if ($incompact) {
        $stat =~ s/^/l/;
    } else {
        $stat= 'P';
    }
    $ltype= pop(@ltypes);
    $incompact-- if $incompact;
}
    
sgml('<FOOTNOTE>', sub {
    push(@stats,$stat);
    $stat= 'p';
    output('\\footnote{');
});
sgml('</FOOTNOTE>', sub {
#    endsection();
    output('}');
    $stat= pop(@stats);
});

sgml('cdata', sub { odata($_[0]); });
sgml('sdata', sub { odata($_[0]); });

sgml('</CHAPT>', sub {
    $stat= '';
});
#sgml('</SECT>', sub { endsection(); });
#sgml('</SECT1>', sub { endsection(); });
#sgml('</SECT2>', sub { endsection(); });
#sgml('</SECT3>', sub { endsection(); });
#sgml('</SECT4>', sub { endsection(); });
#sub endsection {
#}
sub startline {
    output("%startline\n") if $stat =~ s/P/t/;
}
sub finishline {
    startline();
    output("%finishline\n") unless $stat =~ s/p/t/;
}
sgml('<P>', sub {
    output("\n%<P>\n") unless $stat =~ m/p/;
    $stat= 'p';
});
#sgml('</P>', sub {
#    $stat= ($stat =~ m/l/) ? 'l' : '';
#});
sub odata {
    ($data) = @_;
    if (m/\S/) { startline(); $stat =~ s/p/t/; }
    $_= $data;
    if ($stat =~ m/x/) {
        #s,\n, //1vx\n,g;
        output(sani($_,1));
    } else {
        s/\s+/ /g;
        output(sani($_,($stat =~ m/c[^R]*$/)));
    }
}

#sub stripws {
#    my ($in) = @_;
#print STDERR "stripws\`$in'\n";
#    $in =~ s/^\s+//; $out =~ s/\s+$//;
#}

sub a {
    my $el= $element->attribute($_[0]);
    return defined($el) ? $el->value : undef;
}

sub sani {
    my ($in,$hyphens) = @_;

    return $in if $stat =~ m/x/; # no replacement in examples

    $_ = $in;

    s/\\/\\mybackslash/g;
    s/-/--/g if $hyphens;

    # escape command characters:
    s/_/\\_/g;
    s/&/\\&/g;
    s/\#/\\\#/g;
    s/\$/\\\$/g;
    s/\%/\\\%/g;
    s/{/\\{/g;
    s/}/\\}/g;
    s/\^/\\^{}/g;
    s/~/\\~{}/g;
    s//\\copyright/g;

    #s/\"/\"\"/g; - there should be no " in the text ...

    s/\`\`/\"\`/g;
    s/\'\'/\"\'/g;

    # missing `\ ' after "xxx" ->
    s/u\.a\./u\.a\.\\ /g;
    s/etc\./etc\.\\ /g;
    s/usw\./usw\.\\ /g;
#    s/\./\.\\ /g;

    # Dots should be ellipsis "..."
    s/\.\.\./\\dots /g;

    $_;
}


sub numlevel {
    my ($d)= @_;
    return -1 if $d =~ m/^CHAPT/;
    return $1 if $d =~ m/^SECT(\d*)$/;
    warn "unknown toc detail token \`$d'\n";
}

1;
