/*
 * preview.c using 'convert'
 * for Animal Pictures Archive
 * jskim@bulls.kordic.re.kr
 */

#include "preview.h"
#include "NameSearch/AD_Buf.h"

int lang = 0; /* 0 for english 1 for Korean */

int main()
{
	FILE		*fp, *fhtml;
	char		*srcFile, *srcPath;
	char		previewFile[256];
	char		FilePath[256];
	getentry	entries[5];
	int		width;	/* x width in pixel to Resize */

	char		buf[256];
	char		line[256];
	char		*ptr;
	register	int	i, x;

	printf("content-type: text/html\n\n");	/* HTML Header */

#ifdef FILEOUT
	printf("Debugging Mode\n");
	i = 2;
	strcpy(entries[0].name, "img");
	strcpy(entries[0].val, "animal1/AztecAnts_J01-workers_kill_the_invader.jpg");
	strcpy(entries[1].name, "width");
	strcpy(entries[1].val, "400");
#else
	i = ProcessGetMethod( entries );
#endif

	width=0;
	for (x = 0; x <= i; x++)
	{
		if (!strcmp(entries[x].name, "img"))
		{
			strcpy(FilePath, entries[x].val);
			strcpy(buf, entries[x].val);
			while (ptr = (char *)strstr(buf, "/"))
			{
				strcpy(buf, ptr+1);
			}
			srcFile = (char *) malloc(strlen(buf)+1);
			strcpy(srcFile, buf);
			strcpy(buf, entries[x].val);
			ptr = (char *) strstr(buf, srcFile);
			*ptr = '\0';
			srcPath = (char *) malloc(strlen(buf)+1);
			strcpy(srcPath, buf);
			continue;
		}

		if (!strcmp(entries[x].name, "Lang"))
		{
			if (!strcasecmp(entries[x].val, "Korean"))
				lang = 1;
			continue;
		}
		if (!strcmp(entries[x].name, "width"))
		{
			width = atoi(entries[x].val);
			continue;
		}
	}

	if ( width <= 0)
		width = 400;	/* Default to 400 */

	strcpy(buf, srcFile);
	for (i = strlen(srcFile); i > 0; i--)
	{
		if (buf[i] == '.')
		{
			buf[i] = '\0';
			break;
		}
	}

	if (strstr(srcFile, ".jpg") || strstr(srcFile, ".JPG") || \
		    strstr(srcFile, ".gif") || strstr(srcFile, ".GIF"))
	{
	    strcpy(previewFile, buf);

	    if ( strstr(srcFile, ".gif") || strstr(srcFile, ".GIF"))
		sprintf(buf, "-s%d.gif", width);
	    else sprintf(buf, "-s%d.jpg", width);

	    strcat(previewFile, buf);

	    sprintf(buf, "%s/%s", PREVIEW_DIR, previewFile);
	    if ( (fp=fopen(buf, "r")) == NULL )
	    {
		sprintf(buf, "%s -frame 10 -geometry %dx%d \"%s%s\" \"%s/%s\"",\
			CONVERT, width, width, srcPath, srcFile, \
			PREVIEW_DIR, previewFile);
		if (system(buf) == -1) {
		    printf("problem in preview...<br>\n");
		    printf("<a href=\"ViewImg.cgi?img=%s%s\">",\
			    srcPath, srcFile);
		    printf("Click here to see full image</a><p>\n");
		    exit(1);
		}
	    }
	    else
		fclose(fp);
	}
	else
	{
		printf("The Image %s cannot be previewed.<br>\n", srcFile);
		printf("<a href=\"ViewImg.cgi?img=%s%s\">", srcPath, srcFile);
		printf("Click here to see full image</a><p>\n");
		exit(0);
	}

	if (lang == 1)
		fhtml = fopen(PREVIEW_HTML_HAN, "r");
	else
		fhtml = fopen(PREVIEW_HTML, "r");

	if (fhtml == NULL) {
	    printf("can't open the template HTML for preview<br>\n");
	    exit(0);
	}
	
	while (fgets(line, 256, fhtml)) {
	    if (ptr = (char *)strstr(line, "___IMAGE_NAME___")) {
		*ptr = '\0'; printf("%s\n", line);
		printf("%s\n", srcFile);
		printf("%s\n", ptr+16);
		continue;
	    }
	    if (ptr = (char *)strstr(line, "___IMAGE_PATH___")) {
		*ptr = '\0'; printf("%s", line);
		printf("%s", FilePath);
		printf("%s\n", ptr+16);
		continue;
	    }
	    if (ptr = (char *)strstr(line, "___PREVIEW_IMAGE_PATH___")) {
		*ptr = '\0'; printf("%s", line);
		printf("%s/%s", PREVIEW_DIR, previewFile);
		printf("%s\n", ptr+24);
		continue;
	    }
	    if (ptr = (char *)strstr(line, "___DESCRIPTION_FILE___")) {
		*ptr = '\0'; printf("%s\n", line);
		PrintDescriptionFile(FilePath);
		printf("%s\n", ptr+22);
		continue;
	    }
	    printf("%s\n", line);
	}
	fclose(fhtml);

	free(srcFile); free(srcPath);

	exit(0);
}

int PrintDescriptionFile(char FilePath[])
{
	FILE *fp;
	int i;
	char		srcFileDesc[256];

	char		buf[256];
	char		buf2[256];

	strcpy(buf, FilePath);
	for (i = strlen(FilePath); i > 0; i--) {
		if (FilePath[i] == '.') {
			buf[i] = '\0';
			break;
		}
	}

	printf("<p><table><tr><td>\n");
	while (1)
	{
		strcpy(srcFileDesc, buf);
		strcat(srcFileDesc, ".txt");
		if ( (fp=fopen(srcFileDesc, "r")) == NULL ) ;
		else
		{
			printf("<pre>\n");
			while(fgets(buf2, 256, fp))
				PrintLink(buf2);
			printf("</pre>\n");
			fclose(fp);
			break;
		}

		strcpy(srcFileDesc, buf);
		strcat(srcFileDesc, ".TXT");
		if ( (fp=fopen(srcFileDesc, "r")) == NULL ) ;
		else
		{
			printf("<pre>\n");
			while(fgets(buf2, 256, fp))
				PrintLink(buf2);
			printf("</pre>\n");
			fclose(fp);
			break;
		}

		strcpy(srcFileDesc, buf);
		strcat(srcFileDesc, ".html");
		if ( (fp=fopen(srcFileDesc, "r")) == NULL ) ;
		else
		{
			printf("<p>");
			while(fgets(buf2, 256, fp))
				if (!(strstr(buf2, "<img ") || \
					strstr(buf2, "<IMG ")))
					printf("%s", buf2);
			fclose(fp);
			break;
		}
		break;
	}
	printf("</table>\n");

	return 0;
}


/* NCSA Web Library */
void 
getword(char *word, char *line, char stop)
{
	int             x = 0, y;

	for (x = 0; ((line[x]) && (line[x] != stop)); x++)
		word[x] = line[x];

	word[x] = '\0';
	if (line[x])
		++x;
	y = 0;

	while (line[y++] = line[x++]);
}

char           *
makeword(char *line, char stop)
{
	int             x = 0, y;
	char           *word = (char *) malloc(sizeof(char) * (strlen(line) + 1));

	for (x = 0; ((line[x]) && (line[x] != stop)); x++)
		word[x] = line[x];

	word[x] = '\0';
	if (line[x])
		++x;
	y = 0;

	while (line[y++] = line[x++]);
	return word;
}

char           *
fmakeword(FILE * f, char stop, int *cl)
{
	int             wsize;
	char           *word;
	int             ll;

	wsize = 102400;
	ll = 0;
	word = (char *) malloc(sizeof(char) * (wsize + 1));

	while (1)
	{
		word[ll] = (char) fgetc(f);
		if (ll == wsize)
		{
			word[ll + 1] = '\0';
			wsize += 102400;
			word = (char *) realloc(word, sizeof(char) * (wsize + 1));
		}
		--(*cl);
		if ((word[ll] == stop) || (feof(f)) || (!(*cl)))
		{
			if (word[ll] != stop)
				ll++;
			word[ll] = '\0';
			return word;
		}
		++ll;
	}
}

char 
x2c(char *what)
{
	register char   digit;

	digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A') + 10 : (what[0] - '0'));
	digit *= 16;
	digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A') + 10 : (what[1] - '0'));
	return (digit);
}

void 
unescape_url(char *url)
{
	register int    x, y;

	for (x = 0, y = 0; url[y]; ++x, ++y)
	{
		if ((url[x] = url[y]) == '%')
		{
			url[x] = x2c(&url[y + 1]);
			y += 2;
		}
	}
	url[x] = '\0';
}

void 
plustospace(char *str)
{
	register int    x;

	for (x = 0; str[x]; x++)
		if (str[x] == '+')
			str[x] = ' ';
}

int 
rind(char *s, char c)
{
	register int    x;
	for (x = strlen(s) - 1; x != -1; x--)
		if (s[x] == c)
			return x;
	return -1;
}

int 
getline(char *s, int n, FILE * f)
{
	register int    i = 0;

	while (1)
	{
		s[i] = (char) fgetc(f);

		if (s[i] == CR)
			s[i] = fgetc(f);

		if ((s[i] == 0x4) || (s[i] == LF) || (i == (n - 1)))
		{
			s[i] = '\0';
			return (feof(f) ? 1 : 0);
		}
		++i;
	}
}

void 
send_fd(FILE * f, FILE * fd)
{
	int             num_chars = 0;
	char            c;

	while (1)
	{
		c = fgetc(f);
		if (feof(f))
			return;
		fputc(c, fd);
	}
}

/* coded by armian@www.kordic.re.kr */
int
ProcessGetMethod(entries)
getentry	*entries;
{
	char	*cl;
	int	x, m;

	if (strcmp(getenv("REQUEST_METHOD"), "GET"))
        {
                printf("This script should be referenced with a METHOD of GET.\n");
                printf("If you don't understand this, see this ");
                printf("<A HREF=\"http://www.ncsa.uiuc.edu/SDG/Software/Mosaic/Docs/fill-out-forms/overview.html\">forms overview</A>.%c", 10);
                exit(1);
        }

        cl = getenv("QUERY_STRING");
        if (cl == NULL)
        {
                printf("No query information to decode.\n");
                exit(1);
        }

        for (x = 0; cl[0] != '\0'; x++)
        {
                m = x;
                getword(entries[x].val, cl, '&');
                plustospace(entries[x].val);
                unescape_url(entries[x].val);
                getword(entries[x].name, entries[x].val, '=');
        }

	return m;
}
