#!/vol/bin/perl

# author: Nils Jahn
# usage: perl praat2tr.pl tiernumber input-file > output-file

sub preprocess {	#sub searches for DOS line feeds
			#and replaces them with \n, it also
	$file1 = shift ;
	$file2 = shift ;
	open(F1, "<$file1") ;
	open(F2, ">$file2") ;
	while (<F1>) {
		tr/\015// ;
		print F2  $_ ;
	}
	print F2 "\titem\n" ;
	close(F1) ;
	close(F2) ;
}

sub writeFile {
	print "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n" ;
	print "<!DOCTYPE Trans SYSTEM \"trans-13.dtd\">\n" ;
	print "<Trans scribe=\"(unknown)\" audio_filename=\"$name\" version=\"2\" version_date=\"010129\">\n" ;
	print "<Episode>\n" ;
	print "<Section type=\"report\" startTime=\"$min\" endTime=\"$max\">\n" ;
	print "<Turn startTime=\"$min\" endTime=\"$max\">\n" ;
	$length = $#store ;
	for($counter=0; $counter<=$length; $counter++) {
		print "<Sync time=\"$store[$counter]{start}\"\/>\n" ;
		print "<Who nb=\"1\"\/>\n" ;	
		print "$store[$counter]{text}\n" ;
	}
	print "<\/Turn>\n" ;
	print "<\/Section>\n" ;
	print "<\/Episode>\n" ;
	print "<\/Trans>\n" ;
}

sub main {
	$tier = $ARGV[0] ; #specified tier number read in from console
	$name = $ARGV[1] ; #name of file read in from console
	preprocess($name, 'deleteme.tmp') ; #preprocess sub is invoked
	open(FILE, "<deleteme.tmp") ;
	undef $/ ;
	@store = () ;
	$contents = <FILE> ; #file is read into $contents
	if ($contents =~ m/xmin = (\d+\.?\d*).*\n.*?xmax = (\d+\.?\d*)/g) { 
		$min = $1 ; #signal start time is extracted
		$max = $2 ; #signal end time is extracted
		if ($contents =~ m/item *\[\]: *\n*(.+)/s) {
			$cont2 = $1 ; #body of file is stored in $cont
		}
		if ($cont2 =~ m/item *\[$tier\]:.*?\n(.+?)item/sg) {
			$cont3 = $1 ; #specified tier is stored in $cont3
		}
		$index = 0 ;
		while($cont3 =~ m/xmin = (\d+\.?\d*).*\n.*?xmax = \d+\.?\d*.*?\n.*?text = "(.*?)"/g) {
			$store[$index] = {
						start => $1, #start time of signal
						text => $2} ;#signal annotation
			$index++ ;
		}
	}
}


main ;
writeFile ;
