Phpledads 2.2 > Ledads / Lib / Jpgraph / Jpgraph.php

Questions? Need Help? Want to share? » PHP Forum
Script Name:
Phpledads 2.2

Download:
phpledads-2.2.zip

Category:
Ad Management

Archive Content:

Ledads

Ledads > Dev

Ledads > Lib

Ledads > Lib > Jpgraph

Ledads > Lib > Jpgraph > TTF

Ledads > Lib > Jpgraph

Ledads > Lib

Ledads > Data

Ledads

Jpgraph.php:


<?php 
//=======================================================================
// File:    JPGRAPH.PHP
// Description:    PHP4 Graph Plotting library. Base module.
// Created:     2001-01-08
// Author:    Johan Persson (johanp <at> aditus <dot> nu)
// Ver:        $Id: jpgraph.php, v 1.183 2003/02/02 17:13:31 aditus Exp $
//
// License:    This code is released under QPL 1.0 
// Copyright (C) 2001, 2002, 2003 Johan Persson 
//========================================================================

//------------------------------------------------------------------------
// Directories for cache and font directory.
// Leave them undefined to use default values. 
// 
// Default values used if these defines are left commented out are:
// 
// UNIX: 
//   CACHE_DIR = /tmp/jpgraph_cache/
//   TTF_DIR   = /usr/X11R6/lib/X11/fonts/truetype/
//
// WINDOWS:
//   CACHE_DIR = $SERVER_TEMP/jpgraph_cache/
//   TTF_DIR   = $SERVER_SYSTEMROOT/fonts/
//    
//
//------------------------------------------------------------------------

// The full absolute name of the directory to be used to store the
// cached image files. This directory will not be used if the USE_CACHE
// define (further down) is false. If you enable the cache please note that
// this directory MUST be readable and writable for the process running PHP. 
// Must end with '/'
// DEFINE("CACHE_DIR", "/tmp/jpgraph_cache/");

// Directory for jpGraph TTF fonts. Must end with '/'
// DEFINE("TTF_DIR", "/usr/X11R6/lib/X11/fonts/truetype/");


//-------------------------------------------------------------------------
// Cache directory specification for use with CSIM graphs that are
// using the cache.
// The directory must be the filesysystem name as seen by PHP
// and the 'http' version must be the same directory but as 
// seen by the HTTP server relative to the 'htdocs' ddirectory. 
// If a relative path is specified it is taken to be relative from where
// the image script is executed.
// Note: The default setting is to create a subdirectory in the 
// directory from where the image script is executed and store all files
// there. As ususal this directory must be writeable by the PHP process.
DEFINE("CSIMCACHE_DIR", "csimcache/"); 
DEFINE("CSIMCACHE_HTTP_DIR", "csimcache/");

//------------------------------------------------------------------------
// Various JpGraph Settings. Adjust accordingly to your
// preferences. Note that cache functionality is turned off by
// default (Enable by setting USE_CACHE to true)
//------------------------------------------------------------------------

// Deafult graphic format set to "auto" which will automatically
// choose the best available format in the order png, gif, jpg
// (The supported format depends on what your PHP installation supports)
DEFINE("DEFAULT_GFORMAT", "auto");

// Should the image be a truecolor image? 
// Note 1: Has only effect with GD 2.0.1 and above.
// Note 2: GD 2.0.1 + PHP 4.0.6 on Win32 crashes when trying to use 
// trucolor. Truecolor support is to be considered alpha since GD 2.x
// is still not considered stable (especially on Win32). 
// Note 3: MUST be enabled to get background images working with GD2
// Note 4: If enabled then truetype fonts will look very ugly with GD 2.0.1
// => You can't have both background images and truetype fonts in the same
// image until these bugs has been fixed in GD 2.01. There is a patch
// available for GD 2.0.1 though. See the README file.
DEFINE('USE_TRUECOLOR', true);

// Specify what version of the GD library is installed.
// If this is set to 'auto' the version will be automatically 
// determined.
// However since determining the library takes ~1ms you can also 
// manually specify the version if you know what version you have. 
// This means that you should 
// set this define to true if you have GD 2.x installed to save 1ms. 
DEFINE("USE_LIBRARY_GD2", 'auto');

// Should the cache be used at all? By setting this to false no
// files will be generated in the cache directory.  
// The difference from READ_CACHE being that setting READ_CACHE to
// false will still create the image in the cache directory
// just not use it. By setting USE_CACHE=false no files will even
// be generated in the cache directory.
DEFINE("USE_CACHE", false);

// Should we try to find an image in the cache before generating it? 
// Set this define to false to bypass the reading of the cache and always
// regenerate the image. Note that even if reading the cache is 
// disabled the cached will still be updated with the newly generated
// image. Set also "USE_CACHE" below.
DEFINE("READ_CACHE", true);

// Determine if the error handler should be image based or purely
// text based. Image based makes it easier since the script will
// always return an image even in case of errors.
DEFINE("USE_IMAGE_ERROR_HANDLER", true);

// If the color palette is full should JpGraph try to allocate
// the closest match? If you plan on using background images or
// gradient fills it might be a good idea to enable this.
// If not you will otherwise get an error saying that the color palette is 
// exhausted. The drawback of using approximations is that the colors 
// might not be exactly what you specified. 
// Note1: This does only apply to paletted images,  not truecolor 
// images since they don't have the limitations of maximum number
// of colors.
DEFINE("USE_APPROX_COLORS", true);

// Special unicode cyrillic language support
DEFINE("LANGUAGE_CYRILLIC", false);

// If you are setting this config to true the conversion
// will assume that the input text is windows 1251,  if
// false it will assume koi8-r
DEFINE("CYRILLIC_FROM_WINDOWS", false);

// Should usage of deprecated functions and parameters give a fatal error?
// (Useful to check if code is future proof.)
DEFINE("ERR_DEPRECATED", true);

// Should the time taken to generate each picture be branded to the lower
// left in corner in each generated image? Useful for performace measurements
// generating graphs
DEFINE("BRAND_TIMING", false);

// What format should be used for the timing string?
DEFINE("BRAND_TIME_FORMAT", "Generated in: %01.3fs");

//------------------------------------------------------------------------
// The following constants should rarely have to be changed !
//------------------------------------------------------------------------

// What group should the cached file belong to
// (Set to "" will give the default group for the "PHP-user")
// Please note that the Apache user must be a member of the
// specified group since otherwise it is impossible for Apache
// to set the specified group.
DEFINE("CACHE_FILE_GROUP", "wwwadmin");

// What permissions should the cached file have
// (Set to "" will give the default persmissions for the "PHP-user")
DEFINE("CACHE_FILE_MOD", 0664);

// Decide if we should use the bresenham circle algorithm or the
// built in Arc(). Bresenham gives better visual apperance of circles 
// but is more CPU intensive and slower then the built in Arc() function
// in GD. Turned off by default for speed
DEFINE("USE_BRESENHAM", false);

// Special file name to indicate that we only want to calc
// the image map in the call to Graph::Stroke() used
// internally from the GetHTMLCSIM() method.
DEFINE("_CSIM_SPECIALFILE", "_csim_special_");

// HTTP GET argument that is used with image map
// to indicate to the script to just generate the image
// and not the full CSIM HTML page.
DEFINE("_CSIM_DISPLAY", "_jpg_csimd");

// Special filename for Graph::Stroke(). If this filename is given
// then the image will NOT be streamed to browser of file. Instead the
// Stroke call will return the handler for the created GD image.
DEFINE("_IMG_HANDLER", "__handle");

// DON'T SET THIS FLAG YORSELF THIS IS ONLY FOR INTERNAL TESTING
// PURPOSES. ENABLING THIS FLAG WILL MAKE SOME OF YOUR SCRIPT 
// STOP WORKING
// Enable some extra debug information for CSIM etc to be shown. 
DEFINE("JPG_DEBUG", false);

//------------------------------------------------------------------------
// Automatic settings of path for cache and font directory
// if they have not been previously specified
//------------------------------------------------------------------------
if (!defined('CACHE_DIR')) {
    if (
strstrPHP_OS,  'WIN')) {
    
DEFINE('CACHE_DIR',  $_SERVER['TEMP'] . '/');
    } else {
    
DEFINE('CACHE_DIR', '/tmp/jpgraph_cache/');
    }
}

if (!
defined('TTF_DIR')) {
    if (
strstrPHP_OS,  'WIN')) {
    
DEFINE('TTF_DIR',  $_SERVER['SystemRoot'] . '/fonts/');
    } else {
    
DEFINE('TTF_DIR', '/usr/X11R6/lib/X11/fonts/truetype/');
    }
}

//------------------------------------------------------------------
// Constants which are used as parameters for the method calls
//------------------------------------------------------------------

// TTF Font families
DEFINE("FF_COURIER", 10);
DEFINE("FF_VERDANA", 11);
DEFINE("FF_TIMES", 12);
DEFINE("FF_COMIC", 14);
DEFINE("FF_ARIAL", 15);
DEFINE("FF_GEORGIA", 16);
DEFINE("FF_TREBUCHE", 17);
// 
DEFINE("FF_BOOK", 91);    // Deprecated fonts from 1.9
DEFINE("FF_HANDWRT", 92); // Deprecated fonts from 1.9

// TTF Font styles
DEFINE("FS_NORMAL", 1);
DEFINE("FS_BOLD", 2);
DEFINE("FS_ITALIC", 3);
DEFINE("FS_BOLDIT", 4);
DEFINE("FS_BOLDITALIC", 4);

//Definitions for internal font,  new style
DEFINE("FF_FONT0", 1);
DEFINE("FF_FONT1", 2);
DEFINE("FF_FONT2", 4);

//Definitions for internal font,  old style
// (Only defined here to be able to generate an error mesage
// when used)
DEFINE("FONT0", 99);        // Deprecated from 1.2
DEFINE("FONT1", 98);        // Deprecated from 1.2
DEFINE("FONT1_BOLD", 97);    // Deprecated from 1.2
DEFINE("FONT2", 96);        // Deprecated from 1.2
DEFINE("FONT2_BOLD", 95);     // Deprecated from 1.2

// Tick density
DEFINE("TICKD_DENSE", 1);
DEFINE("TICKD_NORMAL", 2);
DEFINE("TICKD_SPARSE", 3);
DEFINE("TICKD_VERYSPARSE", 4);

// Side for ticks and labels. 
DEFINE("SIDE_LEFT", -1);
DEFINE("SIDE_RIGHT", 1);
DEFINE("SIDE_DOWN", -1);
DEFINE("SIDE_BOTTOM", -1);
DEFINE("SIDE_UP", 1);
DEFINE("SIDE_TOP", 1);

// Legend type stacked vertical or horizontal
DEFINE("LEGEND_VERT", 0);
DEFINE("LEGEND_HOR", 1);

// Mark types for plot marks
DEFINE("MARK_SQUARE", 1);
DEFINE("MARK_UTRIANGLE", 2);
DEFINE("MARK_DTRIANGLE", 3);
DEFINE("MARK_DIAMOND", 4);
DEFINE("MARK_CIRCLE", 5);
DEFINE("MARK_FILLEDCIRCLE", 6);
DEFINE("MARK_CROSS", 7);
DEFINE("MARK_STAR", 8);
DEFINE("MARK_X", 9);
DEFINE("MARK_LEFTTRIANGLE", 10);
DEFINE("MARK_RIGHTTRIANGLE", 11);
DEFINE("MARK_FLASH", 12);
DEFINE("MARK_IMG", 13);


// Styles for gradient color fill
DEFINE("GRAD_VER", 1);
DEFINE("GRAD_HOR", 2);
DEFINE("GRAD_MIDHOR", 3);
DEFINE("GRAD_MIDVER", 4);
DEFINE("GRAD_CENTER", 5);
DEFINE("GRAD_WIDE_MIDVER", 6);
DEFINE("GRAD_WIDE_MIDHOR", 7);
DEFINE("GRAD_LEFT_REFLECTION", 8);
DEFINE("GRAD_RIGHT_REFLECTION", 9);

// Inline defines
DEFINE("INLINE_YES", 1);
DEFINE("INLINE_NO", 0);

// Format for background images
DEFINE("BGIMG_FILLPLOT", 1);
DEFINE("BGIMG_FILLFRAME", 2);
DEFINE("BGIMG_COPY", 3);
DEFINE("BGIMG_CENTER", 4);

// Depth of objects
DEFINE("DEPTH_BACK", 0);
DEFINE("DEPTH_FRONT", 1);

// Direction
DEFINE("VERTICAL", 1);
DEFINE("HORIZONTAL", 0);

// Constants for types of static bands in plot area
DEFINE("BAND_RDIAG", 1);    // Right diagonal lines
DEFINE("BAND_LDIAG", 2); // Left diagonal lines
DEFINE("BAND_SOLID", 3); // Solid one color
DEFINE("BAND_VLINE", 4); // Vertical lines
DEFINE("BAND_HLINE", 5);  // Horizontal lines
DEFINE("BAND_3DPLANE", 6);  // "3D" Plane
DEFINE("BAND_HVCROSS", 7);  // Vertical/Hor crosses
DEFINE("BAND_DIAGCROSS", 8); // Diagonal crosses

// Axis styles for scientific style axis
DEFINE('AXSTYLE_SIMPLE', 1);
DEFINE('AXSTYLE_BOXIN', 2);
DEFINE('AXSTYLE_BOXOUT', 3);
DEFINE('AXSTYLE_YBOXIN', 4);
DEFINE('AXSTYLE_YBOXOUT', 5);

//
// Get hold of gradient class (In Verions 2.x)
// A client of the library has to manually include this
//
include "jpgraph_gradient.php";

//
// First of all set up a default error handler
//

//=============================================================
// The default trivial text error handler.
//=============================================================
class JpGraphErrObject {
    function 
JpGraphErrObject() {
    
// Empty. Reserved for future use
    
}

    
// If aHalt is true then execution can't continue. Typical used for
    // fatal errors
    
function Raise($aMsg, $aHalt=true) {
    
$aMsg "<b>JpGraph Error:</b> ".$aMsg;
    if( 
$aHalt )
        die(
$aMsg);
    else 
        echo 
$aMsg."<p>";
    }
}

//==============================================================
// An image based error handler
//==============================================================
class JpGraphErrObjectImg {

    function 
Raise($aMsg, $aHalt=true) {
    if( 
headers_sent() ) {
        
// Special case for headers already sent error. Dont
        // return an image since it can't be displayed
        
die("<b>JpGraph Error:</b> ".$aMsg);        
    }

    
// Create an image that contains the error text.
    
$w=450$h=110;
    
$img = new Image($w, $h);
    
$img->SetColor("darkred");
    
$img->Rectangle(0, 0, $w-1, $h-1);
    
$img->SetFont(FF_FONT1, FS_BOLD);
    
$img->StrokeText(10, 20, "JpGraph Error:");
    
$img->SetColor("black");
    
$img->SetFont(FF_FONT1, FS_NORMAL);
    
$txt = new Text(wordwrap($aMsg, 70), 10, 20);
    
$txt->Align("left", "top");
    
$txt->Stroke($img);
    
$img->Headers();
    
$img->Stream();
    die();
    }
}

//
// A wrapper class that is used to access the specified error object
// (to hide the global error parameter and avoid having a GLOBAL directive
// in all methods.
//
class JpGraphError {
    function 
Install($aErrObject) {
    GLOBAL 
$__jpg_err;
    
$__jpg_err $aErrObject;
    }
    function 
Raise($aMsg, $aHalt=true){
    GLOBAL 
$__jpg_err;
    
$tmp = new $__jpg_err;
    
$tmp->Raise($aMsg, $aHalt);
    }
}

//
// ... and install the default error handler
//
if( USE_IMAGE_ERROR_HANDLER ) {
    
JpGraphError::Install("JpGraphErrObjectImg");
}
else {
    
JpGraphError::Install("JpGraphErrObject");
}


//
//Check if there were any warnings,  perhaps some wrong includes by the
//user
//
if( isset($GLOBALS['php_errormsg']) ) {
    
JpGraphError::Raise("<b>General PHP error:</b><br>".$GLOBALS['php_errormsg']);
}


//
// Routine to determine if GD1 or GD2 is installed
// At the moment this is used to verify that the user
// really has GD2 if he has set USE_GD2 to true. 
//
function CheckGDVersion() {
    
ob_start();
    
phpinfo(8); // Just get the modules loaded
    
$a ob_get_contents();
    
ob_end_clean();
    if( 
preg_match('/.*GD Version.*(1[0-9|\.]+).*/', $a, $m) ) {
    
$r=1;$v=$m[1];
    }
    elseif( 
preg_match('/.*GD Version.*(2[0-9|\.]+).*/', $a, $m) ) {
    
$r=2;$v=$m[1];
    }
    else {
    
$r=0;$v=$m[1];
    }

    return 
$r;
}

//
// Check what version of the GD library is installed.
//
if( USE_LIBRARY_GD2 == 'auto' ) {
    
$gdversion CheckGDVersion();
    if( 
$gdversion == ) {
    
$GLOBALS['gd2'] = true;
    
$GLOBALS['copyfunc'] = 'imagecopyresampled';
    }
    elseif( 
$gdversion == ) {
    
$GLOBALS['gd2'] = false;
    
$GLOBALS['copyfunc'] = 'imagecopyresized';
    }
    else {
    
JpGraphError::Raise(" Your PHP installation does not seem to 
    have the required GD library.
    Please see the PHP documentation on how to install and enable the GD library."
);
    }
}
else {
    if( 
USE_LIBRARY_GD2 ) {
    
$GLOBALS['gd2'] = true;
    
$GLOBALS['copyfunc'] = 'imagecopyresampled';
    }
    else {
    
$GLOBALS['gd2'] = false;
    
$GLOBALS['copyfunc'] = 'imagecopyresized';
    }
}

// Usefull mathematical function
function sign($a) {if( $a>=0) return 1; else return -1;}

// Utility function to generate an image name based on the filename we
// are running from and assuming we use auto detection of graphic format
// (top level),  i.e it is safe to call this function
// from a script that uses JpGraph
function GenImgName() {
    global 
$HTTP_SERVER_VARS;
    
$supported imagetypes();
    if( 
$supported IMG_PNG )
    
$img_format="png";
    elseif( 
$supported IMG_GIF )
    
$img_format="gif";
    elseif( 
$supported IMG_JPG )
    
$img_format="jpeg";
    if( !isset(
$HTTP_SERVER_VARS['PHP_SELF']) )
    
JpGraphError::Raise(" Can't access PHP_SELF,  PHP global variable. You can't run PHP from command line
        if you want to use the 'auto' naming of cache or image files."
);
    
$fname=basename($HTTP_SERVER_VARS['PHP_SELF']);
    
// Replace the ".php" extension with the image format extension
    
return substr($fname, 0, strlen($fname)-4).".".$img_format;
}


class 
LanguageConv {

//  Translate iso encoding to unicode
    
function iso2uni ($isoline){
    for (
$i=0$i strlen($isoline); $i++){
        
$thischar=substr($isoline, $i, 1);
        
$charcode=ord($thischar);
        
$uniline.=($charcode>175) ? "&#" . (1040+($charcode-176)). ";" $thischar;
    }
    return 
$uniline;
    }

    function 
ToCyrillic($aTxt) {
    if( 
CYRILLIC_FROM_WINDOWS ) {
        
$aTxt convert_cyr_string($aTxt,  "w",  "k"); 
    }
    
$isostring convert_cyr_string($aTxt,  "k",  "i");
    
$unistring LanguageConv::iso2uni($isostring);
    return 
$unistring;
    }
}

//===================================================
// CLASS JpgTimer
// Description: General timing utility class to handle
// timne measurement of generating graphs. Multiple
// timers can be started by pushing new on a stack.
//===================================================
class JpgTimer {
    var 
$start;
    var 
$idx;    
//---------------
// CONSTRUCTOR
    
function JpgTimer() {
    
$this->idx=0;
    }

//---------------
// PUBLIC METHODS    

    // Push a new timer start on stack
    
function Push() {
    list(
$ms, $s)=explode(" ", microtime());    
    
$this->start[$this->idx++]=floor($ms*1000) + 1000*$s;    
    }

    
// Pop the latest timer start and return the diff with the
    // current time
    
function Pop() {
    
assert($this->idx>0);
    list(
$ms, $s)=explode(" ", microtime());    
    
$etime=floor($ms*1000) + (1000*$s);
    
$this->idx--;
    return 
$etime-$this->start[$this->idx];
    }
// Class

$gJpgBrandTiming BRAND_TIMING;
$gDateLocale = new DateLocale();
$gJpgDateLocale = new DateLocale();
//===================================================
// CLASS DateLocale
// Description: Hold localized text used in dates
// ToDOo: Rewrite this to use the real local locale
// instead.
//===================================================
class DateLocale {
 
    var 
$iLocale 'C'// environmental locale be used by default

    
var $iDayAbb null;
    var 
$iShortDay null;
    var 
$iShortMonth null;
    var 
$iMonthName null;

//---------------
// CONSTRUCTOR    
    
function DateLocale() {
    
settype($this->iDayAbb,  'array');
    
settype($this->iShortDay,  'array');
    
settype($this->iShortMonth,  'array');
    
settype($this->iMonthName,  'array');


    
$this->Set('C');
    }

//---------------
// PUBLIC METHODS    
    
function Set($aLocale) {
    if ( 
in_array($aLocale,  array_keys($this->iDayAbb)) ){ 
        
$this->iLocale $aLocale;
        return 
TRUE;  // already cached nothing else to do!
    
}

    
$pLocale setlocale(LC_TIME,  0); // get current locale for LC_TIME
    
$res setlocale(LC_TIME,  $aLocale);
    if ( ! 
$res ){
        
JpGraphError::Raise("You are trying to use the locale ($aLocale) which your PHP installation does not support. Hint: Use '' to indicate the default locale for this geographic region.");
        return 
FALSE;
    }
 
    
$this->iLocale $aLocale;

    for ( 
$i 0,  $ofs strftime('%w'); $i 7$i++,  $ofs++ ){
        
$day strftime('%a',  strtotime("$ofs day"));
        
$day{0} = strtoupper($day{0});
        
$this->iDayAbb[$aLocale][]= $day{0};
        
$this->iShortDay[$aLocale][]= $day;
    }

    for(
$i=1$i<=12; ++$i) {
        list(
$short , $full) = explode('|',  strftime("%b|%B", strtotime("2001-$i-01")));
        
$this->iShortMonth[$aLocale][] = ucfirst($short);
        
$this->iMonthName [$aLocale][] = ucfirst($full);
    }
    
    
    
setlocale(LC_TIME,  $pLocale);

    return 
TRUE;
    }


    function 
GetDayAbb() {
    return 
$this->iDayAbb[$this->iLocale];
    }
    
    function 
GetShortDay() {
    return 
$this->iShortDay[$this->iLocale];
    }

    function 
GetShortMonth() {
    return 
$this->iShortMonth[$this->iLocale];
    }
    
    function 
GetShortMonthName($aNbr) {
    return 
$this->iShortMonth[$this->iLocale][$aNbr];
    }

    function 
GetLongMonthName($aNbr) {
    return 
$this->iMonthName[$this->iLocale][$aNbr];
    }

    function 
GetMonth() {
    return 
$this->iMonthName[$this->iLocale];
    }
}

//===================================================
// CLASS FuncGenerator
// Description: Utility class to help generate data for function plots. 
// The class supports both parametric and regular functions.
//===================================================
class FuncGenerator {
    var 
$iFunc='', $iXFunc='', $iMin, $iMax, $iStepSize;
    
    function 
FuncGenerator($aFunc, $aXFunc='') {
    
$this->iFunc $aFunc;
    
$this->iXFunc $aXFunc;
    }
    
    function 
E($aXMin, $aXMax, $aSteps=50) {
    
$this->iMin $aXMin;
    
$this->iMax $aXMax;
    
$this->iStepSize = ($aXMax-$aXMin)/$aSteps;

    if( 
$this->iXFunc != '' )
        
$t 'for($i='.$aXMin.'; $i<='.$aXMax.'; $i += '.$this->iStepSize.') {$ya[]='.$this->iFunc.';$xa[]='.$this->iXFunc.';}';
    elseif( 
$this->iFunc != '' )
        
$t 'for($x='.$aXMin.'; $x<='.$aXMax.'; $x += '.$this->iStepSize.') {$ya[]='.$this->iFunc.';$xa[]=$x;} $x='.$aXMax.';$ya[]='.$this->iFunc.';$xa[]=$x;';
    else
        
JpGraphError::Raise('FuncGenerator : No function specified. ');
            
    @eval(
$t);
        
    
// If there is an error in the function specifcation this is the only
    // way we can discover that.
    
if( empty($xa) || empty($ya) )
        
JpGraphError::Raise('FuncGenerator : Syntax error in function specification ');
                
    return array(
$xa, $ya);
    }
}


//=======================================================
// CLASS Footer
// Description: Encapsulates the footer line in the Graph
//
//=======================================================
class Footer {
    var 
$left, $center, $right;
    var 
$iLeftMargin 3;
    var 
$iRightMargin 3;
    var 
$iBottomMargin 3;

    function 
Footer() {
    
$this->left = new Text();
    
$this->left->ParagraphAlign('left');
    
$this->center = new Text();
    
$this->center->ParagraphAlign('center');
    
$this->right = new Text();
    
$this->right->ParagraphAlign('right');
    }

    function 
Stroke($aImg) {
    
$y $aImg->height $this->iBottomMargin;
    
$x $this->iLeftMargin;
    
$this->left->Align('left', 'bottom');
    
$this->left->Stroke($aImg, $x, $y);

    
$x = ($aImg->width $this->iLeftMargin $this->iRightMargin)/2;
    
$this->center->Align('center', 'bottom');
    
$this->center->Stroke($aImg, $x, $y);

    
$x $aImg->width $this->iRightMargin;
    
$this->right->Align('right', 'bottom');
    
$this->right->Stroke($aImg, $x, $y);
    }
}

    
DEFINE('BGRAD_FRAME', 1);
    
DEFINE('BGRAD_MARGIN', 2);
    
DEFINE('BGRAD_PLOT', 3);



//===================================================
// CLASS Graph
// Description: Main class to handle graphs
//===================================================
class Graph {
    var 
$cache=null;        // Cache object (singleton)
    
var $img=null;            // Img object (singleton)
    
var $plots=array();    // Array of all plot object in the graph (for Y 1 axis)
    
var $y2plots=array();// Array of all plot object in the graph (for Y 2 axis)
    
var $xscale=null;        // X Scale object (could be instance of LinearScale or LogScale
    
var $yscale=null, $y2scale=null;
    var 
$cache_name;        // File name to be used for the current graph in the cache directory
    
var $xgrid=null;        // X Grid object (linear or logarithmic)
    
var $ygrid=null, $y2grid=null//dito for Y
    
var $doframe=true, $frame_color=array(0, 0, 0),  $frame_weight=1;    // Frame around graph
    
var $boxed=false,  $box_color=array(0, 0, 0),  $box_weight=1;        // Box around plot area
    
var $doshadow=false, $shadow_width=4, $shadow_color=array(102, 102, 102);    // Shadow for graph
    
var $xaxis=null;        // X-axis (instane of Axis class)
    
var $yaxis=null,  $y2axis=null;    // Y axis (instance of Axis class)
    
var $margin_color=array(200, 200, 200);    // Margin color of graph
    
var $plotarea_color=array(255, 255, 255);    // Plot area color
    
var $title, $subtitle, $subsubtitle;     // Title and subtitle(s) text object
    
var $axtype="linlin";    // Type of axis
    
var $xtick_factor;    // Factot to determine the maximum number of ticks depending on the plot with
    
var $texts=null;        // Text object to ge shown in the graph
    
var $lines=null;
    var 
$bands=null;
    var 
$text_scale_off=0;    // Text scale offset in world coordinates
    
var $background_image="", $background_image_type=-1, $background_image_format="png";
    var 
$background_image_bright=0, $background_image_contr=0, $background_image_sat=0;
    var 
$image_bright=0,  $image_contr=0,  $image_sat=0;
    var 
$inline;
    var 
$showcsim=0, $csimcolor="red"//debug stuff,  draw the csim boundaris on the image if <>0
    
var $grid_depth=DEPTH_BACK;    // Draw grid under all plots as default
    
var $iAxisStyle AXSTYLE_SIMPLE;
    var 
$iCSIMdisplay=false, $iHasStroked false;
    var 
$footer;
    var 
$csimcachename '',  $csimcachetimeout 0;
    var 
$iDoClipping false;
    var 
$y2orderback=true;
    var 
$tabtitle;
    var 
$bkg_gradtype=-1, $bkg_gradstyle=BGRAD_MARGIN;
    var 
$bkg_gradfrom='navy',  $bkg_gradto='silver';

//---------------
// CONSTRUCTOR

    // aWIdth         Width in pixels of image
    // aHeight      Height in pixels of image
    // aCachedName    Name for image file in cache directory 
    // aTimeOut        Timeout in minutes for image in cache
    // aInline        If true the image is streamed back in the call to Stroke()
    //            If false the image is just created in the cache
    
function Graph($aWidth=300, $aHeight=200, $aCachedName="", $aTimeOut=0, $aInline=true) {
    GLOBAL 
$gJpgBrandTiming;
    
// If timing is used create a new timing object
    
if( $gJpgBrandTiming ) {
        global 
$tim;
        
$tim = new JpgTimer();
        
$tim->Push();
    }
        
    
// Automatically generate the image file name based on the name of the script that
    // generates the graph
    
if( $aCachedName=="auto" )
        
$aCachedName=GenImgName();
            
    
// Should the image be streamed back to the browser or only to the cache?
    
$this->inline=$aInline;
        
    
$this->img    =  new RotImage($aWidth, $aHeight);

    
$this->cache     =  new ImgStreamCache($this->img);
    
$this->cache->SetTimeOut($aTimeOut);

    
$this->title     =  new Text();
    
$this->title->ParagraphAlign('center');
    
$this->title->SetFont(FF_FONT2, FS_BOLD);
    
$this->title->SetMargin(3);

    
$this->subtitle =  new Text();
    
$this->subtitle->ParagraphAlign('center');

    
$this->subsubtitle =  new Text();
    
$this->subsubtitle->ParagraphAlign('center');

    
$this->legend     =  new Legend();
    
$this->footer = new Footer();

    
// If the cached version exist just read it directly from the
    // cache,  stream it back to browser and exit
    
if( $aCachedName!="" && READ_CACHE && $aInline )
        if( 
$this->cache->GetAndStream($aCachedName) ) {
        exit();
        }
                
    
$this->cache_name $aCachedName;
    
$this->SetTickDensity(); // Normal density

    
$this->tabtitle = new GraphTabTitle();
    }
//---------------
// PUBLIC METHODS    

    // Should the grid be in front or back of the plot?
    
function SetGridDepth($aDepth) {
    
$this->grid_depth=$aDepth;
    }
    
    
// Specify graph angle 0-360 degrees.
    
function SetAngle($aAngle) {
    
$this->img->SetAngle($aAngle);
    }

    function 
SetAlphaBlending($aFlg=true) {
    
$this->img->SetAlphaBlending($aFlg);
    }

    
// Shortcut to image margin
    
function SetMargin($lm, $rm, $tm, $bm) {
    
$this->img->SetMargin($lm, $rm, $tm, $bm);
    }

    function 
SetY2OrderBack($aBack=true) {
    
$this->y2orderback $aBack;
    }

    
// Rotate the graph 90 degrees and set the margin 
    // when we have done a 90 degree rotation
    
function Set90AndMargin($lm=0, $rm=0, $tm=0, $bm=0) {
    
$lm $lm ==floor(0.2 $this->img->width)  : $lm ;
    
$rm $rm ==floor(0.1 $this->img->width)  : $rm ;
    
$tm $tm ==floor(0.2 $this->img->height) : $tm ;
    
$bm $bm ==floor(0.1 $this->img->height) : $bm ;

    
$adj = ($this->img->height $this->img->width)/2;
    
$this->img->SetMargin($tm-$adj, $bm-$adj, $rm+$adj, $lm+$adj);
    
$this->img->SetCenter(floor($this->img->width/2), floor($this->img->height/2));
    
$this->SetAngle(90);
    
$this->xaxis->SetLabelAlign('right', 'center');
    
$this->yaxis->SetLabelAlign('center', 'bottom');
    }
    
    function 
SetClipping($aFlg=true) {
    
$this->iDoClipping $aFlg ;
    }

    
// Add a plot object to the graph
    
function Add(&$aPlot) {
    if( 
$aPlot == null )
        
JpGraphError::Raise("<b></b> Graph::Add() You tried to add a null plot to the graph.");
    if( 
is_array($aPlot) && count($aPlot) > )
        
$cl get_class($aPlot[0]);
    else
        
$cl get_class($aPlot);

    if( 
$cl == 'text' 
        
$this->AddText($aPlot);
    elseif( 
$cl == 'plotline' )
        
$this->AddLine($aPlot);
    elseif( 
$cl == 'plotband' )
        
$this->AddBand($aPlot);
    else
        
$this->plots[] = &$aPlot;
    }

    
// Add plot to second Y-scale
    
function AddY2(&$aPlot) {
    if( 
$aPlot == null )
        
JpGraphError::Raise("<b></b> Graph::AddY2() You tried to add a null plot to the graph.");    
    
$this->y2plots[] = &$aPlot;
    }
    
    
// Add text object to the graph
    
function AddText(&$aTxt) {
    if( 
$aTxt == null )
        
JpGraphError::Raise("<b></b> Graph::AddText() You tried to add a null text to the graph.");        
    if( 
is_array($aTxt) ) {
        for(
$i=0$i count($aTxt); ++$i )
        
$this->texts[]=&$aTxt[$i];
    }
    else
        
$this->texts[] = &$aTxt;
    }
    
    
// Add a line object (class PlotLine) to the graph
    
function AddLine(&$aLine) {
    if( 
$aLine == null )
        
JpGraphError::Raise("<b></b> Graph::AddLine() You tried to add a null line to the graph.");        
    if( 
is_array($aLine) ) {
        for(
$i=0$i<count($aLine); ++$i )
        
$this->lines[]=&$aLine[$i];
    }
    else
        
$this->lines[] = &$aLine;
    }

    
// Add vertical or horizontal band
    
function AddBand(&$aBand) {
    if( 
$aBand == null )
        
JpGraphError::Raise(" Graph::AddBand() You tried to add a null band to the graph.");
    if( 
is_array($aBand) ) {
        for(
$i=0$i<count($aBand); ++$i )
        
$this->bands[] = &$aBand[$i];
    }
    else
        
$this->bands[] = &$aBand;
    }

    function 
SetBackgroundGradient($aFrom='navy', $aTo='silver', $aGradType=GRAD_HOR, $aStyle=BGRAD_FRAME) {
    
$this->bkg_gradtype=$aGradType;
    
$this->bkg_gradstyle=$aStyle;
    
$this->bkg_gradfrom $aFrom;
    
$this->bkg_gradto $aTo;
    } 
    
    
// Specify a background image
    
function SetBackgroundImage($aFileName, $aBgType=BGIMG_FILLPLOT, $aImgFormat="auto") {

    if( 
$GLOBALS['gd2'] && !USE_TRUECOLOR ) {
        
JpGraphError::Raise("You are using GD 2.x and are trying to use a background images on a non truecolor image. To use background images with GD 2.x you <b>must</b> enable truecolor by setting the USE_TRUECOLOR constant to TRUE. Due to a bug in GD 2.0.1 using any truetype fonts with truecolor images will result in very poor quality fonts.");
    }

    
// Get extension to determine image type
    
if( $aImgFormat == "auto" ) {
        
$e explode('.', $aFileName);
        if( !
$e ) {
        
JpGraphError::Raise('Incorrect file name for Graph::SetBackgroundImage() : '.$aFileName.' Must have a valid image extension (jpg, gif, png) when using autodetection of image type');
        }

        
$valid_formats = array('png',  'jpg',  'gif');
        
$aImgFormat strtolower($e[count($e)-1]);
        if (
$aImgFormat == 'jpeg')  {
        
$aImgFormat 'jpg';
        }
        elseif (!
in_array($aImgFormat,  $valid_formats) )  {
        
JpGraphError::Raise('Unknown file extension ($aImgFormat) in Graph::SetBackgroundImage() for filename: '.$aFileName);
        }    
    }

    
$this->background_image $aFileName;
    
$this->background_image_type=$aBgType;
    
$this->background_image_format=$aImgFormat;
    }
    
    
// Adjust brightness and constrast for background image
    
function AdjBackgroundImage($aBright, $aContr=0, $aSat=0) {
    
$this->background_image_bright=$aBright;
    
$this->background_image_contr=$aContr;
    
$this->background_image_sat=$aSat;
    }
    
    
// Adjust brightness and constrast for image
    
function AdjImage($aBright, $aContr=0, $aSat=0) {
    
$this->image_bright=$aBright;
    
$this->image_contr=$aContr;
    
$this->image_sat=$aSat;
    }

    
// Specify axis style (boxed or single)
    
function SetAxisStyle($aStyle) {
        
$this->iAxisStyle $aStyle ;
    }
    
    
// Set a frame around the plot area
    
function SetBox($aDrawPlotFrame=true, $aPlotFrameColor=array(0, 0, 0), $aPlotFrameWeight=1) {
    
$this->boxed $aDrawPlotFrame;
    
$this->box_weight $aPlotFrameWeight;
    
$this->box_color $aPlotFrameColor;
    }
    
    
// Specify color for the plotarea (not the margins)
    
function SetColor($aColor) {
    
$this->plotarea_color=$aColor;
    }
    
    
// Specify color for the margins (all areas outside the plotarea)
    
function SetMarginColor($aColor) {
    
$this->margin_color=$aColor;
    }
    
    
// Set a frame around the entire image
    
function SetFrame($aDrawImgFrame=true, $aImgFrameColor=array(0, 0, 0), $aImgFrameWeight=1) {
    
$this->doframe $aDrawImgFrame;
    
$this->frame_color $aImgFrameColor;
    
$this->frame_weight $aImgFrameWeight;
    }
        
    
// Set the shadow around the whole image
    
function SetShadow($aShowShadow=true, $aShadowWidth=5, $aShadowColor=array(102, 102, 102)) {
    
$this->doshadow $aShowShadow;
    
$this->shadow_color $aShadowColor;
    
$this->shadow_width $aShadowWidth;
    
$this->footer->iBottomMargin += $aShadowWidth;
    
$this->footer->iRightMargin += $aShadowWidth;
    }

    
// Specify x, y scale. Note that if you manually specify the scale
    // you must also specify the tick distance with a call to Ticks::Set()
    
function SetScale($aAxisType, $aYMin=1, $aYMax=1, $aXMin=1, $aXMax=1) {
    
$this->axtype $aAxisType;

    if( 
$aYMax $aYMin || $aXMax $aXMin )
        
JpGraphError::Raise('Graph::SetScale(): Specified Max value must be larger than the specified Min value.');

    
$yt=substr($aAxisType, -3, 3);
    if( 
$yt=="lin" )
        
$this->yscale = new LinearScale($aYMin, $aYMax);
    elseif( 
$yt == "int" ) {
        
$this->yscale = new LinearScale($aYMin, $aYMax);
        
$this->yscale->SetIntScale();
    }
    elseif( 
$yt=="log" )
        
$this->yscale = new LogScale($aYMin, $aYMax);
    else
        
JpGraphError::Raise("Unknown scale specification for Y-scale. ($aAxisType)");
            
    
$xt=substr($aAxisType, 0, 3);
    if( 
$xt == "lin" || $xt == "tex" ) {
        
$this->xscale = new LinearScale($aXMin, $aXMax, "x");
        
$this->xscale->textscale = ($xt == "tex");
    }
    elseif( 
$xt == "int" ) {
        
$this->xscale = new LinearScale($aXMin, $aXMax, "x");
        
$this->xscale->SetIntScale();
    }
    elseif( 
$xt == "log" )
        
$this->xscale = new LogScale($aXMin, $aXMax, "x");
    else
        
JpGraphError::Raise(" Unknown scale specification for X-scale. ($aAxisType)");

    
$this->xscale->Init($this->img);
    
$this->yscale->Init($this->img);                        
                    
    
$this->xaxis = new Axis($this->img, $this->xscale);
    
$this->yaxis = new Axis($this->img, $this->yscale);
    
$this->xgrid = new Grid($this->xaxis);
    
$this->ygrid = new Grid($this->yaxis);    
    
$this->ygrid->Show();            
    }
    
    
// Specify secondary Y scale
    
function SetY2Scale($aAxisType="lin", $aY2Min=1, $aY2Max=1) {
    if( 
$aAxisType=="lin" 
        
$this->y2scale = new LinearScale($aY2Min, $aY2Max);
    elseif( 
$aAxisType == "int" ) {
        
$this->y2scale = new LinearScale($aY2Min, $aY2Max);
        
$this->y2scale->SetIntScale();
    }
    elseif( 
$aAxisType=="log" ) {
        
$this->y2scale = new LogScale($aY2Min, $aY2Max);
    }
    else 
JpGraphError::Raise("JpGraph: Unsupported Y2 axis type: $axtype<br>");
            
    
$this->y2scale->Init($this->img);    
    
$this->y2axis = new Axis($this->img, $this->y2scale);
    
$this->y2axis->scale->ticks->SetDirection(SIDE_LEFT); 
    
$this->y2axis->SetLabelSide(SIDE_RIGHT); 
        
    
// Deafult position is the max x-value
    
$this->y2grid = new Grid($this->y2axis);                            
    }
    
    
// Specify density of ticks when autoscaling 'normal',  'dense',  'sparse',  'verysparse'
    // The dividing factor have been determined heuristically according to my aesthetic 
    // sense (or lack off) y.m.m.v !
    
function SetTickDensity($aYDensity=TICKD_NORMAL, $aXDensity=TICKD_NORMAL) {
    
$this->xtick_factor=30;
    
$this->ytick_factor=25;        
    switch( 
$aYDensity ) {
        case 
TICKD_DENSE:
        
$this->ytick_factor=12;            
        break;
        case 
TICKD_NORMAL:
        
$this->ytick_factor=25;            
        break;
        case 
TICKD_SPARSE:
        
$this->ytick_factor=40;            
        break;
        case 
TICKD_VERYSPARSE:
        
$this->ytick_factor=100;            
        break;        
        default:
        
JpGraphError::Raise("JpGraph: Unsupported Tick density: $densy");
    }
    switch( 
$aXDensity ) {
        case 
TICKD_DENSE:
        
$this->xtick_factor=15;                            
        break;
        case 
TICKD_NORMAL:
        
$this->xtick_factor=30;            
        break;
        case 
TICKD_SPARSE:
        
$this->xtick_factor=45;                    
        break;
        case 
TICKD_VERYSPARSE:
        
$this->xtick_factor=60;                                
        break;        
        default:
        
JpGraphError::Raise("JpGraph: Unsupported Tick density: $densx");
    }        
    }
    

    
// Get a string of all image map areas    
    
function GetCSIMareas() {
    if( !
$this->iHasStroked )
        
$this->Stroke(_CSIM_SPECIALFILE);
    
$csim='';
    
$n count($this->plots);
    for( 
$i=0$i<$n; ++$i 
        
$csim .= $this->plots[$i]->GetCSIMareas();

    
$n count($this->y2plots);
    for( 
$i=0$i<$n; ++$i 
        
$csim .= $this->y2plots[$i]->GetCSIMareas();

    
$csim .= $this->legend->GetCSIMAreas();

    return 
$csim;
    }
    
    
// Get a complete <MAP>..</MAP> tag for the final image map
    
function GetHTMLImageMap($aMapName) {
    
$im "<MAP NAME=\"$aMapName\">\n";
    
$im .= $this->GetCSIMareas();
    
$im .= "</MAP>"
    return 
$im;
    }

    function 
CheckCSIMCache($aCacheName, $aTimeOut=60) {
    global 
$HTTP_SERVER_VARS;

    if( 
$aCacheName=='auto' )
        
$aCacheName=basename($HTTP_SERVER_VARS['PHP_SELF']);

    
$this->csimcachename CSIMCACHE_DIR.$aCacheName;
    
$this->csimcachetimeout $aTimeOut;

    
// First determine if we need to check for a cached version
    // This differs from the standard cache in the sense that the
    // image and CSIM map HTML file is written relative to the directory
    // the script executes in and not the specified cache directory.
    // The reason for this is that the cache directory is not necessarily
    // accessible from the HTTP server.
    
if( $this->csimcachename != '' ) {
        
$dir dirname($this->csimcachename);
        
$base basename($this->csimcachename);
        
$base strtok($base, '.');
        
$suffix strtok('.');
        
$basecsim $dir.'/'.$base.'_csim_.html';
        
$baseimg $dir.'/'.$base.'.'.$this->img->img_format;

        
$timedout=false;
        
        
// Does it exist at all ?
        
        
if( file_exists($basecsim) && file_exists($baseimg) ) {
        
// Check that it hasn't timed out
        
$diff=time()-filemtime($basecsim);
        if( 
$this->csimcachetimeout>&& ($diff $this->csimcachetimeout*60) ) {
            
$timedout=true;
            @
unlink($basecsim);
            @
unlink($baseimg);
        }
        else {
            if (
$fh = @fopen($basecsim,  "r")) {
            
fpassthru($fh);
            exit();
            }
            else
            
JpGraphError::Raise(" Can't open cached CSIM \"$basecsim\" for reading.");
        }
        }
    }
    return 
false;
    }

    function 
StrokeCSIM($aScriptName='', $aCSIMName='', $aBorder=0) {
    GLOBAL 
$HTTP_GET_VARS;

    if( 
$aCSIMName=='' ) {
        
// create a random map name
        
srand ((double) microtime() * 1000000);
        
$r rand(0, 100000);
        
$aCSIMName='__mapname'.$r.'__';
    }
    if( empty(
$HTTP_GET_VARS[_CSIM_DISPLAY]) ) {
        
// First determine if we need to check for a cached version
        // This differs from the standard cache in the sense that the
        // image and CSIM map HTML file is written relative to the directory
        // the script executes in and not the specified cache directory.
        // The reason for this is that the cache directory is not necessarily
        // accessible from the HTTP server.
        
if( $this->csimcachename != '' ) {
        
$dir dirname($this->csimcachename);
        
$base basename($this->csimcachename);
        
$base strtok($base, '.');
        
$suffix strtok('.');
        
$basecsim $dir.'/'.$base.'_csim_.html';
        
$baseimg $base.'.'.$this->img->img_format;

        
// Check that apache can write to directory specified

        
if( file_exists($dir) && !is_writeable($dir) ) {
            
JpgraphError::Raise('Apache/PHP does not have permission to write to the CSIM cache directory ('.$dir.'). Check permissions.');
        }
        
        
// Make sure directory exists
        
$this->cache->MakeDirs($dir);

        
// Write the image file
        
$this->Stroke(CSIMCACHE_DIR.$baseimg);

        
// Construct wrapper HTML and write to file and send it back to browser
        
$htmlwrap $this->GetHTMLImageMap($aCSIMName)."\n".
            
'<img src="'.CSIMCACHE_HTTP_DIR.$baseimg.'" ISMAP USEMAP="#'.$aCSIMName.'" border='.$aBorder.'>'."\n";
        if(
$fh =  @fopen($basecsim, 'w') ) {
            
fwrite($fh, $htmlwrap);
            
fclose($fh);
            echo 
$htmlwrap;
        }
        else
            
JpGraphError::Raise(" Can't write CSIM \"$basecsim\" for writing. Check free space and permissions.");
        }
        else {

        if( 
$aScriptName=='' ) {
            
JpGraphError::Raise('Missing script name in call to StrokeCSIM(). You must specify the name of the actual image script as the first parameter to StrokeCSIM().');
            exit();
        }

        
// Construct the HTML wrapper page
        // Get all user defined URL arguments
        
reset($HTTP_GET_VARS);
        
        
// This is a JPGRAPH internal defined that prevents
        // us from recursively coming here again
        
$urlarg='?'._CSIM_DISPLAY.'=1';

        while( list(
$key, $value) = each($HTTP_GET_VARS) ) {
            
$urlarg .= '&'.$key.'='.$value;
        }
        
        echo 
$this->GetHTMLImageMap($aCSIMName);

        echo 
"<img src='".$aScriptName.$urlarg."' ISMAP USEMAP='#".$aCSIMName."' border=$aBorder>";
        }
    }
    else {
        
$this->Stroke();
    }
    }

    function 
GetXMinMax() {
    list(
$min, $ymin) = $this->plots[0]->Min();
    list(
$max, $ymax) = $this->plots[0]->Max();
    foreach( 
$this->plots as $p ) {
        list(
$xmin, $ymin) = $p->Min();
        list(
$xmax, $ymax) = $p->Max();            
        
$min Min($xmin, $min);
        
$max Max($xmax, $max);
    }
    if( 
$this->y2axis != null ) {
        foreach( 
$this->y2plots as $p ) {
        list(
$xmin, $ymin) = $p->Min();
            list(
$xmax, $ymax) = $p->Max();            
            
$min Min($xmin, $min);
            
$max Max($xmax, $max);
        }            
    }
    return array(
$min, $max);
    }

    function 
AdjustMarginsForTitles() {
    
$totrequired 
        (
$this->title->!= '' 
         
$this->title->GetTextHeight($this->img) + $this->title->margin ) +
        (
$this->subtitle->!= '' 
         
$this->subtitle->GetTextHeight($this->img) + $this->subtitle->margin ) + 
        (
$this->subsubtitle->!= '' 
         
$this->subsubtitle->GetTextHeight($this->img) + $this->subsubtitle->margin ) ;
    

    
// Minimum bottom margin
    
if( $this->xaxis->title->!= '' ) {
        if( 
$this->img->== 90 
        
$btotrequired $this->yaxis->title->GetTextHeight($this->img) + ;
        else
        
$btotrequired $this->xaxis->title->GetTextHeight($this->img) + ;
    }
    else
        
$btotrequired 0;
    if( 
$this->img->== 90 ) {
        
$this->img->SetFont($this->yaxis->font_family, $this->yaxis->font_style,
                
$this->yaxis->font_size);
        
$lh $this->img->GetTextHeight('Mg', $this->yaxis->label_angle);
    }
    else {
        
$this->img->SetFont($this->xaxis->font_family, $this->xaxis->font_style,
                
$this->xaxis->font_size);
        
$lh $this->img->GetTextHeight('Mg', $this->xaxis->label_angle);
    }

    
$btotrequired += $lh 5;


    if( 
$this->img->== 90 ) {
        
// DO Nothing. It gets t messy to do this properly for 90 deg...
    
}
    else{
        if( 
$this->img->top_margin $totrequired ) {
        
$this->SetMargin($this->img->left_margin, $this->img->right_margin,
                 
$totrequired, $this->img->bottom_margin);
        }
        if( 
$this->img->bottom_margin $btotrequired ) {
        
$this->SetMargin($this->img->left_margin, $this->img->right_margin,
                 
$this->img->top_margin, $btotrequired);
        }
    }
    }

    
// Stroke the graph
    // $aStrokeFileName    If != "" the image will be written to this file and NOT
    // streamed back to the browser
    
function Stroke($aStrokeFileName="") {        

    
// Start by adjusting the margin so that potential titles will fit.
    
$this->AdjustMarginsForTitles();

    
// If the filename is the predefined value = '_csim_special_'
    // we assume that the call to stroke only needs to do enough
    // to correctly generate the CSIM maps.
    // We use this variable to skip things we don't strictly need
    // to do to generate the image map to improve performance
    // a best we can. Therefor you will see a lot of tests !$_csim in the
    // code below.
    
$_csim = ($aStrokeFileName===_CSIM_SPECIALFILE);

    
// We need to know if we have stroked the plot in the
    // GetCSIMareas. Otherwise the CSIM hasn't been generated
    // and in the case of GetCSIM called before stroke to generate
    // CSIM without storing an image to disk GetCSIM must call Stroke.
    
$this->iHasStroked true;

    
// Do any pre-stroke adjustment that is needed by the different plot types
    // (i.e bar plots want's to add an offset to the x-labels etc)
    
for($i=0$i<count($this->plots) ; ++$i ) {
        
$this->plots[$i]->PreStrokeAdjust($this);
        
$this->plots[$i]->Legend($this);
    }
        
    
// Any plots on the second Y scale?
    
if( $this->y2scale != null ) {
        for(
$i=0$i<count($this->y2plots)    ; ++$i ) {
        
$this->y2plots[$i]->PreStrokeAdjust($this);
        
$this->y2plots[$i]->Legend($this);
        }
    }
        
    
// Bail out if any of the Y-axis not been specified and
    // has no plots. (This means it is impossible to do autoscaling and
    // no other scale was given so we can't possible draw anything). If you use manual
    // scaling you also have to supply the tick steps as well.
    
if( (!$this->yscale->IsSpecified() && count($this->plots)==0) ||
        (
$this->y2scale!=null && !$this->y2scale->IsSpecified() && count($this->y2plots)==0) ) {
        
$e "Can't draw unspecified Y-scale.<br>\nYou have either:<br>\n";
        
$e .= "1. Specified an Y axis for autoscaling but have not supplied any plots<br>\n";
        
$e .= "2. Specified a scale manually but have forgot to specify the tick steps";
        
JpGraphError::Raise($e);
    }
        
    
// Bail out if no plots and no specified X-scale
    
if( (!$this->xscale->IsSpecified() && count($this->plots)==&& count($this->y2plots)==0) )
        
JpGraphError::Raise("<strong>JpGraph: Can't draw unspecified X-scale.</strong><br>No plots.<br>");

    
//Check if we should autoscale y-axis
    
if( !$this->yscale->IsSpecified() && count($this->plots)>) {
        list(
$min, $max) = $this->GetPlotsYMinMax($this->plots);
        
$this->yscale->AutoScale($this->img, $min, $max,
                     
$this->img->plotheight/$this->ytick_factor);
    }
    elseif( 
$this->yscale->IsSpecified() && 
        ( 
$this->yscale->auto_ticks || !$this->yscale->ticks->IsSpecified()) ) {
        
// The tick calculation will use the user suplied min/max values to determine
        // the ticks. If auto_ticks is false the exact user specifed min and max
        // values will be used for the scale. 
        // If auto_ticks is true then the scale might be slightly adjusted
        // so that the min and max values falls on an even major step.
        
$min $this->yscale->scale[0];
        
$max $this->yscale->scale[1];
        
$this->yscale->AutoScale($this->img, $min, $max,
                     
$this->img->plotheight/$this->ytick_factor,
                     
$this->yscale->auto_ticks);
    }

    if( 
$this->y2scale != null) {
        if( !
$this->y2scale->IsSpecified() && count($this->y2plots)>) {
        list(
$min, $max) = $this->GetPlotsYMinMax($this->y2plots);
        
$this->y2scale->AutoScale($this->img, $min, $max, $this->img->plotheight/$this->ytick_factor);
        }            
        elseif( 
$this->y2scale->IsSpecified() && 
            ( 
$this->y2scale->auto_ticks || !$this->y2scale->ticks->IsSpecified()) ) {
        
// The tick calculation will use the user suplied min/max values to determine
        // the ticks. If auto_ticks is false the exact user specifed min and max
        // values will be used for the scale. 
        // If auto_ticks is true then the scale might be slightly adjusted
        // so that the min and max values falls on an even major step.
        
$min $this->y2scale->scale[0];
        
$max $this->y2scale->scale[1];
        
$this->y2scale->AutoScale($this->img, $min, $max,
                      
$this->img->plotheight/$this->ytick_factor,
                      
$this->y2scale->auto_ticks);
        }
    }
                
    
//Check if we should autoscale x-axis
    
if( !$this->xscale->IsSpecified() ) {
        if( 
substr($this->axtype, 0, 4) == "text" ) {
        
$max=0;
        foreach( 
$this->plots as $p ) {
            
$max=max($max, $p->numpoints-1);
        }
        
$min=0;
        if( 
$this->y2axis != null ) {
            foreach( 
$this->y2plots as $p ) {
            
$max=max($max, $p->numpoints-1);
            }            
        }
        
$this->xscale->Update($this->img, $min, $max);
        
$this->xscale->ticks->Set($this->xaxis->tick_step, 1);
        
$this->xscale->ticks->SupressMinorTickMarks();
        }
        else {
        list(
$min, $max) = $this->GetXMinMax();
        
$this->xscale->AutoScale($this->img, $min, $max, $this->img->plotwidth/$this->xtick_factor);
        }
            
        
//Adjust position of y-axis and y2-axis to minimum/maximum of x-scale
        
if( !is_numeric($this->yaxis->pos) && !is_string($this->yaxis->pos) )
            
$this->yaxis->SetPos($this->xscale->GetMinVal());
        if( 
$this->y2axis != null ) {
        if( !
is_numeric($this->y2axis->pos) && !is_string($this->y2axis->pos) )
            
$this->y2axis->SetPos($this->xscale->GetMaxVal());
        
$this->y2axis->SetTitleSide(SIDE_RIGHT);
        }
    }    
    elseif( 
$this->xscale->IsSpecified() &&  
        ( 
$this->xscale->auto_ticks || !$this->xscale->ticks->IsSpecified()) ) {
        
// The tick calculation will use the user suplied min/max values to determine
        // the ticks. If auto_ticks is false the exact user specifed min and max
        // values will be used for the scale. 
        // If auto_ticks is true then the scale might be slightly adjusted
        // so that the min and max values falls on an even major step.
        
$min $this->xscale->scale[0];
        
$max $this->xscale->scale[1];
        
$this->xscale->AutoScale($this->img, $min, $max,
                     
$this->img->plotwidth/$this->xtick_factor,
                     
false);
    }
        
    
// If we have a negative values and x-axis position is at 0
    // we need to supress the first and possible the last tick since
    // they will be drawn on top of the y-axis (and possible y2 axis)
    // The test below might seem strange the reasone being that if
    // the user hasn't specified a value for position this will not
    // be set until we do the stroke for the axis so as of now it
    // is undefined.
    // For X-text scale we ignore all this since the tick are usually
    // much further in and not close to the Y-axis. Hence the test 
    // for 'text'    

    
if( ($this->yaxis->pos==$this->xscale->GetMinVal() || 
         (
is_string($this->yaxis->pos) && $this->yaxis->pos=='min')) &&  
        !
is_numeric($this->xaxis->pos) && $this->yscale->GetMinVal() < && 
        
substr($this->axtype, 0, 4) != 'text' && $this->xaxis->pos!="min" ) {

        
//$this->yscale->ticks->SupressZeroLabel(false);
        
$this->xscale->ticks->SupressFirst();
        if( 
$this->y2axis != null ) {
        
$this->xscale->ticks->SupressLast();
        }
    }
    elseif( !
is_numeric($this->yaxis->pos) && $this->yaxis->pos=='max' ) {
        
$this->xscale->ticks->SupressLast();
    }
    

    if( !
$_csim ) {
        
$this->StrokePlotArea();
        
$this->StrokeAxis();
    }

    
// Stroke bands
    
if( $this->bands != null && !$_csim
        for(
$i=0$i<count($this->bands); ++$i) {
        
// Stroke all bands that asks to be in the background
        
if( $this->bands[$i]->depth == DEPTH_BACK )
            
$this->bands[$i]->Stroke($this->img, $this->xscale, $this->yscale);
        }

    if( 
$this->grid_depth == DEPTH_BACK && !$_csim) {
        
$this->ygrid->Stroke();
        
$this->xgrid->Stroke();
    }
                
    
// Stroke Y2-axis
    
if( $this->y2axis != null && !$_csim) {        
        
$this->y2axis->Stroke($this->xscale);                 
        
$this->y2grid->Stroke();
    }
        
    
$oldoff=$this->xscale->off;
    if(
substr($this->axtype, 0, 4)=="text") {
        
$this->xscale->off += 
        
ceil($this->xscale->scale_factor*$this->text_scale_off*$this->xscale->ticks->minor_step);
    }

    if( 
$this->iDoClipping ) {
        
$oldimage $this->img->CloneCanvasH();
    }

    if( ! 
$this->y2orderback ) {
        
// Stroke all plots for Y1 axis
        
for($i=0$i count($this->plots); ++$i) {
        
$this->plots[$i]->Stroke($this->img, $this->xscale, $this->yscale);
        
$this->plots[$i]->StrokeMargin($this->img);
        }                        
    }

    
// Stroke all plots for Y2 axis
    
if( $this->y2scale != null )
        for(
$i=0$icount($this->y2plots); ++$i ) {    
        
$this->y2plots[$i]->Stroke($this->img, $this->xscale, $this->y2scale);
        }        

    if( 
$this->y2orderback ) {
        
// Stroke all plots for Y1 axis
        
for($i=0$i count($this->plots); ++$i) {
        
$this->plots[$i]->Stroke($this->img, $this->xscale, $this->yscale);
        
$this->plots[$i]->StrokeMargin($this->img);
        }                        
    }


    if( 
$this->iDoClipping ) {
        
// Clipping only supports graphs at 0 and 90 degrees
        
if( $this->img->== ) {
        
$this->img->CopyCanvasH($oldimage, $this->img->img,
                    
$this->img->left_margin, $this->img->top_margin,
                    
$this->img->left_margin, $this->img->top_margin,
                    
$this->img->plotwidth+1, $this->img->plotheight);
        }
        elseif( 
$this->img->== 90 ) {
        
$adj = ($this->img->height $this->img->width)/2;
        
$this->img->CopyCanvasH($oldimage, $this->img->img,
                    
$this->img->bottom_margin-$adj, $this->img->left_margin+$adj,
                    
$this->img->bottom_margin-$adj, $this->img->left_margin+$adj,
                    
$this->img->plotheight+1, $this->img->plotwidth);
        }
        else {
        
JpGraphError::Raise('You have enabled clipping. Cliping is only supported for graphs at 0 or 90 degrees rotation. Please adjust you current angle (='.$this->img->a.' degrees) or disable clipping.');
        }
        
$this->img->Destroy();
        
$this->img->SetCanvasH($oldimage);
    }

    
$this->xscale->off=$oldoff;
        
    if( 
$this->grid_depth == DEPTH_FRONT && !$_csim ) {
        
$this->ygrid->Stroke();
        
$this->xgrid->Stroke();
    }

    
// Stroke bands
    
if( $this->bands!= null )
        for(
$i=0$i<count($this->bands); ++$i) {
        
// Stroke all bands that asks to be in the foreground
        
if( $this->bands[$i]->depth == DEPTH_FRONT )
            
$this->bands[$i]->Stroke($this->img, $this->xscale, $this->yscale);
        }

    
// Stroke any lines added
    
if( $this->lines != null ) {
        for(
$i=0$i<count($this->lines); ++$i) {
        
$this->lines[$i]->Stroke($this->img, $this->xscale, $this->yscale);
        }
    }
        
    
// Finally draw the axis again since some plots may have nagged
    // the axis in the edges.
    
if( !$_csim )
        
$this->StrokeAxis();

    if( 
$this->y2scale != null && !$_csim 
        
$this->y2axis->Stroke($this->xscale);     
        
    if( !
$_csim ) {
        
$this->StrokePlotBox();
        
$this->footer->Stroke($this->img);
    }
        
    if( !
$_csim ) {
        
// The titles and legends never gets rotated so make sure
        // that the angle is 0 before stroking them                
        
$aa $this->img->SetAngle(0);
        
$this->StrokeTitles();
    }

    
$this->legend->Stroke($this->img);        

    if( !
$_csim ) {

        
$this->StrokeTexts();    
        
$this->img->SetAngle($aa);    
            
        
// Draw an outline around the image map    
        
if(JPG_DEBUG)
        
$this->DisplayClientSideaImageMapAreas();        
        
        
// Adjust the appearance of the image
        
$this->AdjustSaturationBrightnessContrast();

        
// If the filename is given as the special "__handle"
        // then the image handler is returned and the image is NOT
        // streamed back
        
if( $aStrokeFileName == _IMG_HANDLER ) {
        return 
$this->img->img;
        }
        else {
        
// Finally stream the generated picture                    
        
$this->cache->PutAndStream($this->img, $this->cache_name, $this->inline,
                       
$aStrokeFileName);        
        }
    }
    }

//---------------
// PRIVATE METHODS    
    
function StrokeAxis() {
        
    
// Stroke axis
    
if( $this->iAxisStyle != AXSTYLE_SIMPLE ) {
        switch( 
$this->iAxisStyle ) {
            case 
AXSTYLE_BOXIN :
                
$toppos SIDE_DOWN;
            
$bottompos SIDE_UP;
                
$leftpos SIDE_RIGHT;
                
$rightpos SIDE_LEFT;
                break;
        case 
AXSTYLE_BOXOUT :
            
$toppos SIDE_UP;
                
$bottompos SIDE_DOWN;        
                
$leftpos SIDE_LEFT;
            
$rightpos SIDE_RIGHT;
                break;
        case 
AXSTYLE_YBOXIN:
                
$toppos = -100;
            
$bottompos SIDE_UP;
                
$leftpos SIDE_RIGHT;
                
$rightpos SIDE_LEFT;
            break;
        case 
AXSTYLE_YBOXOUT:
            
$toppos = -100;
                
$bottompos SIDE_DOWN;        
                
$leftpos SIDE_LEFT;
            
$rightpos SIDE_RIGHT;
            break;
        default:
                
JpGRaphError::Raise('Unknown AxisStyle() : '.$this->iAxisStyle);
                break;
        }
        
$this->xaxis->SetPos('min');
        
        
// By default we hide the first label so it doesn't cross the
        // Y-axis in case the positon hasn't been set by the user.
        // However,  if we use a box we always want the first value
        // displayed so we make sure it will be displayed.
        
$this->xscale->ticks->SupressFirst(false);
        
        
$this->xaxis->SetLabelSide(SIDE_DOWN);
        
$this->xaxis->scale->ticks->SetSide($bottompos);
        
$this->xaxis->Stroke($this->yscale);

        if( 
$toppos != -100 ) {
        
// To avoid side effects we work on a new copy
        
$maxis $this->xaxis;
        
$maxis->SetPos('max');
        
$maxis->SetLabelSide(SIDE_UP);
        
$maxis->SetLabelMargin(7);
        
$this->xaxis->scale->ticks->SetSide($toppos);
        
$maxis->Stroke($this->yscale);
        }

        
$this->yaxis->SetPos('min');
        
$this->yaxis->SetLabelMargin(10);
        
$this->yaxis->SetLabelSide(SIDE_LEFT);
        
$this->yaxis->scale->ticks->SetSide($leftpos);
        
$this->yaxis->Stroke($this->xscale);

        
$myaxis $this->yaxis;
        
$myaxis->SetPos('max');
        
$myaxis->SetLabelMargin(10);
        
$myaxis->SetLabelSide(SIDE_RIGHT);
        
$myaxis->title->Set('');
        
$myaxis->scale->ticks->SetSide($rightpos);
        
$myaxis->Stroke($this->xscale);
        
    }
    else {
        
$this->xaxis->Stroke($this->yscale);
        
$this->yaxis->Stroke($this->xscale);        
    }
    }


    
// Private helper function for backgound image
    
function LoadBkgImage($aImgFormat='', $aFile='') {
    if( 
$aFile == '' )
        
$aFile $this->background_image;
    
// Remove case sensitivity and setup appropriate function to create image
    // Get file extension. This should be the LAST '.' separated part of the filename
    
$e explode('.', $aFile);
    
$ext strtolower($e[count($e)-1]);
    if (
$ext == "jpeg")  {
        
$ext "jpg";
    }
    
    if( 
trim($ext) == '' 
        
$ext 'png';  // Assume PNG if no extension specified

    
if( $aImgFormat == '' )
        
$imgtag $ext;
    else
        
$imgtag $aImgFormat;

    if( 
$imgtag == "jpg" || $imgtag == "jpeg")
    {
        
$f "imagecreatefromjpeg";
        
$imgtag "jpg";
    }
    else
    {
        
$f "imagecreatefrom".$imgtag;
    }

    
// Compare specified image type and file extension
    
if( $imgtag != $ext ) {
        
$t " Background image seems to be of different type (has different file extension)".
         
" than specified imagetype. <br>Specified: '".
        
$aImgFormat."'<br>File: '".$aFile."'";
        
JpGraphError::Raise($t);
    }

    
$img = @$f($aFile);
    if( !
$img ) {
        
JpGraphError::Raise(" Can't read background image: '".$aFile."'");   
    }
    return 
$img;
    }    

    function 
StrokeBackgroundGrad() {
    if( 
$this->bkg_gradtype 0  
        return;
    
$grad = new Gradient($this->img);
    if( 
$this->bkg_gradstyle == BGRAD_PLOT ) {
        
$xl $this->img->left_margin;
        
$yt $this->img->top_margin;
        
$xr $xl $this->img->plotwidth ;
        
$yb $yt $this->img->plotheight ;
    }
    else {
        
$xl 0;
        
$yt 0;
        
$xr $xl $this->img->width 1;
        
$yb $yt $this->img->height 1;
    }
    if( 
$this->doshadow  ) {
        
$xr -= $this->shadow_width
        
$yb -= $this->shadow_width
    }
    
$grad->FilledRectangle($xl, $yt, $xr, $yb,
                   
$this->bkg_gradfrom, $this->bkg_gradto,
                   
$this->bkg_gradtype);
    }

    function 
StrokeFrameBackground() {
    if( 
$this->background_image == "" 
        return;

    
$bkgimg $this->LoadBkgImage($this->background_image_format);
    
$this->img->_AdjBrightContrast($bkgimg, $this->background_image_bright,
                       
$this->background_image_contr);
    
$this->img->_AdjSat($bkgimg, $this->background_image_sat);
    
$bw ImageSX($bkgimg);
    
$bh ImageSY($bkgimg);

    
// No matter what the angle is we always stroke the image and frame
    // assuming it is 0 degree
    
$aa $this->img->SetAngle(0);
        
    switch( 
$this->background_image_type ) {
        case 
BGIMG_FILLPLOT// Resize to just fill the plotarea
        
$this->StrokeFrame();
        
$GLOBALS['copyfunc']($this->img->img, $bkgimg,
                     
$this->img->left_margin+1, $this->img->top_margin+1,
                     
0, 0, $this->img->plotwidth+1, $this->img->plotheight,
                     
$bw, $bh);
        break;
        case 
BGIMG_FILLFRAME// Fill the whole area from upper left corner,  resize to just fit
        
$GLOBALS['copyfunc']($this->img->img, $bkgimg,
                     
0, 0, 0, 0,
                     
$this->img->width, $this->img->height,
                     
$bw, $bh);
        
$this->StrokeFrame();
        break;
        case 
BGIMG_COPY// Just copy the image from left corner,  no resizing
        
$GLOBALS['copyfunc']($this->img->img, $bkgimg,
                     
0, 0, 0, 0,
                     
$bw, $bh,
                     
$bw, $bh);
        
$this->StrokeFrame();
        break;
        case 
BGIMG_CENTER// Center original image in the plot area
        
$centerx round($this->img->plotwidth/2+$this->img->left_margin-$bw/2);
        
$centery round($this->img->plotheight/2+$this->img->top_margin-$bh/2);
        
$GLOBALS['copyfunc']($this->img->img, $bkgimg,
                     
$centerx, $centery,
                     
0, 0,
                     
$bw, $bh,
                     
$bw, $bh);
        
$this->StrokeFrame();
        break;
        default:
        
JpGraphError::Raise(" Unknown background image layout");
    }            
    
$this->img->SetAngle($aa);        
    }

    
// Private
    // Draw a frame around the image
    
function StrokeFrame() {
    if( !
$this->doframe ) return;
    if( 
$this->doshadow ) {
        
$this->img->SetColor($this->frame_color);            
        if( 
$this->background_image_type <= && 
        (
$this->bkg_gradtype || 
        (
$this->bkg_gradtype && $this->bkg_gradstyle==BGRAD_PLOT) ) ) 
        
$c $this->margin_color;
        else
        
$c false;
        
$this->img->ShadowRectangle(0, 0, $this->img->width, $this->img->height,
                    
$c, $this->shadow_width);
    }
    else {
        
$this->img->SetLineWeight($this->frame_weight);
        if( 
$this->background_image_type <= && 
        (
$this->bkg_gradtype || 
         (
$this->bkg_gradtype && $this->bkg_gradstyle==BGRAD_PLOT) ) ) {
        
$this->img->SetColor($this->margin_color);
        
$this->img->FilledRectangle(0, 0, $this->img->width-1, $this->img->height-1); 
        }
        
$this->img->SetColor($this->frame_color);
        
$this->img->Rectangle(0, 0, $this->img->width-1, $this->img->height-1);        
    }
    
$this->StrokeBackgroundGrad();
    }

    
// Stroke the plot area with either a solid color or a background image
    
function StrokePlotArea() {
    
// Note: To be consistent we really should take a possible shadow
    // into account. However,  that causes some problem for the LinearScale class
    // since in the current design it does not have any links to class Graph which
    // means it has no way of compensating for the adjusted plotarea in case of a 
    // shadow. So,  until I redesign LinearScale we can't compensate for this.
    // So just set the two adjustment parameters to zero for now.
    
$boxadj 0//$this->doframe ? $this->frame_weight : 0 ;
    
$adj 0//$this->doshadow ? $this->shadow_width : 0 ;

    
if( $this->background_image != "" ) {
        
$this->StrokeFrameBackground();
    }
    else {
        
$aa $this->img->SetAngle(0);
        
$this->StrokeFrame();
        if( 
$this->bkg_gradtype || 
        (
$this->bkg_gradtype && $this->bkg_gradstyle==BGRAD_MARGIN ) ) {
        
$this->img->SetAngle($aa);            
        
$this->img->PushColor($this->plotarea_color);
        
$this->img->FilledRectangle($this->img->left_margin+$boxadj,
                        
$this->img->top_margin+$boxadj,
                        
$this->img->width-$this->img->right_margin-$adj-2*$boxadj,
                        
$this->img->height-$this->img->bottom_margin-$adj-2*$boxadj);    
        
$this->img->PopColor();
        }
    }    
    }    
    
    
    function 
StrokePlotBox() {
    
// Should we draw a box around the plot area?
    
if( $this->boxed ) {
        
$this->img->SetLineWeight($this->box_weight);
        
$this->img->SetColor($this->box_color);
        
$this->img->Rectangle(
        
$this->img->left_margin, $this->img->top_margin,
        
$this->img->width-$this->img->right_margin,
        
$this->img->height-$this->img->bottom_margin);
    }                        
    }        

    function 
StrokeTitles() {
    
// Stroke title
    
$y $this->title->margin
    
$margin=3;
    
$this->title->Center(0, $this->img->width, $y);
    
$this->title->Stroke($this->img);
        
    
// ... and subtitle
    
$y += $this->title->GetTextHeight($this->img) + $margin $this->subtitle->margin;
    
$this->subtitle->Center(0, $this->img->width, $y);    
    
$this->subtitle->Stroke($this->img);

    
// ... and subsubtitle
    
$y += $this->subtitle->GetTextHeight($this->img) + $margin $this->subsubtitle->margin;
    
$this->subsubtitle->Center(0, $this->img->width, $y);
    
$this->subsubtitle->Stroke($this->img);

    
// ... and fancy title
    
$this->tabtitle->Stroke($this->img);

    }

    function 
StrokeTexts() {
    
// Stroke any user added text objects
    
if( $this->texts != null ) {
        for(
$i=0$i<count($this->texts); ++$i) {
        
$this->texts[$i]->Stroke($this->img);
        }
    }
    }

    function 
DisplayClientSideaImageMapAreas() {
    
// Debug stuff - display the outline of the image map areas
    
foreach ($this->plots as $p) {
        
$csim.= $p->GetCSIMareas();
    }
    
$csim .= $this->legend->GetCSIMareas();
    if (
preg_match_all("/area shape=\"(\w+)\" coords=\"([0-9\,  ]+)\"/",  $csim,  $coords)) {
        
$this->img->SetColor($this->csimcolor);
        for (
$i=0$i<count($coords[0]); $i++) {
        if (
$coords[1][$i]=="poly") {
            
preg_match_all('/\s*([0-9]+)\s*, \s*([0-9]+)\s*, */', $coords[2][$i], $pts);
            
$this->img->SetStartPoint($pts[1][count($pts[0])-1], $pts[2][count($pts[0])-1]);
            for (
$j=0$j<count($pts[0]); $j++) {
            
$this->img->LineTo($pts[1][$j], $pts[2][$j]);
            }
        } else if (
$coords[1][$i]=="rect") {
            
$pts preg_split('/, /',  $coords[2][$i]);
            
$this->img->SetStartPoint($pts[0], $pts[1]);
            
$this->img->LineTo($pts[2], $pts[1]);
            
$this->img->LineTo($pts[2], $pts[3]);
            
$this->img->LineTo($pts[0], $pts[3]);
            
$this->img->LineTo($pts[0], $pts[1]);                    
        }
        }
    }
    }

    function 
AdjustSaturationBrightnessContrast() {
    
// Adjust the brightness and contrast of the image
    
if( $this->image_contr || $this->image_bright )
        
$this->img->AdjBrightContrast($this->image_bright, $this->image_contr);
    if( 
$this->image_sat )                                             
        
$this->img->AdjSat($this->image_sat);
    }

    
// Text scale offset in world coordinates
    
function SetTextScaleOff($aOff) {
    
$this->text_scale_off $aOff;
    
$this->xscale->text_scale_off $aOff;
    }
    
    
// Get min and max values for all included plots
    
function GetPlotsYMinMax(&$aPlots) {
    list(
$xmax, $max) = $aPlots[0]->Max();
    list(
$xmin, $min) = $aPlots[0]->Min();
    for(
$i=0$i<count($aPlots); ++$i ) {
        list(
$xmax, $ymax)=$aPlots[$i]->Max();
        list(
$xmin, $ymin)=$aPlots[$i]->Min();
        if (!
is_string($ymax) || $ymax != ""$max=max($max, $ymax);
        if (!
is_string($ymin) || $ymin != ""$min=min($min, $ymin);
    }
    if( 
$min == "" $min 0;
    if( 
$max == "" $max 0;
    if( 
$min == && $max == ) {
        
// Special case if all values are 0
        
$min=0;$max=1;            
    }
    return array(
$min, $max);
    }

// Class


//===================================================
// CLASS TTF
// Description: Handle TTF font names
//===================================================
class TTF {
    var 
$font_files, $style_names;
//---------------
// CONSTRUCTOR
    
function TTF() {
    
$this->style_names=array(FS_NORMAL=>'normal', FS_BOLD=>'bold', FS_ITALIC=>'italic', FS_BOLDITALIC=>'bolditalic');
    
// File names for available fonts
    
$this->font_files=array(
        
FF_COURIER => array(FS_NORMAL=>'cour',  FS_BOLD=>'courbd',  FS_ITALIC=>'couri',  FS_BOLDITALIC=>'courbi' ),
        
FF_GEORGIA => array(FS_NORMAL=>'georgia',  FS_BOLD=>'georgiab',  FS_ITALIC=>'georgiai',  FS_BOLDITALIC=>'' ),
        
FF_TREBUCHE =>array(FS_NORMAL=>'trebuc',  FS_BOLD=>'trebucbd',    FS_ITALIC=>'trebucit',  FS_BOLDITALIC=>'trebucbi' ),
        
FF_VERDANA => array(FS_NORMAL=>'verdana',  FS_BOLD=>'verdanab',   FS_ITALIC=>'verdanai',  FS_BOLDITALIC=>'' ),
        
FF_TIMES =>   array(FS_NORMAL=>'times',    FS_BOLD=>'timesbd',    FS_ITALIC=>'timesi',    FS_BOLDITALIC=>'timesbi' ),
        
FF_COMIC =>   array(FS_NORMAL=>'comic',    FS_BOLD=>'comicbd',    FS_ITALIC=>'',          FS_BOLDITALIC=>'' ),
        
FF_ARIAL =>   array(FS_NORMAL=>'arial',    FS_BOLD=>'arialbd',    FS_ITALIC=>'ariali',    FS_BOLDITALIC=>'arialbi' ) );
    }

//---------------
// PUBLIC METHODS    
    // Create the TTF file from the font specification
    
function File($family, $style=FS_NORMAL) {
    
    if( 
$family == FF_HANDWRT || $family==FF_BOOK )
        
JpGraphError::Raise('Font families FF_HANDWRT and FF_BOOK are no longer available due to copyright problem with these fonts. Fonts can no longer be distributed with JpGraph. Please download fonts from http://corefonts.sourceforge.net/');

    
$fam = @$this->font_files[$family];
    if( !
$fam JpGraphError::Raise("Specified TTF font family (id=$family) is unknown or does not exist. ".
                    
"Please note that TTF fonts are not distributed with JpGraph for copyright reasons."
                    
" You can find the MS TTF WEB-fonts (arial,  courier etc) for download at ".
                    
" http://corefonts.sourceforge.net/");
    
$f = @$fam[$style];

    if( 
$f==='' )
        
JpGraphError::Raise('Style "'.$this->style_names[$style].'" is not available for font family '.$this->font_files[$family][FS_NORMAL].'.');
    if( !
$f )
        
JpGraphError::Raise("Unknown font style specification [$fam].");
    
$f TTF_DIR.$f.'.ttf';
    if( 
file_exists($f) === false || is_readable($f) === false ) {
        
JpGraphError::Raise("Font file \"$f\" is not readable or does not exist.");
    }
    return 
$f;
    }
// Class

//===================================================
// CLASS LineProperty
// Description: Holds properties for a line
//===================================================
class LineProperty {
    var 
$iWeight=1,  $iColor="black", $iStyle="solid";
    var 
$iShow=true;
    
//---------------
// PUBLIC METHODS    
    
function SetColor($aColor) {
    
$this->iColor $aColor;
    }
    
    function 
SetWeight($aWeight) {
    
$this->iWeight $aWeight;
    }
    
    function 
SetStyle($aStyle) {
    
$this->iStyle $aStyle;
    }
        
    function 
Show($aShow=true) {
    
$this->iShow=$aShow;
    }
    
    function 
Stroke($aImg, $aX1, $aY1, $aX2, $aY2) {
    if( 
$this->iShow ) {
        
$aImg->SetColor($this->iColor);
        
$aImg->SetLineWeight($this->iWeight);
        
$aImg->SetLineStyle($this->iStyle);            
        
$aImg->StyleLine($aX1, $aY1, $aX2, $aY2);
    }
    }
}

//===================================================
// CLASS SuperScriptText
// Description: Format a superscript text
//===================================================
class SuperScriptText extends Text {
    var 
$iSuper="";
    var 
$sfont_family="", $sfont_style="", $sfont_size=8;
    var 
$iSuperMargin=2, $iVertOverlap=4, $iSuperScale=0.65;
    var 
$iSDir=0;
    var 
$iSimple=false;

    function 
SuperScriptText($aTxt="", $aSuper="", $aXAbsPos=0, $aYAbsPos=0) {
    
parent::Text($aTxt, $aXAbsPos, $aYAbsPos);
    
$this->iSuper $aSuper;
    }

    function 
FromReal($aVal, $aPrecision=2) {
    
// Convert a floating point number to scientific notation
    
$neg=1.0;
    if( 
$aVal ) {
        
$neg = -1.0;
        
$aVal = -$aVal;
    }
        
    
$l floor(log10($aVal));
    
$a sprintf("%0.".$aPrecision."f", round($aVal pow(10, $l), $aPrecision));
    
$a *= $neg;
    if( 
$this->iSimple && ($a == || $a==-1) ) $a '';
    
    if( 
$a != '' )
        
$this->$a.' * 10';
    else {
        if( 
$neg == )
        
$this->'10';
        else
        
$this->'-10';
    }
    
$this->iSuper $l;
    }

    function 
Set($aTxt, $aSuper="") {
    
$this->$aTxt;
    
$this->iSuper $aSuper;
    }

    function 
SetSuperFont($aFontFam, $aFontStyle=FS_NORMAL, $aFontSize=8) {
    
$this->sfont_family $aFontFam;
    
$this->sfont_style $aFontStyle;
    
$this->sfont_size $aFontSize;
    }

    
// Total width of text
    
function GetWidth(&$aImg) {
    
$aImg->SetFont($this->font_family, $this->font_style, $this->font_size);
    
$w $aImg->GetTextWidth($this->t);
    
$aImg->SetFont($this->sfont_family, $this->sfont_style, $this->sfont_size);
    
$w += $aImg->GetTextWidth($this->iSuper);
    
$w += $this->iSuperMargin;
    return 
$w;
    }
    
    
// Hight of font (approximate the height of the text)
    
function GetFontHeight(&$aImg) {
    
$aImg->SetFont($this->font_family, $this->font_style, $this->font_size);    
    
$h $aImg->GetFontHeight();
    
$aImg->SetFont($this->sfont_family, $this->sfont_style, $this->sfont_size);
    
$h += $aImg->GetFontHeight();
    return 
$h;
    }

    
// Hight of text
    
function GetTextHeight(&$aImg) {
    
$aImg->SetFont($this->font_family, $this->font_style, $this->font_size);
    
$h $aImg->GetTextHeight($this->t);
    
$aImg->SetFont($this->sfont_family, $this->sfont_style, $this->sfont_size);
    
$h += $aImg->GetTextHeight($this->iSuper);
    return 
$h;
    }

    function 
Stroke($aImg, $ax=-1, $ay=-1) {
    
        
// To position the super script correctly we need different
    // cases to handle the alignmewnt specified since that will
    // determine how we can interpret the x, y coordinates
    
    
$w parent::GetWidth($aImg);
    
$h parent::GetTextHeight($aImg);
    switch( 
$this->valign ) {
        case 
'top':
        
$sy $this->y;
        break;
        case 
'center':
        
$sy $this->$h/2;
        break;
        case 
'bottom':
        
$sy $this->$h;
        break;
        default:
        
JpGraphError::Raise('PANIC: Internal error in SuperScript::Stroke(). Unknown vertical alignment for text');
        exit();
    }

    switch( 
$this->halign ) {
        case 
'left':
        
$sx $this->$w;
        break;
        case 
'center':
        
$sx $this->$w/2;
        break;
        case 
'right':
        
$sx $this->x;
        break;
        default:
        
JpGraphError::Raise('PANIC: Internal error in SuperScript::Stroke(). Unknown horizontal alignment for text');
        exit();
    }

    
$sx += $this->iSuperMargin;
    
$sy += $this->iVertOverlap;

    
// Should we automatically determine the font or
    // has the user specified it explicetly?
    
if( $this->sfont_family == "" ) {
        if( 
$this->font_family <= FF_FONT2 ) {
        if( 
$this->font_family == FF_FONT0 ) {
            
$sff FF_FONT0;
        }
        elseif( 
$this->font_family == FF_FONT1 ) {
            if( 
$this->font_style == FS_NORMAL )
            
$sff FF_FONT0;
            else
            
$sff FF_FONT1;
        }
        else {
            
$sff FF_FONT1;
        }
        
$sfs $this->font_style;
        
$sfz $this->font_size;
        }
        else {
        
// TTF fonts
        
$sff $this->font_family;
        
$sfs $this->font_style;
        
$sfz floor($this->font_size*$this->iSuperScale);        
        if( 
$sfz $sfz 8;
        }        
        
$this->sfont_family $sff;
        
$this->sfont_style $sfs;
        
$this->sfont_size $sfz;        
    } 
    else {
        
$sff $this->sfont_family;
        
$sfs $this->sfont_style;
        
$sfz $this->sfont_size;        
    }

    
parent::Stroke($aImg, $ax, $ay);


    
// For the builtin fonts we need to reduce the margins
    // since the bounding bx reported for the builtin fonts
    // are much larger than for the TTF fonts.
    
if( $sff <= FF_FONT2 ) {
        
$sx -= 2;
        
$sy += 3;
    }

    
$aImg->SetTextAlign('left', 'bottom');    
    
$aImg->SetFont($sff, $sfs, $sfz);
    
$aImg->PushColor($this->color);    
    
$aImg->StrokeText($sx, $sy, $this->iSuper, $this->iSDir, 'left');
    
$aImg->PopColor();    
    }
}



//===================================================
// CLASS Text
// Description: Arbitrary text object that can be added to the graph
//===================================================
class Text {
    var 
$t, $x=0, $y=0, $halign="left", $valign="top", $color=array(0, 0, 0);
    var 
$font_family=FF_FONT1, $font_style=FS_NORMAL, $font_size=12;
    var 
$hide=false,  $dir=0;
    var 
$boxed=false;    // Should the text be boxed
    
var $paragraph_align="left";
    var 
$margin;
    var 
$icornerradius=0, $ishadowwidth=3;

//---------------
// CONSTRUCTOR

    // Create new text at absolute pixel coordinates
    
function Text($aTxt="", $aXAbsPos=0, $aYAbsPos=0) {
    
$this->$aTxt;
    
$this->$aXAbsPos;
    
$this->$aYAbsPos;
    
$this->margin 0;
    }
//---------------
// PUBLIC METHODS    
    // Set the string in the text object
    
function Set($aTxt) {
    
$this->$aTxt;
    }
    
    
// Alias for Pos()
    
function SetPos($aXAbsPos=0, $aYAbsPos=0, $aHAlign="left", $aVAlign="top") {
    
$this->Pos($aXAbsPos, $aYAbsPos, $aHAlign, $aVAlign);
    }
    
    
// Specify the position and alignment for the text object
    
function Pos($aXAbsPos=0, $aYAbsPos=0, $aHAlign="left", $aVAlign="top") {
    
$this->$aXAbsPos;
    
$this->$aYAbsPos;
    
$this->halign $aHAlign;
    
$this->valign $aVAlign;
    }
    
    
// Specify alignment for the text
    
function Align($aHAlign, $aVAlign="top", $aParagraphAlign="") {
    
$this->halign $aHAlign;
    
$this->valign $aVAlign;
    if( 
$aParagraphAlign != "" )
        
$this->paragraph_align $aParagraphAlign;
    }        

    
// Specifies the alignment for a multi line text
    
function ParagraphAlign($aAlign) {
    
$this->paragraph_align $aAlign;
    }

    function 
SetShadow($aShadowColor='gray', $aShadowWidth=3) {
    
$this->ishadowwidth=$aShadowWidth;
    
$this->shadow=$aShadowColor;
    
$this->boxed=true;
    }
    
    
// Specify that the text should be boxed. fcolor=frame color,  bcolor=border color,
    // $shadow=drop shadow should be added around the text.
    
function SetBox($aFrameColor=array(255, 255, 255), $aBorderColor=array(0, 0, 0), $aShadowColor=false, $aCornerRadius=4, $aShadowWidth=3) {
    if( 
$aFrameColor==false )
        
$this->boxed=false;
    else
        
$this->boxed=true;
    
$this->fcolor=$aFrameColor;
    
$this->bcolor=$aBorderColor;
    
// For backwards compatibility when shadow was just true or false
    
if( $aShadowColor === true )
        
$aShadowColor 'gray';
    
$this->shadow=$aShadowColor;
    
$this->icornerradius=$aCornerRadius;
    
$this->ishadowwidth=$aShadowWidth;
    }
    
    
// Hide the text
    
function Hide($aHide=true) {
    
$this->hide=$aHide;
    }
    
    
// This looks ugly since it's not a very orthogonal design 
    // but I added this "inverse" of Hide() to harmonize
    // with some classes which I designed more recently (especially) 
    // jpgraph_gantt
    
function Show($aShow=true) {
    
$this->hide=!$aShow;
    }
    
    
// Specify font
    
function SetFont($aFamily, $aStyle=FS_NORMAL, $aSize=10) {
    
$this->font_family=$aFamily;
    
$this->font_style=$aStyle;
    
$this->font_size=$aSize;
    }
            
    
// Center the text between $left and $right coordinates
    
function Center($aLeft, $aRight, $aYAbsPos=false) {
    
$this->$aLeft + ($aRight-$aLeft    )/2;
    
$this->halign "center";
    if( 
is_numeric($aYAbsPos) )
        
$this->$aYAbsPos;        
    }
    
    
// Set text color
    
function SetColor($aColor) {
    
$this->color $aColor;
    }
    
    function 
SetAngle($aAngle) {
    
$this->SetOrientation($aAngle);
    }
    
    
// Orientation of text. Note only TTF fonts can have an arbitrary angle
    
function SetOrientation($aDirection=0) {
    if( 
is_numeric($aDirection) )
        
$this->dir=$aDirection;    
    elseif( 
$aDirection=="h" )
        
$this->dir 0;
    elseif( 
$aDirection=="v" )
        
$this->dir 90;
    else 
JpGraphError::Raise(" Invalid direction specified for text.");
    }
    
    
// Total width of text
    
function GetWidth($aImg) {
    
$aImg->SetFont($this->font_family, $this->font_style, $this->font_size);
    
$w $aImg->GetTextWidth($this->t);
    return 
$w;    
    }
    
    
// Hight of font
    
function GetFontHeight($aImg) {
    
$aImg->SetFont($this->font_family, $this->font_style, $this->font_size);
    
$h $aImg->GetFontHeight();
    return 
$h;

    }

    function 
GetTextHeight($aImg) {
    
$aImg->SetFont($this->font_family, $this->font_style, $this->font_size);    
    
$h $aImg->GetTextHeight($this->t);
    return 
$h;
    }

    
// Set the margin which will be interpretaed differently depending
    // on the context.
    
function SetMargin($aMarg) {
    
$this->margin $aMarg;
    }
    
    
// Display text in image
    
function Stroke($aImg, $x=null, $y=null) {

    if( !empty(
$x) ) $this->$x;
    if( !empty(
$y) ) $this->$y;

    
// If position been given as a fraction of the image size
    // calculate the absolute position
    
if( $this->&& $this->$this->*= $aImg->width;
    if( 
$this->&& $this->$this->*= $aImg->height;

    
$aImg->PushColor($this->color);    
    
$aImg->SetFont($this->font_family, $this->font_style, $this->font_size);
    
$aImg->SetTextAlign($this->halign, $this->valign);
    if( 
$this->boxed ) {
        if( 
$this->fcolor=="nofill" 
        
$this->fcolor=false;        
        
$aImg->StrokeBoxedText($this->x, $this->y, $this->t,
                   
$this->dir, $this->fcolor, $this->bcolor, $this->shadow,
                   
$this->paragraph_align, 6, 2, $this->icornerradius,
                   
$this->ishadowwidth);
    }
    else {
        
$aImg->StrokeText($this->x, $this->y, $this->t, $this->dir,
                  
$this->paragraph_align);
    }
    
$aImg->PopColor($this->color);    
    }
// Class

class GraphTabTitle extends Text{
    var 
$corner ,  $posx 7,  $posy 4;
    var 
$color='darkred', $fillcolor='lightyellow', $bordercolor='black';
    var 
$align 'left';
    function 
GraphTabTitle() {
    
$this->'';
    
$this->font_style FS_BOLD;
    
$this->hide true;
    }

    function 
SetColor($aTxtColor, $aFillColor='lightyellow', $aBorderColor='black') {
    
$this->color $aTxtColor;
    
$this->fillcolor $aFillColor;
    
$this->bordercolor $aBorderColor;
    }

    function 
SetTabAlign($aAlign) {
    
$this->align $aAlign;
    }
    
    function 
Set($t) {
    
$this->$t;
    
$this->hide false;
    }

    function 
SetCorner($aD) {
    
$this->corner $aD ;
    }

    function 
Stroke($aImg) {
    if( 
$this->hide 
        return;
    
$this->boxed false;
    
$w $this->GetWidth($aImg) + 2*$this->posx;
    
$h $this->GetTextHeight($aImg) + 2*$this->posy;

    
$x $aImg->left_margin;
    
$y $aImg->top_margin;

    if( 
$this->align == 'left' ) {
        
$p = array($x,                 $y,
               
$x,                 $y-$h+$this->corner,
               
$x $this->corner, $y-$h,
               
$x $w $this->corner,  $y-$h,
               
$x $w,  $y-$h+$this->corner,
               
$x $w,  $y);
    }
    elseif( 
$this->align == 'center' ) {
        
$x += round($aImg->plotwidth/2) - round($w/2);
        
$p = array($x,  $y,
               
$x,  $y-$h+$this->corner,
               
$x $this->corner,  $y-$h,
               
$x $w $this->corner,  $y-$h,
               
$x $w,  $y-$h+$this->corner,
               
$x $w,  $y);
    }
    else {
        
$x += $aImg->plotwidth -$w;
        
$p = array($x,  $y,
               
$x,  $y-$h+$this->corner,
               
$x $this->corner, $y-$h,
               
$x $w $this->corner,  $y-$h,
               
$x $w,  $y-$h+$this->corner,
               
$x $w,  $y);
    }

    
$aImg->SetTextAlign('left', 'bottom');
    
$x += $this->posx;
    
$y -= $this->posy;

    
$aImg->SetColor($this->fillcolor);
    
$aImg->FilledPolygon($p);

    
$aImg->SetColor($this->bordercolor);
    
$aImg->Polygon($p, true);
    
    
$aImg->SetColor($this->color);
    
$aImg->SetFont($this->font_family, $this->font_style, $this->font_size);
    
$aImg->StrokeText($x, $y, $this->t, 0, 'center');
    }

}


//===================================================
// CLASS Grid
// Description: responsible for drawing grid lines in graph
//===================================================
class Grid {
    var 
$img;
    var 
$scale;
    var 
$grid_color='#DDDDDD';
    var 
$type="solid";
    var 
$show=false,  $showMinor=false, $weight=1;
    var 
$fill=false, $fillcolor=array('#EFEFEF', '#BBCCFF');
//---------------
// CONSTRUCTOR
    
function Grid(&$aAxis) {
    
$this->scale = &$aAxis->scale;
    
$this->img = &$aAxis->img;
    }
//---------------
// PUBLIC METHODS
    
function SetColor($aColor) {
    
$this->grid_color=$aColor;
    }
    
    function 
SetWeight($aWeight) {
    
$this->weight=$aWeight;
    }
    
    
// Specify if grid should be dashed,  dotted or solid
    
function SetLineStyle($aType) {
    
$this->type $aType;
    }
    
    
// Decide if both major and minor grid should be displayed
    
function Show($aShowMajor=true, $aShowMinor=false) {
    
$this->show=$aShowMajor;
    
$this->showMinor=$aShowMinor;
    }
    
    function 
SetFill($aFlg=true, $aColor1='lightgray', $aColor2='lightblue') {
    
$this->fill $aFlg;
    
$this->fillcolor = array( $aColor1,  $aColor2 );
    }
    
    
// Display the grid
    
function Stroke() {
    if( 
$this->showMinor 
        
$this->DoStroke($this->scale->ticks->ticks_pos);
    else
        
$this->DoStroke($this->scale->ticks->maj_ticks_pos);
    }
    
//--------------
// Private methods    
    // Draw the grid
    
function DoStroke(&$aTicksPos) {
    if( !
$this->show )
        return;    
    
$nbrgrids count($aTicksPos);    

    if( 
$this->scale->type=="y" ) {
        
$xl=$this->img->left_margin;
        
$xr=$this->img->width-$this->img->right_margin;
        
        if( 
$this->fill ) {
        
// Draw filled areas
        
$y2 $aTicksPos[0];
        
$i=1;
        while( 
$i $nbrgrids ) {
            
$y1 $y2;
            
$y2 $aTicksPos[$i++];
            
$this->img->SetColor($this->fillcolor[$i 1]);
            
$this->img->FilledRectangle($xl, $y1, $xr, $y2);
        }
        }

        
$this->img->SetColor($this->grid_color);
        
$this->img->SetLineWeight($this->weight);

        
// Draw grid lines
        
for($i=0$i<$nbrgrids; ++$i) {
        
$y=$aTicksPos[$i];
        if( 
$this->type == "solid" )
            
$this->img->Line($xl, $y, $xr, $y);
        elseif( 
$this->type == "dotted" )
            
$this->img->DashedLine($xl, $y, $xr, $y, 1, 6);
        elseif( 
$this->type == "dashed" )
            
$this->img->DashedLine($xl, $y, $xr, $y, 2, 4);
        elseif( 
$this->type == "longdashed" )
            
$this->img->DashedLine($xl, $y, $xr, $y, 8, 6);
        }
    }
    elseif( 
$this->scale->type=="x" ) {    
        
$yu=$this->img->top_margin;
        
$yl=$this->img->height-$this->img->bottom_margin;
        
$limit=$this->img->width-$this->img->right_margin;

        if( 
$this->fill ) {
        
// Draw filled areas
        
$x2 $aTicksPos[0];
        
$i=1;
        while( 
$i $nbrgrids ) {
            
$x1 $x2;
            
$x2 min($aTicksPos[$i++], $limit) ;
            
$this->img->SetColor($this->fillcolor[$i 1]);
            
$this->img->FilledRectangle($x1, $yu, $x2, $yl);
        }
        }

        
$this->img->SetColor($this->grid_color);
        
$this->img->SetLineWeight($this->weight);

        
// We must also test for limit since we might have
        // an offset and the number of ticks is calculated with
        // assumption offset==0 so we might end up drawing one
        // to many gridlines
        
$i=0;
        
$x=$aTicksPos[$i];        
        while( 
$i<count($aTicksPos) && ($x=$aTicksPos[$i]) <= $limit ) {
        if( 
$this->type == "solid" )                
            
$this->img->Line($x, $yl, $x, $yu);
        elseif( 
$this->type == "dotted" )
            
$this->img->DashedLine($x, $yl, $x, $yu, 1, 6);
        elseif( 
$this->type == "dashed" )
            
$this->img->DashedLine($x, $yl, $x, $yu, 2, 4);
        elseif( 
$this->type == "longdashed" )
            
$this->img->DashedLine($x, $yl, $x, $yu, 8, 6);    
        ++
$i;  
        }
    }    
    else {
        
JpGraphError::Raise('Internal error: Unknown grid axis ['.$this->scale->type.']');
    }
    return 
true;
    }
// Class

//===================================================
// CLASS Axis
// Description: Defines X and Y axis. Notes that at the
// moment the code is not really good since the axis on
// several occasion must know wheter it's an X or Y axis.
// This was a design decision to make the code easier to
// follow. 
//===================================================
class Axis {
    var 
$pos false;
    var 
$weight=1;
    var 
$color=array(0, 0, 0), $label_color=array(0, 0, 0);
    var 
$img=null, $scale=null
    var 
$hide=false;
    var 
$ticks_label=false,  $ticks_label_colors=null;
    var 
$show_first_label=true, $show_last_label=true;
    var 
$label_step=1// Used by a text axis to specify what multiple of major steps
    // should be labeled.
    
var $tick_step=1;
    var 
$labelPos=0;   // Which side of the axis should the labels be?
    
var $title=null, $title_adjust, $title_margin, $title_side=SIDE_LEFT;
    var 
$font_family=FF_FONT1, $font_style=FS_NORMAL, $font_size=12, $label_angle=0;
    var 
$tick_label_margin=5;
    var 
$label_halign '', $label_valign '',  $label_para_align='left';
    var 
$hide_line=false;
    
//var $hide_zero_label=false;

//---------------
// CONSTRUCTOR
    
function Axis(&$img, &$aScale, $color=array(0, 0, 0)) {
    
$this->img = &$img;
    
$this->scale = &$aScale;
    
$this->color $color;
    
$this->title=new Text("");
        
    if( 
$aScale->type=="y" ) {
        
$this->title_margin 25;
        
$this->title_adjust="middle";
        
$this->title->SetOrientation(90);
        
$this->tick_label_margin=7;
        
$this->labelPos=SIDE_LEFT;
        
//$this->SetLabelFormat('%.1f');
    
}
    else {
        
$this->title_margin 5;
        
$this->title_adjust="high";
        
$this->title->SetOrientation(0);            
        
$this->tick_label_margin=3;
        
$this->labelPos=SIDE_DOWN;
        
//$this->SetLabelFormat('%.0f');
    
}
    }
//---------------
// PUBLIC METHODS    
    
    
function SetLabelFormat($aFormStr) {
    
$this->scale->ticks->SetLabelFormat($aFormStr);
    }
    
    function 
SetLabelFormatString($aFormStr) {
    
$this->scale->ticks->SetLabelFormat($aFormStr);
    }
    
    function 
SetLabelFormatCallback($aFuncName) {
    
$this->scale->ticks->SetFormatCallback($aFuncName);
    }

    function 
SetLabelAlign($aHAlign, $aVAlign="top", $aParagraphAlign='left') {
    
$this->label_halign $aHAlign;
    
$this->label_valign $aVAlign;
    
$this->label_para_align $aParagraphAlign;
    }        

    
// Don't display the first label
    
function HideFirstTickLabel($aShow=false) {
    
$this->show_first_label=$aShow;
    }

    function 
HideLastTickLabel($aShow=false) {
    
$this->show_last_label=$aShow;
    }

    function 
HideTicks($aHideMinor=true, $aHideMajor=true) {
    
$this->scale->ticks->SupressMinorTickMarks($aHideMinor);
    
$this->scale->ticks->SupressTickMarks($aHideMajor);
    }

    
// Hide zero label
    
function HideZeroLabel($aFlag=true) {
    
$this->scale->ticks->SupressZeroLabel();
    
//$this->hide_zero_label = $aFlag;
    
}
    
    function 
HideFirstLastLabel() {
    
// The two first calls to ticks method will supress 
    // automatically generated scale values. However,  that
    // will not affect manually specified value,  e.g text-scales.
    // therefor we also make a kludge here to supress manually
    // specified scale labels.
    
$this->scale->ticks->SupressLast();
    
$this->scale->ticks->SupressFirst();
    
$this->show_first_label    false;
    
$this->show_last_label false;
    }
    
    
// Hide the axis
    
function Hide($aHide=true) {
    
$this->hide=$aHide;
    }

    
// Hide the actual axis-line,  but still print the labels
    
function HideLine($aHide=true) {
    
$this->hide_line $aHide;
    }

    
// Weight of axis
    
function SetWeight($aWeight) {
    
$this->weight $aWeight;
    }

    
// Axis color
    
function SetColor($aColor, $aLabelColor=false) {
    
$this->color $aColor;
    if( !
$aLabelColor $this->label_color $aColor;
    else 
$this->label_color $aLabelColor;
    }
    
    
// Title on axis
    
function SetTitle($aTitle, $aAdjustAlign="high") {
    
$this->title->Set($aTitle);
    
$this->title_adjust=$aAdjustAlign;
    }
    
    
// Specify distance from the axis
    
function SetTitleMargin($aMargin) {
    
$this->title_margin=$aMargin;
    }
    
    
// Which side of the axis should the axis title be?
    
function SetTitleSide($aSideOfAxis) {
    
$this->title_side $aSideOfAxis;
    }

    
// Utility function to set the direction for tick marks
    
function SetTickDirection($aDir) {
        
// Will be deprecated from 1.7        
        
if( ERR_DEPRECATED )
        
JpGraphError::Raise('Axis::SetTickDirection() is deprecated. Use Axis::SetTickSide() instead');
    
$this->scale->ticks->SetSide($aDir);
    }
    
    function 
SetTickSide($aDir) {
    
$this->scale->ticks->SetSide($aDir);
    }
    
    
// Specify text labels for the ticks. One label for each data point
    
function SetTickLabels($aLabelArray, $aLabelColorArray=null) {
    
$this->ticks_label $aLabelArray;
    
$this->ticks_label_colors $aLabelColorArray;
    }
    
    
// How far from the axis should the labels be drawn
    
function SetTickLabelMargin($aMargin) {
    if( 
ERR_DEPRECATED )        
        
JpGraphError::Raise('SetTickLabelMargin() is deprecated. Use Axis::SetLabelMargin() instead.');
          
$this->tick_label_margin=$aMargin;
    }

    function 
SetLabelMargin($aMargin) {
    
$this->tick_label_margin=$aMargin;
    }
    
    
// Specify that every $step of the ticks should be displayed starting
    // at $start
    // DEPRECATED FUNCTION: USE SetTextTickInterval() INSTEAD
    
function SetTextTicks($step, $start=0) {
    
JpGraphError::Raise(" SetTextTicks() is deprecated. Use SetTextTickInterval() instead.");        
    }

    
// Specify that every $step of the ticks should be displayed starting
    // at $start    
    
function SetTextTickInterval($aStep, $aStart=0) {
    
$this->scale->ticks->SetTextLabelStart($aStart);
    
$this->tick_step=$aStep;
    }
     
    
// Specify that every $step tick mark should have a label 
    // should be displayed starting
    
function SetTextLabelInterval($aStep) {
    if( 
$aStep )
        
JpGraphError::Raise(" Text label interval must be specified >= 1.");
    
$this->label_step=$aStep;
    }
    
    
// Which side of the axis should the labels be on?
    
function SetLabelPos($aSidePos) {
        
// This will be deprecated from 1.7
    
if( ERR_DEPRECATED )        
        
JpGraphError::Raise('SetLabelPos() is deprecated. Use Axis::SetLabelSide() instead.');
    
$this->labelPos=$aSidePos;
    }
    
    function 
SetLabelSide($aSidePos) {
    
$this->labelPos=$aSidePos;
    }

    
// Set the font
    
function SetFont($aFamily, $aStyle=FS_NORMAL, $aSize=10) {
    
$this->font_family $aFamily;
    
$this->font_style $aStyle;
    
$this->font_size $aSize;
    }

    
// Position for axis line on the "other" scale
    
function SetPos($aPosOnOtherScale) {
    
$this->pos=$aPosOnOtherScale;
    }
    
    
// Specify the angle for the tick labels
    
function SetLabelAngle($aAngle) {
    
$this->label_angle $aAngle;
    }    
    
    
// Stroke the axis.
    
function Stroke($aOtherAxisScale) {        
    if( 
$this->hide ) return;        
    if( 
is_numeric($this->pos) ) {
        
$pos=$aOtherAxisScale->Translate($this->pos);
    }
    else {    
// Default to minimum of other scale if pos not set        
        
if( ($aOtherAxisScale->GetMinVal() >= && $this->pos==false) || $this->pos=="min" ) {
        
$pos $aOtherAxisScale->scale_abs[0];
        }
        elseif(
$this->pos == "max") {
        
$pos $aOtherAxisScale->scale_abs[1];
        }
        else { 
// If negative set x-axis at 0
        
$this->pos=0;
        
$pos=$aOtherAxisScale->Translate(0);
        }
    }    
    
$this->img->SetLineWeight($this->weight);
    
$this->img->SetColor($this->color);        
    
$this->img->SetFont($this->font_family, $this->font_style, $this->font_size);
    if( 
$this->scale->type == "x" ) {
        if( !
$this->hide_line 
        
$this->img->FilledRectangle($this->img->left_margin, $pos,
                        
$this->img->width-$this->img->right_margin, $pos+$this->weight-1);
        
$y=$pos+$this->img->GetFontHeight()+$this->title_margin+$this->title->margin;
        if( 
$this->title_adjust=="high" )
        
$this->title->Pos($this->img->width-$this->img->right_margin, $y, "right", "top");
        elseif( 
$this->title_adjust=="middle" || $this->title_adjust=="center" 
        
$this->title->Pos(($this->img->width-$this->img->left_margin-$this->img->right_margin)/2+$this->img->left_margin, $y, "center", "top");
        elseif(
$this->title_adjust=="low")
        
$this->title->Pos($this->img->left_margin, $y, "left", "top");
        else {    
        
JpGraphError::Raise('Unknown alignment specified for X-axis title. ('.$this->title_adjust.')');
        }
    }
    elseif( 
$this->scale->type == "y" ) {
        
// Add line weight to the height of the axis since
        // the x-axis could have a width>1 and we want the axis to fit nicely together.
        
if( !$this->hide_line 
        
$this->img->FilledRectangle($pos-$this->weight+1, $this->img->top_margin,
                        
$pos, $this->img->height-$this->img->bottom_margin+$this->weight-1);
        
$x=$pos ;
        if( 
$this->title_side == SIDE_LEFT ) {
        
$x -= $this->title_margin;
        
$x -= $this->title->margin;
        
$halign="right";
        }
        else {
        
$x += $this->title_margin;
        
$x += $this->title->margin;
        
$halign="left";
        }
        
// If the user has manually specified an hor. align
        // then we override the automatic settings with this
        // specifed setting. Since default is 'left' we compare
        // with that. (This means a manually set 'left' align
        // will have no effect.)
        
if( $this->title->halign != 'left' 
        
$halign $this->title->halign;
        if( 
$this->title_adjust=="high" 
        
$this->title->Pos($x, $this->img->top_margin, $halign, "top"); 
        elseif(
$this->title_adjust=="middle" || $this->title_adjust=="center")  
        
$this->title->Pos($x, ($this->img->height-$this->img->top_margin-$this->img->bottom_margin)/2+$this->img->top_margin, $halign, "center");
        elseif(
$this->title_adjust=="low")
        
$this->title->Pos($x, $this->img->height-$this->img->bottom_margin, $halign, "bottom");
        else    
        
JpGraphError::Raise('Unknown alignment specified for Y-axis title. ('.$this->title_adjust.')');
        
    }
    
$this->scale->ticks->Stroke($this->img, $this->scale, $pos);
    
$this->StrokeLabels($pos);
    
$this->title->Stroke($this->img);
    }

//---------------
// PRIVATE METHODS    
    // Draw all the tick labels on major tick marks
    
function StrokeLabels($aPos, $aMinor=false) {

    
$this->img->SetColor($this->label_color);
    
$this->img->SetFont($this->font_family, $this->font_style, $this->font_size);
    
$yoff=$this->img->GetFontHeight()/2;

    
// Only draw labels at major tick marks
    
$nbr count($this->scale->ticks->maj_ticks_label);

    
// We have the option to not-display the very first mark
    // (Usefull when the first label might interfere with another
    // axis.)
    
$i $this->show_first_label ;
    if( !
$this->show_last_label ) --$nbr;
    
// Now run through all labels making sure we don't overshoot the end
    // of the scale.    
    
$ncolor=0;
    if( isset(
$this->ticks_label_colors) )
        
$ncolor=count($this->ticks_label_colors);
    
    while( 
$i<$nbr ) {
        
// $tpos holds the absolute text position for the label
        
$tpos=$this->scale->ticks->maj_ticklabels_pos[$i];

        
// Note. the $limit is only used for the x axis since we
        // might otherwise overshoot if the scale has been centered
        // This is due to us "loosing" the last tick mark if we center.
        
if( $this->scale->type=="x" && $tpos $this->img->width-$this->img->right_margin+) {
            return; 
        }
        
// we only draw every $label_step label
        
if( ($i $this->label_step)==) {

        
// Set specific label color if specified
        
if( $ncolor )
            
$this->img->SetColor($this->ticks_label_colors[$i $ncolor]);
        
        
// If the label has been specified use that and in other case
        // just label the mark with the actual scale value 
        
$m=$this->scale->ticks->GetMajor();
                
        
// ticks_label has an entry for each data point and is the array
        // that holds the labels set by the user. If the user hasn't 
        // specified any values we use whats in the automatically asigned
        // labels in the maj_ticks_label
        
if( isset($this->ticks_label[$i*$m]) )
            
$label=$this->ticks_label[$i*$m];
        else {
            
$label=$this->scale->ticks->maj_ticks_label[$i];
            if( 
$this->scale->textscale ) {
            ++
$label;
            
            }
        }
                    
        
//if( $this->hide_zero_label && $label==0.0 ) {
        //    ++$i;
        //    continue;
        //}                    
                    
        
if( $this->scale->type == "x" ) {
            if( 
$this->labelPos == SIDE_DOWN ) {
            if( 
$this->label_angle==|| $this->label_angle==90 ) {
                if( 
$this->label_halign=='' && $this->label_valign=='')
                
$this->img->SetTextAlign('center', 'top');
                else
                    
$this->img->SetTextAlign($this->label_halign, $this->label_valign);
                
            }
            else {
                if( 
$this->label_halign=='' && $this->label_valign=='')
                
$this->img->SetTextAlign("right", "top");
                else
                
$this->img->SetTextAlign($this->label_halign, $this->label_valign);
            }

            
$this->img->StrokeText($tpos, $aPos+$this->tick_label_margin, $label,
                           
$this->label_angle, $this->label_para_align);
            }
            else {
            if( 
$this->label_angle==|| $this->label_angle==90 ) {
                if( 
$this->label_halign=='' && $this->label_valign=='')
                
$this->img->SetTextAlign("center", "bottom");
                else
                    
$this->img->SetTextAlign($this->label_halign, $this->label_valign);
            }
            else {
                if( 
$this->label_halign=='' && $this->label_valign=='')
                
$this->img->SetTextAlign("right", "bottom");
                else
                    
$this->img->SetTextAlign($this->label_halign, $this->label_valign);
            }
            
$this->img->StrokeText($tpos, $aPos-$this->tick_label_margin, $label,
                           
$this->label_angle, $this->label_para_align);
            }
        }
        else {
            
// scale->type == "y"
            //if( $this->label_angle!=0 ) 
            //JpGraphError::Raise(" Labels at an angle are not supported on Y-axis");
            
if( $this->labelPos == SIDE_LEFT ) { // To the left of y-axis                    
            
if( $this->label_halign=='' && $this->label_valign=='')    
                
$this->img->SetTextAlign("right", "center");
            else
                
$this->img->SetTextAlign($this->label_halign, $this->label_valign);
            
$this->img->StrokeText($aPos-$this->tick_label_margin, $tpos, $label, $this->label_angle, $this->label_para_align);    
            }
            else { 
// To the right of the y-axis
            
if( $this->label_halign=='' && $this->label_valign=='')    
                
$this->img->SetTextAlign("left", "center");
            else
                
$this->img->SetTextAlign($this->label_halign, $this->label_valign);
            
$this->img->StrokeText($aPos+$this->tick_label_margin, $tpos, $label, $this->label_angle, $this->label_para_align);    
            }
        }
        }
        ++
$i;    
    }                                
    }            

// Class

//===================================================
// CLASS Ticks
// Description: Abstract base class for drawing linear and logarithmic
// tick marks on axis
//===================================================
class Ticks {
    var 
$minor_abs_size=3,  $major_abs_size=5;
    var 
$direction=1// Should ticks be in(=1) the plot area or outside (=-1)?
    
var $scale;
    var 
$is_set=false;
    var 
$precision=-1;
    var 
$supress_zerolabel=false, $supress_first=false;
    var 
$supress_last=false, $supress_tickmarks=false, $supress_minor_tickmarks=false;
    var 
$mincolor="", $majcolor="";
    var 
$weight=1;
    var 
$label_formatstr='';   // C-style format string to use for labels
    
var $label_formfunc='';


//---------------
// CONSTRUCTOR
    
function Ticks(&$aScale) {
    
$this->scale=&$aScale;
    }

//---------------
// PUBLIC METHODS    
    // Set format string for automatic labels
    
function SetLabelFormat($aFormatString) {
    
$this->label_formatstr=$aFormatString;
    }
    
    function 
SetFormatCallback($aCallbackFuncName) {
    
$this->label_formfunc $aCallbackFuncName;
    }
    
    
// Don't display the first zero label
    
function SupressZeroLabel($aFlag=true) {
    
$this->supress_zerolabel=$aFlag;
    }
    
    
// Don't display minor tick marks
    
function SupressMinorTickMarks($aHide=true) {
    
$this->supress_minor_tickmarks=$aHide;
    }
    
    
// Don't display major tick marks
    
function SupressTickMarks($aHide=true) {
    
$this->supress_tickmarks=$aHide;
    }
    
    
// Hide the first tick mark
    
function SupressFirst($aHide=true) {
    
$this->supress_first=$aHide;
    }
    
    
// Hide the last tick mark
    
function SupressLast($aHide=true) {
    
$this->supress_last=$aHide;
    }

    
// Size (in pixels) of minor tick marks
    
function GetMinTickAbsSize() {
    return 
$this->minor_abs_size;
    }
    
    
// Size (in pixels) of major tick marks
    
function GetMajTickAbsSize() {
    return 
$this->major_abs_size;        
    }
    
    function 
SetSize($aMajSize, $aMinSize=3) {
    
$this->major_abs_size $aMajSize;        
    
$this->minor_abs_size $aMinSize;        
    }

    
// Have the ticks been specified
    
function IsSpecified() {
    return 
$this->is_set;
    }
    
    
// Set the distance between major and minor tick marks
    
function Set($aMaj, $aMin) {
    
// "Virtual method"
    // Should be implemented by the concrete subclass
    // if any action is wanted.
    
}
    
    
// Specify number of decimals in automatic labels
    // Deprecated from 1.4. Use SetFormatString() instead
    
function SetPrecision($aPrecision) {     
        if( 
ERR_DEPRECATED )
        
JpGraphError::Raise('Ticks::SetPrecision() is deprecated. Use Ticks::SetLabelFormat() (or Ticks::SetFormatCallback()) instead');
    
$this->precision=$aPrecision;
    }

    function 
SetSide($aSide) {
    
$this->direction=$aSide;
    }
    
    
// Which side of the axis should the ticks be on
    
function SetDirection($aSide=SIDE_RIGHT) {
    
$this->direction=$aSide;
    }
    
    
// Set colors for major and minor tick marks
    
function SetMarkColor($aMajorColor, $aMinorColor="") {
    
$this->SetColor($aMajorColor, $aMinorColor);
    }
    
    function 
SetColor($aMajorColor, $aMinorColor="") {
    
$this->majcolor=$aMajorColor;
        
    
// If not specified use same as major
    
if( $aMinorColor=="" 
        
$this->mincolor=$aMajorColor;
    else
        
$this->mincolor=$aMinorColor;
    }
    
    function 
SetWeight($aWeight) {
    
$this->weight=$aWeight;
    }
    
// Class

//===================================================
// CLASS LinearTicks
// Description: Draw linear ticks on axis
//===================================================
class LinearTicks extends Ticks {
    var 
$minor_step=1,  $major_step=2;
    var 
$xlabel_offset=0, $xtick_offset=0;
    var 
$label_offset=0// What offset should the displayed label have
    // i.e should we display 0, 1, 2 or 1, 2, 3, 4 or 2, 3, 4 etc
    
var $text_label_start=0;
//---------------
// CONSTRUCTOR
    
function LinearTicks() {
    
// Empty
    
}

//---------------
// PUBLIC METHODS    
    
    
    // Return major step size in world coordinates
    
function GetMajor() {
    return 
$this->major_step;
    }
    
    
// Return minor step size in world coordinates
    
function GetMinor() {
    return 
$this->minor_step;
    }
    
    
// Set Minor and Major ticks (in world coordinates)
    
function Set($aMajStep, $aMinStep=false) {
    if( 
$aMinStep==false 
        
$aMinStep=$aMajStep;
        
    if( 
$aMajStep <= || $aMinStep <= ) {
        
JpGraphError::Raise(" Minor or major step size is 0. Check that you haven't
                got an accidental SetTextTicks(0) in your code.<p>
                If this is not the case you might have stumbled upon a bug in JpGraph.
                Please report this and if possible include the data that caused the
                problem."
);
    }
        
    
$this->major_step=$aMajStep;
    
$this->minor_step=$aMinStep;
    
$this->is_set true;
    }

    
// Draw linear ticks
    
function Stroke(&$img, &$scale, $pos) {
    
$maj_step_abs $scale->scale_factor*$this->major_step;        
    
$min_step_abs $scale->scale_factor*$this->minor_step;        

    if( 
$min_step_abs==|| $maj_step_abs==
        
JpGraphError::Raise(" A plot has an illegal scale. This could for example be 
            that you are trying to use text autoscaling to draw a line plot with only one point 
            or similair abnormality (a line needs two points!)."
);
    
$limit $scale->scale_abs[1];    
    
$nbrmajticks=floor(1.000001*(($scale->GetMaxVal()-$scale->GetMinVal())/$this->major_step))+1;
    
$first=0;
        
    
// If precision hasn't been specified set it to a sensible value
    
if( $this->precision==-) { 
        
$t log10($this->minor_step);
        if( 
$t )
        
$precision 0;
        else
        
$precision = -floor($t);
    }
    else
        
$precision $this->precision;
            
    
$img->SetLineWeight($this->weight);            
        
    
// Handle ticks on X-axis
    
if( $scale->type == "x" ) {
        
// Draw the major tick marks
            
        
$yu $pos $this->direction*$this->GetMajTickAbsSize();
            
        
// TODO: Add logic to set label_offset for text labels
        
$label = (float)$scale->GetMinVal()+$this->text_label_start+$this->label_offset;    
            
        
$start_abs=$scale->scale_factor*$this->text_label_start;
            
        
$nbrmajticks=ceil(($scale->GetMaxVal()-$scale->GetMinVal()-$this->text_label_start )/$this->major_step)+1;    
        for( 
$i=0$label<=$scale->GetMaxVal()+$this->label_offset; ++$i ) {
        
$x=$scale->scale_abs[0]+$start_abs+$i*$maj_step_abs+$this->xlabel_offset*$min_step_abs;    
        
$this->maj_ticklabels_pos[$i]=ceil($x);                

        
// Apply format
        
if( $this->label_formfunc != "" ) {
            
$f=$this->label_formfunc;
            
$l $f($label);
        }    
        elseif( 
$this->label_formatstr != "" 
            
$l sprintf($this->label_formatstr, $label);
        else {
            
$v round($label, $precision);
            
$l sprintf("%01.".$precision."f", $v);
        }
                    
        if( (
$this->supress_zerolabel && ($l 0)==0) || ($this->supress_first && $i==0) ||
            (
$this->supress_last  && $i==$nbrmajticks-1) ) {
            
$l="";
        }

        
$this->maj_ticks_label[$i]=$l;
        
$label+=$this->major_step;
                
        
// The x-position of the tick marks can be different from the labels.
        // Note that we record the tick position (not the label) so that the grid
        // happen upon tick marks and not labels.
        
$xtick=$scale->scale_abs[0]+$start_abs+$i*$maj_step_abs+$this->xtick_offset*$min_step_abs;
        
$this->maj_ticks_pos[$i]=ceil($xtick);                
        if(!(
$this->xtick_offset && $i==$nbrmajticks-1) && !$this->supress_tickmarks) {
            if( 
$this->majcolor!="" $img->PushColor($this->majcolor);
            
$img->Line($xtick, $pos, $xtick, $yu);
            if( 
$this->majcolor!="" $img->PopColor();
        }
        }
        
// Draw the minor tick marks
            
        
$yu $pos $this->direction*$this->GetMinTickAbsSize();
        
$label $scale->GetMinVal();        
        
$x=$scale->scale_abs[0];
        while( 
$x $limit ) {        
        
$this->ticks_pos[]=$x;
        
$this->ticks_label[]=$label;
        
$label+=$this->minor_step;
         if( !
$this->supress_tickmarks && !$this->supress_minor_tickmarks) {
            if( 
$this->mincolor!="" $img->PushColor($this->mincolor);
            
$img->Line($x, $pos, $x, $yu); 
            if( 
$this->mincolor!="" $img->PopColor();
        }
        
$x += $min_step_abs;
        }
    }
    elseif( 
$scale->type == "y" ) {

        
// Draw the major tick marks
        
$xr $pos $this->direction*$this->GetMajTickAbsSize();
        
$label $scale->GetMinVal();
        
        
$tmpmaj=array();
        
$tmpmin=array();

        for( 
$i=0$i<$nbrmajticks; ++$i) {
        
$y=$scale->scale_abs[0]+$i*$maj_step_abs;                

        
$tmpmaj[]=$y;

    
        
// THe following two lines might seem to be unecessary but they are not!
        // The reason being that for X-axis we separate the position of the labels
        // and the tick marks which we don't do for the Y-axis.
        // We therefore need to make sure both arrays are corcectly filled
        // since Axis::StrokeLabels() uses the label positions and Grid::Stroke() uses
        // the tick positions.
        
$this->maj_ticklabels_pos[$i]=$y;
        
$this->maj_ticks_pos[$i]=$y;
        
        if( 
$this->label_formfunc != "" ) {
            
$f=$this->label_formfunc;
            
$l $f($label);
        }    
        elseif( 
$this->label_formatstr != "" 
            
$l sprintf($this->label_formatstr, $label);
        else
            
$l sprintf("%01.".$precision."f", round($label, $precision));
                                
        if( (
$this->supress_zerolabel && ($l 0)==0) ||  ($this->supress_first && $i==0) ||
            (
$this->supress_last  && $i==$nbrmajticks-1) ) {
            
$l="";
        }
        
        
$this->maj_ticks_label[$i]=$l
        
$label+=$this->major_step;    
        if( !
$this->supress_tickmarks ) {
            if( 
$this->majcolor!="" $img->PushColor($this->majcolor);
            
$img->Line($pos, $y, $xr, $y);    
            if( 
$this->majcolor!="" $img->PopColor();
        }
        }

        
// Draw the minor tick marks
        
$xr $pos $this->direction*$this->GetMinTickAbsSize();
        
$label $scale->GetMinVal();    
        for( 
$i=0, $y=$scale->scale_abs[0]; $y>=$limit; ) {

        
$tmpmin[]=$y;

        
$this->ticks_pos[$i]=$y;
        
$this->ticks_label[$i]=$label;                
        
$label+=$this->minor_step;                
        if( !
$this->supress_tickmarks && !$this->supress_minor_tickmarks)    {
            if( 
$this->mincolor!="" $img->PushColor($this->mincolor);
            
$img->Line($pos, $y, $xr, $y);
            if( 
$this->mincolor!="" $img->PopColor();
        }
        ++
$i;
        
$y=$scale->scale_abs[0]+$i*$min_step_abs;
        }    
    }    
    }
//---------------
// PRIVATE METHODS
    // Spoecify the offset of the displayed tick mark with the tick "space"
    // Legal values for $o is [0, 1] used to adjust where the tick marks and label 
    // should be positioned within the major tick-size
    // $lo specifies the label offset and $to specifies the tick offset
    // this comes in handy for example in bar graphs where we wont no offset for the
    // tick but have the labels displayed halfway under the bars.
    
function SetXLabelOffset($aLabelOff, $aTickOff=-1) {
    
$this->xlabel_offset=$aLabelOff;
    if( 
$aTickOff==-)    // Same as label offset
        
$this->xtick_offset=$aLabelOff;
    else
        
$this->xtick_offset=$aTickOff;
    if( 
$aLabelOff>)
        
$this->SupressLast();    // The last tick wont fit
    
}

    
// Which tick label should we start with?
    
function SetTextLabelStart($aTextLabelOff) {
    
$this->text_label_start=$aTextLabelOff;
    }
    
// Class

//===================================================
// CLASS LinearScale
// Description: Handle linear scaling between screen and world 
//===================================================
class LinearScale {
    var 
$scale=array(0, 0);
    var 
$scale_abs=array(0, 0);
    var 
$scale_factor// Scale factor between world and screen
    
var $world_size;    // Plot area size in world coordinates
    
var $world_abs_size// Plot area size in pixels
    
var $off// Offset between image edge and plot area
    
var $type// is this x or y scale ?
    
var $ticks=null// Store ticks
    
var $autoscale_min=false// Forced minimum value,  auto determine max
    
var $autoscale_max=false// Forced maximum value,  auto determine min
    
var $gracetop=0, $gracebottom=0;
    var 
$intscale=false// Restrict autoscale to integers
    
var $textscale=false// Just a flag to let the Plot class find out if
    // we are a textscale or not. This is a cludge since
    // this ionformatyion is availabale in Graph::axtype but
    // we don't have access to the graph object in the Plots
    // stroke method. So we let graph store the status here
    // when the linear scale is created. A real cludge...
    
var $text_scale_off 0;
    var 
$auto_ticks=false// When using manual scale should the ticks be automatically set?
//---------------
// CONSTRUCTOR
    
function LinearScale($aMin=0, $aMax=0, $aType="y") {
    
assert($aType=="x" || $aType=="y" );
    
assert($aMin<=$aMax);
        
    
$this->type=$aType;
    
$this->scale=array($aMin, $aMax);        
    
$this->world_size=$aMax-$aMin;    
    
$this->ticks = new LinearTicks();
    }

//---------------
// PUBLIC METHODS    
    // Second phase constructor
    
function Init(&$aImg) {
    
$this->InitConstants($aImg);    
    
// We want image to notify us when the margins changes so we 
    // can recalculate the constants.
    // PHP <= 4.04 BUGWARNING: IT IS IMPOSSIBLE TO DO THIS IN THE CONSTRUCTOR
    // SINCE (FOR SOME REASON) IT IS IMPOSSIBLE TO PASS A REFERENCE
    // TO 'this' INSTEAD IT WILL ADD AN ANONYMOUS COPY OF THIS OBJECT WHICH WILL
    // GET ALL THE NOTIFICATIONS. (This took a while to track down...)
        
    // Add us as an observer to class Image
    
$aImg->AddObserver("InitConstants", $this);
    }
    
    
// Check if scale is set or if we should autoscale
    // We should do this is either scale or ticks has not been set
    
function IsSpecified() {
    if( 
$this->GetMinVal()==$this->GetMaxVal() ) {        // Scale not set
        
return false;
    }
    return 
true;
    }
    
    
// Set the minimum data value when the autoscaling is used. 
    // Usefull if you want a fix minimum (like 0) but have an
    // automatic maximum
    
function SetAutoMin($aMin) {
    
$this->autoscale_min=$aMin;
    }

    
// Set the minimum data value when the autoscaling is used. 
    // Usefull if you want a fix minimum (like 0) but have an
    // automatic maximum
    
function SetAutoMax($aMax) {
    
$this->autoscale_max=$aMax;
    }

    
// If the user manually specifies a scale should the ticks
    // still be set automatically?
    
function SetAutoTicks($aFlag=true) {
    
$this->auto_ticks $aFlag;
    }

    
// Specify scale "grace" value (top and bottom)
    
function SetGrace($aGraceTop, $aGraceBottom=0) {
    if( 
$aGraceTop<|| $aGraceBottom 0  )
        
JpGraphError::Raise(" Grace must be larger then 0");
    
$this->gracetop=$aGraceTop;
    
$this->gracebottom=$aGraceBottom;
    }
    
    
// Get the minimum value in the scale
    
function GetMinVal() {
    return 
$this->scale[0];
    }
    
    
// get maximum value for scale
    
function GetMaxVal() {
    return 
$this->scale[1];
    }
        
    
// Specify a new min/max value for sclae    
    
function Update(&$aImg, $aMin, $aMax) {
    
$this->scale=array($aMin, $aMax);        
    
$this->world_size=$aMax-$aMin;        
    
$this->InitConstants($aImg);                    
    }
    
    
// Translate between world and screen
    
function Translate($aCoord) {
    return 
$this->off+($aCoord $this->GetMinVal()) * $this->scale_factor
    }
    
    
// Relative translate (don't include offset) usefull when we just want
    // to know the relative position (in pixels) on the axis
    
function RelTranslate($aCoord) {
    return (
$aCoord $this->GetMinVal()) * $this->scale_factor
    }
    
    
// Restrict autoscaling to only use integers
    
function SetIntScale($aIntScale=true) {
    
$this->intscale=$aIntScale;
    }
    
    
// Calculate an integer autoscale
    
function IntAutoScale(&$img, $min, $max, $maxsteps, $majend=true) {
    
// Make sure limits are integers
    
$min=floor($min);
    
$max=ceil($max);
    if( 
abs($min-$max)==) {
        --
$min; ++$max;
    }
    
$maxsteps floor($maxsteps);
        
    
$gracetop=round(($this->gracetop/100.0)*abs($max-$min));
    
$gracebottom=round(($this->gracebottom/100.0)*abs($max-$min));
    if( 
is_numeric($this->autoscale_min) ) {
        
$min ceil($this->autoscale_min);
        if( 
$min >= $max ) {
        
JpGraphError::Raise('You have specified a min value with SetAutoMin() which is larger than the maximum value used for the scale. This is not possible.');
        die();
        }
    }

    if( 
is_numeric($this->autoscale_max) ) {
        
$max ceil($this->autoscale_max);
        if( 
$min >= $max ) {
        
JpGraphError::Raise('You have specified a max value with SetAutoMax() which is smaller than the miminum value used for the scale. This is not possible.');
        die();
        }
    }

    if( 
abs($min-$max ) == ) {
        ++
$max;
        --
$min;
    }
            
    
$min -= $gracebottom;
    
$max += $gracetop;        

    
// First get tickmarks as multiples of 1,  10,  ...    
    
if( $majend ) {
        list(
$num1steps, $adj1min, $adj1max, $maj1step) = 
        
$this->IntCalcTicks($maxsteps, $min, $max, 1);
    }
    else {
        
$adj1min $min;
        
$adj1max $max;
        list(
$num1steps, $maj1step) = 
        
$this->IntCalcTicksFreeze($maxsteps, $min, $max, 1);
    }

    if( 
abs($min-$max) > ) {
        
// Then get tick marks as 2:s 2,  20,  ...
        
if( $majend ) {
        list(
$num2steps, $adj2min, $adj2max, $maj2step) = 
            
$this->IntCalcTicks($maxsteps, $min, $max, 5);
        }
        else {
        
$adj2min $min;
        
$adj2max $max;
        list(
$num2steps, $maj2step) = 
            
$this->IntCalcTicksFreeze($maxsteps, $min, $max, 5);
        }
    }
    else {
        
$num2steps 10000;    // Dummy high value so we don't choose this
    
}
    
    if( 
abs($min-$max) > ) {    
        
// Then get tickmarks as 5:s 5,  50,  500,  ...
        
if( $majend ) {
        list(
$num5steps, $adj5min, $adj5max, $maj5step) = 
            
$this->IntCalcTicks($maxsteps, $min, $max, 2);
        }
        else {
        
$adj5min $min;
        
$adj5max $max;
        list(
$num5steps, $maj5step) = 
            
$this->IntCalcTicksFreeze($maxsteps, $min, $max, 2);
        }
    }
    else {
        
$num5steps 10000;    // Dummy high value so we don't choose this        
    
}
    
    
// Check to see whichof 1:s,  2:s or 5:s fit better with
    // the requested number of major ticks        
    
$match1=abs($num1steps-$maxsteps);        
    
$match2=abs($num2steps-$maxsteps);
    if( !empty(
$maj5step) && $maj5step )
        
$match5=abs($num5steps-$maxsteps);
    else
        
$match5=10000;     // Dummy high value 
        
    // Compare these three values and see which is the closest match
    // We use a 0.6 weight to gravitate towards multiple of 5:s 
    
if( $match1 $match2 ) {
        if( 
$match1 $match5 )
        
$r=1;            
        else 
        
$r=3;
    }
    else {
        if( 
$match2 $match5 )
        
$r=2;            
        else 
        
$r=3;        
    }    
    
// Minsteps are always the same as maxsteps for integer scale
    
switch( $r ) {
        case 
1:
        
$this->Update($img, $adj1min, $adj1max);
        
$this->ticks->Set($maj1step, $maj1step);
        break;            
        case 
2:
        
$this->Update($img, $adj2min, $adj2max);        
        
$this->ticks->Set($maj2step, $maj2step);
        break;                                    
        case 
3:
        
$this->Update($img, $adj5min, $adj5max);
        
$this->ticks->Set($maj5step, $maj2step);        
        break;            
    }        
    }
    
    
    
// Calculate autoscale. Used if user hasn't given a scale and ticks
    // $maxsteps is the maximum number of major tickmarks allowed.
    
function AutoScale(&$img, $min, $max, $maxsteps, $majend=true) {
    if( 
$this->intscale ) {    
        
$this->IntAutoScale($img, $min, $max, $maxsteps, $majend);
        return;
    }
    if( 
abs($min-$max) < 0.00001 ) {
        
// We need some difference to be able to autoscale
        // make it 5% above and 5% below value
        
if( $min==&& $max==) {        // Special case
        
$min=-1$max=1;
        }
        else {
        
$delta = (abs($max)+abs($min))*0.005;
        
$min -= $delta;
        
$max += $delta;
        }
    }
        
    
$gracetop=($this->gracetop/100.0)*abs($max-$min);
    
$gracebottom=($this->gracebottom/100.0)*abs($max-$min);
    if( 
is_numeric($this->autoscale_min) ) {
        
$min $this->autoscale_min;
        if( 
$min >= $max ) {
        
JpGraphError::Raise('You have specified a min value with SetAutoMin() which is larger than the maximum value used for the scale. This is not possible.');
        die();
        }
        if( 
abs($min-$max ) < 0.00001 )
        
$max *= 1.2;
    }

    if( 
is_numeric($this->autoscale_max) ) {
        
$max $this->autoscale_max;
        if( 
$min >= $max ) {
        
JpGraphError::Raise('You have specified a max value with SetAutoMax() which is smaller than the miminum value used for the scale. This is not possible.');
        die();
        }
        if( 
abs($min-$max ) < 0.00001 )
        
$min *= 0.8;
    }

    
    
$min -= $gracebottom;
    
$max += $gracetop;

    
// First get tickmarks as multiples of 0.1,  1,  10,  ...    
    
if( $majend ) {
        list(
$num1steps, $adj1min, $adj1max, $min1step, $maj1step) = 
        
$this->CalcTicks($maxsteps, $min, $max, 1, 2);
    }
    else {
        
$adj1min=$min;
        
$adj1max=$max;
        list(
$num1steps, $min1step, $maj1step) = 
        
$this->CalcTicksFreeze($maxsteps, $min, $max, 1, 2, false);
    }
        
    
// Then get tick marks as 2:s 0.2,  2,  20,  ...
    
if( $majend ) {
        list(
$num2steps, $adj2min, $adj2max, $min2step, $maj2step) = 
        
$this->CalcTicks($maxsteps, $min, $max, 5, 2);
    }
    else {
        
$adj2min=$min;
        
$adj2max=$max;
        list(
$num2steps, $min2step, $maj2step) = 
        
$this->CalcTicksFreeze($maxsteps, $min, $max, 5, 2, false);
    }
        
    
// Then get tickmarks as 5:s 0.05,  0.5,  5,  50,  ...
    
if( $majend ) {
        list(
$num5steps, $adj5min, $adj5max, $min5step, $maj5step) = 
        
$this->CalcTicks($maxsteps, $min, $max, 2, 5);        
    }
    else {
        
$adj5min=$min;
        
$adj5max=$max;
        list(
$num5steps, $min5step, $maj5step) = 
        
$this->CalcTicksFreeze($maxsteps, $min, $max, 2, 5, false);
    }

    
// Check to see whichof 1:s,  2:s or 5:s fit better with
    // the requested number of major ticks        
    
$match1=abs($num1steps-$maxsteps);        
    
$match2=abs($num2steps-$maxsteps);
    
$match5=abs($num5steps-$maxsteps);
    
// Compare these three values and see which is the closest match
    // We use a 0.8 weight to gravitate towards multiple of 5:s 
    
$r=$this->MatchMin3($match1, $match2, $match5, 0.8);
    switch( 
$r ) {
        case 
1:
        
$this->Update($img, $adj1min, $adj1max);
        
$this->ticks->Set($maj1step, $min1step);
        break;            
        case 
2:
        
$this->Update($img, $adj2min, $adj2max);        
        
$this->ticks->Set($maj2step, $min2step);
        break;                                    
        case 
3:
        
$this->Update($img, $adj5min, $adj5max);
        
$this->ticks->Set($maj5step, $min5step);        
        break;            
    }
    }

//---------------
// PRIVATE METHODS    

    // This method recalculates all constants that are depending on the
    // margins in the image. If the margins in the image are changed
    // this method should be called for every scale that is registred with
    // that image. Should really be installed as an observer of that image.
    
function InitConstants(&$img) {
    if( 
$this->type=="x" ) {
        
$this->world_abs_size=$img->width $img->left_margin $img->right_margin;
        
$this->off=$img->left_margin;
        
$this->scale_factor 0;
        if( 
$this->world_size )
        
$this->scale_factor=$this->world_abs_size/($this->world_size*1.0);
    }
    else { 
// y scale
        
$this->world_abs_size=$img->height $img->top_margin $img->bottom_margin
        
$this->off=$img->top_margin+$this->world_abs_size;            
        
$this->scale_factor 0;            
        if( 
$this->world_size )            
        
$this->scale_factor=-$this->world_abs_size/($this->world_size*1.0);    
    }
    
$size $this->world_size $this->scale_factor;
    
$this->scale_abs=array($this->off, $this->off $size);    
    }
    
    
// Initialize the conversion constants for this scale
    // This tries to pre-calculate as much as possible to speed up the
    // actual conversion (with Translate()) later on
    // $start    =scale start in absolute pixels (for x-scale this is an y-position
    //                 and for an y-scale this is an x-position
    // $len         =absolute length in pixels of scale             
    
function SetConstants($aStart, $aLen) {
    
$this->world_abs_size=$aLen;
    
$this->off=$aStart;
        
    if( 
$this->world_size<=) {
        
JpGraphError::Raise("<b>JpGraph Fatal Error</b>:<br>
         You have unfortunately stumbled upon a bug in JpGraph. <br>
         It seems like the scale range is "
.$this->world_size." [for ".
                
$this->type." scale] <br>
             Please report Bug #01 to jpgraph <at> aditus <dot> nu and include the script
         that gave this error. <br>
         This problem could potentially be caused by trying to use \"illegal\"
         values in the input data arrays (like trying to send in strings or
         only NULL values) which causes the autoscaling to fail."
);
    }
        
    
// scale_factor = number of pixels per world unit
    
$this->scale_factor=$this->world_abs_size/($this->world_size*1.0);
        
    
// scale_abs = start and end points of scale in absolute pixels
    
$this->scale_abs=array($this->off, $this->off+$this->world_size*$this->scale_factor);        
    }
    
    
    
// Calculate number of ticks steps with a specific division
    // $a is the divisor of 10**x to generate the first maj tick intervall
    // $a=1,  $b=2 give major ticks with multiple of 10,  ..., 0.1, 1, 10, ...
    // $a=5,  $b=2 give major ticks with multiple of 2:s ..., 0.2, 2, 20, ...
    // $a=2,  $b=5 give major ticks with multiple of 5:s ..., 0.5, 5, 50, ...
    // We return a vector of
    //     [$numsteps, $adjmin, $adjmax, $minstep, $majstep]
    // If $majend==true then the first and last marks on the axis will be major
    // labeled tick marks otherwise it will be adjusted to the closest min tick mark
    
function CalcTicks($maxsteps, $min, $max, $a, $b, $majend=true) {
    
$diff=$max-$min
    if( 
$diff==)
        
$ld=0;
    else
        
$ld=floor(log10($diff));

    
// Gravitate min towards zero if we are close        
    
if( $min>&& $min pow(10, $ld) ) $min=0;
        
    
//$majstep=pow(10, $ld-1)/$a; 
    
$majstep=pow(10, $ld)/$a
    
$minstep=$majstep/$b;
    
    
$adjmax=ceil($max/$minstep)*$minstep;
    
$adjmin=floor($min/$minstep)*$minstep;    
    
$adjdiff $adjmax-$adjmin;
    
$numsteps=$adjdiff/$majstep
    
    while( 
$numsteps>$maxsteps ) {
        
$majstep=pow(10, $ld)/$a
        
$numsteps=$adjdiff/$majstep;
        ++
$ld;
    }

    
$minstep=$majstep/$b;
    
$adjmin=floor($min/$minstep)*$minstep;    
    
$adjdiff $adjmax-$adjmin;        
    if( 
$majend ) {
        
$adjmin floor($min/$majstep)*$majstep;    
        
$adjdiff $adjmax-$adjmin;        
        
$adjmax ceil($adjdiff/$majstep)*$majstep+$adjmin;
    }
    else
        
$adjmax=ceil($max/$minstep)*$minstep;

    return array(
$numsteps, $adjmin, $adjmax, $minstep, $majstep);
    }

    function 
CalcTicksFreeze($maxsteps, $min, $max, $a, $b) {
    
// Same as CalcTicks but don't adjust min/max values
    
$diff=$max-$min
    if( 
$diff==)
        
$ld=0;
    else
        
$ld=floor(log10($diff));

    
//$majstep=pow(10, $ld-1)/$a; 
    
$majstep=pow(10, $ld)/$a
    
$minstep=$majstep/$b;
    
$numsteps=floor($diff/$majstep); 
    
    while( 
$numsteps $maxsteps ) {
        
$majstep=pow(10, $ld)/$a
        
$numsteps=floor($diff/$majstep);
        ++
$ld;
    }
    
$minstep=$majstep/$b;
    return array(
$numsteps, $minstep, $majstep);
    }

    
    function 
IntCalcTicks($maxsteps, $min, $max, $a, $majend=true) {
    
$diff=$max-$min
    if( 
$diff==)
        
JpGraphError::Raise('Can\'t automatically determine ticks since min==max.');
    else
        
$ld=floor(log10($diff));
        
    
// Gravitate min towards zero if we are close        
    
if( $min>&& $min pow(10, $ld) ) $min=0;
        
    if( 
$ld == $ld=1;
    
    if( 
$a == 
        
$majstep 1;
    else
        
$majstep=pow(10, $ld)/$a
    
$adjmax=ceil($max/$majstep)*$majstep;

    
$adjmin=floor($min/$majstep)*$majstep;    
    
$adjdiff $adjmax-$adjmin;
    
$numsteps=$adjdiff/$majstep
    while( 
$numsteps>$maxsteps ) {
        
$majstep=pow(10, $ld)/$a
        
$numsteps=$adjdiff/$majstep;
        ++
$ld;
    }
        
    
$adjmin=floor($min/$majstep)*$majstep;    
    
$adjdiff $adjmax-$adjmin;        
    if( 
$majend ) {
        
$adjmin floor($min/$majstep)*$majstep;    
        
$adjdiff $adjmax-$adjmin;        
        
$adjmax ceil($adjdiff/$majstep)*$majstep+$adjmin;
    }
    else
        
$adjmax=ceil($max/$majstep)*$majstep;
            
    return array(
$numsteps, $adjmin, $adjmax, $majstep);        
    }


    function 
IntCalcTicksFreeze($maxsteps, $min, $max, $a) {
    
// Same as IntCalcTick but don't change min/max values
    
$diff=$max-$min
    if( 
$diff==)
        
JpGraphError::Raise('Can\'t automatically determine ticks since min==max.');
    else
        
$ld=floor(log10($diff));
        
    if( 
$ld == $ld=1;
    
    if( 
$a == 
        
$majstep 1;
    else
        
$majstep=pow(10, $ld)/$a

    
$numsteps=floor($diff/$majstep); 
    while( 
$numsteps $maxsteps ) {
        
$majstep=pow(10, $ld)/$a
        
$numsteps=floor($diff/$majstep);
        ++
$ld;
    }
                    
    return array(
$numsteps, $majstep);        
    }


    
    
// Determine the minimum of three values witha  weight for last value
    
function MatchMin3($a, $b, $c, $weight) {
    if( 
$a $b ) {
        if( 
$a < ($c*$weight) ) 
        return 
1// $a smallest
        
else 
        return 
3// $c smallest
    
}
    elseif( 
$b < ($c*$weight) ) 
        return 
2// $b smallest
    
return 3// $c smallest
    
}
// Class

//===================================================
// CLASS RGB
// Description: Color definitions as RGB triples
//===================================================
class RGB {
    var 
$rgb_table;
    var 
$img;
    function 
RGB($aImg=null) {
    
$this->img $aImg;
        
    
// Conversion array between color names and RGB
    
$this->rgb_table = array(
        
"aqua"=> array(0, 255, 255),         
        
"lime"=> array(0, 255, 0),         
        
"teal"=> array(0, 128, 128),
        
"whitesmoke"=>array(245, 245, 245),
        
"gainsboro"=>array(220, 220, 220),
        
"oldlace"=>array(253, 245, 230),
        
"linen"=>array(250, 240, 230),
        
"antiquewhite"=>array(250, 235, 215),
        
"papayawhip"=>array(255, 239, 213),
        
"blanchedalmond"=>array(255, 235, 205),
        
"bisque"=>array(255, 228, 196),
        
"peachpuff"=>array(255, 218, 185),
        
"navajowhite"=>array(255, 222, 173),
        
"moccasin"=>array(255, 228, 181),
        
"cornsilk"=>array(255, 248, 220),
        
"ivory"=>array(255, 255, 240),
        
"lemonchiffon"=>array(255, 250, 205),
        
"seashell"=>array(255, 245, 238),
        
"mintcream"=>array(245, 255, 250),
        
"azure"=>array(240, 255, 255),
        
"aliceblue"=>array(240, 248, 255),
        
"lavender"=>array(230, 230, 250),
        
"lavenderblush"=>array(255, 240, 245),
        
"mistyrose"=>array(255, 228, 225),
        
"white"=>array(255, 255, 255),
        
"black"=>array(0, 0, 0),
        
"darkslategray"=>array(47, 79, 79),
        
"dimgray"=>array(105, 105, 105),
        
"slategray"=>array(112, 128, 144),
        
"lightslategray"=>array(119, 136, 153),
        
"gray"=>array(190, 190, 190),
        
"lightgray"=>array(211, 211, 211),
        
"midnightblue"=>array(25, 25, 112),
        
"navy"=>array(0, 0, 128),
        
"cornflowerblue"=>array(100, 149, 237),
        
"darkslateblue"=>array(72, 61, 139),
        
"slateblue"=>array(106, 90, 205),
        
"mediumslateblue"=>array(123, 104, 238),
        
"lightslateblue"=>array(132, 112, 255),
        
"mediumblue"=>array(0, 0, 205),
        
"royalblue"=>array(65, 105, 225),
        
"blue"=>array(0, 0, 255),
        
"dodgerblue"=>array(30, 144, 255),
        
"deepskyblue"=>array(0, 191, 255),
        
"skyblue"=>array(135, 206, 235),
        
"lightskyblue"=>array(135, 206, 250),
        
"steelblue"=>array(70, 130, 180),
        
"lightred"=>array(211, 167, 168),
        
"lightsteelblue"=>array(176, 196, 222),
        
"lightblue"=>array(173, 216, 230),
        
"powderblue"=>array(176, 224, 230),
        
"paleturquoise"=>array(175, 238, 238),
        
"darkturquoise"=>array(0, 206, 209),
        
"mediumturquoise"=>array(72, 209, 204),
        
"turquoise"=>array(64, 224, 208),
        
"cyan"=>array(0, 255, 255),
        
"lightcyan"=>array(224, 255, 255),
        
"cadetblue"=>array(95, 158, 160),
        
"mediumaquamarine"=>array(102, 205, 170),
        
"aquamarine"=>array(127, 255, 212),
        
"darkgreen"=>array(0, 100, 0),
        
"darkolivegreen"=>array(85, 107, 47),
        
"darkseagreen"=>array(143, 188, 143),
        
"seagreen"=>array(46, 139, 87),
        
"mediumseagreen"=>array(60, 179, 113),
        
"lightseagreen"=>array(32, 178, 170),
        
"palegreen"=>array(152, 251, 152),
        
"springgreen"=>array(0, 255, 127),
        
"lawngreen"=>array(124, 252, 0),
        
"green"=>array(0, 255, 0),
        
"chartreuse"=>array(127, 255, 0),
        
"mediumspringgreen"=>array(0, 250, 154),
        
"greenyellow"=>array(173, 255, 47),
        
"limegreen"=>array(50, 205, 50),
        
"yellowgreen"=>array(154, 205, 50),
        
"forestgreen"=>array(34, 139, 34),
        
"olivedrab"=>array(107, 142, 35),
        
"darkkhaki"=>array(189, 183, 107),
        
"khaki"=>array(240, 230, 140),
        
"palegoldenrod"=>array(238, 232, 170),
        
"lightgoldenrodyellow"=>array(250, 250, 210),
        
"lightyellow"=>array(255, 255, 200),
        
"yellow"=>array(255, 255, 0),
        
"gold"=>array(255, 215, 0),
        
"lightgoldenrod"=>array(238, 221, 130),
        
"goldenrod"=>array(218, 165, 32),
        
"darkgoldenrod"=>array(184, 134, 11),
        
"rosybrown"=>array(188, 143, 143),
        
"indianred"=>array(205, 92, 92),
        
"saddlebrown"=>array(139, 69, 19),
        
"sienna"=>array(160, 82, 45),
        
"peru"=>array(205, 133, 63),
        
"burlywood"=>array(222, 184, 135),
        
"beige"=>array(245, 245, 220),
        
"wheat"=>array(245, 222, 179),
        
"sandybrown"=>array(244, 164, 96),
        
"tan"=>array(210, 180, 140),
        
"chocolate"=>array(210, 105, 30),
        
"firebrick"=>array(178, 34, 34),
        
"brown"=>array(165, 42, 42),
        
"darksalmon"=>array(233, 150, 122),
        
"salmon"=>array(250, 128, 114),
        
"lightsalmon"=>array(255, 160, 122),
        
"orange"=>array(255, 165, 0),
        
"darkorange"=>array(255, 140, 0),
        
"coral"=>array(255, 127, 80),
        
"lightcoral"=>array(240, 128, 128),
        
"tomato"=>array(255, 99, 71),
        
"orangered"=>array(255, 69, 0),
        
"red"=>array(255, 0, 0),
        
"hotpink"=>array(255, 105, 180),
        
"deeppink"=>array(255, 20, 147),
        
"pink"=>array(255, 192, 203),
        
"lightpink"=>array(255, 182, 193),
        
"palevioletred"=>array(219, 112, 147),
        
"maroon"=>array(176, 48, 96),
        
"mediumvioletred"=>array(199, 21, 133),
        
"violetred"=>array(208, 32, 144),
        
"magenta"=>array(255, 0, 255),
        
"violet"=>array(238, 130, 238),
        
"plum"=>array(221, 160, 221),
        
"orchid"=>array(218, 112, 214),
        
"mediumorchid"=>array(186, 85, 211),
        
"darkorchid"=>array(153, 50, 204),
        
"darkviolet"=>array(148, 0, 211),
        
"blueviolet"=>array(138, 43, 226),
        
"purple"=>array(160, 32, 240),
        
"mediumpurple"=>array(147, 112, 219),
        
"thistle"=>array(216, 191, 216),
        
"snow1"=>array(255, 250, 250),
        
"snow2"=>array(238, 233, 233),
        
"snow3"=>array(205, 201, 201),
        
"snow4"=>array(139, 137, 137),
        
"seashell1"=>array(255, 245, 238),
        
"seashell2"=>array(238, 229, 222),
        
"seashell3"=>array(205, 197, 191),
        
"seashell4"=>array(139, 134, 130),
        
"AntiqueWhite1"=>array(255, 239, 219),
        
"AntiqueWhite2"=>array(238, 223, 204),
        
"AntiqueWhite3"=>array(205, 192, 176),
        
"AntiqueWhite4"=>array(139, 131, 120),
        
"bisque1"=>array(255, 228, 196),
        
"bisque2"=>array(238, 213, 183),
        
"bisque3"=>array(205, 183, 158),
        
"bisque4"=>array(139, 125, 107),
        
"peachPuff1"=>array(255, 218, 185),
        
"peachpuff2"=>array(238, 203, 173),
        
"peachpuff3"=>array(205, 175, 149),
        
"peachpuff4"=>array(139, 119, 101),
        
"navajowhite1"=>array(255, 222, 173),
        
"navajowhite2"=>array(238, 207, 161),
        
"navajowhite3"=>array(205, 179, 139),
        
"navajowhite4"=>array(139, 121, 94),
        
"lemonchiffon1"=>array(255, 250, 205),
        
"lemonchiffon2"=>array(238, 233, 191),
        
"lemonchiffon3"=>array(205, 201, 165),
        
"lemonchiffon4"=>array(139, 137, 112),
        
"ivory1"=>array(255, 255, 240),
        
"ivory2"=>array(238, 238, 224),
        
"ivory3"=>array(205, 205, 193),
        
"ivory4"=>array(139, 139, 131),
        
"honeydew"=>array(193, 205, 193),
        
"lavenderblush1"=>array(255, 240, 245),
        
"lavenderblush2"=>array(238, 224, 229),
        
"lavenderblush3"=>array(205, 193, 197),
        
"lavenderblush4"=>array(139, 131, 134),
        
"mistyrose1"=>array(255, 228, 225),
        
"mistyrose2"=>array(238, 213, 210),
        
"mistyrose3"=>array(205, 183, 181),
        
"mistyrose4"=>array(139, 125, 123),
        
"azure1"=>array(240, 255, 255),
        
"azure2"=>array(224, 238, 238),
        
"azure3"=>array(193, 205, 205),
        
"azure4"=>array(131, 139, 139),
        
"slateblue1"=>array(131, 111, 255),
        
"slateblue2"=>array(122, 103, 238),
        
"slateblue3"=>array(105, 89, 205),
        
"slateblue4"=>array(71, 60, 139),
        
"royalblue1"=>array(72, 118, 255),
        
"royalblue2"=>array(67, 110, 238),
        
"royalblue3"=>array(58, 95, 205),
        
"royalblue4"=>array(39, 64, 139),
        
"dodgerblue1"=>array(30, 144, 255),
        
"dodgerblue2"=>array(28, 134, 238),
        
"dodgerblue3"=>array(24, 116, 205),
        
"dodgerblue4"=>array(16, 78, 139),
        
"steelblue1"=>array(99, 184, 255),
        
"steelblue2"=>array(92, 172, 238),
        
"steelblue3"=>array(79, 148, 205),
        
"steelblue4"=>array(54, 100, 139),
        
"deepskyblue1"=>array(0, 191, 255),
        
"deepskyblue2"=>array(0, 178, 238),
        
"deepskyblue3"=>array(0, 154, 205),
        
"deepskyblue4"=>array(0, 104, 139),
        
"skyblue1"=>array(135, 206, 255),
        
"skyblue2"=>array(126, 192, 238),
        
"skyblue3"=>array(108, 166, 205),
        
"skyblue4"=>array(74, 112, 139),
        
"lightskyblue1"=>array(176, 226, 255),
        
"lightskyblue2"=>array(164, 211, 238),
        
"lightskyblue3"=>array(141, 182, 205),
        
"lightskyblue4"=>array(96, 123, 139),
        
"slategray1"=>array(198, 226, 255),
        
"slategray2"=>array(185, 211, 238),
        
"slategray3"=>array(159, 182, 205),
        
"slategray4"=>array(108, 123, 139),
        
"lightsteelblue1"=>array(202, 225, 255),
        
"lightsteelblue2"=>array(188, 210, 238),
        
"lightsteelblue3"=>array(162, 181, 205),
        
"lightsteelblue4"=>array(110, 123, 139),
        
"lightblue1"=>array(191, 239, 255),
        
"lightblue2"=>array(178, 223, 238),
        
"lightblue3"=>array(154, 192, 205),
        
"lightblue4"=>array(104, 131, 139),
        
"lightcyan1"=>array(224, 255, 255),
        
"lightcyan2"=>array(209, 238, 238),
        
"lightcyan3"=>array(180, 205, 205),
        
"lightcyan4"=>array(122, 139, 139),
        
"paleturquoise1"=>array(187, 255, 255),
        
"paleturquoise2"=>array(174, 238, 238),
        
"paleturquoise3"=>array(150, 205, 205),
        
"paleturquoise4"=>array(102, 139, 139),
        
"cadetblue1"=>array(152, 245, 255),
        
"cadetblue2"=>array(142, 229, 238),
        
"cadetblue3"=>array(122, 197, 205),
        
"cadetblue4"=>array(83, 134, 139),
        
"turquoise1"=>array(0, 245, 255),
        
"turquoise2"=>array(0, 229, 238),
        
"turquoise3"=>array(0, 197, 205),
        
"turquoise4"=>array(0, 134, 139),
        
"cyan1"=>array(0, 255, 255),
        
"cyan2"=>array(0, 238, 238),
        
"cyan3"=>array(0, 205, 205),
        
"cyan4"=>array(0, 139, 139),
        
"darkslategray1"=>array(151, 255, 255),
        
"darkslategray2"=>array(141, 238, 238),
        
"darkslategray3"=>array(121, 205, 205),
        
"darkslategray4"=>array(82, 139, 139),
        
"aquamarine1"=>array(127, 255, 212),
        
"aquamarine2"=>array(118, 238, 198),
        
"aquamarine3"=>array(102, 205, 170),
        
"aquamarine4"=>array(69, 139, 116),
        
"darkseagreen1"=>array(193, 255, 193),
        
"darkseagreen2"=>array(180, 238, 180),
        
"darkseagreen3"=>array(155, 205, 155),
        
"darkseagreen4"=>array(105, 139, 105),
        
"seagreen1"=>array(84, 255, 159),
        
"seagreen2"=>array(78, 238, 148),
        
"seagreen3"=>array(67, 205, 128),
        
"seagreen4"=>array(46, 139, 87),
        
"palegreen1"=>array(154, 255, 154),
        
"palegreen2"=>array(144, 238, 144),
        
"palegreen3"=>array(124, 205, 124),
        
"palegreen4"=>array(84, 139, 84),
        
"springgreen1"=>array(0, 255, 127),
        
"springgreen2"=>array(0, 238, 118),
        
"springgreen3"=>array(0, 205, 102),
        
"springgreen4"=>array(0, 139, 69),
        
"chartreuse1"=>array(127, 255, 0),
        
"chartreuse2"=>array(118, 238, 0),
        
"chartreuse3"=>array(102, 205, 0),
        
"chartreuse4"=>array(69, 139, 0),
        
"olivedrab1"=>array(192, 255, 62),
        
"olivedrab2"=>array(179, 238, 58),
        
"olivedrab3"=>array(154, 205, 50),
        
"olivedrab4"=>array(105, 139, 34),
        
"darkolivegreen1"=>array(202, 255, 112),
        
"darkolivegreen2"=>array(188, 238, 104),
        
"darkolivegreen3"=>array(162, 205, 90