// Prime Number Generator
// code by Mark Chamness
// any suggestions are appreciated.
//
// This applet calculates prime numbers
// It stores the first 100 primes it generates
// Then it evaluates the rest based on those
// up to prime[100] squared

import java.awt.*;

public class CalcPrimes extends java.applet.Applet
{
	public CalcPrimes()
	{
        Color app_color = Color.lightGray;
		setLayout(new BorderLayout());
		Panel q=new Panel();
		q.setLayout(new  GridLayout(2,1));
		q.setBackground(Color.gray);
		q.add(new Label("Calculate some Primes" , Label.CENTER));
		q.add(new Label("Click Run to Start!" , Label.CENTER));
		q.setBackground(app_color);
		add("North",q);
		Panel p=new Panel();
		p.setBackground(app_color);
		p.setLayout(new FlowLayout());
		Button runButton=new Button("Run");
		runButton.setBackground(Color.green);
		p.add(runButton);
		p.add(new Button("Pause"));
		p.add(new Button("Resume"));
		Button stopButton=new Button("Stop");
		stopButton.setBackground(Color.red);
		p.add(stopButton);
		add("South",p);
		ta=new TextArea(20,10);
		add("Center", ta);
		setBackground(app_color);
		th_alive=false; th_paused=false;
	}

	public Insets insets()
	{	return new Insets(10,10,10,10);
	}
	
	public boolean action(Event evt, Object arg)
	{	
		if(arg.equals("Run") )
		{ 	if(!th_alive && !th_paused )
			/*note that I cannot call thread.isAlive() */
			/*because initially it is just null */
			{	th_alive=true;	
				calc= new Calculate(ta); 
				calc.setPriority(Thread.NORM_PRIORITY+1); 
				calc.start();
			}
		}
		else if(arg.equals("Pause") )
		{	if(th_alive && !th_paused) 
			{	calc.suspend();
				th_paused=true;
			}
		}
		else if(arg.equals("Resume") )
		{	if(th_paused) 	
			{	calc.resume();
				th_paused=false;
			}
		}
		else if(arg.equals("Stop") )
		{	if(th_alive && !th_paused) 
			{	th_alive=false;
				calc.stop();
				ta.appendText("Stop\n\n");
			}
		}
		else return false;
		return true;
	}
		
	public boolean handleEvent(Event evt)
	{	if(evt.id == Event.WINDOW_DESTROY) System.exit(0);		
			return super.handleEvent(evt);
	}

	private TextArea ta;
	private Calculate calc;
	Boolean running;
	private boolean th_alive, th_paused;

}	

class Calculate extends Thread
{
	public Calculate(TextArea t) 
	{	text_area=t;
	}
	private TextArea text_area;

	public void run()
	{	int[] prime = new int[100];
        int test=5, index=0;
        int i,num=0;
		boolean check=true;
        prime[0]=3;
		text_area.appendText("3\n");
        while(test<(prime[num]*prime[num]))
        {	
			try {sleep(10);} catch (InterruptedException e) {}
        	index=0; check=true;
        	while(check==true && index<=num && test>=(prime[index]*prime[index]))
        	{	if(test%prime[index] == 0)  check=false;
        		else index++;
        	}
        	if(check==true)
        	{
				text_area.appendText(test + "\n");
				if(num<(prime.length-1))
 				{	num++;
					prime[num]=test;
				}
			}
		test+=2;
        }
	}
}
