#!/usr/bin/perl

@types = ("devoir", "oraux", "ficheprog");
@formations = ("mastere", "majeure", "mineure","fip", "master", "fc","option");
@matieres = ("gl", "po", "conc", "base", "avance");

@liste = ("devoir","devoir,majeure,po,gl","option,ficheprog","fc,base","mineure,po");

$initname = "doc";

local(*RES);
open(RES, ">res.tex") or die "Could not create [res.tex]!\n";

foreach $target (@liste) {
  $dest = "$initname-$target";
  print "generating $dest\n";
  generateVersion($initname,$target) or die "Cannot generate [$dest.tex]!\n";
  system("makeDoc.pl -norename $dest") == 0 or die "Cannot generate [$dest.pdf]!\n";
  unlink("$dest.tex");
  print RES "Options $target :\n\n";
  print RES "\\fbox{\\pgfimage[page=1,width=7.2cm]{exemples/$dest}}\n";
  print RES "\\hspace{2cm}\n";
  print RES "\\fbox{\\pgfimage[page=2,width=7.2cm]{exemples/$dest}}\n\n";
}

close(RES);

system("makeDoc.pl -norename cours") == 0 or die "Cannot generate [cours.pdf]!\n";
system("makeDoc.pl -norename texte") == 0 or die "Cannot generate [texte.pdf]!\n";
system("makeDoc.pl -cor -norename texte");

sub generateVersion {
  my $name = shift;
  my $version = shift;
  my $destname = "$name-$version";
  my $options = "";
  local(*IN);
  local(*OUT);

  $name .= ".tex";
  $destname .= ".tex";

  open(IN,$name) or die "Could not open input file [$name]!\n";
  open(OUT, ">$destname") or die "Could not create [$destname]!\n";
  while(<IN>) {
    if (/\\documentclass(\[([a-zA-Z,]+)\])?{(\w+)}/) {
      if ($2) {
	$options = $2;
	$options = "$version,$options" unless ($options =~ /$version/);
      } else {
	$options = $version;
      }
      print OUT "\\documentclass[$options]{$3}\n";
    } else {
      print OUT;
    }
  }
  close(IN);
  close(OUT);
}
