/* graph module 3.0. Copyright 1993, 1994, Quest Protein Database Center,
   Cold Spring Harbor Labs. Permission granted to copy and distribute
   this work provided that this notice remains intact. Modified
   versions should be cleared through Quest first; if this is not
   done, any modified version of the program must be clearly labeled
   as such. 

   By Thomas Boutell, 11/93 - 5/94. Please contact boutell@cshl.org
   with any questions regarding this software. */

#include <stdio.h>
#include "configure.h"
#include "usage.h"
#include "gd.h"

int values[WEEKS_MAX];

void graph(/* int sizex, int sizey, int base, char *name */);

void graphs() {
#ifdef VMS
	graph(320, 240, 16, "usage_graph.gif");
	graph(40, 30, 0, "usage_graph_small.gif");
#else
	graph(320, 240, 16, "usage.graph.gif");
	graph(40, 30, 0, "usage.graph.small.gif");
#endif
}

void graph(sizex, sizey, base, name)
	int sizex; 
	int sizey; 
	int base; 
	char *name; 
{
	FILE *out;
	FILE *in;
	int weeks = 0;
	int max = - 1;
	int maxx = sizex-1;
	int basex = base;
	int rangex = maxx - basex*2;
	int i;
	int maxy = sizey-1;
	int basey = base;
	int rangey = maxy - basey*2;
	char s[1024];
	int lx, ly;
	gdImagePtr im;
	int gray, red, blue;
	wusage(1, 0, 1, values, &weeks);
	for (i=0; (i<weeks); i++) {
		if ((!i) || (values[i] > max)) {
			max = values[i];
		}
	}
	im = gdImageCreate(sizex, sizey);
	gray = gdImageColorAllocate(im, 240, 240, 240);
	gdImageColorTransparent(im, gray);
	red = gdImageColorAllocate(im, 255, 0, 0);	
	blue = gdImageColorAllocate(im, 0, 0, 255);	
	gdImageLine(im, basex, basey, maxx-basex, basey, red);
	gdImageLine(im, maxx-basex, basey, maxx-basex, maxy-basey, red);
	gdImageLine(im, maxx-basex, maxy-basey, basex, maxy-basey, red);
	gdImageLine(im, basex, maxy-basey, basex, basey, red);
	if (base) {
		sprintf(s, "%d", weeks);
		gdImageString(im, basex, maxy-basey+1, "1", blue);
		gdImageString(im, maxx-basex-strlen(s)*gdFontWidth, 
			maxy-basey+1, s, blue);
		gdImageString(im, sizex/2-gdFontWidth*5/2, maxy-16+1, 
			"Weeks", blue);
		gdImageStringUp(im, basex-16, maxy-basey, "0", blue);
		gdImageStringUp(im, basex-16, sizey/2+gdFontWidth*8/2, 
			"Accesses", blue);	
		sprintf(s, "%d", max);
		gdImageStringUp(im, basex-16, basey+strlen(s) * gdFontWidth,
			s, blue);
	}
	if (weeks > 1) {
		for (i=0; (i<weeks); i++) {
			int x;
			int y;
			y = rangey-(values[i]*rangey/max)+basey;
			x = i*rangex/(weeks-1)+basex;
			if (i>0) {
				gdImageLine(im, lx, ly, x, y, red);
			}
			lx = x;
			ly = y;	
		}
	}
	sprintf(s, "%s/%s", filepath, name);
	out = fopen(s, "w");
	gdImageGif(im, out);
	fclose(out);
}
