#include "cgic.h"
#include <string.h>
#include <stdlib.h>

/* This filename must be changed. The file it points to
	must contain a list of GIF files on your system,
	specified by complete paths. */

#define GIF_LIST_FILE "/CHANGE/THIS/PATH/giflist.txt"

/* Returns true if the browser supports server push,
	false otherwise. */
int SupportsServerPush();

int SupportsServerPush() {
	char *versionString;
	float version = 0.0;
	sscanf(cgiUserAgent, "Mozilla/%f", &version);
	if (version >= 1.1) {
		return 1;
	} else {
		return 0;
	}	
}
	
int cgiMain()
{
	FILE *in, *gifIn;
	int choice = 0;
	int count = 0;
	int pushFlag = 1;
	fprintf(cgiOut, "HTTP/1.0 200 OK\n");
	if (!SupportsServerPush()) {
		/* Uh-oh, no server push. */
		pushFlag = 0;
	}

	if (pushFlag) {
		cgiHeaderContentType(
			"multipart/x-mixed-replace;boundary=goober\n\n");
	}

	in = fopen(GIF_LIST_FILE, "r");
	while (1) {
		char s[256];
		char *filename;
		if (!fgets(s, 256, in)) {
			fclose(in);
			break;
		}
		/* The filename is everything up to the line break */
		filename = strtok(s, "\r\n\t ");
		if (pushFlag) {
			fprintf(cgiOut, "\n--goober\n");
		}
		/* Now output the file */
		gifIn = fopen(filename, "rb");
		if (!gifIn) {
			/* Missing frame, skip it */
			continue;
		}
		cgiHeaderContentType("image/gif");
		while (1) {
			int ch;
			ch = getc(gifIn);
			if (ch == EOF) {
				break;
			}
			putc(ch, cgiOut);
		}	
		fclose(gifIn);
		if (!pushFlag) {
			/* Just the first image if server push is not used */
			break;
		}
		/* A short delay to make sure each frame is appreciated */
		sleep(1);
		count++;	
	}
	fclose(in);
	if (pushFlag) {
		/* Now terminate the server push sequence altogether */
		fprintf(cgiOut, "\n--goober--\n");
	}
	return 0;		
}
