#!/usr/bin/env perl
use strict;
use warnings;
use autodie;
use utf8;

use feature ':5.20';
use feature 'signatures'; no warnings qw(experimental::signatures);
use warnings FATAL => qw{ uninitialized };

use Perl6::Slurp;

my $FOUT;

################################################################

sub decideonparagraph {
  my $t= $_[0];

  ($t =~ /\s\&\s/) and return;
  $t =~ s/\\footnote\{(.*?)\}/ \[ FOOTNOTE: $1 \]/g;
  $t =~ s/\\nada\{(.*?)\}//g;
  $t =~ s/[^\\]\%.*//;  ## wipe out comments
  $t =~ s/\\ref\{.*?\}/X/g;
  $t =~ s/\~/ /g;
  $t =~ s/\\href\{(.*?)\}\{(.*?)\}/\[$2\]($1) /g;
  $t =~ s/\\emph\{(.*?)\}/*$1*/g;
  $t =~ s/\\%/%/g;
  $t =~ s/\\CO/CO/g;
  $t =~ s/\\\$/\$/g;
  $t =~ s/\\times/ x /g;
  $t =~ s/\\approx/ \~ /g;
  $t =~ s/\\text\{(.*?)\}/$1/g;

  my ($u, $l);
  $u = () = $t =~ m/\p{Uppercase}/g ;
  $l = () = $t =~ m/\p{Lowercase}/g ;

  ## print $FOUT "\t\t>>[$u,$l]  $t\n";

  ($u < 1) and return;  ## one sentence paragraphs are ok
  ($l <= 30) and return;

  print $FOUT "\n$t\n\n";
}

sub fixt { my $v= $_[0]; $v =~ s/\}.*?\\label\{.*//g; return $v; }


################################################################

foreach my $ifnm (glob("[0-2][0-9]\-*.tex")) {
  print STDERR "$ifnm\n";

  (my $ofnm = $ifnm) =~ s/\.tex$/\.txt/;
  open( my $FIN, "<", $ifnm );
  open( $FOUT, ">", $ofnm );

  my $enumi=0; my $enum=0;

  while (<$FIN>) {
    #  print STDERR "Line $.: $_\n";
    if (/^\\chapter\{(.*)\}/) {
      print $FOUT  "\n\n\n# Chapter ".fixt($1)."\n";
    } elsif (/^\\section\{(.*)\}/) {
      print $FOUT  "\n\n## Section: ".fixt($1)."\n";
    } elsif (/^\\subsection\{(.*)\}/) {
      print $FOUT  "\n\n### ".fixt($1)."\n";
    } elsif (/^\\subsubsection\{(.*)\}/) {
      print $FOUT  "\n\n### ".fixt($1)."\n";
    } elsif (s/^\s*\\item/  /) {
      if ($enum) { ++$enumi; print $FOUT "$enumi. "; } else { print $FOUT "* "; }
      decideonparagraph($_);
    } elsif (/^\s*\\begin\{enumerate\}/) {
      $enum= 1; $enumi=0;  ## bug: does not handle nesting well
    } elsif (/^\s*\\begin\{itemize\}/) {
      $enum= 0; $enumi=0;
    } elsif (/^\s*\\begin\{description\}/) {
      $enum= 0; $enumi=0;
    } elsif (/^\s*\\begin\{document\}/) {
      next;
    } elsif (/^\s*\\begin\{(.*?)\}/) {
      if (($1 eq "fig") || ($1 eq "table") || ($1 eq "figure") || ($1 eq "tabular") || ($1 eq "ctabular") || ($1 eq "fctabular") || ($1 eq "readings")) {
	print $FOUT  "\n\t[insert $1 here]\n";
	while (<$FIN>) {
	  (/\\end\{$1\}/) and last;
	}
      }
    } elsif (/^\s*\\/) {
      next;
    } else {
      decideonparagraph($_);
    }
  }

  close($FIN); close($FOUT);
  system("ls -l $ifnm $ofnm");
}
