#!/usr/bin/perl -s

use common::sense;
use Data::Dumper;

use IPC::Run qw'run';

our $iter ||= 1500;
our $continue;
our $n = 3;
our $tot = 30;

print STDERR "Computing language list...\n";
my @langs = compute_langs(@ARGV);

if (!$continue) {
	print STDERR "Writing classes file...\n";
	write_classes(@langs);
	
	print STDERR "Computing trigrams...\n";
	check_trigrams(@langs);
	
	print STDERR "Computing features...\n";
	compute_features(@langs);
	
	#print STDERR "Computing specific features...\n";
	#add_specific_features(@langs);
	
	print STDERR "Computing dataset...\n";
	make_data_set(@langs);
}

print STDERR "Training Neuronal Network...\n";
run_octave();

print STDERR "Serializing Results...\n";
serialize();

sub add_specific_features {
	my @langs = @_;

	my $groups = {
		'pt' => ['pt', 'pt-br'],
#		'zw' => ['zh-tw', 'zh-cn', 'ja', 'ko'], # order kind of matters
	};

	for my $group (values %$groups) {

		my @l = ();
		for my $l (@$group) {
			push @l, $l if grep { $l eq $_ } @langs;
		}

		if (@l > 1) {
			for (my $i = 0; $i < scalar(@l)-1; $i++) {
				for (my $j = $i+1; $j < scalar(@l); $j++) {
					print STDERR "Comparing $l[$i] with $l[$j]...\n";
					`tools/compareLangs.pl -n=$n -add $l[$i] $l[$j]`;
				}
			}
		}
	}

}


sub serialize {
	`tools/serializeThetas.pl -f 3-Thetas.dat 3-Thetas.ser`;
	`tools/serializeThetas.pl -f -gsl 3-Thetas.dat 3-Thetas.gsl`;
}

sub run_octave {
	if (!$continue) {
		unlink "octave/X.txt" if -f "octave/X.txt";
		link "3-X.dat", "octave/X.txt";
	}
	# XXX - would be great to have output someday

	my $octave;
	{
		undef $/;
		open OCTAVE, "<", "octave/learner.m.tt" or die "...$!";
		$octave = <OCTAVE>;
		close OCTAVE;
	}

	$octave =~ s/__ITERACOES__/$iter/g;

	run [qw.octave -p octave.], \$octave, \*STDOUT, \*STDERR;

#	open OCTAVE, "-|", "octave -p octave" or die "...$!";
#	print OCTAVE $octave;
#	close OCTAVE;

	# `cd octave; octave < learner.m`;
	##	unlink "3-Thetas.dat" if -f "3-Thetas.dat";
	link "octave/thetas.dat", "3-Thetas.dat";
}

sub make_data_set {
	my $langs = join " " => @_;

	`tools/mkDatSet.pl -n=$n $langs > $n-X.dat`;
}

sub compute_features {
	my $langs = join " " => @_;

	`tools/compute_features.pl -n=$n -ssize=$tot $langs`;
}




sub check_trigrams {
	my @langs = @_;
	for my $l (@langs) {
		my @files = <out/${l}_*.txt>;
		for my $f (@files) {
			my $out = $f;
			$out =~ s/txt/dmp/;
			$out =~ s{out/}{out/$n-};

			if (!-f $out || -M $f < -M $out) {
				`$^X tools/ngrams.pl -n=$n $f`;
			}
		}
	}
}

sub write_classes {
	open my $fh, ">", "classes.txt" or die "Can not write classes file: $!";
	my $i = 1;
	for (@_) {
		printf $fh "%d\t%s\n", $i++, $_;
	}
	close $fh;
}

sub compute_langs {
	my @requested_langs = @_;

	my %existing_langs = ();
	my @files = <out/*.txt>;
	for my $file (@files) {
		$file =~ m{out/([^_]+)};
		$existing_langs{$1}++;
	}

	if (@requested_langs) {
		grep { $a = $_; grep { $_ eq $a} @requested_langs } sort keys %existing_langs;
	} else {
		sort keys %existing_langs;
	}
}
