#! /usr/bin/perl
#
# Do a precission alignment using a
# cross-corelations (lag -0.2, 0.2)
# between downsampled (4000 Hz) original and recorded
# Alignment is done by "shifting" the sound in the file,
# adding silence where needed.
# files.
#
# Use: AlignFiles.pl filenameglob1 filenameglob2 [outputfile]
#
#	filenameglob1 A glob that gives the first list of files (originals)
#	filenameglob2 A glob that gives the corresponding list of files (recordings)
#	outputfile    Receives the difference numbers
# 
#    
# Copyright (C) 2002  R.J.J.H. van Son
#
#  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
# 
#
# Get arguments
my $Files1Glob = shift(@ARGV);
my $Files2Glob = shift(@ARGV);
my $OutputFile = shift(@ARGV) || "difference.txt";

my @FirstList = glob($Files1Glob);
my @SecondList = glob($Files2Glob);

while(@FirstList && @SecondList)
{
	my $CurrentFile1 = shift(@FirstList);
	my $CurrentFile2 = shift(@SecondList);
print "$CurrentFile1 - $CurrentFile2\n";
	# Get offset by DTW
	my $DetermineOffset = << "DETERMINEOFFSETEND";
# Use Cross correlation to determine offset
lagduration = 0.2
Read from file... $CurrentFile1
Resample... 4000 50
Rename... Target
Read from file... $CurrentFile2
Resample... 4000 50
Rename... Source
duration = Get duration
select Sound Target
plus Sound Source
Cross-correlate... -lagduration lagduration yes
Rename... CrossCorrelation
Formula... abs(self)
offset = Get time of maximum... 0 0 Sinc70

# Write to output
output\$ = "'offset' = $CurrentFile1 - $CurrentFile2 'newline\$'"
output\$ >> $OutputFile

select all
Remove

DETERMINEOFFSETEND
	push(@PraatMasterScript, $DetermineOffset);
			
	# Play Praat script (if necesarry)
	if(@PraatMasterScript)
	{
		my $time = time;
		my $ScratchFile = "SCRATCH$time.praat";
		open(PRAATSCRIPT, ">$ScratchFile");
		# print @PraatMasterScript;
		print PRAATSCRIPT @PraatMasterScript;
		print PRAATSCRIPT "Quit\n";
		close(PRAATSCRIPT);
		`praat $ScratchFile;rm $ScratchFile`;
		@PraatMasterScript = ();
	};
};
