import java.awt.*;

public class Plot extends java.awt.Canvas{

private int xpoint, ypoint; 
private int xoffset, yoffset, xsize, ysize;
private double xscale, yscale;
private int  xmin, xmax, ymin, ymax;

private Image image2;
private Graphics g2;
private Dimension oldSize;

private int xpath[],ypath[];
private int xcluster[],ycluster[];
private int MAX;
private int lastClusterPoint=-1;
private int lastPathPoint=-1;
private int latticeSize;

// default constructor - allocates arrays etc 
 
Plot(int lattice){ 
MAX=lattice*lattice;
latticeSize=lattice;
xpath = new int[2*MAX];
ypath = new int[2*MAX];
xcluster = new int[MAX];
ycluster = new int[MAX];
setBackground(Color.white);
}

// clear screen when changing parameter 

public void clearCluster(){
lastClusterPoint=-1;
}

public int getlastClusterPoint(){
return(lastClusterPoint);
}

public void clearPath(){
lastPathPoint=-1;
}

// determines sizes, scaling etc 

private void determineSize(){

// physical sizes first

xmin=0;
xmax=latticeSize-1;
ymin=0;
ymax=latticeSize-1;

// pixel stuff now

xoffset=40;
yoffset=40;
xsize=this.size().width-2*xoffset;
ysize=this.size().height-2*yoffset;
yoffset=yoffset+ysize;

// scaling required

xscale=(double)xsize/(double)(xmax-xmin);
yscale=-(double)ysize/(double)(ymax-ymin);

}

// computes local coords on new point and paints to screen 

public void addPathPoint(int x, int y){

if(++lastPathPoint>=MAX){lastPathPoint=0;}
xpath[lastPathPoint]=x;
ypath[lastPathPoint]=y;

repaint();

}

public void addClusterPoint(int x, int y){


if(++lastClusterPoint>=MAX){lastClusterPoint=0;}
xcluster[lastClusterPoint]=x;
ycluster[lastClusterPoint]=y;

repaint();

}

// if parameters change or resize need to recompute size stuff

public void paint(Graphics g){
int xpoint,ypoint,xpoint2,ypoint2;

if(g2==null) {paintSetup();determineSize();}
else if ((this.size().width!=oldSize.width) || 
         (this.size().height!=oldSize.height)) paintSetup();

// double buffering here

g2.setColor(this.getBackground());
g2.fillRect(0,0,oldSize.width,oldSize.height);

g2.setColor(Color.blue);
for(int i=0;i<=lastClusterPoint;i++){
xpoint=(int)((xcluster[i]-xmin)*xscale)+xoffset;
ypoint=(int)((ycluster[i]-ymin)*yscale)+yoffset;
g2.fillOval(xpoint-4,ypoint-4,8,8);}

g2.setColor(Color.red);
for(int i=0;i<lastPathPoint;i++){
xpoint=(int)((xpath[i]-xmin)*xscale)+xoffset;
ypoint=(int)((ypath[i]-ymin)*yscale)+yoffset;
xpoint2=(int)((xpath[i+1]-xmin)*xscale)+xoffset;
ypoint2=(int)((ypath[i+1]-ymin)*yscale)+yoffset;
g2.drawLine(xpoint,ypoint,xpoint2,ypoint2);}

g.drawImage(image2,0,0,this);

}

private void paintSetup(){
oldSize=this.size();

image2=createImage(oldSize.width,oldSize.height);
g2=image2.getGraphics();
}


public void update(Graphics g){
paint(g);
}

}


