/*
 * @(#)pk.java	 96/07/13 Torsten Sillke
 */

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/**
 * Can be run either as a standalone application by
 * typing "java pk" or as an applet in the AppletViewer.
 *
 * Apply the '137'-Code 
 *
 */
public class pk extends Applet {
    ArcControls controls;
    public void init() {
	setLayout(new BorderLayout());
	ArcCanvas c = new ArcCanvas();
	add("Center", c);
	add("South", controls = new ArcControls(c));
    }

    public void start() {
	controls.setEnabled(true);
    }

    public void stop() {
	controls.setEnabled(false);
    }

    public static void main(String args[]) {
	Frame f = new Frame("Check Code");
	pk chc = new pk();

	chc.init();
	chc.start();

	f.add("Center", chc);
	f.setSize(300, 200);
	f.show();
    }

    public String getAppletInfo() {
	return "LH Check Digit by Torsten Sillke";
    }
}
    

class ArcCanvas extends Canvas {
    int		number = 0;
    int         pcode  = 0;
    Font	font;
    private final static String  code_letter = "ABCDEFGHIK";
    private final static int     factors[]   = {7,3,1};

    public static int checkcode(int n) {
	int rest      = n;
	int pos       = 0;
	int p         = 0;

	while (rest > 0) {
           p += (rest % 10)*factors[ pos % 3 ];
	   rest = rest / 10;
	   pos += 1;
	}
        return 9 - p % 10;
    }

    public void paint(Graphics g) {

	Rectangle r = getBounds();
	//font = new java.awt.Font("TimesRoman", Font.PLAIN, 24);
	font = new java.awt.Font("Courier", Font.PLAIN, 24);
	g.setFont(font);

	int sx = 10;
	int sy = r.height - 28;
	g.drawString("Number = " + number, sx, 28); 
	g.drawString("Control-Letter = " + code_letter.substring(pcode,pcode+1) , sx, 56); 
    }

    public void redraw(int n) {
	number = n;
	pcode  = checkcode(n);
	repaint();
    }
}

class ArcControls extends Panel 
		  implements KeyListener {
    TextField e;
    ArcCanvas canvas;

    public ArcControls(ArcCanvas canvas) {
	this.canvas = canvas;
	add(e = new TextField("5111", 6));
	canvas.redraw(Integer.parseInt(e.getText().trim()));
  	e.addKeyListener(this);
    }

    public void keyTyped(KeyEvent ev) {
    }

    public void keyPressed(KeyEvent ev) {
	if (ev.getKeyCode() == KeyEvent.VK_ENTER) {
	    canvas.redraw(Integer.parseInt(e.getText().trim()));
	}
    }

    public void keyReleased(KeyEvent ev) {
    }
}
