import java.io.*;

class FortuneIndexer {

    public static void main(String[] args) {
	try {
	    RandomAccessFile textFile =
		new RandomAccessFile("fortunes.text", "r");
	    RandomAccessFile indexFile =
		new RandomAccessFile("fortunes.index", "rw");

	    try {
		while (true) {
		    indexFile.writeLong(textFile.getFilePointer());
		    String line;
		    do {
			line = textFile.readLine();
		    } while (!line.startsWith("%%"));
		}
	    } catch (EOFException ignore) {
	    }
	    textFile.close();
	    indexFile.close();
	} catch (IOException e) {
	    error("I/O Exception: " + e);
	}		
    }

    public static void error(String err) {
	System.err.println("FortuneIndexer: " + err);
	System.exit(1); // non-zero argument means "not good"
    }
}



import java.io.*;

class Fortune {

    public static void main(String[] args) {
	try {
	    RandomAccessFile textFile =
		new RandomAccessFile("fortunes.text", "r");
	    RandomAccessFile indexFile =
		new RandomAccessFile("fortunes.index", "r");

	    long total = indexFile.length() / 8;
	    long choice = (long)(Math.random() * total);
	    indexFile.seek(choice * 8);
	    long offset = indexFile.readLong();
	    textFile.seek(offset);
	    while (true) {
		String line = textFile.readLine();
		if (line.startsWith("%%"))
		    break;
		System.out.println(line);
	    }
	} catch (IOException e) {
	    error("I/O Exception: " + e);
	}
    }

    public static void error(String err) {
	System.err.println("Fortune: " + err);
	System.exit(1); // non-zero argument means "not good"
    }
}

