import java.io.*;

/**
 * Analyze the frequency of occurrence of various words in a text
 * 
 * @author Russell C. Bjork 
 * @version March 22, 2008
 */

public class AnalyzeWordFrequency
{
    /** 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 {
        
        WordFrequencyList list = new EmptyWordFrequencyList();
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        boolean allLinesProcessed = false;
        
        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)
                        list = list.recordOccurrence(words[i]); 
            }
        } while (! allLinesProcessed);
        
        if (args.length > 0) {
            for (int i = 0; i < args.length; i ++)
                System.out.println(args[i] + " occurred " + 
                                   list.occurrencesFor(args[i]) + " times.");
        }
        else {
            // Print frequencies for all words
            System.out.println(list.length() + " words, occurring a total of " +
                               list.totalFrequencies() + " times:");
            list.print();
        }
        System.exit(0);
    }
}
