# Counts types of onsets in wordlist in ARPAbet format.
# 1st argument: name of dictionary file with ARPABET entries and syllable boundaries.
# 2nd argument: name of output file
# 3rd argument (optional): list of flags:
#       w	consider only word-initial onsets


 
if ( scalar( @ARGV ) >=  2 )
{ 
            $TheFile = $ARGV[0];
            $TheMainOutFile = ">" . $ARGV[1];
} 

else 
{           print  "Not enough arguments given to operate; goodbye."; 
            exit;
}

$Options = $ARGV[2];

if ( $Options =~ m/w/ ) { $WordInitialOnly = 1; } else {$WordIntialOnly = 0; }

open (INFILE, $TheFile) or die "The file $TheFile could not be found";
open (OUTFILE, $TheMainOutFile);

################################################################################# 
 
$WordCount =0;
$Counter = 0;

READWORD: while (<INFILE>)	{
	$TheLine= $_;
	chomp ($TheLine);
	$NumberOfWords++;	

	
	@Letters=split(/ /, $TheLine); 

	$Number = shift(@Letters);			
	$Spelling = shift (@Letters);
	$Spelling = shift (@Letters);

	while ( @Letters )	
	{	
		@Onset = (); 		
		while ( $Letter = shift ( @Letters ) )
		{
			
			$StrippedLetter = $Letter;
			$StrippedLetter =~ s/\d//;		 

			if ($StrippedLetter =~ /(AY|AH|ER|AW|EY|IY|OW|UW|OY|AE|AO|AA|EH|IH|OH|UH)/ )	 
			{ 
			    last; 
			}

			if ($Letter eq '') { next;} 
		
			push @Onset, $Letter;
	
		} 	 
	
		$Onset = join "-", @Onset ;
	
		
		if ($Onset eq '') {
			$Onset = "NULL";
			@TallyBySize[0]++;
		}

		$Tally{$Onset} ++;	
		@TallyBySize[scalar(@Onset)]++;

		if ($WordInitialOnly) { last;}	
		while ($Letter = shift ( @Letters) )
		{ if ( $Letter eq "\$" ) 
			{ last; }
		} 


	} 

}
	print "\nFinished reading dictionary.";
 
	$Entropy = 0;
	@SortedList = sort { $Tally{$b} <=> $Tally{$a} } keys(%Tally);
	 
	
	while ($ThisOnset = shift (@SortedList)) 
	{
		$OnsetTally = $Tally{$ThisOnset};
		$RunningTally += $OnsetTally/$NumberOfWords;
		$OnsetFreq = $OnsetTally/$NumberOfWords;
		print OUTFILE "\n $ThisOnset \t $OnsetTally \t $OnsetFreq \t $RunningTally"; 
	}
 
	print OUTFILE "\n\n","#"x40, "\nNumber of Onsets by length";
	for ($i=0;$i<9; $i++) 
	{
		if ($TallyBySize[$i] > 0 ) {
			$TallyFreq = $TallyBySize[$i]/$NumberOfWords;
			print OUTFILE "\n $i \t $TallyBySize[$i] \t  $TallyFreq";
	}
}

close OUTFILE;

	
 
 