#!/usr/bin/perl -w
#
use strict;
use Cwd;
use warnings;


if (@ARGV < 3)
{
	print "<i: scores> <i: dossier res> <o: dossier align>\n";
	exit 0;
}

my $RepRes=$ARGV[1];
my $RepAlign=$ARGV[2];


open SCORE, "$ARGV[0]" or die "impossible d'ouvrir $ARGV[0] \n";

opendir REP, $RepRes;

my $currWorkDir = &Cwd::cwd();



chdir ($RepRes);

my @ListRes=readdir(REP);

closedir(REP);


chdir($currWorkDir);


my %Scores;
my %MotsRef;

foreach my $Ligne (<SCORE>)
{
	$Ligne=~/(.*?\.res)_(.*?)_(.*?)_(.*?)\t(.*)/;

	if (! exists $Scores{$1})
	{
		my %NewTable;
		my %NewTable2;
		$Scores{$1}=\%NewTable;
		$MotsRef{$1}=\%NewTable2;
	}

	my $mot = $4;
	my $sc = $5+0.0;
	my $time = $2*100;

	$time=int($time);

	$Scores{$1}->{$time}=$sc;
	$MotsRef{$1}->{$time}=$mot;

	#print "$1 : $time : $mot : $sc\n";

}
close(SCORE);

foreach my $FichierRes (@ListRes)
{
	my $First=1;
	my $ZERO=0.0;

	if ($FichierRes=~/.*\.res$/)
	{

		open RES, "$RepRes/$FichierRes" or die "(res) impossible d'ouvrir $RepRes/$FichierRes\n";

		open ALIGN, ">$RepAlign/$FichierRes" or die "(align) impossible d'ouvrir $RepAlign/$FichierRes\n";
		#open ALIGN, ">to" or die "(align) impossible d'ouvrir $RepAlign/$FichierRes\n";


		foreach my $Ligne (<RES>)
		{
			my $NotFound=1;
			chomp $Ligne;
			
			$Ligne=~/.*? .*? (.*?) .* ([^ ]+) ?$/;
			
			if ($First == 1)
			{
				$ZERO=$1*100;
				$ZERO=int($ZERO);
			}

			my $time=($1*100)-$ZERO;
			$time=int($time);

			$First=0;

			#print "----> $2\n";

			#print "a : $FichierRes\n";

			for (my $i = -10; $i < 10 ; $i++)
			
			{
				my $tmp = $time+$i;
				if (exists $Scores{$FichierRes}->{$tmp} && $MotsRef{$FichierRes}->{$tmp} eq $2)
				{
					print ALIGN "$Ligne $Scores{$FichierRes}->{$tmp}\n";
					$NotFound=0;
					last;
				}
			}
			
			if ($NotFound == 1)
			{
				print ALIGN "$Ligne 0.6\n";
			}
		}


		close RES;
	}
}



