import java.io.EOFException;		// So we can determine end-of-file
import java.util.Hashtable;		// For storing information on accesses
import rebelsky.io.SimpleOutput;	// Yes, we're generating output
import rebelsky.io.SimpleReader;	// And reading input
import rebelsky.util.Counter;		// For counting accesses

/**
 * Count a series of web page accesses and report on the most
 * frequently accessed page.  Takes the name of the file
 * containing this information from the command line.
 *
 * @author Samuel A. Rebelsky
 * @version 1.0 of February 1998
 */
public class PageCounter 
{
  /**
   * Count those pages.
   *
   * @exception Exception
   *   when any trouble occurs.  Yes, that's right.  This crashes and
   *   burns horribly without any real error checking.
   */
  public static void main(String[] args)
    throws Exception
  {
    // Input to the program.
    SimpleReader file;
    // Output from the program.
    SimpleOutput out = new SimpleOutput();
    // The hash table that stores the pages we've seen.
    Hashtable pages = new Hashtable();
    // The host that requested the page
    String host;
    // The page that was requested
    String page;
    // The number of pages we've processed
    Counter processed = new Counter();

    // Sanity check.  Was the program called correctly?
    if (args.length != 1) {
      out.println("Usage: java PageCounter filename");
      out.println("   or: ji PageCounter filename");
      System.exit(1);
    }

    // Initialize input
    file = new SimpleReader(args[0]);

    // Read lines until end of file
    try {
      while (true) {
        // Read the host and page.
        host = file.readString();
        page = file.readString();
        // Skip anything else on the line.
        file.readLine();
        // And processs ...
        // If we've already seen the page, just increment its counter.
        if (pages.containsKey(page)) {
          ((Counter) pages.get(page)).increment();
        }
        // If we haven't seen the page, build a new counter with base
        // value 1.
        else {
          pages.put(page, new Counter(1));
        }
        // Note that we've processed another line
        processed.increment();
      } // while
    } //try
    catch (EOFException e) {
      // Do nothing except exit the loop.
    }
    
    // Okay, we're done, report anything interesting.
    out.println("We've processed " + processed.value() + " lines.");
    out.println("We've seen " + pages.size() + " different pages.");
    // ...
 
    // That's it.
    System.exit(0);
  } // main
} // PageCounter

