/* e_thumbcache.c */

#include <stddef.h>
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>

#include <Epeg.h>

#define BACKGROUNDS "backgrounds"
#define THUMBCACHE  "thumbcache"
#define LEN 1024

void update_thumbcache	(DIR *, DIR *);
void init_thumbcache	(DIR *);
void create_thumb		(char *, char *);
char *fullpath			(char *, char *);

int
main (void)
{
	DIR * backgrounds, * thumbcache;

	backgrounds = opendir(BACKGROUNDS);
	if (backgrounds == NULL) {
		printf("Cannot find %s - exiting\n", BACKGROUNDS);
		closedir(backgrounds);
		exit (1);
	}

	thumbcache  = opendir(THUMBCACHE);
	if (thumbcache == NULL) {
		closedir(thumbcache);
		init_thumbcache(backgrounds);
		return 0;
	} 

	update_thumbcache(backgrounds, thumbcache);

	return 0;
}

void
update_thumbcache(DIR * backgrounds, DIR * thumbcache)
{
	int i, j, k;
	char dst[LEN];
	char src[LEN];
	struct dirent *src_dp, *dst_dp;

	i = 0;

	while (src_dp = readdir(backgrounds)) {
		if (i > 1) {
			j = 0;
			k = 0;
		
			while (dst_dp = readdir(thumbcache)) {
				if (j > 1) 
					if (strcmp(src_dp->d_name, dst_dp->d_name) == 0) 
						k++;

				j++;
			}

		}

		if (k == 0) {
			strcpy(src, fullpath(src_dp->d_name, BACKGROUNDS));
			strcpy(dst, fullpath(src_dp->d_name, THUMBCACHE));
			create_thumb(src, dst);
		}

		i++;
		rewinddir(thumbcache);
	}

	(void)closedir(backgrounds);
	(void)closedir(thumbcache);
}

void 
init_thumbcache(DIR * backgrounds)
{
	int i;
	char dst[LEN];
	char src[LEN];
	DIR	 *thumbcache;
	struct dirent *src_dp, dst_dp;

	if (mkdir(THUMBCACHE, 0755)) {
		printf("Could not create directory %s\n", THUMBCACHE);
		exit (1);
	}

	i = 0;

	while (src_dp = readdir(backgrounds)) {
		if (i > 1) {
			strcpy(src, fullpath(src_dp->d_name, BACKGROUNDS));
			strcpy(dst, fullpath(src_dp->d_name, THUMBCACHE));
			create_thumb(src, dst);
		} 

		i++;
	}

	(void)closedir(backgrounds);
}

void
create_thumb(char *src, char *dst)
{
	Epeg_Image * image;

	image = epeg_file_open(src);

	if (!image) {
		printf("Cannot open %s\n", src);
		exit(1);
	}

	epeg_decode_size_set(image, 128, 96);
	epeg_quality_set(image, 75);
	epeg_file_output_set(image, dst);
	epeg_encode(image);
	epeg_close(image);
}

char 
*fullpath(char *file, char *dir)
{
	static char path[LEN];

	strcpy(path, dir);	
	strcat(path, "/");
	strcat(path, file);

	return (path);
}


