/***** TranscriptLinker.m -- liason object implementation
	NeXTstep Measurement Kit
	by Alex Meyer <ameyer@phoenix.Princeton.EDU>
	for computer science senior thesis
	16 April 1992 -- created
	21 April 1992 -- cleaned up by using new TranscriptManager methods
*****/

#import <stdlib.h>
#import <stdio.h>
#import <string.h>
#import <appkit/Application.h>
#import "TranscriptLinker.h"

@implementation TranscriptLinker

- init
{
	NXAtom tName;
	char temp[512];

	sprintf(temp,"%s/%s.%s",NXHomeDirectory(),[NXApp appName],FILEEXT);
	tName = NXUniqueString(temp);
	manager = [TranscriptManager alloc];
	[manager init];
	[manager setFile:tName];
	[manager load];
	storage = [Storage alloc];
	[storage initCount:0
		elementSize:sizeof(tlRec)
		description:NULL];
	return (self);
}


- free	/* updates linked stats and saves first */
{
	unsigned i,num;

	num = [storage count];
	for (i = 0;i < num;++i) {
		tlPtr link;
		void *Stats;

		link = (tlPtr) [storage elementAt:i];
		Stats = (void *) [link->obj copyOfStats];
		[manager copyIndex:link->index
			statsFrom:Stats];
		free(Stats);
	}
	[manager save];
	[manager free];
	[storage free];
	[super free];
	return (nil);
}


- connect:sender
{
	id succ;
	unsigned ind;
	tlRec link;
	tmRec rec;

	link.obj = sender;
	link.type = (unsigned) [sender type];
	link.key = (NXAtom) [sender key];
	succ = [manager copyRecordKey:link.key
		ofType:link.type
		into:&rec
		where:&ind];
	if (succ) {
		[sender copyInStats:rec.Stats];
		link.index = ind;
	}
	else {
		rec.type = link.type;
		rec.key = link.key;
		rec.desc = (NXAtom) [sender desc];
		rec.statsSize = (unsigned) [sender statsSize];
		rec.Stats = (void *) [sender copyOfStats];
		link.index = [manager addRecord:&rec];
	}
	[storage addElement:&link];
	return (self);
}

@end
