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

#ifndef CALCFIELD_H
#define CALCFIELD_H

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

void StringToDate(char datestr[], struct EventNode *node)
{
	char tmp[3], *dummy, buf[8];

	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);
		}
	}
	getclk(buf);
	if(node->day==0)
		node->day=buf[3];
	if(node->month==0)
		node->month=buf[2];
	if(node->year==0)
		node->year=buf[1]+80;
}

int CountYears(struct EventNode *node)
{
	char buf[8];
	int year, node_year;

	getclk(buf);
	year=buf[1]+1980;

	node_year=AdjustYear(node->year);
	return abs(year-node_year);
}

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

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

	t=MakeDate(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))
			{
				StringToDate(calc, calcdate);
				after=text+pos+7;
				text[pos-1]='\0';
				sprintf(text, "%s%ld%s", before,
																(node->calc==1 ? CountDays(calcdate) : CountYears(calcdate)),
																after);
			}
		}
		FreeMem(calcdate, sizeof(struct EventNode));
	}
	return text;
}
#endif
