#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#include <stdbool.h>
#include "png.h"

int main(int argc, char *argv[]) {
	// Error handling
	if (argc != 2) {
		printf("Usage: %s <png file>\n", argv[0]);
		exit(EXIT_FAILURE);
	}
	if (strlen(argv[1]) > PATH_MAX) {
		printf("Path too long\n");
		exit(EXIT_FAILURE);
	}
	// Read file
	char *path = argv[1];
	char *png_buffer = load_file(path);
	if (!is_png(png_buffer)) {
		printf("It's not a PNG file\n");
		exit(EXIT_FAILURE);
	} else {
		printf("It's a PNG file\n");
	}
	png_chunk **chunks = get_png_chunks(png_buffer);
	free(png_buffer);
	// Done with buffer, as chunks are a structured way to access the data
	// Iterate over chunks to display info and "decrypt" IDAT chunks
	int size = get_number_of_chunks(chunks);
	for (int i = 0; i < size; i++) {
		// Check if header is IDAT or IEND
		bool is_idat = memcmp(chunks[i]->type, "IDAT", 4) == 0;
		bool is_iend = memcmp(chunks[i]->type, "IEND", 4) == 0;
		if (is_idat || is_iend) {
			printf("Found %.4s\n", chunks[i]->type);
			if (is_idat) {
				xor_data(chunks[i]);
			}
		} else {
			printf("Found unknown: %.4s\n", chunks[i]->type);
		}
		printf("Chunk size is:%d\n", chunks[i]->length);
	}
	// Write file and free memory
	write_png_chunks(path, chunks);
	destroy_chunks(chunks);
	return EXIT_SUCCESS;
}
