#!/usr/bin/perl -w

use Getopt::Std;
getopts('hflds:o:', \%opt);

$DEBUG = 1 if exists $opt{d};

%fontsize = (
22 => 12,
24 => 11,
25 => 10,
31 => 9,
35 => 8,
39 => 7,
45 => 6,
);


if (($#ARGV < 0 && $opt{l}) || exists $opt{h}) {
  my $prog = `basename $0`;
  $prog =~ s/\n//;
  print STDERR "Usage:
Generate a directory tree file with:
$prog [-h] [-f]
    Prints the directory tree on stdout. Options are:
        -h       this help
        -f       list files also

Edit the file to your liking, then use:

$prog -l [-h] [-s fontsize] [-o output_file] serial_number input_file
    Prints a LaTeX file using input_file for input. Options are:
        -l             write the LaTeX file (mandatory)
        -s size        force a font size (6-12)
        -o output_file output TeX file (default: append .tex to input_file)
";
  exit 1;
}

sub clean_name {
  my $s = shift(@_);
  $s =~ s/_/ /g;
  $s =~ s/-/ - /g;
  $s =~ s/ ([lnj]) / $1'/i;
  return $s;
}

$output = "";

sub parse_dir {
  my ($dir, $level) = @_;
  opendir(D,$dir) || die "opendir: $@";
  my @l = readdir(D);
  closedir(D);
  foreach $e (sort @l) {
    next if $e =~ /^\./;
    if (-d "$dir/$e") {
      $output .= ' ' x $level .&clean_name($e)."\n";
      &parse_dir("$dir/$e", $level+1);
    }
    elsif ($opt{f} && -f "$dir/$e") {
      $output .= ' ' x $level . &clean_name($e)."\n";
    }
  }
}
 
$file = "";

sub write_latex {
  $outfile = exists $opt{o} ? $opt{o} : "$ARGV[1]";
  open(OUT, ">$outfile.tex");

  print OUT '\documentclass{noursycd}
  \begin{document}
  \serial{'.$ARGV[0].'}
  \begin{contents}{';
  
  my $output = "";
  my $nblines = 0;
  open(F, "$ARGV[1]") || die "Cannot open file $file";
  while(<F>) {
    s/\n//;
    my ($ws, $text) = (/^(\s*)(.*)$/);
    $output .= '\>' x length($ws) . "$text\\\\\n";
    $nblines ++;
  }
  close(F);

  if (! exists $opt{s}) {
    $found_proper_fontsize = 0;
    foreach $n (sort keys(%fontsize)) {
      if ($nblines <= $n) {
        print OUT $fontsize{$n};
        $found_proper_fontsize = 1;
        last;
      }
    }
    if (! $found_proper_fontsize) {
      print STDERR "Warning: no proper fontsize found, abort.\n";
      exit 1;
    }
  }
  else {
    print OUT "$opt{s}";
    $found_proper_fontsize = 1;
  }
  
  print OUT '}
' . $output . '\end{contents}
\end{document}
';
  close(OUT);
}

if (! $opt{l}) {
  &parse_dir(".", 0);
  print $output;
}
else {
  &write_latex();
  if ($found_proper_fontsize) {
    system("latex $outfile");
    system("dvips -o $outfile.ps $outfile");
    system("pdflatex $outfile");
    if (! $DEBUG) {
      unlink "$outfile.aux";
      unlink "$outfile.log";
      unlink "$outfile.dvi";
    }
  }
}
