// Monitor.java  computes and displays the one dimensional voltage

import java.awt.*;

class Monitor extends Thread {
    static int[] field, volts;   // field(x) & potential(x)(x)
    Graphics gc;
    int height, width, yMin, yMax;
    int scale=5;   // scale factor for voltage display: 0->X1, 1->X.5, 2->X.25, etc.
    Component cpnt;
    public final static Color darkGreen = new Color(0, 96, 0);
    Color fg=Color.green;
    Color bg=darkGreen;

    Monitor(Component cpnt, int a) {
        this.cpnt=cpnt;
        gc=cpnt.getGraphics();
        height=cpnt.size().height-2;
        width=cpnt.size().width-2;
        yMin=1;
        yMax=height-1;
        gc.setColor(Color.black);
        gc.drawRect(0,0,width, height);
        gc.setColor(bg);
        gc.fillRect(1,yMin,width-1,yMax);
        field = IonCompartment.field;
        volts = new int[field.length];
		scale = a;
        start();
    }

    public void run() {
        try {
            while (true) {
				if (NewIon.run) {
					draw();
				}
				this.yield();
				try {sleep(100);}
				catch(InterruptedException e) {}
            }
        } catch(ThreadDeath t) {
            gc.dispose();
            throw(t);
        }
    }

    private int clip(int y) {
        if (y<yMin) return yMin;
        if (y>yMax) return yMax;
        return y;
    }
	
	void draw() {
		int i;
		gc.setColor(Color.black);
		gc.drawRect(0,0,width, height);
        int tmp=volts[0];
        for (i=1; i<field.length; i++) {
			volts[i]=tmp;
			tmp=volts[i]+field[i];
		}
		int err = (tmp+volts[0])/2;
        for (i=0; i<field.length; i++) {
			volts[i] -= err;
		}
		int lasty=clip( (volts[1]>>scale)+height/2 );
		gc.setColor(bg);
		gc.fillRect(1, yMin, width-1, yMax);
		gc.setColor(fg);
		for (i=2; i<width; i++) {
			gc.drawLine(i-1,lasty,i,lasty=clip( (volts[i]>>scale)+height/2 ) );//compiler dep.
		}
	}
}


