The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.
$|++;
 
BEGIN { require 5.005 }

use strict;
use ExtUtils::MakeMaker;
use Config;

$ENV{SNOWBALL_SRC} = "snowball_src";
$ENV{SNOWBALL_STEMMER} = "stemmers_src";

my $ext = $Config{obj_ext};

my @stemmers;
my $yes = 0;
foreach my $stemdir (grep { /\.h$/ } glob $ENV{SNOWBALL_STEMMER}.'/*') {
	$yes++;
	my $lang;
	if ($stemdir =~ /stem_(.+)\.h/) {
		push @stemmers, $1;
	}
}

if ( $#stemmers < 0 ) { die "There are no stemmers. Exiting...\n"; }

my $list = join(', ', @stemmers);
print <<EOT;
####################################################
  List of stemmers: $list 
  To add a stemmer to the list, launch add_stemmer.pl
  and try again:
  > perl Makefile.PL
####################################################
EOT

# config.c generation
open(OUT_H,">config.c") || die "Can't open file for writing";
print OUT_H "/* Autogenerated file! */\n";
print OUT_H join("\n", map { qq|#include "$ENV{SNOWBALL_STEMMER}/stem_$_.h"| } @stemmers);
print OUT_H "\n#define NUMSTEM (".($#stemmers + 1).")\n";
print OUT_H "STEM stemmers[] = {\n";
print OUT_H join(",\n", map { qq|   {"$_", NULL, ${_}_create_env, ${_}_close_env, ${_}_stem}| } @stemmers);
print OUT_H "\n};\n";
close(OUT_H);

# postamble
my @snowballfiles = ('api.h', 'api.c', 'header.h', 'utilities.c');

my $act = "\n";
foreach my $file (@snowballfiles) {
	$act .= "$file: $ENV{SNOWBALL_SRC}/q/$file\n\t\$(CP) $ENV{SNOWBALL_SRC}/q/$file $file\n";
}

my $commonheaders = join(' ', grep { /\.h$/ } @snowballfiles);

foreach my $lang (@stemmers) {
	$act .= "stem_$lang.h: $ENV{SNOWBALL_STEMMER}/stem_$lang.h\n\t\$(CP) $ENV{SNOWBALL_STEMMER}/stem_$lang.h stem_$lang.h\n";
	$act .= "stem_$lang.c: $ENV{SNOWBALL_STEMMER}/stem_$lang.c $commonheaders stem_$lang.h\n\t\$(CP) $ENV{SNOWBALL_STEMMER}/stem_$lang.c stem_$lang.c\n";
}  

my $copyfile = join(' ', @snowballfiles, map { "stem_$_.h stem_$_.c" } @stemmers);

my $objects = join(' ', map { "stem_$_$ext" } @stemmers).' '.
	join(' ', map { $_ =~ s/\.c$/$ext/; "$_" } grep { /\.c$/ } @snowballfiles); 

my $headers = join(' ', map { "stem_$_.h" } @stemmers).' '.$commonheaders;

WriteMakefile(
	PREREQ_PM         => {
		'POSIX' => 0,
	},
	VERSION_FROM	=> 'lib/Lingua/Stem/Snowball.pm',
	NAME		=> 'Lingua::Stem::Snowball',
	AUTHOR		=> 'Fabien POTENCIER <fabpot@cpan.org>',
	INC		=> "-I. -I$ENV{SNOWBALL_SRC}/q -I$ENV{SNOWBALL_STEMMER}",
	OBJECT		=> "Snowball$ext $objects",
	clean		=> { FILES => "config.c $copyfile" },
	depend		=> { 'Snowball$ext' => "config.c $headers", },
	EXE_FILES	=> [ 'bin/add_stemmer.pl' ],
);

sub MY::postamble{
	return $act;
}