#! /usr/bin/perl
#
# Read a Praat label sentence file, correct id's of indicated,
# items and their progeny.
#
# Use: 
my $helptext =<< 'ENDOFHELPTEXT';
./RepairIDcodesInLabelFile.pl [options] File1 ....

Read a Praat label sentence file, correct id's of indicated,
items and their progeny. Write output to a NEW file.
Generates a new filename or writes output in a designated directory
(Will overwrite existing files if names clash)

File1 ... 
   A list of names of Praat short Label files to process. 
   Uses '-' (<STDIN>) if no input filenames are given.

Options
-t --tier <name> [WORDS]
   Name of tier to use as master
-o --output <directory> [input file path]
   Name of output directory
-l --label <label> [.CORRECTED]
   Label added to filename id input filename would be overwritten
-m --marker <marker> [!!!]
   Search marker indicating items to be processed, '' means all
-a --all
   Process all items
-h --help
   This text
-v --version
   License and copyrights
ENDOFHELPTEXT
# 
my $VersionText =<< 'ENDOFVERSIONTEXT';
###############################################################################
#
# Copyright R.J.J.H. van Son © 2003
#
# Author Rob van Son
# Institute of Phonetic Sciences & ACLC
# University of Amsterdam
# Herengracht 338
# NL-1016CG Amsterdam, The Netherlands
# Email: Rob.van.Son@hum.uva.nl
#        ifa@hum.uva.nl
# WWW  : http://www.fon.hum.uva.nl/rob/
# mail:  Institute of Phonetic Sciences
#        University of Amsterdam
#        Herengracht 338
#        NL-1016CG Amsterdam
#        The Netherlands
#        tel +31 205252183
#        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.
#
#
#######################################################
ENDOFVERSIONTEXT
#
require "SentenceLabel.pl" || die "$!\n";

my $MASTERTIER = "WORDS";   # What Tier to use as master
my $OUTPUTDIRECTORY = '';   # Where to write the result
my $CORRECTIONLABEL = '.CORRECTED'; # How to label results in the SAME directory
my $CORRECTIONMARKER = "!!!";   # What items to process

# Process command line options
my $i = 0;
while($i <= scalar(@ARGV))
{
    if($ARGV[$i] =~ /\-[\-]?v(ersion)?$/i)
    {
        print STDERR $VersionText;
        exit;
    }
    elsif($ARGV[$i] =~ /\-[\-]?h(elp)?$/i)
    {
        print STDERR $helptext;
        exit;
    }
    # Which tier?
    elsif($ARGV[$i] =~ /\-[\-]?t(ier)?$/i)
    {
        $MASTERTIER = uc($ARGV[$i+1]);
        splice(@ARGV, $i, 2);
        --$i;
    } 
    # Output Directory
    elsif($ARGV[$i] =~ /\-[\-]?o(utput)?$/i)
    {
        $OUTPUTDIRECTORY = $ARGV[$i+1];
        splice(@ARGV, $i, 2);
        --$i;
    } 
    # Label to add to 
    elsif($ARGV[$i] =~ /\-[\-]?l(abel)?$/i)
    {
        $CORRECTIONLABEL = $ARGV[$i+1];
        splice(@ARGV, $i, 2);
        --$i;
    } 
    # What corrector marker symbol?
    elsif($ARGV[$i] =~ /\-[\-]?m(arker)?$/i)
    {
        $CORRECTIONMARKER = $ARGV[$i+1];
        splice(@ARGV, $i, 2);
        --$i;
    } 
    # Just do everything
    elsif($ARGV[$i] =~ /\-[\-]?a(ll)?$/i)
    {
        $CORRECTIONMARKER = '';
        splice(@ARGV, $i, 1);
        --$i;
    }; 
    ++$i;
};


push(@ARGV, '-') unless @ARGV;
my $File;
foreach $File (@ARGV)
{
    # Construct a unique output filename
    my $OutputFile = $File ne '-' ? $File : 'STDOUT';
    if($OUTPUTDIRECTORY && $OutputFile ne 'STDOUT')
    {
        $OutputFile = $1 if $OutputFile =~ m!([^/]+)$!;
        $OutputFile = "$OUTPUTDIRECTORY/$OutputFile";
    };
    $OutputFile = $OutputFile.$CORRECTIONLABEL if $OutputFile eq $File;
    
    # Check whether the outputfile exists and is more recent
    next if -e "$OutputFile"; 
    
	my $TextGrid = new SentenceLabel;
	$TextGrid->ReadLabelFile($File);
    
    print STDERR "Tier: '$MASTERTIER' Marker: '$CORRECTIONMARKER' File: $File\n";
    
    # Walk the mastertier
    $TextGrid->presetItem($MASTERTIER);
    while($TextGrid->nextItem($MASTERTIER) > -1)
    {
        # Do only something when needed
        next unless $CORRECTIONMARKER eq '' ||
                    $TextGrid->currentValue($MASTERTIER) =~ /\Q$CORRECTIONMARKER\E/;
        
        # We have to correct this item
        # Start with removing the corrector symbol
        my $currentValue = $TextGrid->currentValue($MASTERTIER);
        $currentValue =~ s/\Q$CORRECTIONMARKER\E//g if $CORRECTIONMARKER;
        $TextGrid->currentValue($MASTERTIER, $currentValue);
        # Get the next tier down
        $TextGrid->reconstructIDcodes($MASTERTIER);
        
        # Reconstruct the values
        $TextGrid->reconstructValues($MASTERTIER, 'SYLLPARTS', 'PHONEMES', '', '');
        $TextGrid->reconstructValues($MASTERTIER, 'SYLLABLES', 'PHONEMES', '', '[\"]');
        $TextGrid->reconstructValues($MASTERTIER, 'CGN', 'SYLLABLES', '-', '');
    };
    
    # Print output
    $TextGrid->FoldedIDcodes(@{$TextGrid->{'TIERORDER'}});
    $TextGrid->print($OutputFile, reverse(@{$TextGrid->{'TIERORDER'}}));
};
