#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct
{
   char name[128];
   char val[128];
} entry;

void generate_no_cookie_page(void);
void generate_have_cookie_page(char *name, int user_id);
void generate_list(int user_id);

void getword(char *word, char *line, char stop);
char x2c(char *what);
void unescape_url(char *url);
void plustospace(char *str);

void main()
{
	entry entries[10000];
	register x,m=0;
	char *cookie;
	char name[8];
	int user_id;

	printf("Content-type: text/html%c%c",10,10);

/*	if(strcmp(getenv("REQUEST_METHOD"),"GET"))
	{
		printf("This script should be referenced with a METHOD of GET.\n");
		exit(1);
	} */

	cookie = getenv("HTTP_COOKIE");

	if (cookie == NULL)
		generate_no_cookie_page();
	else
	{
		for (x=0; cookie[0] != '\0'; x++)
		{
			m=x;
			getword(entries[x].val,cookie,';');
			getword(entries[x].name,entries[x].val,'=');
		}

		user_id = atoi(entries[0].val);
		strncpy(name,(char *) &user_id,sizeof(user_id));
		name[4] = '\0';
		generate_have_cookie_page(name, user_id);
	}
};

void generate_no_cookie_page(void)
{
	printf("<html>\n");
	printf("<head>\n");
	printf("<title>Welcome to Dave's interactive Wish List!</title>\n");
	printf("</head>\n");

	printf("<body>\n");
	printf("You don't seem to be logged on.  In order to use this page, you need to either\n");
	printf("<a href=\"new_account.html\">create an account</a> or log in using an \n");
	printf("<a href=\"login.html\">existing account</a>.\n");

	printf("<P>\n");

	printf("If you do not wish to transmit any information, you may \n");
	printf("<a href=\"wish_list.html\">view the list</a> without logging in.\n");

	printf("</body>\n");
	printf("</html>\n");
};

void generate_have_cookie_page(char *name, int user_id)
{
	printf("<html>\n");
	printf("<head>\n");
	printf("<title>Welcome to Dave's Wish List</title>\n");
	printf("</head>\n");

	printf("<body>\n");
	printf("Welcome %s!\n",name);

	printf("<p>\n");

	printf("For your convenience, items added since your last visit \n");
	printf("use red bullets.\n");

	printf("<p>\n");

	generate_list(user_id);

	printf("<p>\n");

	printf("<a href=\"login.html\">Login as a different user</a>\n");
	printf("</body>\n");
	printf("</html>\n");
};

void generate_list(int user_id)
{
	char *item[5] = 
		{"Quake","Quake II","CD ROM Drive","Casio DataBank Watch","Laser Pointer"};
	int id_list[2] = {1702256964,1752395594};
	int new[2][5] = {{1,1,0,1,1},{0,0,1,0,1}};

	int curr_user, counter;

	curr_user = 0;
	while (id_list[curr_user] != user_id)
		curr_user++;

	printf("<ul>\n");
	for (counter = 0 ; counter < 5 ; counter++)
	{
		printf("<li");
		if (new[curr_user][counter])
			printf(" style=\"color: red\"");
		printf("> %s",item[counter]);
		printf("\n");
	};
	printf("</ul>\n");
};
