#! /bin/bash/perl

$USAGE=<<ENDUSAGE;

SORT_TXGD.PL : sorts the TextGrid files into files with prosodic labels and files without prosodic labels
 
Usage:
  sort_txgd.pl scp1 scp2 dir

  scp1 contains prosody independent TextGrid files
  scp2 contains prosody dependent TextGrid files
  dir is the directory containing all the ws97 ToBI labeled files

Example: 
  praat2mlf.pl ind.scp prosody.scp ToBI

Scp1 and scp2 are in the format:
   
   file.wav file.mfc

for use with HCopy.  Both files can be used with praat2mlf.pl as follows:

   praat2mlf.pl 2 1 < prosody.scp > prosody.mlf;
   praat2mlf.pl 1 < ind.scp > ind.mlf;
   cat prosody.mlf ind.mlf > all.mlf;

ENDUSAGE

sub peruse_tree {

  opendir (TOPDIR, $_[0]) || die "Can't opendir $_[0]: $!";
  print STDERR "Reading from directory ",$_[0],"\n";
  my(@filelist) = readdir(TOPDIR);
  close(TOPDIR);

  foreach $filename (@filelist) {
     if ( $filename =~ /\.$/ ) {}
     elsif ( -d "$_[0]/$filename" ) {
     peruse_tree("$_[0]/$filename", "$_[1]", "$_[2]");
     }

    if ("$_[0]/$filename" =~ /\.TextGrid$/) {
       my ($file) = "$_[0]/$filename";
       open (FILE, "$file") or die "can't open $file : $!";
       $prosody = 0;
       for $_ (<FILE>)  {
          /mark =/ && { $prosody = 1, last }
       }
       close FILE; 
       $filename =~ s/TextGrid/wav/;
       $a = "$filename";
       $a =~ s/wav/MFC/g;
       if ($prosody == 0)  {
          print NEW "$_[0]/$filename data/$a\n";
       }
       else {
          print NEW2 "$_[0]/$filename data/$a\n";
       }
    }
else {}
}}

if (@ARGV==0) { print $USAGE; exit; }
open (NEW, ">$ARGV[0]") or die "cannot open scp file $ARGV[0] : $!";
open (NEW2, ">$ARGV[1]") or die "cannot open scp file $ARGV[1] : $!";
peruse_tree("$ARGV[2]") or die "cannot open directory $ARGV[2] : $!";
close NEW;
close NEW2;
