/*
 * Copyright (c) 1995-1997 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Permission to use, copy, modify, and distribute this software
 * and its documentation for NON-COMMERCIAL purposes and without
 * fee is hereby granted provided that this copyright notice
 * appears in all copies. Please refer to the file "copyright.html"
 * for further important copyright and licensing information.
 *
 * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
 * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
 * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */
import java.io.*;

class RhymingWords {
    public static void main(String[] args) {

        try {
            FileReader words = new FileReader("words.txt");

                // do the reversing and sorting
            Reader rhymedWords = reverse(sort(reverse(words)));

                // write new list to standard out
            BufferedReader br = new BufferedReader(rhymedWords);
            String input;
	    PrintWriter stdout = new PrintWriter(System.out, true);

            while ((input = br.readLine()) != null) {
                stdout.println(input);
            }
            br.close();

        } catch (Exception e) {
            System.err.println("RhymingWords: " + e);
        }
    }

    public static Reader reverse(Reader source) {
        PipedWriter pw = null;
        PipedReader pr = null;

        try {
            BufferedReader br = new BufferedReader(source);

            pw = new PipedWriter();
            pr = new PipedReader(pw);
            PrintWriter output = new PrintWriter(pw);

            new WriteReversedThread(output, br).start();

        } catch (Exception e) {
            System.err.println("RhymingWords reverse: " + e);
        }
        return pr;
    }

    public static Reader sort(Reader source) {
        PipedWriter pw = null;
        PipedReader pr = null;

        try {
            BufferedReader br = new BufferedReader(source);

            pw = new PipedWriter();
            pr = new PipedReader(pw);
            PrintWriter output = new PrintWriter(pw);

            new SortThread(output, br).start();

        } catch (Exception e) {
            System.err.println("RhymingWords sort: " + e);
        }
        return pr;
    }
}
