import java.awt.*;
import java.io.*;

/**
 * Simple class to read lines in from a text file. To use, create a
 * <code>LineReader</code> object, then send it the <code>readLine()</code>
 * message as many times as desired. When <code>readLine()</code> returns
 * the value <code>null</code>, the last line has been read,
 * and you should <code>close()</code> the file.
 * 
 * @author: David Matuszek
 * @version 2.0
 */
class LineReader {
    BufferedReader bufferedReader;
    
    /**
     * Creates a LineReader to read lines (as Strings) from a file.
     * Calling this constructor causes a standard file dialog box to
     * open, allowing the user to choose a file; the message is
     * displayed at the top of the dialog box.
     */
    LineReader(String message) {
        // use a file dialog to get the name and directory of a file
        FileDialog dialog = new FileDialog(new Frame(), message, FileDialog.LOAD);
        dialog.setVisible(true);
        String dir = dialog.getDirectory();
        String file = dialog.getFile();
        
        // make sure we got a file
        if (dir == null || file == null) {
            System.err.println("No file selected.");
            return;
        }
        
        // construct the full path name of the file
        String fileName = dir + file;

        // create and remember a reader for the file
        FileReader fileReader = null;
        try {
            fileReader = new FileReader(fileName);
        }
        catch (FileNotFoundException e) {
            System.err.println ("LineReader can't find input file: " + fileName);
            e.printStackTrace ();
        }
        bufferedReader = new BufferedReader (fileReader);
    }
    
    /**
     * This constructor is used if you forget to supply a message to
     * be displayed in the dialog box.
     */
    LineReader() {
        this("Read lines from what file?");
    }
    
    /**
     * Once you have created a LineReader for a file, each call to
     * <code>readLine()</code> will return another line from that file.
     * After the last line in read, <code>readLine()</code> will return
     * <code>null</code> instead of a String.
     */
    String readLine () {
        if (bufferedReader == null) {
            System.err.println("readLine() called without a valid input file.");
            return null;
        }
        try { return bufferedReader.readLine (); }
        catch (IOException e) { e.printStackTrace (); }
        return null;
    } 

    /**
     * Closes the file used by this LineReader.
     */
     void close () {
        try { bufferedReader.close (); }
        catch (IOException e) { }
    } 
}
