/* WordCounter.java
 * CS 136 Spring 2007
 * Tutorial 11: File I/O and Java Arrays
 */

import java.util.Scanner;
import java.io.*;

/* This class can be used to count the frequency of words in
 * a given text file.
 */
public class WordCounter extends FrequencyList<String> {
  
  /* Makes a new WordCounter, reading in words from the
   * file with the given name.
   * pre: filename is the name of a file which exists
   *      and is readable.
   */
  public WordCounter( String filename ) {
    super();
    Scanner in = null;
    try {
      in = new Scanner(new File(filename));
    } 
    catch( FileNotFoundException e ) {
      throw new Error("Can't find input file: " + filename);
    }
    
    while( in.hasNext() )
      add(in.next());
    
    in.close();
  }
  
  /* Writes out the frequencies in this list to the given
   * named file, in order from most to least frequent. One word
   * per line is printed, along with the corresponding frequency.
   * pre: filename is able to be created and/or written to.
   * post: true
   */
  public void writeFrequencies(String filename) {
    PrintWriter out = null;
    try {
      out = new PrintWriter(filename);
    }
    catch( FileNotFoundException e ) {
      throw new Error("Can't open output file: " + filename);
    }
    
    GenList<FrequencyPair<String>> mf = mostFrequent(length());
    String[] toPrint = new String[length()];
    int i = toPrint.length - 1;
    
    while( mf != null ) {
      toPrint[i] = mf.first.getFrequency() + "\t" + mf.first.getItem();
      --i;
      mf = mf.rest;
    }
    
    for( i = 0; i < toPrint.length; ++i )
      out.println(toPrint[i]);
    
    out.close();
  }

}
