#!/usr/bin/perl -w

use Getopt::Std;
getopts('tpfln');
$texmode = $opt_t ? 1 : 0;
$parchaptitle = $opt_p ? 1 : 0;
$onelinechaptitle = $opt_l ? 1 : 0;
$convertendash = $opt_n ? 1 : 0;
$french = $opt_f ? 1 : 0;
undef $opt_t;
undef $opt_p;
undef $opt_l;
undef $opt_n;
undef $opt_f;


$tmppar = "";

sub fix_line {
  my $s = shift(@_);
  
  # Fix abbreviations
  $s =~ s/(Mr|Ms|Mrs|Dr|Prof|Rt|Hon)\. /$1.~/g;
  # Use real em-dashes
  $s =~ s/([^-])--([^-])/$1---$2/g if $convertendash;
  $s =~ s/â\x80\x93/--/g;
  $s =~ s/â\x80\x94/---/g;
  # Sometimes, underscores are used for em-dashes :(
  $s =~ s/_/---/g;

  # Thinspace before and after en-dashes
  $s =~ s/([^-]) ?-- ?([^-])/$1\\thinspace --\\thinspace $2/g;

  # Replace the non-breakable space with normal space (UTF-8 and ISO-8859)
  $s =~ s/Â\xa0/ /g;
  $s =~ s/\xa0/ /g;

  # Unicode ellipsis
  $s =~ s/ ?â\x80\xA6/.../g;
  
  # Escape pound marks
  $s =~ s/\#/\\#/g;
  
  # Escape & (disabled because of possible tex markup)
  #$s =~ s/\&/\\&/;
  
  # Process series of blanks
  $s =~ s/\s{20,}(.*)$/\\hfill $1\n/gm;
  
  sub ustosp {
    my ($s) = @_;
    $s =~ tr/_/ /;
    return $s;
   }
  # Replace _XX_XXX_  and _XX XXX_ by emphasise
  $s =~ s/(^|\W)_([^ ]+)_(\W|$)/"$1\\emph{".&ustosp($2)."}$3"/esg;
  $s =~ s/_([^_]+)_/\\emph{$1}/gs;
  $s =~ s/\("([^"]+)"\)/"\\emph{$1}"/gs;

  $s =~ s/\[([^\]]{3,})\]/\\emph{$1}/s unless $texmode;

  $s =~ s/ ?\[([^\]]{3,})\]/\\footnote{$1}/gs if $texmode;

  # Replace opening '" with ` `` before checking for single '
  $s =~ s/' ?"/'\\thinspace"/g;

  # Replace 'XYZ' with `XYZ'
  $s =~ s/([^A-Za-z0-9])'([^']+)'([ \n{\-\(\?\.,;:])/$1`$2'$3/g;
  
  # Folowing is disabled, because it messes up things like "shoot 'em up"
  # and besides, there is a low probability that a single-quoted text will
  # be spread over 2 or more paragraphs
  
  # Replace "XYZ" with ``XYZ''
  $s =~ s/"([^"]+)"/``$1''/g;
  # The next two are necessary when the double quotes are spread over 2 or
  # more paragraphs
  # Replace closing " with ''
  $s =~ s/([^ ])"([ \n}\.,;\-\)]|$)/$1''$2/g;
  # Replace opening " with ``
  $s =~ s/(^|[ \n{\-\(])"/$1``/g;

  $s =~ s/â\x80\x9C/``/g;
  $s =~ s/â\x80\x9D/''/g;

  # Ellipsis at the end of a sentence: no space before, then the final
  # punctuation mark (.,?!) (ENGLISH TYPOGRAPHY)
  $s =~ s/ ?\. \. \. ([\.,!\?])/\\el~$1/g;
  $s =~ s/ ?\.\.\. ?([\.,!\?])/\\el~$1/g;
  
  $s =~ s/ ?\.\.\. ?'/\\el\\nobreak '/g;
  $s =~ s/ ?\. \. \. '/\\el\\nobreak '/g;
  
  $s =~ s/ ?\. \. \. ?$/\\el/g;
  $s =~ s/ ?\.\.\. ?$/\\el/g;
  
  $s =~ s/ ?\. \. \. ?([A-Z`])/\\el\\ $1/g;
  $s =~ s/ ?\.\.\. ?([A-Z`])/\\el\\ $1/g;
  # Ellipsis in a sentence is preceded and followed by a thin space
  #$s =~ s/ ?\. \. \. ?/\\el\\thinspace /g;
  #$s =~ s/ ?\.\.\. ?/\\el\\thinspace /g;
  $s =~ s/ ?\. \. \. ?/\\el\\ /g;
  $s =~ s/ ?\.\.\. ?/\\el\\ /g;
  
  # Fix quotes after em-dashes
  $s =~ s/---'/---\\nobreak'/g;
  return $s;
}

sub replace_footnotes {
  my $s = shift(@_);
  return $s if $texmode;

  if (%footnotes) {
    if ($s =~ /\[([^\]]{1,2})\]/) {
      my $note = '\protect\footnote{'.$footnotes{$1}.'}';
      $s =~ s/%/%%/;
      $s =~ s/\[([^\]]{1,2})\]/%s/;
      $s = sprintf($s, $note);
    }
  }
  else {
    if (! $warned) {
      print STDERR "No footnotes, rerun\n";
      $warned = 1;
    }
  }
  return $s;
}

sub title_case {
  my $s = shift(@_);
  my $word_count = 0;
  my @words = split(/ /,$s);

  sub myuc {
    my $s = shift(@_);
    $s =~ tr/a-zàâéèêëîïôùü/A-ZÀÂÉÈÊËÎÏÔÙÜ/;
    return $s;
  }
  sub myucfirst {
    my $s = shift(@_);
    $s =~ /^([^a-zàâéèêëîïôùü]*)(.)(.*)/;
    my ($pre,$first,$rest) = ($1, $2, $3);
    $first = &myuc($first);
    return $pre.$first.$rest;
  }
  sub mylc {
    my $s = shift(@_);
    $s = lc($s);
    $s =~ tr/ÀÂÉÈÊËÎÏÔÙÜ/àâéèêëîïôùü/;
    $s =~ s/<(.)>/&myuc($1)/eg;
    return $s;
  }
  
  for my $w (@words) {
    $w = &mylc($w);
    if ($w =~ /^(\w\.)+$/) {
      $w = uc($w);
    }
    elsif ($word_count++ == 0 || $w =~ /\w\./ || $w eq "i") {
      $w = &myucfirst($w);
    }
    else { 
      $w = &myucfirst($w) if ! $french && length($w) > 2 && $w !~ /^(the|for)$/;
    }
  }
  return join(" ", @words);
}

sub process_chapter_title {
  my $text = shift(@_);
  $text =~ s/^\s+//;
  $text =~ s/\n/ /g;
  $text =~ s/^(one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty|thirty|fourty|fifty|sixty|seventy|eighty|ninety|hundred|-):?  ?//i;
  my $footnote = "";
  # Extract the footnote, if any (no support for multiple footnote in a
  # chapter title)
  if ($text =~ s/\[([^\]]{1,2})\]//) {
    $footnote = "[".$1."]";
  }
  my $toc_text = &title_case($text);
  $text = &fix_line($text);
  $text =~ s/[<>]//g;
  $toc_text = &fix_line($toc_text);
  #print STDERR "Chapter line $line\n";
  print "\n\\chapter\[$toc_text\]\{$text".&replace_footnotes("$footnote")."\}\n";
  $footnotes_mode = 0;
}

sub process_special_chapter_title {
  my $chap = shift(@_);
  my $text = shift(@_);
  $text =~ s/^\s+//;
  $text =~ s/\n/ /g;
  my $footnote = "";
  # Extract the footnote, if any (no support for multiple footnote in a
  # chapter title)
  if ($text =~ s/\[([^\]]{1,2})\]//) {
    $footnote = "[".$1."]";
  }
  my $toc_text = &title_case($text);
  $text = &fix_line($text);
  $text =~ s/[<>]//g;
  $toc_text = &fix_line($toc_text);
  #print STDERR "Chapter line $line\n";
  print "\n\\chapter*\{$chap".($text ? "\\[20pt] $text".&replace_footnotes("$footnote"):"")."\}\n";
  print "\\addcontentsline\{toc\}\{chapter\}\{$toc_text\}\n";
  $footnotes_mode = 0;
}


sub process_paragraph {
  my $l = $par;
 
  if ($l =~ /^\s*(CHAPTER )?[IVX\d]+\.?$/im) {
    print STDERR "CHAPTER\n";
    if ($parchaptitle) {
      $l =~ s/^\s*(CHAPTER )?[IVX\d]+\.?\n\s*-*\n\s*//s;
      &process_chapter_title($l);
    }
    elsif ($onelinechaptitle) {
      $l =~ s/^\s*(CHAPTER )?[IVX\d]+\.?\s*(.*)//s;
      my $title = defined $2 ? $2 : "";
      &process_chapter_title($title);
      $empty_after = 1; # Dirty hack, so that no \bigskip is added after
                        # the \chapter
    }
    else {
      $next_par_is_chapter_title = 1;
    }
  }
  elsif ($l =~ /^CHAPTER ?(.*)/im) {
    if ($onelinechaptitle) {
      &process_chapter_title($1);
      $empty_after = 1; # Dirty hack, so that no \bigskip is added after
                        # the \chapter
    }
    else {
      print STDERR "CHAPTER\n";
      &process_chapter_title("");
      $empty_after = 1; # Dirty hack, so that no \bigskip is added after
                        # the \chapter
    }
  }
  elsif ($l =~ /^EPILOGUE/im) {
    &process_special_chapter_title("EPILOGUE","");
    $empty_after = 1; # Dirty hack, so that no \bigskip is added after
                      # the \chapter
  }
  elsif ($l =~ /^AFTERMATHS/im) {
    &process_special_chapter_title("AFTERMATHS","");
    $empty_after = 1; # Dirty hack, so that no \bigskip is added after
                      # the \chapter
  }
  elsif ($next_par_is_chapter_title) {
    $next_par_is_chapter_title = 0;
    $previous_par_is_chapter_title = 1;
    &process_chapter_title($par);
  }
  # The line that starts the footnote section of a chapter says "FOOTNOTES:"
  elsif ($l =~ /^FOOTNOTES:/) {
    $footnotes_mode = 1;
    #print STDERR "Start footnode mode line $line\n";
  }
  elsif ($footnotes_mode == 1) {
    # Start a new footnote
    if($l =~ /\[Footnote (\S+): (.*)$/) {
      #print STDERR "Start footnote $1 line $line\n";
      $current_footnote = $1;
      $footnotes{$1} = &fix_line($2)." ";
    }
    # End a footnote
    elsif($l =~ /([^\]]+)\]$/) {
      $footnotes{$current_footnote} .= &fix_line($1);
      #print STDERR "End footnote $current_footnote line $line\n";
      $current_footnote = "";
    }
    # Continue a footnote
    elsif ($current_footnote ne "") {
      #print STDERR "  add footnote text line $line\n";
      $footnotes{$current_footnote} .= &fix_line($_)." ";
    }
  }
  elsif ($l =~ /^\[(\d+)\] (.*)$/s) {
    $footnotes{$1} = $2;
  }
  # Separators within a chapter
  elsif ($l eq "       *       *       *       *       *") {
      my $wspace='\hspace{1.5cm}';
      print '\bigskip

\begin{center}'.
"*$wspace*$wspace*$wspace*$wspace*".
'\end{center}
\bigskip
';
  }
  elsif ($l =~ /\* \* \*/) {
      my $wspace='\hspace{.5cm}';
      print '\bigskip

\begin{center}'.
"*$wspace*$wspace*".
'\end{center}
\bigskip
';
  }
  elsif ($l =~ /^\s*$/) {
    print "\\bigskip\n\n";
  }  
  # Normal text 
  else {
    my $foo;
    $foo = "$empty_before before" if $empty_before > 1 && ! $previous_par_is_chapter_title;
    #$foo .= ($foo ? " and ":"")."$empty_after after" if $empty_after > 1;
    print STDERR "Blank lines: $foo § '".substr($l,0,20)."...\n" if $foo;
    print "\\bigskip\n" if $empty_before > 1;
    print "\n".&replace_footnotes(&fix_line($l));
    $previous_par_is_chapter_title = 0;
  }
}

sub read_par {
  $empty_before = $empty_after;
  $empty_after = 0;

  while(<>) {
    if (/^\s*$/) {
      $empty_after ++;
      if ($accumulator ne "") {
        $tmppar = $accumulator;
        $accumulator = "";
        $empty_after = 1;
      }
    }
    else {
      $accumulator .= $_;
      if ($tmppar ne "") {
        $par = $tmppar;
        $tmppar = "";
        return 1;
      }
    }
  }
  $par = $tmppar.$accumulator;
  return 0;
}

#########################
# 
# Main
#
#########################

$footnotes_mode = 0;
$current_footnote = "";

$next_par_is_chapter_title = 0;

$empty_before = 0;
$empty_after = 0;

$cont = 1;

require "aux.pl" if -e "aux.pl";

print 
'\documentclass{romana5}
\makeatletter
\InputIfFileExists{metainfo}{}
\makeatother
\begin{document}

';
#while($cont) {
#  #$previous_par = $par;
#  $cont = &read_par();
#  &process_paragraph();
#} 
while (<>) {
  $par=$_;
  &process_paragraph();
}
print '\end{document}';

open(AUX,">aux.pl");
print AUX "\%footnotes = (\n";
foreach $k (keys(%footnotes)) {
  print AUX "\"$k\" => \"$footnotes{$k}\",\n";
}
print AUX ");\n1;\n";
close(AUX);
