import java.io.*;
import java.util.*;

/**
 * Analyze the frequency of occurrence of various words in a text - non
 * recursive solution
 * 
 * @author Russell C. Bjork 
 * @version March 22, 2008
 */

public class NonRecursiveSolution
{
    /** Main method for program.  The text will be read from standard input.
     *  If there are any command line arguments, then frequency counts for
     *  those words will be written to standard output; if none, frequency 
     *  counts for all words occurring in the text will be written to standard 
     *  output
     *  
     *  @exception IOException if there was a problem reading standard input
     */
    public static void main(String [] args) throws IOException {
        
        TreeMap<String, Integer> list = new TreeMap<String, Integer>();
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        boolean allLinesProcessed = false;
        int totalWords = 0;
        
        do {
            String oneLine = input.readLine();
            if (oneLine == null)
                allLinesProcessed = true;
            else {
                // Break line apart into words separated by non-word characters
                String [] words = oneLine.trim().toLowerCase().split("\\W+");
                for (int i = 0; i < words.length; i ++)
                    if (words[i].length() != 0) {
                        
                        Integer countSoFar = list.get(words[i]);
                        if (countSoFar == null)
                            list.put(words[i], 1);
                        else
                            list.put(words[i], countSoFar + 1);
                        totalWords ++;
                    }
            }
        } while (! allLinesProcessed);
        
        if (args.length > 0) {
            for (int i = 0; i < args.length; i ++) {
                Integer count = list.get(args[i]);
                if (count != null)
                    System.out.println(args[i] + " occurred " + 
                                   count + " times.");
                else
                    System.out.println(args[i] + " did not occur");
            }
        }
        else {
            // Print frequencies for all words
            System.out.println(list.size() + " words, occurring a total of " +
                               totalWords + " times:");
            for (String word : list.keySet())
                System.out.println(word + " " + list.get(word));
        }
        System.exit(0);
    }

}
