#!/usr/bin/perl

# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.


########################### CONFIGURABLE PART

#La couleur du fond, important si certaines images sont tournées d'un
#angle non multiple de 90° Doit être au format standard #rrggbb .
#Pour choisir une couleur et connaître son code, allez sur l'un des
#nombreux sites web proposant cela, par exemple
#http://www.pourpre.com/chromograf/

#The color of the background of the page, important if some images are
#to be rotated by an angle not multiple of 90°. It has to be of the
#standard form #rrggbb .  To choose a color and find its code, try one
#of the many relevant sites, for example
#http://www.pourpre.com/chromograf/

# #000000 = black, #ffffff= white
$bgcolor="#000000";

#fgcolor = foreground color = text(e) = avant-plan
$fgcolor="#ffffff";

#Les résolutions et qualités (échelle de compression JPEG) choisies
%resolutions_qualites=(
		       "640x480" => "55", 
#		       "800x600" => "75",
		       "1024x768" => "95",
#		       "1600x1200" => "95",
		       );

#Résolution par défaut (si vide, la première de la liste sera choisie).
$defaultresol="";

#La taille des imagettes
#The size of the mini-images (thumnbails)

$minisize="128x96";
$miniquality="65";

########################### LISTE

%jpeg_qualites=(
		"00" => "mauvaise",
		"55" => "quelconque", 
		"75" => "assez bonne",
		"95" => "bonne",
		);

$version="NavImg version 0.8";

print $version.", Copyright 2001-2003 Stéphane Gourichon\n";
print "NavImg comes with ABSOLUTELY NO WARRANTY; for details\n";
print "see the source code.  This is free software, and you are welcome\n";
print "to redistribute under the terms of the GNU General Public License.\n";

print "Author: Stéphane Gourichon.\n\n";
print "Thanks: Pascal Gouedo, for two corrections.\n\n";

print "\n\n";

#TODO: highlight


if (! $defaultresol) {
    @resoltriees=sort { $a <=> $b } keys %resolutions_qualites;
    
    $defaultresol=unshift(@resoltriees);
}

print "Le visiteur sera mené par défaut vers des images de résolution: $defaultresol.\n";

# exif est-il disponible ?
@args = ("exif", "--help");
if (system(@args) == 0) {
    $exif=1;
    print "'exif' est disponible.\n";
} else {
    $exif=0;
    print "'exif' n'est disponible.\n";
}

$attentionorigine="<p>Attention: vous consultez ici les fichiers
d'origine produits directement par l'appareil photo. Ils incluent des
informations de calibration de couleur qui sont nécessaire pour une
impression de bonne qualité, mais qui ne conviennent pas à un
affichage dans un navigateur internet quelconque.</p>\n";

$photosource=shift;

$nomake=$photosource;

sub lisfichier {
    my $nomfichier=shift;
    my $monexemple=shift;
    my $oldseparator=$/;
    undef $/;
    
    print "Lecture de \"$nomfichier\".\n";
    
    if (open(FICHIER, "$nomfichier")) {
	$contenu=<FICHIER>;
	close (FICHIER);
    } else {
	print "\n\*** Attention: pas trouvé de fichier \"$nomfichier\".\n";
	print "Il s'agit probablement d'une nouvelle galerie d'images.\n";
	print "Tapez ce que vous souhaitez comme $nomfichier, par exemple:\n> $monexemple\n";
	print "Pour finir, faire [Entrée] puis Ctrl-D. Pour tout annuler: Ctrl-C.\n> ";
	$contenu = <STDIN>;
	print "Ce que vous venez de taper est placé dans le fichier \"$nomfichier\".\n";
	print "Pour faire des modifications, il vous suffira de modifier $nomfichier\net relancer le script.\n";
	
	open(FICHIER, ">$nomfichier") or die "Argh! Pas pu créer de fichier $nomfichier!";
	print FICHIER $contenu;
	close (FICHIER);
    }
    $/=$oldseparator;
    return $contenu;
}



########################### LISTE

print "Vérification de la présence du fichier \"liste\".\n";

# Si on ne trouve aucune image on n'y va pas
$onyva=0;

@extensions=("jpg","jpeg","png","xpm","gif","ppm","pgm","bmp","ps","eps","epsi");

$outext="-r.jpg";

sub nomfichierconvenable {
    my $nom=lc(shift);
    #    print "testons $nom\n";
    return 0 unless -f "$some_dir/$_";
    
    foreach $ext (@extensions) {
	$pext=".".$ext;
	#	print "\nmof, nom $nom ext $pext :".(rindex $nom, $pext)." comparé à ".(length $nom)." - ".(length $pext)." = ".((length $nom) - (length $pext))."\n";
	if ((rindex $nom, $pext) == ((length $nom) - (length $pext))) {
	    return 1;
	}
    }
    return 0;
}

if (!stat("liste")) {
    print "* Il n'y a pas de liste des images.\nIl s'agit probablement d'une nouvelle galerie d'images.\nCréation de la liste.\n";
    
    $some_dir="origine";
    
    if (opendir(DIR, $some_dir)) {
	@images = grep { nomfichierconvenable($_); } readdir(DIR);
	closedir DIR;
    }
    
    
    $sep="\t\t\t...\n";
    
    if (@images) {
	open(FICHIER, ">liste") or die "Argh! Pas pu créer de fichier $nomfichier!";
	print "Il y a déjà ".@images." image(s) dans le répertoire origine. On crée une liste.\n";
	print FICHIER join($sep, @images);
	print FICHIER $sep;
	close (FICHIER);
    }
} else {
    $onyva=1;
}

$some_dir=".";

#actuellement, on déplace et on ajoute à la liste avant de se poser
#des questions. On devrait d'abord lire la liste et déplacer, puis
#regarder s'il en reste.

opendir(DIR, $some_dir) || die "can't opendir $some_dir: $!";
# haha Kate s'emmelle les pinceaux avec les guillemets
@images_nonplacees = grep { nomfichierconvenable($_); } readdir(DIR);
closedir DIR;

$sep="\t\t\t...\n";

if (@images_nonplacees) {
    print @images_nonplacees." nouvelle(s) image(s) incorporée(s)\n";
    open(FICHIER, ">>liste") or die "Argh! Pas pu créer de fichier $nomfichier!";
    print FICHIER join($sep, @images_nonplacees);
    print FICHIER $sep;
    close (FICHIER);
    $onyva=1;
}


if ($onyva==0) {
    print "\nARRÊT DU PROGRAMME. Pas trouvé d'image ni de liste d'images. Vérifiez qu'il y a dans le répertoire courant des fichiers avec extension convenable (".join(",",@extensions).").\n";
    exit 1;
}
# haha Kate s'emmelle les pinceaux avec les guillemets

########################### DÉPLACEMENT DES FICHIERS

if (!(-d "origine")) {
    print "Création du répertoire 'origine' dans lequel les photos sont déplacées.\n";
    mkdir "origine", 0777 or die "Pas pu créer répertoire 'origine' dans lequel les fichiers images doivent être placés. Veuillez vous assurer qu'un fichier de ce nom n'existe pas déjà.\n";
}

foreach $image (@images_nonplacees) {
    rename $image, "origine/$image" or print "Argh! Pas pu déplacer image $image.\n";
}

########################### INFOS ACCESSOIRES

$titre=lisfichier("titre", "2001.08.05 Tour de la forêt de Saint-Germain en Laye à vélo");
chomp $titre;

$commentairegeneral=lisfichier("commentairegeneral", "Voici les quelques photos de la ballade en vélo dans la forêt de Saint-Germain en Laye, le 05 août 2001.
");

$pieddepagegeneral=lisfichier("pieddepagegeneral", "<a href=\"mailto:monadresse\@mondomaine.org\">pour joindre l'auteur</a>");

########################### PAGES 

print "*** Début de la génération des pages.\n";


$texte="<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
                      \"http://www.w3.org/TR/REC-html40/loose.dtd\">
<html>
<head>
  <title>$titre</title>
  <meta http-equiv=\"Content-Type\" content=\"text/html;charset=iso-8859-1\">
</head>

<body background=\"$bgcolor\" bgcolor=\"$bgcolor\" text=\"$fgcolor\" link=\"#FFC020\"
vlink=\"#FF80FF\" alink=\"#00FF00\">

<h1 align=\"center\">$titre</h1>
\n<center>
$commentairegeneral
<hr width=\"90%\">

";


sub faisindex {
    my $resol=shift; #640x480

    ($resolx,$resoly,$junk)=split /x/, $resol, 3;
    if ($resolx && $resoly && (!$junk)) {
	#$widthheight="width=\"$resolx\" height=\"$resoly\" ";
	$widthheight=""; # we don't actually know the real image size for sure...
    } else {
	die ("Bad resolution spec ? Not XxY format: $resol");
	$widthheight="";
    }

    my $quality;
    $quality=shift or $quality=75; #75
    my $resollink=shift; #640x480

    ($resollinkx,$resollinky,$junk)=split /x/, $resollink, 3;
    if ($resollinkx && $resollinky && (!$junk)) {
	#$linkwidthheight="width=\"$resollinkx\" height=\"$resollinky\" ";
	$linkwidthheight=""; # we don't actually know the real image size for sure...
    } else {
	#ie ("Bad resolution spec ? Not XxY format: $resollink");
	$linkwidthheight="";
    }

    my $dirorig="origine";
    my $rulesonly=0;
    if (!$resollink) {
	$rulesonly=1;
    }

    my ($precedentenom, $precedenteoptions, $precedentecommentaire, $precedentenomhtml, $precedentenomimgmade);
    my ($nom, $options, $commentaire, $nomhtml);
    
    if ($resollink) { 
	$ihfile="index$resol-$resollink.html"; 
	print "** Pages de résolution $resol avec liens vers résolution $resollink. **\n";
    } else {
	$ihfile="index$resol.html"; 
    }
    if ($faisrule) {
	print "* Règles pour les images de résolution $resol.\n";
    }


    if ($resollink) {
	open(INDEXHTML, ">$ihfile")
	    or die "Can't open $ihfile for writing: $!";
# haha Kate s'emmelle les pinceaux avec les guillemets
	print INDEXHTML $texte;

	if ($resollink == "origine") {
	    print INDEXHTML $attentionorigine;
	} else {
	    print INDEXHTML "<p>Cliquez sur une imagette pour la voir en résolution $resollink.</p>\n";
	}
	
	print INDEXHTML "<p>Si vous préférez une autre résolution, vous avez le choix entre ";

	@listequal=();
foreach $rez (sort { $a <=> $b } keys %resolutions_qualites) {
    $qualitestr=$jpeg_qualites{$resolutions_qualites{$rez}};

    push @listequal, "<a href=\"index".$minisize."-".$rez.".html\">"
	.$rez." ".(($qualitestr)?("(qualité ".$qualitestr.")"):"")."</a>";
}
	print INDEXHTML join (", ", @listequal).".";

	print INDEXHTML "<br>1024x768 donne déjà d\'excellentes images, je vous la recommande si votre connexion est assez rapide.</p>
\n";
    }
    
    open(INL, "liste")
	or die "Can't open liste for reading: $!";
    open(INLSUIV, "liste")
	or die "Can't open liste for reading: $!";
    <INLSUIV>;

    my $suivhabituelle=1;
    my $nrsection=0;
    my $section="";

LIGNELISTE:    while (<INL>) {
    chomp;
    $ligneactuelle=$_;

    if ($suivhabituelle==1) {
	$lignephotosuivante=<INLSUIV>;
	if ($lignephotosuivante =~ s/^SECTION //) {
	    #print "\nOn saute la ligne de INLSUIV section $lignephotosuivante...";
	    $lignephotosuivante=<INLSUIV>;
	    #print "pour arriver à $lignephotosuivante\n";
	    $suivhabituelle=0;
	}
	chomp $lignephotosuivante;
    } else {
	$suivhabituelle=1;
	#print "\nOn évite d'avancer trop vite, pour bien tenir compte de $lignephotosuivante\n";
    }
    
    ($precedentenom, $precedenteoptions, $precedentecommentaire,
     $precedentenomhtml, $precedentenomimgmade)
	=($nom, $options, $commentaire, $nomhtml, $nomimgmade);

    #Si pas de tabulation dans la ligne c'est un changement de section, on lit.
    if (s/^SECTION //) {
	if ($changementsection==1) {
	    die("Section vide, après avoir lu $section et face à la ligne $_");
	}
	$section=$_;
	$nrsection++;
	$nmsection=$nrsection.$section;
	$nmsection =~ s/[aeiouy]//g;
	$nmsection =~ s/[^AEIOUYA-Za-z0-9_-]//g;
	$nmsection =~ s/(......).*/$1/;

	if ($premierpassage==1) {
	    print "* Section: $section *\n";
	}
	if ($rulesonly==0) {
	    $changementsection=1;	    
	}
	#$_=<INL>;
	#if (!(/	/)) {
	#	warn("Section vide, après avoir lu $section et face à la ligne $_");
	#    }
	next LIGNELISTE;
    }
    
    ($nom, $optionsav, $optionsap, $commentaire) = split /	/, $_, 4;

    $nomsansext=$nom;
    $nomsansext =~ s/(.*)\.[^-]*(.*)/$1$2/;
    $ext = $nom;
    $ext =~ s/.*\.([^-]*).*/$1/;

    $nomsource=$nom;
    $nomsource =~ s/(.*)-.*/$1/;

    $imgsrc="origine/".$nomsource;

#    $nomimgmade=$nomsansext.".".$ext;
    $nomimgmade=$nomsansext.$outext;

    $imgdest=$resol."/".$nomimgmade;


    #pour le lien "image precedente"

    $precedentecommentairestrip=$precedentecommentaire;

    # virer les tags html. J'ai pris exemple sur le truc qui
    # vire les precedentecommentaires pascal dans man perlfunc.
    while ($precedentecommentairestrip =~ s|(<.*>.*)<.*>|$1|) {};
    $precedentecommentairestrip =~ s|<.*>||;
    $precedentecommentairestrip =~ s/\"/\&quot\;/g;



    $commentairestrip=$commentaire;
    
    # virer les tags html. J'ai pris exemple sur le truc qui
    # vire les commentaires pascal dans man perlfunc.
    while ($commentairestrip =~ s|(<.*>.*)<.*>|$1|) {};
    $commentairestrip =~ s|<.*>||;
    $commentairestrip =~ s/\"/\&quot\;/g;

    #pour le lien "image suivante"

    ($suivantenom, $suivanteoptionsav, $suivanteoptionsap, $suivantecommentaire)= split /	/, $lignephotosuivante, 4;

    $suivantecommentairestrip=$suivantecommentaire;
    
    # virer les tags html. J'ai pris exemple sur le truc qui
    # vire les commentaires pascal dans man perlfunc.
    while ($suivantecommentairestrip =~ s|(<.*>.*)<.*>|$1|) {};
    $suivantecommentairestrip =~ s|<.*>||;
    $suivantecommentairestrip =~ s/\"/\&quot\;/g;

    $suivantenomsansext=$suivantenom;
    $suivantenomsansext =~ s/(.*)\.[^-]*(.*)/$1$2/;
    $suivanteext = $suivantenom;
    $suivanteext =~ s/.*\.([^-]*).*/$1/;

    $suivantenomsource=$suivantenom;
    $suivantenomsource =~ s/(.*)-.*/$1/;

    $suivantenomhtml=$suivantenomsansext.".html";

    $suivanteimgsrc="origine/".$suivantenomsource;
#    $suivantenomimgmade=$suivantenomsansext.".".$suivanteext;
	    $suivantenomimgmade=$suivantenomsansext.$outext;
    $suivanteimgdest=$resol."/".$suivantenomimgmade;

    if ($resollink) {
#	    $imglink=$resollink."/".$nomimgmade;

	$nomhtml=$nomsansext.".html";
	
	$htmllink=$resollink."/".$nomhtml;
	
	if ($changementsection==1) {
	    print INDEXHTML 
		#"\n<hr width=\"90%\">",
		"\n<a name=\"$nmsection\"></a>",
		"\n<h2>$section</h2>";
	    $changementsection=0;
	}

	print INDEXHTML "<a href=\"$htmllink\"><img $widthheight src=\"$imgdest\" alt=\"$commentairestrip (cliquez pour agrandir)\" title=\"$commentairestrip (cliquez pour agrandir)\"></a>\n";
	
	open(IMGHTML, ">$htmllink")
	    or die "Can't open $htmllink for writing: $!";
# haha Kate s'emmelle les pinceaux avec les guillemets
	print IMGHTML "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
                      \"http://www.w3.org/TR/REC-html40/loose.dtd\">
<html>
<head>
  <title>$titre - $commentairestrip</title>
  <meta http-equiv=\"Content-Type\" content=\"text/html;charset=iso-8859-1\">
</head>

<body background=\"$bgcolor\" bgcolor=\"$bgcolor\" text=\"$fgcolor\" link=\"#FFC020\"
vlink=\"#FF80FF\" alink=\"#00FF00\">

<h1 align=\"center\">$titre</h1>\n\n<center>\n";
	if ($commentairephotoscommun) {
	    print IMGHTML "<p>$commentairephotoscommun</p>\n";
	}
	
	print IMGHTML "<hr width=\"90%\">\n\n";

	if ($resollink == "origine") {
	    print IMGHTML $attentionorigine;
	}

	print IMGHTML "<table width=\"100%\">\n  <tbody>\n",
	"    <tr>\n      <td align=\"center\" valign=\"middle\" width=\"33%\">\n";

	if ($precedentenom) {
	    #width=64 height=48 
	    print IMGHTML "        <a href=\"$precedentenomhtml\"><img src=\"../".$minisize."/$precedentenomimgmade\" alt=\"image precedente: $precedentecommentairestrip\"> &lt;= Image précédente</a>\n";
	} #else {
	#print IMGHTML "&nbsp;";
	#}

	print IMGHTML "      </td>\n";
	
	#width=64 height=48 
	print IMGHTML
	    "      <td align=\"center\" valign=\"middle\" width=\"33%\">\n",
	    "        <a href=\"#centree\"><img src=\"../".$minisize."/$nomimgmade\" alt=\"Cliquez ici pour caler l'image\"></a>\n",
	    "      </td>\n";
	
	print IMGHTML "      <td align=\"center\" valign=\"middle\" width=\"33%\">\n";
	
	if ($suivantenom) {

	    print IMGHTML "<script type=\"text/javascript\" language=\"javascript\">\n",
		"       <!--\n",
		"       if (document.images)    {\n",
		"          Image1          = new Image();\n",
		"          Image1.src      = \"$suivantenomimgmade\";\n",
		"       }       //-->   \n",
		"   </script>";
	    #width=64 height=48 
	    print IMGHTML "        <a href=\"$suivantenomhtml\">Image suivante =&gt; <img src=\"../".$minisize."/$suivantenomimgmade\" alt=\"image suivante: $suivantecommentairestrip\"></a>\n";
	} #else
	#{
	#	print IMGHTML "&nbsp;";
	#    }
	print IMGHTML "      </td>\n    </tr>\n  </tbody>\n</table>\n";

	print IMGHTML "\n<hr width=\"90%\">\n<a name=\"centree\"></a>\n";

# Commentaire
#	    print IMGHTML 
#		"        <p>";
	if ($section) {
	    print IMGHTML 
#		    "\n<hr width=\"90%\">",
		#"\n<p>
		"<b>$section</b> - ";
	}
	print IMGHTML 
	    "        $commentaire<br>\n";

	if ($suivantenom) {
	    print IMGHTML "<a href=\"$suivantenomhtml#centree\">\n";
	}
	# L'image centrale, la grande, la vraie, la belle

    if ($resollink == "origine") {
	$nomimggrande=$nomsource;  
    } else {
	$nomimggrande=$nomimgmade;  
    }

	print IMGHTML "<img $linkwidthheight src=\"$nomimggrande\" alt=\"$commentairestrip\" border=0>\n";
	if ($suivantenom) {
	    print IMGHTML "</a>\n";
	}

	print IMGHTML
	    "<br>\n",
	    "Résolutions disponibles (et qualité):\n";

	@listequal=();
	    foreach $rez (sort { $a <=> $b } keys %resolutions_qualites) {
		$qualitestr=$jpeg_qualites{$resolutions_qualites{$rez}};
		
		push @listequal, "<a href=\"../".$rez."/$nomhtml\">"
		    .$rez." ".(($qualitestr)?("(qualité ".$qualitestr.")"):"")."</a>";
	    }
	
	$rez="origine"; $qualitestr="";
	push @listequal, "<a href=\"../".$rez."/$nomhtml\">"
	    .$rez." ".(($qualitestr)?("(qualité ".$qualitestr.")"):"")."</a>";
	
	print IMGHTML join (", ", @listequal).".";
	
	
	print IMGHTML
	    "\n<hr width=\"90%\">\n\n",
	    "<table width=\"90%\">\n  <tbody>\n",
	    "    <tr>\n",
	    "      <td align=\"left\" width=\"30%\">\n";

	if ($precedentenom) {
	    #width=64 height=48
	    print IMGHTML "        <a href=\"$precedentenomhtml\"><img src=\"../".$minisize."/$precedentenomimgmade\" alt=\"image precedente: $precedentecommentairestrip\"> &lt;= Image précédente</a>\n";
	} #else {
	#print IMGHTML "&nbsp;";
	#}
	print IMGHTML "      </td>\n";
	# width=64 height=48
	print IMGHTML
	    "      <td align=\"center\" valign=\"middle\" width=\"33%\">\n",
	    "        <a href=\"#centree\">\n",
	    "        <img src=\"../".$minisize."/$nomimgmade\" alt=\"Cliquez ici pour centrer sur la grande image\"></a>\n",
	    "        <p>$commentaire</p>\n",
	    "      </td>\n";
	
	print IMGHTML "      <td align=\"center\" valign=\"middle\" width=\"33%\">\n";
	
	if ($suivantenom) {
	    # width=64 height=48 
	    print IMGHTML "        <a href=\"$suivantenomhtml\">Image suivante =&gt; <img src=\"../".$minisize."/$suivantenomimgmade\" alt=\"image suivante: $suivantecommentairestrip\"></a>\n";
	} #else
	#{
	#	print IMGHTML "&nbsp;";
	#    }
	print IMGHTML "      </td>\n    </tr>\n  </tbody>\n</table>\n";
	
	print IMGHTML 
	    "\n<hr width=\"90%\">\n\n",
	    "<p><a href=\"../index".$minisize."-$resollink.html#$nmsection\">",
	    "Retour à la vue d'ensemble...</a>", 
# haha Kate s'emmelle les pinceaux avec les guillemets
	    "</p>\n";

	print IMGHTML
	    "\n<hr width=\"90%\">\n\n",
	    $pieddepagegeneral,
	    "<p><small>Ces pages ont été générées automatiquement par <a href=\"http://amphi-gouri.org/navimg/\">$version</a>.</small>\n",
	    "</body></html>\n";
	close IMGHTML;
    }
# else {
#	    if ($changementsection==1) {
#		print INDEXHTML "<p>$section</p>";
#	    }
#	    print INDEXHTML "<img src=\"$imglink\" alt=\"$commentaire\"><br>\n";
#	}
    
    if ($faisrule) {
	push @dests, $imgdest;

	$makefilelocal=$nomsansext.".rule";
	$makefilelocalwpath= $resol."/".$makefilelocal;
	$tmpname=".makefile.tmp";

	print MAKEF "-include $makefilelocalwpath\n";
	
	open(MAKEFL, ">$tmpname");

	#hack pour reprendre
	my $cheminpo=`pwd`;
	if ($cheminpo =~ /photosbis/) {
	    chomp ($cheminpo);
	    $cheminpo =~ s/photosbis/photos/;
	    print MAKEFL "$imgsrc: $cheminpo/$imgsrc\n";
	    print MAKEFL "\tcp -avl \$< \$@\n";
	    print MAKEFL "$imgdest: $cheminpo/$imgdest\n";
	    print MAKEFL "\tcp -avl \$< \$@\n";
	}	
	print MAKEFL "$imgdest: $makefilelocalwpath $imgsrc\n";
	
	if ($optionsav =~ /gamma/) {
#	    if ($premierpassage==1) {
#		print "gamma déjà donné";
#	    }
	    $optiongamma="";
	} else {
	    $optiongamma="-gamma 1.4";
	}
	#-bordercolor \"$bgcolor\" 
	print MAKEFL "\t( convert -background \"$bgcolor\" $imgsrc $optionsav $optiongamma -filter gaussian -geometry \'$resol>\' $optionsap -quality $quality -interlace Plane $imgdest )\n";

#	print MAKEFL "\tconvert -background \"$bgcolor\" $optionsav $optiongamma -filter gaussian -geometry \'$resol>\' $imgsrc MIFF:- | convert $optionsap -quality $quality -interlace Plane MIFF:- $imgdest\n";

	close (MAKEFL);


	@args = ("diff", $makefilelocalwpath, $tmpname);
	if (-f $makefilelocalwpath) {
	    if (system(@args) == 0) {
		# Si pas de changement on laisse l'ancien makefile
		    unlink $tmpname;   
	    } else {
		# Si changement on écrase l'ancien makefile avec le nouveau
		rename($tmpname, $makefilelocalwpath);
		if ($premierpassage==1) {
		    print "\n$nom\t$commentaire\t";
		    print "(changements)";
		}
	    };
	} else {
	    # S'il n'y avait pas de makefile on le place.
	    rename($tmpname, $makefilelocalwpath);
	    if ($premierpassage==1) {
		print "\n$nom\t$commentaire\t";
		print "nouvelle image";
	    }
	} 
	unlink $tmpname;   
    }
}
#    print "\n*** Fin de la liste. ***\n";
    print "\n";
    
    if ($resollink) {
	if ($resollink ne "origine") {
	    print INDEXHTML "\n<hr width=\"90%\">\n\n";
	    print INDEXHTML
		"<p>Vous pouvez également télécharger les <a\n",
		"href=\"index".$minisize."-origine.html\">fichiers d'origine</a> produits directement par\n",
		"l'appareil photo. Ils incluent des informations de calibration de couleur qui\n",
		"sont nécessaire pour une <b>impression</b> de bonne qualité avec un logiciel\n",
		"convenable.</p>\n";
	    
	}
	
	print INDEXHTML "\n<hr width=\"90%\">\n\n",
	"<a href=\"../index.html\">Retour à la page de niveau supérieur</a>\n",
	"\n<hr width=\"90%\"><center>\n",
	$pieddepagegeneral,
	"</center>\n",
#	"<p><a href=\"/\"><img src=\"/cochon_icon.png\" align=\"left\" border=\"0\"\n",
#	"alt=\"Cochon\" height=\"64\" width=\"104\">Retour à l\'accueil du site.</a>\n",
	"<p align=\"right\"><small>Ces pages ont été générées automatiquement<br>\n",
	"par <a href=\"http://amphi-gouri.org/navimg/\">$version</a>.</small>\n",
	"  <a href=\"http://validator.w3.org/check/referer\"><img border=\"0\"\n",
	"      src=\"http://amphi-gouri.org/valid-html40.png\" align=\"right\"\n",
	"      alt=\"Valid HTML 4.0!\" height=\"31\" width=\"88\"></a>\n",
	"</p>\n",
	"</center>\n",
	"\n</body>\n</html>\n";
	close INDEXHTML;
    }

    close INL;
    close INLSUIV;
} # sub faisindex


# début de la partie principale

open(MAKEF, ">Makefile_navimg.makefile")
    or die "Can't open Makefile_navimg.makefile for writing: $!";
# haha Kate s'emmelle les pinceaux avec les guillemets

print MAKEF "PHOTOSOURCE=$photosource\n";
print MAKEF "all: images\n";
print MAKEF "origine/%: \$(PHOTOSOURCE)/%\n";
print MAKEF "\tcp -avl \$< \$@ 2>/dev/null || cp -av \$< \$@\n";
print MAKEF "mrproper:\n\t\\rm -rv *x*/ index".$minisize."* origine/*html *~\n";

mkdir($minisize, 0777);

$premierpassage=1;
$faisrule=1;

foreach $rez (sort { $a <=> $b } keys %resolutions_qualites) {
mkdir($rez, 0777);
faisindex($minisize, $miniquality, $rez);
$premierpassage=0;
$faisrule=0;
}

faisindex($minisize, 65, "origine");

$faisrule=1;
foreach $rez (sort { $a <=> $b } keys %resolutions_qualites) {
faisindex($rez, $resolutions_qualites{$rez});
}

print MAKEF "images: ".(join " ", @dests)."\n";

close MAKEF;

if ( eval { symlink("",""); 1 } ) {
    print "Choix de l'index principal (=résolution proposée par défaut).\n";
# haha Kate s'emmelle les pinceaux avec les guillemets
    if ((symlink "index".$minisize."-".$defaultresol.".html","index.html") == 1 ) {
	print "Un lien index.html a été créé pour avoir un index par défaut.\n";
    } else {
	print "Il existe probablement déjà un fichier index.html, on va supposer que c'est normal. Supprimer \"index.html\" et relancer le script pour remettre un lien symbolique vers l'index par défaut.\n";
    }
} else {
    print "Hum. Votre système ne supporte pas les liens symboliques, semble-t-il. Débrouillez-vous pour créer un fichier index.html .\n";
}

if ($nomake ne "nomake") {
    print "Génération des imagettes et images de différentes résolutions.\n";
    
    @args = ("make", "-f", "Makefile_navimg.makefile", "-k");
    if (system(@args) == 0) {
	print "Ça a l'air bien.\n";
# haha Kate s'emmelle les pinceaux avec les guillemets
	$rc=0;
    } else {
	print "Un problème avec make ? Hum...\n";
	$rc=1;
    }
}

print "Si vous voulez changer le titre, les commentaires général ou les commentaires associés à chaque images, éditez les fichiers suivants: titre, commentairegénéral et liste, puis relancez le script pour propager les modifications.\n";

exit $rc;
