/*
 * NewImg.c
 * for Bioinfo Animal Pictures Archive
 * jskim@bulls.kordic.re.kr
 * prints imge info in ascending order of date
 */

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <dirent.h>

#define NEW_IMG_DIR "New"
#define HTML_TEMPLATE "HTMLSrc/NewImg.html"


#define CGI_PREVIEW "preview.cgi"
#define CGI_VIEW "ViewImg.cgi"
#define CGI_MAIL "uu2mail.cgi"

typedef struct {
	char	name[256];
	int	size;	/* file size in bytes */
	time_t	time;	/* when added */
}IMAGE;

int int_comp(IMAGE *, IMAGE *);

main()
{
	FILE	*fp;

	DIR *dirp;
	struct dirent *direntp;

	struct stat Stat;

	IMAGE img[512];

	char *ptr;
	char line[256];
	char path[256];	/* file path */

	int cnt;
	time_t CurTime;

	int i;


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

	fp = fopen(HTML_TEMPLATE, "r");
	if (fp == NULL) { printf("HTML template error\n"); exit(0); }

	cnt = 0;
	dirp = opendir( NEW_IMG_DIR );
	while ( (direntp = readdir( dirp )) != NULL ) {
		ptr = (char *) strstr(direntp->d_name, ".");
		if (!strcasecmp(ptr+1, "jpg") || !strcasecmp(ptr+1, "gif")) {
			sprintf(path, "%s/%s", NEW_IMG_DIR, direntp->d_name);
			lstat(path, &Stat);
			strcpy(img[cnt].name, direntp->d_name);
			img[cnt].size = Stat.st_size;
			img[cnt].time = Stat.st_ctime;
			cnt++;
		}
	}
	closedir( dirp );

	qsort(img, cnt, sizeof(IMAGE), (int *)int_comp);
	time(&CurTime);

	while (fgets(line, 256, fp)) {
		if (!strncasecmp(line, "__RESULT__", 10)) {
			printf("<table width=650 border=1>\n");
			printf("<tr><th>No.</th><th>PV</th><th>Image Name</th><th>Size</th><th>D:H</th><th>Download</th></tr>\n");
			for (i=0; i< cnt; i++) {
				if ( i%30 == 0 && i > 0) printf("</table>\n<table width=650 border=1>\n");
				printf("<tr><td align=right width=20>%d.</td>\n", i+1);
				PrintImgInfo(img[i], CurTime);
			}
			printf("</table>\n");
		}
		else printf("%s", line);
	}


	fclose(fp);

	exit(0);
}

int PrintImgInfo(IMAGE img, time_t CurTime)
{
	char path[256];	/* path */
	int days;
	int hours;

	days = (CurTime - img.time)/(24*3600);
	hours = ( (CurTime - img.time)%(24*3600) )/3600;

	sprintf(path, "%s/%s", NEW_IMG_DIR, img.name);

	printf( "<td width=20><a href=%s?img=%s><img src=/~jskim/img/preview.gif></a></td>\n", CGI_PREVIEW, path);
	printf( "<td width=470><a href=%s?img=%s>", CGI_VIEW, path);
	printf( "<b>%s</b></a></td><td align=right width=25>%dkb</td>\n", img.name, (int)img.size/1024 );
	printf( "<td align=center width=35>%d:%d</td>\n", days, hours );
	printf( "<td align=center width=80><a href=%s?email=&srcFile=%s>mail it</a></td></tr>\n", CGI_MAIL, path);

	return 0;
}

int int_comp(IMAGE *i, IMAGE *j)
{
        if ( i->time > j->time)
                return (1);
        if (i->time < j->time)
                return (-1);
        return (0);
}
