#include <ascii.h>
#include "fido.h"
#include "fidomem.h"
#include "proto.h"

/* Update (or create) the time of day log. Increment the counter for the
particular hr and day. */

void timelog(net)
int net;		/* 1 == fidonet log else fido log */
{
int dwk,hr,i;
int timefile;
char oldname[SS],newname[SS];
struct _tlog tlg;

	hr= gtod3(4); if (hr > 23) hr= 0;		/* get time (error */
	dwk= gtod3(3); if (dwk > 6) dwk= 0;		/* check & bound) */

	strcpy(oldname,(net ? "NETLOG.BBS" : "TIMELOG.BBS"));
	timefile= open(oldname,2);			/* if not there, create, */
	if (timefile == -1) {
		timefile= creat(oldname,2);
		if (timefile == -1) {
			clprintf(LM+39,oldname);	/* "cant create %s" */
			return;
		}
		gtod(tlg.fdate);			/* set first date */
		gtod(tlg.ldate);			/* and last date */
		tlg.calls= 0;
		for (dwk= 0; dwk < 7; dwk++) {
			for (hr= 0; hr < 24; hr++)
				tlg.log[dwk][hr]= 0;
		}
	} else {
		read(timefile,&tlg,sizeof(tlg));	/* else read it in, */

		if ((dwk == 0) 				/* if Sunday, */
		    && (days(tlg.fdate,date) > 1)) {	/* and a week old, */
			close(timefile);		/* close it up, */
			gtod(newname);			/* rename to todays */
			newname[9]= NUL;		/* date, */
			strcpy(&newname[2],&newname[3]);/* remove spaces */
			strcpy(&newname[5],&newname[6]);
			strcat(newname,(net ? ".NLG" : ".TLG"));
			rename(oldname,newname);	/* rename it */
			delete(oldname);		/* last chance stop recursion */
			timelog(net);			/* create new one */
			return;
		}
	}
	++tlg.log[dwk][hr];				/* increment */
	++tlg.calls;
	strcpy(tlg.ldate,date);				/* last access, */
	lseek(timefile,0L,0);
	write(timefile,&tlg,sizeof(tlg));		/* write it out, */
	close(timefile);
}
