#include <stdio.h>
#include <string.h>
#include "u816.h"
#include "dupname.h"

extern const char *self;

int safe_print_filename(const char *fname, FILE *fh) {
	char fn[50] = "";
	char xbuf[5];
	int i;
	u8 c;

	for(i = 0; (c = (u8)fname[i]) && i < 12; i++) {
		if(c < ' ' || c > '|') {
			/* not printable, insert a hex escape */
			sprintf(xbuf, "$%02X", c);
			strcat(fn, xbuf);
		} else {
			strncat(fn, (char *)&c, 1);
		}
	}

	fputs(fn, fh);
	return strlen(fn);
}

void bad_atari_filename(const char *fname, const char *msg) {
	fprintf(stderr, "%s: warning: bad Atari filename \"", self);
	safe_print_filename(fname, stderr);
	fprintf(stderr, "\": %s\n", msg);
}

/* note to self: it's tempting to use isalpha(), isprint(), etc
	from ctype.h... but those are locale-aware. we want ASCII-only
	versions. */
void sanity_check_filename(const char *fname) {
	u8 c;
	unsigned int i, bad = 0, dots = 0, uscore = 0;

	c = fname[0];
	if(!c) {
		bad_atari_filename(fname, "empty!");
		return;
	} else if(c < 'A' || c > 'Z') {
		bad_atari_filename(fname, "does not begin with A-Z");
	}

	for(i = 0; (i < 12) && (c = fname[i]); i++) {
		if(c >= 'A' && c <= 'Z')
			continue;
		if(c >= '0' && c <= '9')
			continue;
		if(c == '_') {
			uscore++;
			continue;
		}
		if(c == '.') {
			dots++;
			continue;
		}
		bad++;
	}

	if(!dots) {
		bad_atari_filename(fname, "no \".\"");
	} else if(dots > 1) {
		bad_atari_filename(fname, "more than one \".\"");
	}

	if(bad)
		bad_atari_filename(fname, "invalid characters.");
	else if(uscore)
		fprintf(stderr, "%s: filename has underscore, OK on Sparta/MyDOS, not Atari DOS 2.x\n", self);

	if(is_dup_filename(fname)) {
		fprintf(stderr, "%s: warning: duplicate Atari filename %s\n",
				self, fname);
	}
}
