#!/usr/bin/perl

# Perl program to convert .lbl file into .rttm ones
#
# Author: Xavier Bost
# email: xavier.bost@univ-avignon.fr
#
# Synopsis:
#
# Source file: (arg1).lbl
#
# Retained informations are written in:
# (arg2).rttm

use strict;

my $line;                  # current source file line
my @fields;                # current line fields
my $file_in;
my $file_out;
my $speaker;
my %start = ();
my %end = ();
my $base_name;
my $i;
my $dur;

my $nArgs = scalar(@ARGV); # command line arguments number

# die out if improper number of arguments
($nArgs == 2)
    or 
    die "Error: two arguments expected (input file, output file).\n";

$file_in = shift(@ARGV);
$file_out = shift(@ARGV);

if ($file_in =~ /.*\/(.+)\.lbl/) {
    $base_name = $1;
}

open(IN, $file_in);

# parsing input file
while ($line = <IN>) {
    chomp($line);

    @fields = split(/\ /, $line);

    $speaker = $fields[2];
    $start{$speaker}{$i} = $fields[0];
    $end{$speaker}{$i} = $fields[1];

    $i++;
}

close(IN);

open(OUT, "> $file_out");

# writing out data
for $speaker (sort keys %start) {
    print OUT "SPKR-INFO ".$base_name." 1 <NA> <NA> <NA> unknown ".$speaker." <NA>\n";
}

foreach $speaker (sort keys %start) {
    foreach $i (sort {$start{$speaker}{$a}<=>$start{$speaker}{$b}} keys %{$start{$speaker}}) {
	$dur = $end{$speaker}{$i} - $start{$speaker}{$i};
	printf OUT ("SPEAKER %s 1 %.2f %.2f <NA> <NA> %s <NA>\n", $base_name, $start{$speaker}{$i}, $dur, $speaker);
    }
}

close(OUT);
