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




int main(int argc, char *argv[])
{
	unsigned char	*address;
	unsigned short	checksum0;
	unsigned short	checksum1;
	unsigned char	*buf;
	int		romwidth;
	int		bootloader_size;
	FILE		*f;

	romwidth = 0;
	bootloader_size = 0;
	
	checksum0 = 0;
	checksum1 = 0;
	
	if (argc < 4) {
		fprintf(stderr, "Error: Insufficient parameters\n");
		return 1;
	}
	
	if (!strcmp(argv[1], "8")) {
		romwidth = 0;
	}
	else if (!strcmp(argv[1], "16")) {
		romwidth = 1;
	}
	else {
		fprintf(stderr, "Error: Invalid ROM width specified\n");
		return 1;
	}
	
	f = fopen(argv[2], "r");
	
	if (!f) {
		fprintf(stderr, "Error: Cannot open file %s\n", argv[2]);
		return 1;
	}
	
	bootloader_size = strtoul(argv[3], NULL, 10);
	
	buf = malloc(bootloader_size);
	
	fread(buf, bootloader_size, 1, f);

	for (address = buf;
		    (unsigned long)address <= ((unsigned long)buf + (unsigned long)bootloader_size - 1); address++)
	{
		if (((unsigned long)address & 0x01) == 0 || romwidth == 0)
		{
			checksum0 = (unsigned short)(checksum0 + *address);
		}
		else
		{
			checksum1 = (unsigned short)(checksum1 + *address);
		}
		if ((unsigned long)address == ((unsigned long)buf + (unsigned long)bootloader_size - 1))
		{
			break;
		}
	}
	
	if (romwidth == 1)
		fprintf(stdout, "%04X-%04X\n", checksum0, checksum1);
	else if (romwidth == 0)
		fprintf(stdout, "%04X\n", checksum0);
	
	free(buf);
	
	return 0;
}


