#!/vol/perl/bin/perl 
#USAGE: praat2tasx.pl INFILE OUTFILE TIMESHIFT

my $numberoftiers = 0;
$infilename = $ARGV[0] ; #name of file read in from console
$outfilename = $ARGV[1] ;
$aligntime = $ARGV[2];

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

#print "Give start time (signal aligned) \n
#	for $infilename in seconds.\n
#        Use period for decimal postions.\n";
#$aligntime = <STDIN>;

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



@store = () ;
$contents = <INFILE> ; #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
	$alignedmin = $min+$aligntime;
	$alignedmax = $max+$aligntime;

	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 OUTFILE "<layer l-id=\"$layeridbase-$tier\">\n";
	}
	while($cont3 =~ m/xmin = (\d+\.?\d*).*\n.*?xmax = (\d+\.?\d*).*?\n.*?text = "(.*?)"/g) {
		$store[$index] = {
					start => $1+$aligntime, #start time of signal
				        end => $2+$aligntime, #end time of signal
					text => $3} ;#signal annotation
		$index++ ;
	}
}

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

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

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


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

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