#!/vol/bin/perl

# author: Nils Jahn
# usage: perl tasx2textgrid.pl input > output
# The program converts an XML file (tasx) into a praat TextGrid file.

sub initVariables {	
	$items = 0 ;
	$sges = 1000 ;
	$eges = 0 ;
	undef $/ ;
	$fname = $ARGV[0] ;
	$cont = readFile($fname) ;
	$laynr = 1 ;
}

sub readFile {
	$file = shift ;
	open(FILE, "<$file") ;
	return $fileContents = <FILE> ;
}

sub getValues {
	while ($cont =~ m/<layer/g) {	# how many items are in one tier
		$items++ ;
	}
	# get signal's start and end time
	while ($cont =~ m/<event .*? start=\"(\d+\.?\d*)\" end=\"(\d+\.?\d*)/g) {
		$sges = $1 if $1 < $sges ;	
		$eges = $2 if $2 > $eges ;
	}
}

sub main {
	# print header of output file
	print "File type = \"ooTextFile\"\n" ;
	print "Object class = \"TextGrid\"\n\n" ;
	print "xmin = $sges\n" ;
	print "xmax = $eges\n" ;
	print "tiers? <exists>\n" ;
	print "size = $items\n" ;
	print "item []:\n" ;
	# write layer information to output file
	while ($cont =~ m/<layer l-id=\"(.*?)\"(.+?)<\/layer/sg) {
		$id = $1 ;
		$layer = $2 ;
		$noitems = 0 ;
		while ($layer =~ m/<event/g) {
			$noitems++ ;
		}
		$interval = 1 ;
		print "\titem \[$laynr\]:\n" ;
		print "\t\tclass = \"IntervalTier\"\n" ;
		print "\t\tname = \"$id\"\n" ;
		print "\t\txmin = $sges\n" ;
		print "\t\txmax = $eges\n" ;
		print "\t\tintervals: size = $noitems\n" ;	
		while ($layer =~ m/<event .+? start=\"(\d+\.?\d*)\" end=\"(\d+\.?\d*)\">(.*?)</g) {
			print "\t\tintervals \[$interval\]:\n" ;
			print "\t\t\txmin = $1\n" ;
			print "\t\t\txmax = $2\n" ;
			print "\t\t\ttext = \"$3\"\n" ;
			$interval++ ;	
		}
		$laynr ++ ;	
	}
	close(FILE) ;
}

initVariables ;
getValues ;
main ;
