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

#define MAXLEN 64
#define MAXCACHE 17*1024

int used_cache = 0;
unsigned int *cache;

int in_cache(unsigned int z, unsigned int x, unsigned int y) {
	unsigned int i;
	for (i = 0; i < used_cache; i++) {
		if (cache[i] == z &&
		    cache[i + (MAXCACHE)] == x &&
		    cache[i + (MAXCACHE * 2)] == y)
			return 1;
	}

	return 0;
}

int main(int argc, char *argv[]) {
	FILE *expireFile;
	unsigned int i;
	unsigned int maxlen = 0;
	char rpath [ 128 ];
	char spath [ 128 ];

	if (argc < 3) {
		fprintf(stderr, "%s [expirefile] [path-to-files] [styles]\n", argv[0]);
		_exit(-1);
	}
	
	if (!(expireFile = fopen(argv[1], "r"))) {
		fprintf(stderr, "Can't open expirefile %s\n", argv[1]);
	}

	for (i = 3; i < argc; i++) {
		unsigned int len = strlen(argv[i]);
		if (len > maxlen) maxlen = len;
	}

	if (maxlen > MAXLEN) {
		fprintf(stderr, "Recompile with bigger MAXLEN, for long stylesheetnames\n");
	}

	if (chdir(argv[2]) == -1) {
		fprintf(stderr, "Can't chdir to %s\n", argv[2]);
		_exit(-1);
	}

	cache = (unsigned int *) malloc(MAXCACHE * sizeof(unsigned int) * 3);
	if (cache == NULL) {
		fprintf(stderr, "Can't allocate the cache\n");
		_exit(-1);
	}

	while (fgets ( rpath, sizeof(rpath)-MAXLEN, expireFile ) != NULL ) {
		unsigned int z, x, y;
		if (sscanf(rpath, "%d/%d/%d", &z, &x, &y) == 3) {
			rpath[strlen(rpath)-1] = '\0';
			strncat(rpath, ".png", 4);

			while (z > 12) {
		                x = x >> 1;
	        	        y = y >> 1;
		                z = z - 1;

				if (!in_cache(z,x,y)) {
					if (used_cache < MAXCACHE) {
						cache[used_cache] = z;
						cache[used_cache + (MAXCACHE)] = x;
						cache[used_cache + (MAXCACHE * 2)] = y;
						used_cache++;
					} else {
						fprintf(stderr, "Cache exhausted\n");
					}

					snprintf(spath, 127, "%d/%d/%d.png", z, x, y);

					for (i = 3; i < argc; i++) {
						if (chdir(argv[i]) == 0) {
							if (z == 17) unlink(rpath); /* so this is actually 18 */
//							printf("%s\n", rpath);
							unlink(spath);
							chdir("..");
						}
					}
				}
			}
		}
	}
	free(cache);
	fclose(expireFile);
}

