#!/usr/bin/env perl
use strict;
use 5.006;
use warnings;

my $progname = $0;

if (scalar @ARGV != 2) {
  print "Usage: $progname <outfile> <modules description file>\n";
  exit 1;
}

my $outname = shift(@ARGV);
my $modules = shift(@ARGV);

my @algorithms_by_length = ();

my %algorithm_name = ();

sub add_name {
    my ($alias, $name) = @_;
    $algorithm_name{$alias} = $name;
    push @{$algorithms_by_length[length($alias)]}, $alias;
}

open my $out, '>', $outname or die "Can't open output file '$outname': $!\n";

print $out <<END;
#include "stemmer.h"
END

open my $in, '<', $modules or die $!;
while (<$in>) {
    next if m/^\s*#/;
    next if m/^\s*$/;
    my ($alg, $encstr, $aliases) = split(/\s+/, $_);

    print $out <<END;
#include "${alg}_stemmer.h"
END
    foreach my $alias (split(/,/, $aliases)) {
        add_name($alias, $alg);
    }
}
close $in;

print $out <<END;
// $outname: Snowball stemmer factory
//
// This file is generated by $0 from a list of module names.
// Do not edit manually.

#include <string.h>

namespace Snowball {

Stemmer* make_stemmer(const char* language)
{
    switch (strlen(language)) {
END

for (my $i = 1; $i < @algorithms_by_length; ++$i) {
    my $l = $algorithms_by_length[$i];
    next unless defined $l;
print $out <<END;
        case $i:
END
    for (@$l) {
        my $class = $algorithm_name{$_};
        $class =~ s/_(.)/\U$1/g;
        $class = ucfirst $class . "Stemmer";
print $out <<END;
            if (memcmp(language, "$_", $i) == 0) return new Snowball::$class();
END
    }
print $out <<END;
            break;
END
}

print $out <<END;
    }
    return NULL;
}

}
END
