// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
// EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
// TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE
// SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
// REPAIR OR CORRECTION. IN NO EVENT WILL THE AUTHOR OR ANY OTHER PARTY WHO
// MAY HAVE DISTRIBUTED THE SOFTWARE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING
// ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF
// THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS
// OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR
// THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER
// PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGES.

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

/**
 *  Sorts the lines in a file alphabetically.
 */
public class FileSorter
{
  /**
   *  Contains all lines in a file.
   */
  private List lines = new ArrayList ();

  /**
   *  Test method for this class
   */
  public static void main (String[] args)
  {
    if (args.length == 2)
    {
      FileSorter fs = new FileSorter ();
      try
      {
        fs.readFrom (args [0]);
        fs.sort ();
        fs.writeTo (args [1]);
      }
      catch (IOException ex)
      {
        System.err.println ("Error: " + ex);
      }
    }
    else
    {
      System.err.println ("Usage: FileSorter  ");
      System.err.println (" - sorts the lines in a text file");
    }

  }

  /**
   *  Sort the {@link #lines} list.
   */
  public void sort ()
  {
    for (int i = lines.size() - 1 ; i > 0 ; i--)
    {
      for (int j = 0 ; j < i ; j++)
      {
        // swap the items
        String s1 = (String) lines.get(i);
        String s2 = (String) lines.get(j);
        if (s1.compareTo(s2) < 0)
        {
          lines.set (i, s2);
          lines.set (j, s1);
        }
      }
    }
  }

  /**
   *  Read all lines from a file, and store them in {@link #lines}.
   */
  public void readFrom (String filename) throws IOException
  {
    FileInputStream fis = new FileInputStream (filename);
    int c;
    String line = new String ();
    do
    {
      c = fis.read();
      if ((c == -1) || c == '\n')
      {
        lines.add(line);
        line = new String ();
      }
      else if (c != '\r')
      {
        line += (char) c;
      }
    }
    while (c != -1);
    fis.close();
  }

  /**
   *  Write all elements in {@link #lines} to a file.
   */
  public void writeTo (String filename) throws IOException
  {
    FileOutputStream fos = new FileOutputStream (filename);
    for (int i = 0 ; i < lines.size() ; i++)
    {
      fos.write (((String) lines.get(i)).getBytes ());
      fos.write ((byte) '\r');
      fos.write ((byte) '\n');
    }
    fos.close ();
  }
}