import java.awt.*;

class DrawSim extends java.awt.Canvas {

//double-buffering

private Image image2;
private Graphics g2;

private Dimension mySize;

private int XSIZE,YSIZE,XOFFSET,YOFFSET;
private int MAXPOINTS=1000;
private double xscale,yscale,XMAX,XMIN,YMAX,YMIN;
private int xpoints[];
private int ypoints[];
private int lastPoint;


DrawSim(){
  xpoints = new int[MAXPOINTS];
  ypoints = new int[MAXPOINTS];
  setBackground(Color.white);
}

public void paint(Graphics g){

// setup offscreen graphics object, setup axes and scale parameters
// resize background size if necessary 

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

// paint background

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

// graph axes etc
  myAxes();


// go through all points and paint
  g2.setColor(Color.blue);
  
  for(int i=0;i<lastPoint;i++) 
  g2.drawLine(xpoints[i],ypoints[i],xpoints[i+1],ypoints[i+1]);

// copy image to live version

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

private void paintSetup() {

  mySize=this.size();

// Create second image space 

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

private void determineSize(){

  XOFFSET=50;
  YOFFSET=50;
  YSIZE=this.size().height-2*YOFFSET;
  YOFFSET=YSIZE+YOFFSET;
  XSIZE=this.size().width-2*XOFFSET;
  XMAX=10.0;
  XMIN=0.0;
  YMIN=0.0;
  YMAX=0.1;
  
  xscale=(double)XSIZE/(XMAX-XMIN);
  yscale=-(double)YSIZE/(YMAX-YMIN);

}


private void myAxes(){
double x;

  g2.setColor(Color.black);
  g2.drawLine(XOFFSET,YOFFSET,XSIZE+XOFFSET,
                      YOFFSET);
  g2.drawLine(XOFFSET,YOFFSET,XOFFSET,YOFFSET-YSIZE);

  for(int i=0;i<=4;i++){
  x=myformat(XMIN+i*(XMAX-XMIN)/4.0,100);
  g2.drawString(String.valueOf(x),
  (int)(XMIN+i*(XMAX-XMIN)/4.0*xscale+XOFFSET), YOFFSET+20);}

  for(int i=0;i<=6;i++){
  x=myformat(YMIN+i*(YMAX-YMIN)/6.0,100);
  g2.drawString(String.valueOf(x),
  XOFFSET-40,(int)(YMIN+i*(YMAX-YMIN)/6.0*yscale+YOFFSET));}
}


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

public void addToScreen(double x, double y){
  int ix, iy, dum;
  
  ix=(int)((x-XMIN)*xscale)+XOFFSET;
  iy=(int)((y-YMIN)*yscale)+YOFFSET;


// only plot new pixels to screen

  if ( !( (lastPoint>=0) &&
          (ix==xpoints[lastPoint]))) 
           {

// wrap arrays around to avoid out-of-bounds problems

    if (++lastPoint>=MAXPOINTS) lastPoint=0;
    xpoints[lastPoint]=ix;
    ypoints[lastPoint]=iy;
  }

  repaint();
}




private double myformat(double x, int n){
double d;
int i;
d=x*n;
i=(int)d;
d=(double)i/(double)n;
return(d);
}

public void clearScreen(){
lastPoint=-1;
}

} 

