# initialize dict to the command line arguments
foreach $i (@ARGV) {
  $word = lc($i);
  push(@lowercase_words, $word);
  $dict{$word} = 0;
}

while($line = <STDIN>){  # get the words
  # make everything lowercase using the lc function
  $line = lc($line);
  $line =~ s/^\s+//;  # remove leading spaces
  @fields = split(/\s+/, $line);
  foreach $word (@fields) {
    # strip trailing punctuation 
    $word =~ /^(\w+)/;
    # if the word is in the dictionary, increment its frequency count
    if (exists($dict{$1})) {
      $dict{$1}++;
    }
  }
}

# the primary sort key is word frequency and the secondary key is
# alphabetical order. Note that if the word frequencies are equal, then
# <=> returns 0, which is interpreted as false, and the second string
# comparison is performed. I sort using the lowercase words but print
# out using @ARGV, because I want the original words.
@keys = sort {$dict{$b} <=> $dict{$a} || $a cmp $b} @lowercase_words;
foreach $word (@keys) {
  print "$word: $dict{lc($word)}\n"
}

