<?php
class FunctionGraph {
  var 
$x0;
  var 
$y0;
  var 
$x1;
  var 
$y1;
  var 
$posX0;
  var 
$posY0;
  var 
$scale;
  var 
$img;
  var 
$bg;
  var 
$col0;
  var 
$col1;

  function 
FunctionGraph($width$height$x1 2$y1 2)
  {
    
$this->x0 = -$x1;
    
$this->y0 = -$y1;
    
$this->x1 $x1;
    
$this->y1 $y1;
    
$this->posX0 $width/2;
    
$this->posY0 $height/2;
    
$this->scale = (double)($width-20)/($this->x1-$this->x0);
    
$this->img imageCreate($width$height);
    
$this->bg imageColorAllocate($this->img255255255);
    
$this->col0 imageColorAllocate($this->img000);
    
$this->col1 imageColorAllocate($this->img01270);
  }

  function 
drawAxes() {
    
imageLine($this->img$this->posX0 $this->x0*$this->scale-2,
                          
$this->posY0,
                          
$this->posX0 $this->x1*$this->scale+2,
              
$this->posY0$this->col0);
    
imageLine($this->img$this->posX0,
                          
$this->posY0 $this->y0*$this->scale+2,
                          
$this->posX0,
              
$this->posY0 $this->y1*$this->scale-2$this->col0);
    for (
$x 1$x <= $this->x1$x += 1) {
      
imageLine($this->img$this->posX0+$x*$this->scale,
                            
$this->posY0-3,
                        
$this->posX0+$x*$this->scale,
                
$this->posY0+3$this->col0);
      
imageLine($this->img$this->posX0-$x*$this->scale,
                            
$this->posY0-3,
                        
$this->posX0-$x*$this->scale,
                
$this->posY0+3$this->col0);
    }
    for (
$y 1$y <= $this->y1$y += 1) {
      
imageLine($this->img$this->posX0-3,
                            
$this->posY0-$y*$this->scale,
                            
$this->posX0+3,
                
$this->posY0-$y*$this->scale$this->col0);
      
imageLine($this->img$this->posX0-3,
                            
$this->posY0+$y*$this->scale,
                            
$this->posX0+3,
                
$this->posY0+$y*$this->scale$this->col0);
    }
  }

  function 
drawFunction($function$dx 0.1) {
    
$xold $x $this->x0;
    eval(
"\$yold=".$function.";");
    for (
$x += $dx$x <= $this->x1$x += $dx) {
      eval(
"\$y = ".$function.";");
      
imageLine($this->img$this->posX0+$xold*$this->scale,
                            
$this->posY0-$yold*$this->scale,
                            
$this->posX0+$x*$this->scale,
                
$this->posY0-$y*$this->scale$this->col1);
      
$xold $x;
      
$yold $y;
    }
  }

  function 
writePNG() {
    
imagePNG($this->img);
  }

  function 
destroy() {
    
imageDestroy($this->img);
  }
}