#include "common.h"

#include <string.h>

/* hardcoded magic values; stored at 0x18... */
static const uint8_t magic_veg[16] = {0xEF, 0x29, 0xC4, 0x46, 0x4A, 0x90, 0xD2, 0x11, 0x87, 0x22, 0x00, 0xC0, 0x4F, 0x8E, 0xDB, 0x8A};
static const uint8_t magic_vf[16]  = {0xF6, 0x1B, 0x3C, 0x53, 0x35, 0xD6, 0xF3, 0x43, 0x8A, 0x90, 0x64, 0xB8, 0x87, 0x23, 0x1F, 0x7F};

int set_file_information(FILE* target, uint8_t version, enum types type) {
	const uint8_t* magic = (type == TYPES_VF) ? magic_vf : magic_veg;

	if (fseek(target, 0x46, SEEK_SET))
		return -1;

	if (fputc(version, target) == EOF)
		return -1;

	if (fseek(target, 0x18, SEEK_SET))
		return -1;

	if (fwrite(magic, sizeof(*magic), 16, target) < 16)
		return -1;

	return 0;
}

int get_file_information(FILE* input, uint8_t* version, enum types* type) {
	uint8_t magic[16] = {0};

	if (fseek(input, 0x46, SEEK_SET))
		return -1;

	*version = fgetc(input);

	if (fseek(input, 0x18, SEEK_SET))
		return -1;

	/* read the WHOLE magic, then memcmp */
	if (fread(magic, sizeof(*magic), ARRAYSIZE(magic), input) < ARRAYSIZE(magic))
		return -1;

	if (!memcmp(magic, magic_veg, ARRAYSIZE(magic))) {
		*type = TYPES_VEG;
	} else if (!memcmp(magic, magic_vf, ARRAYSIZE(magic))) {
		*type = TYPES_VF;
	} else {
		*type = TYPES_UNKNOWN;
	}

	return 0;
}
