import java.awt.*;
import java.awt.event.*;
import java.applet.*;

import myutil.*;

public class GUISort extends Applet implements ActionListener
{
    Label nLabel;
    TextField nText;
    Button genData;
    Button sortData;

    double[] data = null;

    public static void main(String[] args) 
    {
	new AppletFrame(new GUISort(), 500, 100);
    }

    public void init()
    {
	nLabel = new Label("n: ");
	nText  = new TextField("1000", 8);
	genData = new Button("Gen Data");
	sortData = new Button("Sort Data");

	genData.addActionListener(this);
	sortData.addActionListener(this);

	add(nLabel);
	add(nText);
	add(genData);
	add(sortData);
    }

    public void actionPerformed(ActionEvent e)
    {
	if (e.getSource() == genData) {
	    int n = SL.atoi(nText.getText());
	    data = new double[n];
	    for (int j=0; j<n; j++) {
		data[j] = Math.random();
	    }
	} else
	if (e.getSource() == sortData) {
	    if (data != null) {
		SortFrame sf = new SortFrame(data);
		sf.setVisible(true);
	    }
	}
    }
}

class SortFrame extends Frame implements ActionListener
{
    SortPanel sp;
    Button closeButton;

    public SortFrame(double[] d)
    {
	sp = new SortPanel(d);
	closeButton = new Button("Close");

	closeButton.addActionListener(this);

	/*
	Panel bp = new Panel();
	bp.add(closeButton);

	setLayout(new BorderLayout(10,10));
	add("Center", sp);
	add("South", bp);
	*/
	setSize(500, 500);

	add("Center", sp);
	add("South", closeButton);
    }

    public void actionPerformed(ActionEvent e)
    {
	if (e.getSource() == closeButton) {
	    dispose();
	}
    }
}

class SortPanel extends Panel
{
    double[] d;
    public SortPanel(double[] d)
    {
	this.d = d;
	quickSort( d, 0, d.length-1 );
    }

    public void paint (Graphics g)
    {
	GL.ginit(getGraphics(), getSize().width, getSize().height, this,
		false);
	GL.ortho2(0,d.length,0,1);
	GL.color(Color.black);
	GL.clear();

        for (int i=0; i<d.length; i++) {
            GL.color(Color.white);
            GL.pnt2(i, d[i]);
        }   
    }

    public static synchronized void quickSort(double[] d, int left, int right)
    {
        int i, last;

        if (left >= right) return;
        swap(d, left, (left+right)/2);
        last = left;
        for (i=left+1; i<=right; i++) {
            if (d[i] < d[left]) {
                last++;
                swap(d, last, i);
            }
        }
        swap(d, left, last);
        quickSort(d, left, last-1);
        quickSort(d, last+1, right);
    }   

    static void swap(double[] d, int i, int j)
    {
        double temp;

        /* update the 'graph' */

        GL.color(Color.black);
        GL.pnt2(i,d[i]);
        GL.pnt2(j,d[j]);

        temp= d[j];
        d[j]= d[i];
        d[i] = temp;

        /* update the 'graph' */

        GL.color(Color.white);
        GL.pnt2(i,d[i]);
        GL.pnt2(j,d[j]);
    }
}
