/*  vocstr.C   */
/*  Copyright 1989 Mountain Math Software  */
/*  All Rights Reserved                    */
#include <stream.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include "sysintfc.h"
#include "portable.h"
#include "errcode.h"
#include "environ.h"

#include <limits.h>
#include <complex.h>
#include "shared.h"
#include "yacintfc.h"
#include "remcom.h"
#include "cgidbg.h"

#include "sysconst.h"

#include "vocstr.h"
#include "vocstrf.h"
#include "mkstr.h"
#ifdef __NT_VC__
#include <io.h>
#endif


VoiceStripOutputFile::VoiceStripOutputFile(const char * node_name,
	const char * Name):
	delete_file_name(0),
	exp_file_name(0),
	TheFile(-1)
{
/*
 *	LogOut << "VoiceStripOutputFile::VoiceStripOutputFile(" << node->GetName()
 *		<< ", \"" << Name << "\")" ;
 */
	FileName = Name ;
	NodeName = node_name ;
	open(0);
}

void VoiceStripOutputFile::open(int force_error)
{
	const char * new_file_name = FileName ;
	int flags = force_error ? 1:0 ;
    const char * exp_name = TargetNode::create_file(
        &new_file_name,TheFile,(const char *) 0,flags);
    if (!exp_name) return ;
	delete exp_file_name ;
	exp_file_name = 0 ;
    if (exp_name != new_file_name) exp_file_name = Concatenate(exp_name);
    if (FileName != new_file_name) {
        delete delete_file_name ;
        FileName = delete_file_name = Concatenate(new_file_name);
    }
}

void VoiceStripOutputFile::Reset()
{
	if (TheFile > 0) close(TheFile);
	TheFile = 0 ;
	open(0);
}

VoiceStripOutputFile::~VoiceStripOutputFile()
{
	delete delete_file_name ;
	delete exp_file_name ;
	if (TheFile > 0) close(TheFile);
	TheFile = -1 ;
}

enum ErrCode VoiceStripOutputFile::Write(MachWord Val)
{
	if (State.IsError()) return FatalError ;
	if (TheFile < 1) open(1);
	if (TheFile < 1) return FatalError ;
	int Out ;
	MachWordCast test = (MachWordCast) Val.val();
	MachWordCast abs_test = test < 0 ? -test : test ;
	const lim  = INT_MAX ;
	int warn = 0 ;
#ifdef INTEGER_MACH_WORD_TYPE
	Out = (int) Val.val();
#else
	if (abs_test <= lim) Out = (int) Val.val();
	else Out = (test < 0 ? -lim : lim),warn=1 ;
#endif
	// LogOut << "Out >> = 0x" << hex(Out) << "\n" ;
	Out += 128 ;
	if (Out < 0) Out = 0,warn=1 ;
	if (Out > 255) Out = 255,warn=1 ;
	if (warn) State.Warning("overflow in `",
		NodeName,"', output hard limited");
	if (write(TheFile,(char *) &Out,1) != 1) {
		State.Error("Write failure in file `", FileName,
			"' in node `", NodeName, "'.\n") ;
		return FatalError ;
	}
		
	return OK ;
}


