/**
 * A word frequency list containing one or more words
 * 
 * @author Russell C. Bjork 
 * @version March 22, 2008
 */

public class NonEmptyWordFrequencyList implements WordFrequencyList
{
    /**
     * Constructor for objects of class NonEmptyWordFrequencyList
     * 
     * @param firstWord the firstWord in this list
     * @param firstWordFrequency the frequency for this word
     * @param rest the rest of this list
     */
    public NonEmptyWordFrequencyList(String firstWord, 
                                     int firstWordFrequency,
                                     WordFrequencyList rest) {
        this.firstWord = firstWord;
        this.firstWordFrequencyCount = firstWordFrequency;
        this.rest = rest;
    }

    // The following methods are specified by interface WordFrequencyList
    
    public WordFrequencyList recordOccurrence(String word) {

        if (firstWord.equals(word)) {
            // The word matches the first word in this list - create
            // a new list with modified frequency for this word, and the
            // same rest
            return new NonEmptyWordFrequencyList(firstWord,
                                                 firstWordFrequencyCount + 1,
                                                 rest);
        }
        else if (firstWord.compareTo(word) < 0) {
            // The word is after the first word in this list - create
            // a new list containing the same first word, but with a rest
            // that records the modified count for the word
            return new NonEmptyWordFrequencyList(firstWord,
                                                 firstWordFrequencyCount,
                                                 rest.recordOccurrence(word));
        }
        else {
            // The word belongs before the first word in this list - hence
            // needs to be added before rest of list
            return new NonEmptyWordFrequencyList(word, 1, this);
        }
    }
    
    public int length() {
        int restLength = rest.length();
        return restLength + 1;
    }
    
    public int totalFrequencies() {
        int restTotalFrequencies = rest.totalFrequencies();
        return restTotalFrequencies + firstWordFrequencyCount;
    }
    
    public int occurrencesFor(String word) {
        if (firstWord.equals(word))
            return firstWordFrequencyCount;
        else if (firstWord.compareTo(word) < 0)
            return rest.occurrencesFor(word);
        else // Word would have occurred by now if it were present
            return 0;
    }
    
    public void print() {
        System.out.println(firstWord + " " + firstWordFrequencyCount);
        rest.print();
    }
    
    private String firstWord;               // The first word in the list
    private int firstWordFrequencyCount;    // Its frequency of occurrence
    private WordFrequencyList rest;         // The rest of the list
}
