package kryptoScript;

//
// http://www-ti.informatik.uni-tuebingen.de/~haeusser/krypto/
// java/GeneratePrime.java
// 
// Copyright (c) 1999 Matthias Haeusser
//
// last change: 14.11.1999
//

import java.awt.*;
import java.applet.*;
import java.math.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class GeneratePrime extends Applet implements ActionListener {
   TextField startfield, outfield;
   Button startButton;

   // layout   
  public void init() {
     setLayout(new GridBagLayout()); GridBagConstraints c;

     c = new GridBagConstraints();
     c.gridx = 0; c.gridy = 0; c.anchor = GridBagConstraints.WEST;
     add(new Label(getParameter("startAt") + ":"), c);
     
     c = new GridBagConstraints();
     c.gridx = 1; c.gridy = 0;  c.anchor = GridBagConstraints.WEST;
     add(startfield = new TextField("1000000000",40), c);

     c = new GridBagConstraints();
     c.gridx = 0; c.gridy = 1; c.anchor = GridBagConstraints.WEST;
     c.gridwidth = 2;
     add(startButton = new Button(getParameter("startSearch")), c);

     c = new GridBagConstraints();
     c.gridx = 0; c.gridy = 2; c.anchor = GridBagConstraints.WEST;
     add(new Label(getParameter("nextPrime") + "="), c);

     c = new GridBagConstraints();
     c.gridx = 1; c.gridy = 2; c.anchor = GridBagConstraints.WEST;
     add(outfield = new TextField(40), c);
     outfield.setEditable(false);


     // register listeners
     startfield.addActionListener(this);
     startButton.addActionListener(this);
  }
   
   // listen, dispatch
   public void actionPerformed(ActionEvent e) {
      search();
   }

   // search for next prime
   public void search() {
      String input = startfield.getText();
      BigInteger n = new BigInteger("0");
      BigInteger one = new BigInteger("1");
      BigInteger two = new BigInteger("2");
      boolean ok = true;
      
      try {
	 BigInteger temp = new BigInteger(input);
	 n = temp;
      }
      catch (NumberFormatException ex) {
	 outfield.setText(getParameter("invalid"));
	 ok = false;
      }
      
      if (ok) {
	 if ((n.signum() <= 0) | (n.equals(one))) { // n < 2 => n := 2
	    n = two;
	 }
	 
	 if ((n.getLowestSetBit() != 0) & (! n.equals(two))) {
	    n = n.add(one); // even -> odd (except for 2)
	 }
	 
	 while (! n.isProbablePrime(7)) {
	    n = n.add(two);
	    //	    System.out.println(n);
	 }
	 
	 outfield.setText(""+n);
      }
      return;
   }
}
