#! /usr/bin/perl
#
if(grep(/^(\-h|\-\-help)$/, @ARGV))
{
print << "ENDOFHELPTEXT";
Update the tiernames to the correct speaker and tier names

Use:
<<<<<<< HEAD:Annotations/scripts/EnterCorrectTierNames.pl
./EnterCorrectOrtTierNames.pl type ... [--rectable] [--root=<dir>] 2> error.txt
=======
./EnterCorrectOrtTierNames.pl <../type/filename> ... [--rectable] [--root=<dir>] 2> error.txt
>>>>>>> 5b08cbe... Added CombineTiers.sh:Annotations/scripts/EnterCorrectTierNames.pl

Options:
--rectable=<file>
  Use different table with speaker names
  Default is "../../tables/recordings.txt"

--subjable=<file>
  Use different table with speaker names
  Default is "../../tables/subjects.txt"

--root=<dir>
  CGN annotation text root directory. 
  Default is "../"

-l
--license
  License text
  
-h
--help
  This help text

Processing:
Files are read from "\$CGNrootDir/<type>".
The output TextGrids are placed in "\$CGNrootDir/<type>/"
the filename will be extended with an indication that the 
tiernames have been changed

ENDOFHELPTEXT
exit;
};
if(grep(/\-?\-l(icense)?/, @ARGV))
{
print << "ENDOFLICENSETEXT";
###############################################################################
#
# Copyright R.J.J.H. van Son © 2007
#
# Author Rob van Son
# Institute of Phonetic Sciences & ACLC
# University of Amsterdam
# Herengracht 338
# NL-1016CG Amsterdam, The Netherlands
# Email: R.J.J.H.vanSon\@uva.nl
# WWW  : http://www.fon.hum.uva.nl/rob/
# mail:  Institute of Phonetic Sciences
#        University of Amsterdam
#        Spuistraat 210-212
#        NL-1012VT Amsterdam
#        The Netherlands
#        tel +31 205252196
#        fax +31 205252197
#
# License for use and disclaimers
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
#
#######################################################
ENDOFLICENSETEXT
exit;
};
#
require "SentenceLabel.pl";
require "CGN_phonemes.pl";

my $CGNrootDir = "../";
if(grep(/\-\-root\=/, @ARGV))
{
    my ($Option) = grep(/\-\-root\=/i, @ARGV);
    $Option =~ s/\-\-root\=//isg;
    $CGNrootDir = $Option;
    @ARGV = grep(!/\-\-root\=/i, @ARGV);
};

my $CGNrectable = "../../tables/recordings.txt";
if(grep(/\-\-rectable\=/, @ARGV))
{
    my ($Option) = grep(/\-\-rectable\=/i, @ARGV);
    $Option =~ s/\-\-rectable\=//isg;
    $CGNrootDir = $Option;
    @ARGV = grep(!/\-\-rectable\=/i, @ARGV);
};

my $CGNsubjtable = "../../tables/subjects.txt";
if(grep(/\-\-subjtable\=/, @ARGV))
{
    my ($Option) = grep(/\-\-subjtable\=/i, @ARGV);
    $Option =~ s/\-\-subjtable\=//isg;
    $CGNrootDir = $Option;
    @ARGV = grep(!/\-\-subjtable\=/i, @ARGV);
};

# Read the recordings table
my %RecTable = ();
my %SubjCountTable = ();
open(RECTAB, "<$CGNrectable") || die "$CGNrectable: $!\n";
my @reccolumnnames = ();
$skip = 1;
while(<RECTAB>)
{
    chomp;
    # Skip header
    if(m!Start tab separated data: Content-type="text/tab-separated-values"!)
    {
        $skip = 0;
        next;
    }
    elsif($skip)
    {
        next;
    };
    
    # Get the fields
    my @fieldlist = split(/\t/);
    
    # Get the column names
    unless(@reccolumnnames)
    {
        @reccolumnnames = @fieldlist;
        next;
    };
    
    for($i=0;$i < scalar(@fieldlist); ++$i)
    {
        $RecTable{$fieldlist[0]}{$reccolumnnames[$i]} = $fieldlist[$i];
    };
    
    # Update subject count
    ++$SubjCountTable{$RecTable{$fieldlist[0]}{subA}};
    ++$SubjCountTable{$RecTable{$fieldlist[0]}{subB}};
    $RecTable{$fieldlist[0]}{subAcnt} = $SubjCountTable{$RecTable{$fieldlist[0]}{subA}};
    $RecTable{$fieldlist[0]}{subBcnt} = $SubjCountTable{$RecTable{$fieldlist[0]}{subB}};
};
close(RECTAB);

# Read the subjects table
my %subjtable = ();
open(SUBTAB, "<$CGNsubjtable") || die "$CGNsubjtable: $!\n";
my @subjcolumnnames = ();
$skip = 1;
while(<SUBTAB>)
{
    chomp;
    # Skip header
    if(m!Start tab separated data: Content-type="text/tab-separated-values"!)
    {
        $skip = 0;
        next;
    }
    elsif($skip)
    {
        next;
    };
    
    # Get the fields
    my @fieldlist = split(/\t/);
    
    # Get the column names
    unless(@subjcolumnnames)
    {
        @subjcolumnnames = @fieldlist;
        next;
    };
    
    for($i=0;$i < scalar(@fieldlist); ++$i)
    {
        $subjtable{$fieldlist[2]}{$subjcolumnnames[$i]} = $fieldlist[$i];
        $subjtable{$fieldlist[2]}{fullidcode} = 
            $subjtable{$fieldlist[2]}{"Sex"}
            .$subjtable{$fieldlist[2]}{"Age"}
            .$subjtable{$fieldlist[2]}{"IDcode"};
    };
};
close(SUBTAB);

# Read and process the annotation files
foreach my $AnnotationFile (@ARGV)
{
    $AnnotationFile =~ m!(^|/)DV([AB])(\d+)([A-Z]+)(_|\.)!;
    my $camera = $2;
    my $recording = $3;
    my $perspective = $4;
    my $fullID = $&;
    
    my $othercamera = $camera eq 'A' ? 'B' : 'A';
    
    my %subject = ();
    $subject{A} = $RecTable{$recording}{subA};
    $subject{B} = $RecTable{$recording}{subB};
    my %subjectCnt = ();
    $subjectCnt{A} = $RecTable{$recording}{subAcnt};
    $subjectCnt{B} = $RecTable{$recording}{subBcnt};
    
    my $speaker1 = $subjtable{$subject{$camera}}{fullidcode}.$subjectCnt{$camera};
    my $speaker2 = $subjtable{$subject{$othercamera}}{fullidcode}.$subjectCnt{$othercamera};
    
    
    print "$fullID: $speaker1 + $speaker2\n";
    
    my $OutputFile = "$AnnotationFile.TierName";
    while(-s "$OutputFile")
    {
        $OutputFile .= ".TierName";
    };
    
    open(ANNOTFILE, "<$AnnotationFile") || die "$AnnotationFile:$!\n";
    open(OUTFILE, ">$OutputFile") || die "$OutputFile:$!\n";
    
    my $skip = 1;
    while(<ANNOTFILE>)
    {
        s/\x00//g;
        if($AnnotationFile =~ /\.gaze/i && / (\[[mv]\] )?\(TIE\d\)/)
        {
            $_ =~ s/spreker1/DV$camera$recording${speaker1}ort/g;
            $_ =~ s/spreker2/DV$othercamera$recording${speaker2}ort/g;
            
            # Clean up EAF files
            $_ =~  s/kijkrichting( DV)?/GD/g;
            $_ =~ s/ (\[[mv]\] )?\(TIE\d+\)//g;
            $_ =~ s/ort\"/gaze\"/g if $_ =~ /\"GD[AB]\d+/;
        }
        elsif(/"IntervalTier"/)
        {
            $skip = 0;
        }
        elsif(!$skip)
        {
            $skip = 1;
            $_ =~ s/spreker1/DV$camera$recording$speaker1/g;
            $_ =~ s/spreker2/DV$othercamera$recording$speaker2/g;
        };
        
        print OUTFILE $_;
    };
    
};
