/*  datfile.c   */
/*  Copyright 1989 Mountain Math Software  */
/*  All Rights Reserved                    */
#include "usriotyp.h"
#include "datfile.h"
#include "timing.h"
#include "netlnk.h"
#include "cgidbg.h"
#include "dskchnhd.h"

const char * DataFilePrologue = "DSP++ binary data file.\nversion 0000.0000\n" ;
	// The last five characters of this are ignored on reads.
	// This allows updated versions of the software to
	// generate new information and store it
	// at the end of the file or wherever a packet of
	// type `FileEltsChannelHeader' is expected. The new information
	// will be ignored by the older versions of the software,
	// but the basic information can still be processed.
	// The characters ignored are everything past the `.' i. e. `0000\n'.


#define CONVERT_AND_CHECK(type,round) \
{ \
	type temp = *((type *) Data) ; round \
	if (temp > MachWord::max_positive) { \
		temp = (type) MachWord::max_positive ; \
		OverflowFlag=1; \
	} \
	else if (temp < MachWord::min_negative) { \
		temp = (type) MachWord::min_negative ; \
		OverflowFlag=1; \
	} \
	return (MachWordCast) temp ; \
} 

#define ROUND_TEMP	if (to_int) temp += temp < 0 ? -.5 : .5 ; 

MachWord ConvertToMachWord(DataType type, void * Data, int& OverflowFlag)
{
	int to_int = 1 ;
	if (TheArithType == ArithType::ArithFloat ||
		TheArithType == ArithType::ArithDouble) to_int = 0 ;
	OverflowFlag = 0 ;
	switch (type) {
case DataTypeDouble:
		CONVERT_AND_CHECK(double,ROUND_TEMP) ;
case DataTypeInt16:
		CONVERT_AND_CHECK(int16,;) ;
case DataTypeInt32:
		CONVERT_AND_CHECK(int32,;) ;
case DataTypeFloat:
		CONVERT_AND_CHECK(float,ROUND_TEMP) ;

case DataTypeNull:
case DataTypeUpperLim:
default:
		DbgError("ConvertToMachWord","bad type");	
	}
	return  0 ;
}

#undef ROUND_TEMP
#undef CONVERT_AND_CHECK

int GetSizeOfDataType(DataType type)
{
	static int TheSizes[DataTypeUpperLim];
	static int Init = 0 ;
	if (!Init) {
		for (Init = 0 ; Init < DataTypeUpperLim; Init++)
			TheSizes[Init] = 0 ;
		TheSizes[DataTypeDouble] = sizeof(double) ;
		TheSizes[DataTypeInt16] = sizeof(int16) ;
		TheSizes[DataTypeInt32] = sizeof(int32) ;
		TheSizes[DataTypeFloat] = sizeof(float) ;
	}
	if (type <= DataTypeNull || type >= DataTypeUpperLim) return 0;
	return TheSizes[type];
}

const char * GetNameOfDataType(DataType type)
{
	static char * TheNames[DataTypeUpperLim];
	static int Init = 0 ;
	if (!Init) {
		for (Init = 0 ; Init < DataTypeUpperLim; Init++)
			TheNames[Init] = "UNDEFINED" ;
		TheNames[DataTypeDouble] = "double" ;
		TheNames[DataTypeInt16] = "int16" ;
		TheNames[DataTypeInt32] = "int32" ;
		TheNames[DataTypeFloat] = "float" ;
	}
	if (type <= DataTypeNull || type >= DataTypeUpperLim) return 0;
	return TheNames[type];
}


