#include "gd.h"
#include "cgic.h"

#define IMAGE_FILE "/CHANGE/THIS/FILE/name.gif"

void Magnify(int x, int y, gdImagePtr im);

int cgiMain() {
	int x = -1, y = -1;
	gdImagePtr im = 0;
	if (strstr(cgiPathInfo, ".gif")) {
		/* This is a request for an image */
		FILE *in;
		in = fopen(IMAGE_FILE, "rb");	
		im = gdImageCreateFromGif(in);
		fclose(in);
	}
	sscanf(cgiQueryString, "%d,%d", &x, &y);
	if ((x != -1) && (y != -1)) {
		/* This is a request for a magnified portion
			of the image, or the page it will appear in */
		Magnify(x, y, im);
		return 0;
	}
	if (im) {
		/* Top view: no magnification */
		cgiHeaderContentType("image/gif");
		gdImageGif(im, cgiOut);
	} else {
		/* Top page, with an <img src> tag pointing to
			an unmagnified gif */
		cgiHeaderContentType("text/html");
		fprintf(cgiOut, "<html>\n");	
		fprintf(cgiOut, "<head>\n");	
		fprintf(cgiOut, "<title>CGI Magnifying Glass</title>\n");	
		fprintf(cgiOut, "</head>\n");	
		fprintf(cgiOut, "<body>\n");	
		fprintf(cgiOut, "<h1>CGI Magnifying Glass</h1>\n");	
		fprintf(cgiOut, "Click anywhere in the image for a\n");
		fprintf(cgiOut, "magnified view.\n");
		fprintf(cgiOut, "<p>\n");
		fprintf(cgiOut, "<a href=\"index.html\">\n");
		fprintf(cgiOut, "<img src=\"image.gif\" ISMAP>\n");
		fprintf(cgiOut, "</a>\n");
		fprintf(cgiOut, "</body>\n");
		fprintf(cgiOut, "</html>\n");	
	}
	/* Free the memory associated with the image */
	if (im) {
		gdImageDestroy(im);
	}
	return 0;
}
 
void Magnify(int x, int y, gdImagePtr im) 
{
	if (im) {
		/* Generate a 4x magnified image */
		gdImagePtr mag;
		mag = gdImageCreate(200, 200);
		/* Copies and stretches the desired portion of the image */
		gdImageCopyResized(mag, im,
			0, 0, 
			x - 25, y - 25, 
			200, 200,
			50, 50);
		cgiHeaderContentType("image/gif");
		gdImageGif(mag, cgiOut);
		gdImageDestroy(mag);
	} else {
		/* A page with an <img src> tag pointing to
			the magnified GIF and a link to return
			to the normal top-down view */

		cgiHeaderContentType("text/html");
		fprintf(cgiOut, "<html>\n");	
		fprintf(cgiOut, "<head>\n");	
		fprintf(cgiOut, "<title>Magnified View</title>\n");	
		fprintf(cgiOut, "</head>\n");	
		fprintf(cgiOut, "<body>\n");	
		fprintf(cgiOut, "<h1>Magnified View</h1>\n");	
		fprintf(cgiOut, "<a href=\"index.html\">\n");
		fprintf(cgiOut, "Up to the complete image</a>\n");

		/* A trick to remember: we generate a src attribute
			which will appear to the program just like the original
			imagemap click did, but with "/image.gif" in
			the PATH_INFO variable. This will invoke the
			other branch of this function to generate the image. */

		fprintf(cgiOut, "<p><img src=\"image.gif?%d,%d\">\n", x, y);

		fprintf(cgiOut, "</body>\n");
		fprintf(cgiOut, "</html>\n");	
	}
	if (im) {
		gdImageDestroy(im);
	}
}

