#include "unalf.h"

/* 20251104 bkw: implement the simple checksum used by ALF.
   Dumbest possible algo: all the bytes are added together and
   the bottom 16 bits of the result is the checksum. */

void alfsum(const char *file, FILE *f) {
	int c;
	unsigned long sum = 0;

	while((c = fgetc(f)) != EOF)
		sum += c;

	printf("%04x\t%s\n", (unsigned int)(sum & 0xffff), file);
}

int main(int argc, char **argv) {
	int errs = 0;
	char *file;
	FILE *f;

	set_self(argv[0]);

	if(argc < 2 || !strcmp(argv[1], "--help") || !strcmp(argv[1], "-h")) {
		printf("alfsum (ALF checksum calculator) v" VERSION " by B. Watson. WTFPL.\n"
				"Usage: %s filename [filename(s) ...] | [--help | -h] | [--version | -V]\n"
				"Use - to read from standard input.\n",
				self);
		puts("Options:");
		puts("  --version, -V: show version number.");
		puts("  --help,    -h: show this help message.");
		return (argc < 2) ? -1 : 0;
	}

	if(!strcmp(argv[1], "-V") || !strcmp(argv[1], "--version")) {
		puts(VERSION);
		exit(0);
	}

	while((file = *++argv)) {
		if(argv[0][0] == '-' && !argv[0][1]) {
			if(isatty(0))
				fprintf(stderr, "%s: reading from stdin...\n", self);
			f = stdin;
			file = " (stdin)";
		} else if(!(f = fopen(file, "rb"))) {
			fprintf(stderr, "%s: ", self);
			perror(file);
			errs++;
			continue;
		}
		alfsum(file, f);
		fclose(f);
	}

	return errs > 254 ? 254 : errs;
}
