import java.awt.*;
import java.lang.*;
import java.applet.Applet;

public class ModCalcAdd extends Applet 
{
	
	TextField num1, num2, modulus, outputint;
 	Choice operation;
	
	public void init() 
	{		
   		num1 = new TextField("0",4);
   		num2 = new TextField("0",4);
   		modulus = new TextField("12",4);
    		outputint = new TextField("",4);
    		operation = new Choice();
   		operation.addItem(" + ");
    		operation.addItem(" - ");
    		operation.addItem(" x ");
		
		add(num1);
		add(operation);
   		add(num2);
		add(new Label("mod"));
		add(modulus);
		add(new Button("=")); 
		add(outputint);

		show();	
	}
	
	int getValue(TextField s) 
	{
		int f;
		try 
		{
			int col = s.getColumns();
			double max = Math.pow(10, (double)col);
			f = Integer.parseInt(s.getText());	
			if (Math.abs((double)f) > max)
			{
				s.setText("E");
			}
		}
		catch (java.lang.NumberFormatException e) 
		{
			f = 0;
			s.setText("E");
		}
		return f;
	}
	
	int residue(int a, int m)
	{
		int f;
		try {
			f=a%m;
			if (f < 0) 
			{
				return f+m;
			}
			else 
			{
				return f;
			}
		}
		catch (java.lang.ArithmeticException e)
		{ return 0 ; }
	}
	
	public boolean handleEvent(Event e) 
	{
		int a1, a2, c;
		if (e.id == Event.ACTION_EVENT){
		int m=getValue(modulus);

		if (m<2) 
		{
			modulus.setText("E");
			outputint.setText("E");
		}
		
		if ((e.target instanceof TextField) || (e.target instanceof Button) || (e.target instanceof Choice) )
		{
        		a1=getValue(num1);
        		a2=getValue(num2);
        	        int op = this.operation.getSelectedIndex();
        		if (op == 0) {
        		c=residue(a1+a2,m);
        		}
        		else if (op == 1) {
        		c=residue(a1-a2,m);
        		}	
        		else if (op == 2) {
        		c=residue(a1*a2,m);
        		}
        		else {
        		c=0;
        		}		
          		outputint.setText(Integer.toString(c));
          		return true;
		}
		else
		{
			return true;
		}
		}
		return false;
	}
}
