#include <limits.h>
#include <stdlib.h>
#include "tarnod.h"
#include "netlnk.h"
#include "cgidbg.h"
#include "dskchnhd.h"
#include "exec.h"
#include "ramio.h"
#include "cgidbg.h"

const char * LastNodeInDspNetwork = 0 ;
int InNodeInDspNetwork = 0 ;


ErrCode TargetNode::Reset()
{
	int i ;
	ErrCode Ret = OK ;
	ErrCode Loc = OK ;
	for (i = 0 ; i < In ; i++) if ((Loc = InLinks[i].Reset())
		> Ret) Ret = Loc ;
	for (i = 0 ; i < Out ; i++) if ((Loc = OutLinks[i].Reset())
		> Ret) Ret = Loc ;
	Init();
	// TheLog << "TargetNode::Reset for `" << GetName() << "'\n" ;
	// TestAlloc("Before NodeReset");
	Loc = NodeReset();
	Init(); // resets history and sequence indices
	// TestAlloc("After NodeReset");
	if (Loc > Ret) Ret = Loc ;
	History = 0 ;
	SequenceIndex = 0 ;
	return Ret ;
} 



int32 TargetNode::GetDynamicCount() 
{
	// Get input count
	// TheLog << "TargetNode::GetDynamicCount\n" ;
	// TheLog << "In = " << In << ", Out = " << Out << "\n" ;
	// TheLog << "Node is `" << GetName() << "'\n" ;
	int i ;
	int32 Count = INT_MAX ;
	for (i = 0 ; i < In ; i++) {
		int32 LocCount = InLinks[i].GetDynamicCount(SequenceIndex);
		if (LocCount < Count) Count = LocCount ;
		if (!LocCount) break ;
	}
	int32 DelHist = Delay - History ;
	// TheLog << "DelHist = " << DelHist << ", Delay = " << Delay << "\n" ;
	if (DelHist > 0) Count += DelHist ;
	if (!Count) return 0 ;
	// Get output count
	for (i = 0 ; i < Out ; i++) {
		int32 LocCount = OutLinks[i].GetDynamicCount();
		if (!LocCount) return 0 ;
		if (LocCount < Count) Count = LocCount ;
	}
	if (Count == INT_MAX) {
		// TheLog << "Count == INT_MAX\n" ;
		// TheLog << "In node `" << GetName() << "'\n" ;
		
		DebugCodeError(53,"TargetNode::GetDynamicCount",
			"No input or output links in node!",0);
		exit(1);
	}
	// return minimum count
	// TheLog << "returning " << Count << "\n" ;
	if (Count) SequenceIndex = 1 ;
	return Count ;
}


int32 TargetNode::GetInEltSize(int in_channel) const
{
	return InLinks[in_channel].GetElementSize();
}

NodeOutChannelHeader * TargetNode::GetDiskState(int Chan)
{
	return new NodeOutChannelHeader(*this,Chan);
}


