#!/usr/bin/perl 
# USAGE: praat2tasx.pl INFILE

my $numberoftiers = 0;


$filename = $ARGV[0] ; #name of file read in from console

($CTIME) = (stat($filename))[9];
$CREATIONDAY= localtime($CTIME);
($MONTH, $DAY, $YEAR) = (localtime $CTIME)[4,3,5];
$MONTH = $MONTH+1;
$YEAR= $YEAR+1900;

open(FILE, "<$filename") ;

undef $/ ;#
print "<!DOCTYPE tasx system \"/homes/ttrippel/GENERICDTD/tasx.dtd\">\n";
 print "<tasx>\n";
print "<session s-id=\"$filename\" day=\"$DAY\" month=\"$MONTH\" year=\"$YEAR\">\n";
print "       <meta m-id=\"$filename\">\n";
print "       <desc>\n<name>Audio-Filename</name>\n<val>$filename</val>\n</desc>\n";
print "       </meta>\n\n\n";



@store = () ;
$contents = <FILE> ; #file is read into $contents
$contents =~ s/</\&lt;/g ; # < is replaced by &lt;
$contents =~ s/>/\&gt;/g ; # > is replaced by &gt;
$contents =~ m/(?<!intervals:\s)size =\s*(\d)/g;
$tiernumber = $1;
$numberoftier=$tiernumber;


for ($tier=1; $tier <= $numberoftier; $tier++){
@store = () ;
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
	}
if ($cont2 =~ m/item *\[$tier\]:.*?\n(.+?)$/sg) {
		$cont3 = $1 ; #specified tier is stored in $cont3
	}
	$index = 0 ;
        while($cont3 =~ m/name = \"(.*)\"/g){
		$layernamelong= $1;
		$layeridbase=removewspace($layernamelong);
		print "<layer l-id=\"$layeridbase-$tier\">\n";
	}
	while($cont3 =~ m/xmin = (\d+\.?\d*).*\n.*?xmax = (\d+\.?\d*).*?\n.*?text = "(.*?)"/g) {
		$store[$index] = {
					start => $1, #start time of signal
				        end => $2, #end time of signal
					text => $3} ;#signal annotation
		$index++ ;
	}
}

$length = $#store ;
for($counter=0; $counter<=$length; $counter++) {
	print "<event e-id=\"$filename-$tier-$counter\" start=\"$store[$counter]{start}\" end=\"$store[$counter]{end}\">" ;
	print "$store[$counter]{text}<\/event>\n" ;
}

print "<\/layer>\n\n\n" ;

}
print "<\/session>\n" ;
print "<\/tasx>\n" ;


##########################
##########################
###### Sub-functions #####
##########################
##########################  

sub removewspace {
$_= $layernamelong;
s/ //g;
s/\(//g;
s/\)//g;
return $_;
}
