#include <stdlib.h>
#include "outfile.h"
#include "outnode.h"
#include "yacintfc.h"
#include "drvout.h"
#include "cgidbg.h" 
#include "hrdcmp.h"




// TestAlloc is necessry for interactive checks
// It may also be used in standalone mode with TESTALLOC defined
// #define TESTALLOC
#if defined (INTERACTIVE) || defined (TESTALLOC)
void TestAlloc(const char * Msg=0)
{
	LogOut << "Enter TestAlloc(\"" ;
	if (Msg) LogOut << Msg ;
	LogOut << "\")\n" ;
	const Number = 77 ;
	const big = 119 ;
	double * x_double = new double[big];
	for (int i = 0 ; i < big ;i ++) x_double[i] = .45989568958654598e13 ;
	delete x_double ;
	char * Tests[Number];
#ifdef INTERACTIVE
	StreamStr * strs[Number] ;
#endif
	for (i = 0 ; i < Number; i++) {
		int Limit = 2*i+4 ;
		char * Temp ;
#ifdef INTERACTIVE
		strs[i] = new StreamStr(StreamNotInitialized);
#endif
		Tests[i] = Temp = new char[Limit];
		for (int j = 0 ; j < Limit ; j++) Temp[j] = rand();
	}
	for (i = 0 ; i < Number; i++) {
		delete Tests[i] ;
#ifdef INTERACTIVE
		delete strs[Number -i -1] ;
#endif
	}
	x_double = new double[big];
	for (i = 0 ; i < big ;i ++) x_double[i] = .7333333;
	delete  x_double ;
	LogOut << "Exit TestAlloc\n" ;
}
#endif



int32 DefaultDriverOutputInterface(OutputNode * TheNode,int Channel,
	int32 Size, MachWord*  Val)
{
/*
 *	LogOut<<"DefaultDriverOutputInterface for `" << TheNode->GetName()
 *		<< "'.\n" ;
 */
	if (Channel == ResetDriverSystemInterface) return OK ;
	OutputFile * Out = TheNode->GetOutputFile() ;
	if (!Out) DbgError("DefaultDriverOutputInterface","no file");
	int Count ;
	if (TheNode->GetFlags() & 8) {
		const int32 int32_max = 0x7fffffff ;
		for (int i = 0 ; i < Size ; i++) {
			int32 val ;
			MachWord v = Val[i].val() ;
			MachWord abs_v = v ;
			if ((MachWordCast) v < 0) abs_v = -v ;
			int warn = 0 ;
			if ((MachWordCast) abs_v <= int32_max) val = (int32) v.val() ;
			else if ((MachWordCast) v <0) (val = -0x7fffffff),warn=1 ;
			else (val = 0x7fffffff),warn=1 ;
			if (warn)
				State.Warning("32 bit integer overflow, value hard limited");
			int count = Out->Write((BinMachWord *) &val,1,Channel);
			if (count != 1) return Size - i ;
		}
		return Size ;
	}
	if (TheNode->read_binary()) {
		BinMachWord * b_val = (BinMachWord *)  Val ;
		for (int i = 0 ; i < Size ; i++) {
			MachWord v = (MachWord) (int) b_val[i] ;
			Out->Write((BinMachWord *) &v,1,Channel);
		}
		return Size ;
	} else if (TheNode->GetFlags() & 4) Count =
		Out->Write((BinMachWord *)Val,Size,Channel);
	else Count = Out->Write(Val, Size, Channel) ;
	return Count ;
}

