/*
 * tron: general utility routines
 */

#include	"tron.h"

isexc(f)
char *f;
{
	register short i;
	char fb[16];

	strncpy(fb, f, DIRSIZ);
	fb[DIRSIZ] = 0;
	if(strcmp(fb, ".") == 0 || strcmp(fb, "..") == 0)
		return(1);
	for(i = 0; i < nex; i++)
		if(gmatch(fb, exc[i]) == 1)return(1);
	return(0);
}

pr(s)
char *s;
{
	if(any++ == 0)
		fprintf(stdout, "**TRON: %s", s);
	else	fprintf(stdout, ", %s", s);
}

addi(ip, s)
struct stat *ip;
char *s;
{
	outs(s, DIRSIZ);
	outs(ip, sizeof (struct stat));
}

outs(s, c)
register short *s;
register short c;
{
	c >>= 1;
	while(c--){
		*po++ = *s;
		exchksum += (unsigned)(*s++);
		if(po >= &obuf[512])
			flusho();
	}
}

flusho()
{
	if(po != obuf){
		write(fo, obuf, (char *)po-obuf);
		po = obuf;
	}
}

long
chks(f, tv)
long *tv;
char *f;
{
	static short cbuf[256];
	register unsigned short *i;
	short fd, r;
	long sum;

	if((fd = open(f, 0)) == -1)
		return(0L);
	sum = 0;
	while((r = read(fd, cbuf, 512)) > 0){
		r = (r >> 1) & ~1;
		for(i = &cbuf[r-1]; i >= cbuf; i--)
			sum += *i;
	}
	close(fd);
	if(exflg & ATIME)
		utime(f, tv);
	return(sum);
}


savfil(f)
char *f;
{
	register short i;
	struct stat statb;
	register char c;
	static char tfile[64];

	strcpy(tfile, f);
	i = strlen(f);
	for(c = '0'; c < '~'; c++){
		tfile[i] = c;
		if(stat(tfile, &statb)){
			link(f, tfile);
			unlink(f);
			return(0);
		}
	}
	fprintf(stdout, "***TRON: Not enough places to link to to save %s\n",f);
	return(1);
}


inlog(s)
register char *s;
{
	register short i;
	for(i = nth-1; i>= 0; i--)
		if(strncmp(s, newthings[i], THINGLEN) == 0)
			return(1);
	return(0);
}

wasdeleted(p)
char *p;
{
	register short i;

	for(i = nent-1; i >= 0; i--)
		if(stbuf[i].ss_name[0] && !inlog(stbuf[i].ss_name) && !isexc(stbuf[i].ss_name))
			fprintf(stdout, "*TRON: %s/%.14s has disappeared\n",
				p, stbuf[i].ss_name);
}
