/*
 *	File:					CalcField.h
 *	Description:	Replaces date fields with it's true value.
 *
 *	(C) 1993-1994, Ketil Hunn
 *
 */

#ifndef CALCFIELD_H
#define CALCFIELD_H

#include <time.h>
#include <string.h>
#include <dos.h>
#include "MakeDate().h"
#include "AdjustYear().h"

void NewStringToDate(char datestr[], struct EventNode *node)
{
	struct timeval		tv;
	struct ClockData	clockdata;
	char							tmp[3], *dummy;

	if(strmid(datestr,tmp,1,2)==0)
	{
		node->day=strtol(tmp,&dummy,10);
		if(strmid(datestr,tmp,3,2)==0)
		{
			node->month=strtol(tmp,&dummy,10);
			if(strmid(datestr,tmp,5,2)==0)
				node->year=strtol(tmp,&dummy,10);
		}
	}

	GetSysTime(&tv);
	Amiga2Date(tv.tv_secs, &clockdata);

	if(node->day==0)
		node->day=clockdata.mday;
	if(node->month==0)
		node->month=clockdata.month;
	if(node->year==0)
		node->year=clockdata.year;
}

int NewCountYears(struct EventNode *node)
{
	struct timeval		tv;
	struct ClockData	clockdata;

	GetSysTime(&tv);
	Amiga2Date(tv.tv_secs, &clockdata);
	return abs(clockdata.year-AdjustYear(node->year));
}

int CountDays(struct EventNode *node)
{
	struct DateStamp *date;
	time_t t;
	long	days1, days2;

	t=NewMakeDate(NULL);
	date=__timecvt(t);
	days1=date->ds_Days;

	t=NewMakeDate(node);
	date=__timecvt(t);
	days2=date->ds_Days;

	return abs(days2-days1);
}

long PosChr(char string[], int f, long pos)
{
	for(; string[pos]!=f & string[pos]!='\0'; ++pos)
		;
	if(string[pos]=='\0')
		return 0;
	return ++pos;
}

char *CalcField(struct EventNode *node, char text[])
{
	struct EventNode *calcdate;
	char calc[7], *before=text, *after;
	long pos=0;

	if(calcdate=AllocMem(sizeof(struct EventNode), MEMF_CLEAR))
	{
		while((pos=PosChr(text, '{', pos))!=0)
		{
			if(!strmid(text, calc, pos+1, 6))
			{
				NewStringToDate(calc, calcdate);
				after=text+pos+7;
				text[pos-1]='\0';
				sprintf(text, "%s%ld%s", before,
																(node->calc==1 ? CountDays(calcdate) : NewCountYears(calcdate)),
																after);
			}
		}
		FreeMem(calcdate, sizeof(struct EventNode));
	}
	return text;
}
#endif
