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

static char verid[] = "@(#) $Ver: TRIMHIST v0.2 - LKC - 940408 $";

/*

History:

v0.1 - "TRIMHIST <days>"

  Trim ASCII version of history file.
  - Copy to T:
  - Read line by line, writing only lines to UULIB: that have data stamp greater
  than "current Julian Date - <days>".
  
v0.2 - "TRIMHIST <days>"

  Trim Binary version of history file.
  - Read record by record into memory, only update array index when data stamp is
  greater than "current Julian Date - <days>".
  - Write copy in memory in place of original file.
  
*/

#define IGREG (15+31L*(10+12L*1582))

#define LOCK "T:HISTORY.LCK"

struct _history {
	long stamp;
	char msgid[80];
} *history;
long histcnt;
long histsiz;

int SetLock(char *name)
{
	FILE *lck;

	while (lck = fopen(name,"r"))
	{
		fclose(lck);
		Delay(10000);
	}
	lck = fopen(name,"w");
	fputs("LOCK",lck);
	fclose(lck);
	return 0;
}

void FreeLock(char *name)
{
	remove(name);
}

void main(argc, argv)
	int argc;
	char *argv[];
{
	long tv;
	struct tm *tp;
	int m, d, y;
	int ja, jy, jm;
	long jul;

	int days;

	FILE *hist;
	long i;
	
	tv = time(NULL);
	tp = localtime(&tv);
	m = tp->tm_mon+1;
	d = tp->tm_mday;
	y = tp->tm_year + 1900L;
	
	if (m > 2)
	{
		jy = y;
		jm = m+1;
	}
	else
	{
		jy = y-1;
		jm = m + 13;
	}
	jul = (long)((long)(365.25*(float)jy)+(long)(30.6001*(float)jm)+d+1720995L);
	if (d+31L*(m+12L*y) >= IGREG)
	{
		ja = 0.01*jy;
		jul += 2-ja+(int)(0.025*ja);
	}

	if (argc == 0)
		exit(0);

	if (argc != 2)
	{
		fprintf(stderr,"Usage: %s days\n",argv[0]);
		exit(5);
	}

	days = atoi(argv[1]);
	if (days <= 0)
		exit(0);

	jul -= days;

	if (SetLock(LOCK))
		exit(0);

	histcnt = 0;
	system("copy UULIB:HISTORY.FIL UULIB:HISTORY.BAK");
	hist = fopen("UULIB:HISTORY.FIL","r");
	fread(&histsiz,sizeof(long),1,hist);
	if (feof(hist) || histsiz == 0)
		fclose(hist);
	else
	{
		history = calloc(histsiz,sizeof(struct _history));
		for (i = 0; i < histsiz; i++)
		{
			fread(&history[histcnt],sizeof(struct _history),1,hist);
			if (history[histcnt].stamp > jul)
				histcnt++;
		}
		fclose(hist);
		hist = fopen("UULIB:HISTORY.FIL","w");
		fwrite(&histcnt,sizeof(long),1,hist);
		fwrite(history,sizeof(struct _history),histcnt,hist);
		fclose(hist);
	}
	FreeLock(LOCK);
}

