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

FILE *index1;

void GetVars(char entry[200], char word[80]);
void GetGlWord(char word[80], char gl_word[80]);

void main(char *argv[], int argvc)
{
	char word[80];
	char entry[200];
	char gl_word[80];

	scanf("%s", &entry);

	index1 = fopen("../gather/glossary/index", "r");

	GetVars(entry, word);
	GetGlWord(word, gl_word);

	printf("Location: ../frames/glossary.html#%s\n", gl_word);
	printf("Content-type: text/html\n\n\n");
}

void GetGlWord(char word[80], char gl_word[80])
{
	char line[80];

	fscanf(index1, "%s", line);
	if((line[0] == '<') && (line[2] == '>'))
	{
		line[0] = line[1];
		line[1] = '\0';
	}
	
	while(1)
	{
		if(strcmp(word, line) > 0) strcpy(gl_word, line);
		else if(strcmp(word, line) == 0) 
		{
			strcpy(gl_word, line);
			break;
		}
		else break;
	
		fscanf(index1, "%s", &line);	
		if((line[0] == '<') && (line[2] == '>')) 
		{
			line[0] = line[1];
			line[1] = '\0';
		}	
	}
}

void GetVars(char entry[200], char word[80])
{
	int a, b;
	char check;

	strcpy(word, "");

	a = 5;
	while(entry[a] != '\0')
	{
		if(entry[a] == '+')
			word[a - 5] = '`';
		else	
			word[a - 5] = entry[a];
		a++;
	}

	word[a - 5] = '\0';


//Make all lower case
	a = 0;
	while(word[a] != '\0')
	{
		if((word[a] <= 90) && (word[a] >= 65)) word[a] += 32;
		a++;
	}

	a = 0;
	check = 0;

//Convert % Characters

	int InPos = 0;
	char digit;
	char Out[900];
	char temp[10];

	strcpy(Out, "");

	while(InPos < strlen(word))
	{
		if(word[InPos] == '%')
		{
			digit = ((word[InPos+1] >= 'A') ? ((word[InPos+1] & 0xdf) - 'A')+10 : (word[InPos+1] - '0'));
			digit *= 16;
			digit += (word[InPos+2] >= 'A' ? ((word[InPos+2] & 0xdf) - 'A')+10 : (word[InPos+2] - '0'));
			strcpy(temp, " ");
			temp[0] = digit;
			strcat(Out, temp); 
			InPos += 3;
		}	
		else 
		{
			strcpy(temp, " ");
			temp[0] = word[InPos];
			strcat(Out, temp);
			InPos++;
		}
	}
	
	strcpy(word, Out);

}


